context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== using System.Reflection; using System.Text; using System.Collections; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using System.Diagnostics.Tracing; namespace System { [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible { #region Private Static Data Members private static readonly char [] enumSeperatorCharArray = new char [] {','}; private const String enumSeperator = ", "; private static Hashtable fieldInfoHash = Hashtable.Synchronized(new Hashtable()); private const int maxHashElements = 100; // to trim the working set #endregion #region Private Static Methods // This method is not thread-safe despite the usage of SynchronizedHashTable. // After GetHashEntry returns another thread can set fieldInfoHash[enumType] // to a different object. But that is not a problem for us because both HashEntry // objects will contain correct information. private static HashEntry GetHashEntry(RuntimeType enumType) { Contract.Requires(enumType != null); Contract.Ensures(Contract.Result<HashEntry>() != null); HashEntry hashEntry = (HashEntry)fieldInfoHash[enumType]; if (hashEntry == null) { // To reduce the workingset we clear the hashtable when a threshold number of elements are inserted. if (fieldInfoHash.Count > maxHashElements) fieldInfoHash.Clear(); hashEntry = new HashEntry(null, null); fieldInfoHash[enumType] = hashEntry; } return hashEntry; } [System.Security.SecuritySafeCritical] // auto-generated private static void GetCachedValuesAndNames(RuntimeType enumType, out ulong[] values, out String[] names, bool getValues, bool getNames) { HashEntry hashEntry = GetHashEntry(enumType); values = hashEntry.values; if (values != null) getValues = false; names = hashEntry.names; if (names != null) getNames = false; if (getValues || getNames) { #if MONO if (!GetEnumValuesAndNames (enumType, out values, out names)) Array.Sort (values, names, System.Collections.Generic.Comparer<ulong>.Default); #else GetEnumValuesAndNames( enumType.GetTypeHandleInternal(), JitHelpers.GetObjectHandleOnStack(ref values), JitHelpers.GetObjectHandleOnStack(ref names), getValues, getNames); #endif if (getValues) hashEntry.values = values; if (getNames) hashEntry.names = names; } } private static String InternalFormattedHexString(Object value) { TypeCode typeCode = Convert.GetTypeCode(value); switch (typeCode) { case TypeCode.SByte : { Byte result = (byte)(sbyte)value; return result.ToString("X2", null); } case TypeCode.Byte : { Byte result = (byte)value; return result.ToString("X2", null); } case TypeCode.Boolean: { // direct cast from bool to byte is not allowed Byte result = Convert.ToByte((bool)value); return result.ToString("X2", null); } case TypeCode.Int16: { UInt16 result = (UInt16)(Int16)value; return result.ToString("X4", null); } case TypeCode.UInt16 : { UInt16 result = (UInt16)value; return result.ToString("X4", null); } case TypeCode.Char: { UInt16 result = (UInt16)(Char)value; return result.ToString("X4", null); } case TypeCode.UInt32: { UInt32 result = (UInt32)value; return result.ToString("X8", null); } case TypeCode.Int32 : { UInt32 result = (UInt32)(int)value; return result.ToString("X8", null); } case TypeCode.UInt64 : { UInt64 result = (UInt64)value; return result.ToString("X16", null); } case TypeCode.Int64 : { UInt64 result = (UInt64)(Int64)value; return result.ToString("X16", null); } // All unsigned types will be directly cast default : Contract.Assert(false, "Invalid Object type in Format"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } } private static String InternalFormat(RuntimeType eT, Object value) { Contract.Requires(eT != null); Contract.Requires(value != null); if (!eT.IsDefined(typeof(System.FlagsAttribute), false)) // Not marked with Flags attribute { // Try to see if its one of the enum values, then we return a String back else the value String retval = GetName(eT, value); if (retval == null) return value.ToString(); else return retval; } else // These are flags OR'ed together (We treat everything as unsigned types) { return InternalFlagsFormat(eT, value); } } private static String InternalFlagsFormat(RuntimeType eT, Object value) { Contract.Requires(eT != null); Contract.Requires(value != null); ulong result = ToUInt64(value); // These values are sorted by value. Don't change this String[] names; ulong[] values; GetCachedValuesAndNames(eT, out values, out names, true, true); Contract.Assert(names.Length == values.Length); int index = values.Length - 1; StringBuilder retval = new StringBuilder(); bool firstTime = true; ulong saveResult = result; // We will not optimize this code further to keep it maintainable. There are some boundary checks that can be applied // to minimize the comparsions required. This code works the same for the best/worst case. In general the number of // items in an enum are sufficiently small and not worth the optimization. while (index >= 0) { if ((index == 0) && (values[index] == 0)) break; if ((result & values[index]) == values[index]) { result -= values[index]; if (!firstTime) retval.Insert(0, enumSeperator); retval.Insert(0, names[index]); firstTime = false; } index--; } // We were unable to represent this number as a bitwise or of valid flags if (result != 0) return value.ToString(); // For the case when we have zero if (saveResult==0) { if (values.Length > 0 && values[0] == 0) return names[0]; // Zero was one of the enum values. else return "0"; } else return retval.ToString(); // Return the string representation } internal static ulong ToUInt64(Object value) { // Helper function to silently convert the value to UInt64 from the other base types for enum without throwing an exception. // This is need since the Convert functions do overflow checks. TypeCode typeCode = Convert.GetTypeCode(value); ulong result; switch(typeCode) { case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: result = (UInt64)Convert.ToInt64(value, CultureInfo.InvariantCulture); break; case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Boolean: case TypeCode.Char: result = Convert.ToUInt64(value, CultureInfo.InvariantCulture); break; default: // All unsigned types will be directly cast Contract.Assert(false, "Invalid Object type in ToUInt64"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } return result; } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int InternalCompareTo(Object o1, Object o2); [System.Security.SecuritySafeCritical] [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern RuntimeType InternalGetUnderlyingType(RuntimeType enumType); #if MONO [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool GetEnumValuesAndNames (RuntimeType enumType, out ulong[] values, out string[] names); #else [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [System.Security.SuppressUnmanagedCodeSecurity] private static extern void GetEnumValuesAndNames(RuntimeTypeHandle enumType, ObjectHandleOnStack values, ObjectHandleOnStack names, bool getValues, bool getNames); #endif [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern Object InternalBoxEnum(RuntimeType enumType, long value); #endregion #region Public Static Methods private enum ParseFailureKind { None = 0, Argument = 1, ArgumentNull = 2, ArgumentWithParameter = 3, UnhandledException = 4 } // This will store the result of the parsing. private struct EnumResult { internal object parsedEnum; internal bool canThrow; internal ParseFailureKind m_failure; internal string m_failureMessageID; internal string m_failureParameter; internal object m_failureMessageFormatArgument; internal Exception m_innerException; internal void Init(bool canMethodThrow) { parsedEnum = 0; canThrow = canMethodThrow; } internal void SetFailure(Exception unhandledException) { m_failure = ParseFailureKind.UnhandledException; m_innerException = unhandledException; } internal void SetFailure(ParseFailureKind failure, string failureParameter) { m_failure = failure; m_failureParameter = failureParameter; if (canThrow) throw GetEnumParseException(); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) { m_failure = failure; m_failureMessageID = failureMessageID; m_failureMessageFormatArgument = failureMessageFormatArgument; if (canThrow) throw GetEnumParseException(); } internal Exception GetEnumParseException() { switch (m_failure) { case ParseFailureKind.Argument: return new ArgumentException(Environment.GetResourceString(m_failureMessageID)); case ParseFailureKind.ArgumentNull: return new ArgumentNullException(m_failureParameter); case ParseFailureKind.ArgumentWithParameter: return new ArgumentException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument)); case ParseFailureKind.UnhandledException: return m_innerException; default: Contract.Assert(false, "Unknown EnumParseFailure: " + m_failure); return new ArgumentException(Environment.GetResourceString("Arg_EnumValueNotFound")); } } } public static bool TryParse<TEnum>(String value, out TEnum result) where TEnum : struct { return TryParse(value, false, out result); } public static bool TryParse<TEnum>(String value, bool ignoreCase, out TEnum result) where TEnum : struct { result = default(TEnum); EnumResult parseResult = new EnumResult(); parseResult.Init(false); bool retValue; if (retValue = TryParseEnum(typeof(TEnum), value, ignoreCase, ref parseResult)) result = (TEnum)parseResult.parsedEnum; return retValue; } [System.Runtime.InteropServices.ComVisible(true)] public static Object Parse(Type enumType, String value) { return Parse(enumType, value, false); } [System.Runtime.InteropServices.ComVisible(true)] public static Object Parse(Type enumType, String value, bool ignoreCase) { EnumResult parseResult = new EnumResult(); parseResult.Init(true); if (TryParseEnum(enumType, value, ignoreCase, ref parseResult)) return parseResult.parsedEnum; else throw parseResult.GetEnumParseException(); } private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, ref EnumResult parseResult) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); if (value == null) { parseResult.SetFailure(ParseFailureKind.ArgumentNull, "value"); return false; } value = value.Trim(); if (value.Length == 0) { parseResult.SetFailure(ParseFailureKind.Argument, "Arg_MustContainEnumInfo", null); return false; } #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EnumTryParseEnum(rtType.GetFullNameForEtw(), value); } #endif // We have 2 code paths here. One if they are values else if they are Strings. // values will have the first character as as number or a sign. ulong result = 0; if (Char.IsDigit(value[0]) || value[0] == '-' || value[0] == '+') { Type underlyingType = GetUnderlyingType(enumType); Object temp; try { temp = Convert.ChangeType(value, underlyingType, CultureInfo.InvariantCulture); parseResult.parsedEnum = ToObject(enumType, temp); return true; } catch (FormatException) { // We need to Parse this as a String instead. There are cases // when you tlbimp enums that can have values of the form "3D". // Don't fix this code. } catch (Exception ex) { if (parseResult.canThrow) throw; else { parseResult.SetFailure(ex); return false; } } } String[] values = value.Split(enumSeperatorCharArray); // Find the field.Lets assume that these are always static classes because the class is // an enum. String[] enumNames; ulong[] enumValues; GetCachedValuesAndNames(rtType, out enumValues, out enumNames, true, true); for (int i = 0; i < values.Length; i++) { values[i] = values[i].Trim(); // We need to remove whitespace characters bool success = false; for (int j = 0; j < enumNames.Length; j++) { if (ignoreCase) { if (String.Compare(enumNames[j], values[i], StringComparison.OrdinalIgnoreCase) != 0) continue; } else { if (!enumNames[j].Equals(values[i])) continue; } ulong item = enumValues[j]; result |= item; success = true; break; } if (!success) { // Not found, throw an argument exception. parseResult.SetFailure(ParseFailureKind.ArgumentWithParameter, "Arg_EnumValueNotFound", value); return false; } } try { parseResult.parsedEnum = ToObject(enumType, result); return true; } catch (Exception ex) { if (parseResult.canThrow) throw; else { parseResult.SetFailure(ex); return false; } } } [System.Runtime.InteropServices.ComVisible(true)] public static Type GetUnderlyingType(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.Ensures(Contract.Result<Type>() != null); Contract.EndContractBlock(); #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EnumGetUnderlyingType(enumType.GetFullNameForEtw()); } #endif return enumType.GetEnumUnderlyingType(); } [System.Runtime.InteropServices.ComVisible(true)] public static Array GetValues(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.Ensures(Contract.Result<Array>() != null); Contract.EndContractBlock(); #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EnumGetValues(enumType.GetFullNameForEtw()); } #endif return enumType.GetEnumValues(); } internal static ulong[] InternalGetValues(RuntimeType enumType) { // Get all of the values ulong[] values; String[] names; GetCachedValuesAndNames(enumType, out values, out names, true, false); return values; } [System.Runtime.InteropServices.ComVisible(true)] public static String GetName(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.EndContractBlock(); #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EnumGetName(enumType.GetFullNameForEtw()); } #endif return enumType.GetEnumName(value); } [System.Runtime.InteropServices.ComVisible(true)] public static String[] GetNames(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EnumGetNames(enumType.GetFullNameForEtw()); } #endif return enumType.GetEnumNames(); } internal static String[] InternalGetNames(RuntimeType enumType) { // Get all of the names ulong[] values; String[] names; GetCachedValuesAndNames(enumType, out values, out names, false, true); return names; } [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, Object value) { if (value == null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); // Delegate rest of error checking to the other functions TypeCode typeCode = Convert.GetTypeCode(value); // NetCF doesn't support char and boolean conversion if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8 && ((typeCode == TypeCode.Boolean) || (typeCode == TypeCode.Char))) { throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"), "value"); } switch (typeCode) { case TypeCode.Int32 : return ToObject(enumType, (int)value); case TypeCode.SByte : return ToObject(enumType, (sbyte)value); case TypeCode.Int16 : return ToObject(enumType, (short)value); case TypeCode.Int64 : return ToObject(enumType, (long)value); case TypeCode.UInt32 : return ToObject(enumType, (uint)value); case TypeCode.Byte : return ToObject(enumType, (byte)value); case TypeCode.UInt16 : return ToObject(enumType, (ushort)value); case TypeCode.UInt64 : return ToObject(enumType, (ulong)value); case TypeCode.Char: return ToObject(enumType, (char)value); case TypeCode.Boolean: return ToObject(enumType, (bool)value); default: // All unsigned types will be directly cast throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"), "value"); } } [Pure] [System.Runtime.InteropServices.ComVisible(true)] public static bool IsDefined(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.EndContractBlock(); #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EnumIsDefined(enumType.GetFullNameForEtw()); } #endif return enumType.IsEnumDefined(value); } [System.Runtime.InteropServices.ComVisible(true)] public static String Format(Type enumType, Object value, String format) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); if (value == null) throw new ArgumentNullException("value"); if (format == null) throw new ArgumentNullException("format"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.BeginEnumFormat(rtType.GetFullNameForEtw()); } #endif // Check if both of them are of the same type Type valueType = value.GetType(); Type underlyingType = GetUnderlyingType(enumType); // If the value is an Enum then we need to extract the underlying value from it if (valueType.IsEnum) { Type valueUnderlyingType = GetUnderlyingType(valueType); if (!valueType.IsEquivalentTo(enumType)) throw new ArgumentException(Environment.GetResourceString("Arg_EnumAndObjectMustBeSameType", valueType.ToString(), enumType.ToString())); valueType = valueUnderlyingType; value = ((Enum)value).GetValue(); } // The value must be of the same type as the Underlying type of the Enum else if (valueType != underlyingType) { throw new ArgumentException(Environment.GetResourceString("Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType", valueType.ToString(), underlyingType.ToString())); } if( format.Length != 1) { // all acceptable format string are of length 1 throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification")); } #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EndEnumFormat(rtType.GetFullNameForEtw()); } #endif char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { return value.ToString(); } if (formatCh == 'X' || formatCh == 'x') { // Retrieve the value from the field. return InternalFormattedHexString(value); } if (formatCh == 'G' || formatCh == 'g') { return InternalFormat(rtType, value); } if (formatCh == 'F' || formatCh == 'f') { return InternalFlagsFormat(rtType, value); } throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification")); } #endregion #region Definitions private class HashEntry { // Each entry contains a list of sorted pair of enum field names and values, sorted by values public HashEntry(String [] names, ulong [] values) { this.names = names; this.values = values; } public String[] names; public ulong [] values; } #endregion #if MONO [MethodImplAttribute (MethodImplOptions.InternalCall)] extern object get_value (); #endif #region Private Methods [System.Security.SecuritySafeCritical] internal unsafe Object GetValue() { #if MONO return get_value (); #else fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data) { switch (InternalGetCorElementType()) { case CorElementType.I1: return *(sbyte*)pValue; case CorElementType.U1: return *(byte*)pValue; case CorElementType.Boolean: return *(bool*)pValue; case CorElementType.I2: return *(short*)pValue; case CorElementType.U2: return *(ushort*)pValue; case CorElementType.Char: return *(char*)pValue; case CorElementType.I4: return *(int*)pValue; case CorElementType.U4: return *(uint*)pValue; case CorElementType.R4: return *(float*)pValue; case CorElementType.I8: return *(long*)pValue; case CorElementType.U8: return *(ulong*)pValue; case CorElementType.R8: return *(double*)pValue; case CorElementType.I: return *(IntPtr*)pValue; case CorElementType.U: return *(UIntPtr*)pValue; default: Contract.Assert(false, "Invalid primitive type"); return null; } } #endif } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern bool InternalHasFlag(Enum flags); [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] #if MONO private extern int get_hashcode (); #else private extern CorElementType InternalGetCorElementType(); #endif #endregion #region Object Overrides #if MONO public override bool Equals (object obj) { return DefaultEquals (this, obj); } #else [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern override bool Equals(Object obj); #endif [System.Security.SecuritySafeCritical] public override unsafe int GetHashCode() { #if MONO return get_hashcode (); #else // Avoid boxing by inlining GetValue() // return GetValue().GetHashCode(); fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data) { switch (InternalGetCorElementType()) { case CorElementType.I1: return (*(sbyte*)pValue).GetHashCode(); case CorElementType.U1: return (*(byte*)pValue).GetHashCode(); case CorElementType.Boolean: return (*(bool*)pValue).GetHashCode(); case CorElementType.I2: return (*(short*)pValue).GetHashCode(); case CorElementType.U2: return (*(ushort*)pValue).GetHashCode(); case CorElementType.Char: return (*(char*)pValue).GetHashCode(); case CorElementType.I4: return (*(int*)pValue).GetHashCode(); case CorElementType.U4: return (*(uint*)pValue).GetHashCode(); case CorElementType.R4: return (*(float*)pValue).GetHashCode(); case CorElementType.I8: return (*(long*)pValue).GetHashCode(); case CorElementType.U8: return (*(ulong*)pValue).GetHashCode(); case CorElementType.R8: return (*(double*)pValue).GetHashCode(); case CorElementType.I: return (*(IntPtr*)pValue).GetHashCode(); case CorElementType.U: return (*(UIntPtr*)pValue).GetHashCode(); default: Contract.Assert(false, "Invalid primitive type"); return 0; } } #endif } public override String ToString() { // Returns the value in a human readable format. For PASCAL style enums who's value maps directly the name of the field is returned. // For PASCAL style enums who's values do not map directly the decimal value of the field is returned. // For BitFlags (indicated by the Flags custom attribute): If for each bit that is set in the value there is a corresponding constant //(a pure power of 2), then the OR string (ie "Red | Yellow") is returned. Otherwise, if the value is zero or if you can't create a string that consists of // pure powers of 2 OR-ed together, you return a hex value return Enum.InternalFormat((RuntimeType)GetType(), GetValue()); } #endregion #region IFormattable [Obsolete("The provider argument is not used. Please use ToString(String).")] public String ToString(String format, IFormatProvider provider) { return ToString(format); } #endregion #region IComparable [System.Security.SecuritySafeCritical] // auto-generated public int CompareTo(Object target) { const int retIncompatibleMethodTables = 2; // indicates that the method tables did not match const int retInvalidEnumType = 3; // indicates that the enum was of an unknown/unsupported unerlying type if (this == null) throw new NullReferenceException(); Contract.EndContractBlock(); int ret = InternalCompareTo(this, target); if (ret < retIncompatibleMethodTables) { // -1, 0 and 1 are the normal return codes return ret; } else if (ret == retIncompatibleMethodTables) { Type thisType = this.GetType(); Type targetType = target.GetType(); throw new ArgumentException(Environment.GetResourceString("Arg_EnumAndObjectMustBeSameType", targetType.ToString(), thisType.ToString())); } else { // assert valid return code (3) Contract.Assert(ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } } #endregion #region Public Methods public String ToString(String format) { if (format == null || format.Length == 0) format = "G"; if (String.Compare(format, "G", StringComparison.OrdinalIgnoreCase) == 0) return ToString(); if (String.Compare(format, "D", StringComparison.OrdinalIgnoreCase) == 0) return GetValue().ToString(); if (String.Compare(format, "X", StringComparison.OrdinalIgnoreCase) == 0) return InternalFormattedHexString(GetValue()); if (String.Compare(format, "F", StringComparison.OrdinalIgnoreCase) == 0) return InternalFlagsFormat((RuntimeType)GetType(), GetValue()); throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification")); } [Obsolete("The provider argument is not used. Please use ToString().")] public String ToString(IFormatProvider provider) { return ToString(); } [System.Security.SecuritySafeCritical] public Boolean HasFlag(Enum flag) { if (flag == null) throw new ArgumentNullException("flag"); Contract.EndContractBlock(); if (!this.GetType().IsEquivalentTo(flag.GetType())) { throw new ArgumentException(Environment.GetResourceString("Argument_EnumTypeDoesNotMatch", flag.GetType(), this.GetType())); } return InternalHasFlag(flag); } #endregion #region IConvertable public TypeCode GetTypeCode() { Type enumType = this.GetType(); Type underlyingType = GetUnderlyingType(enumType); if (underlyingType == typeof(Int32)) { return TypeCode.Int32; } if (underlyingType == typeof(sbyte)) { return TypeCode.SByte; } if (underlyingType == typeof(Int16)) { return TypeCode.Int16; } if (underlyingType == typeof(Int64)) { return TypeCode.Int64; } if (underlyingType == typeof(UInt32)) { return TypeCode.UInt32; } if (underlyingType == typeof(byte)) { return TypeCode.Byte; } if (underlyingType == typeof(UInt16)) { return TypeCode.UInt16; } if (underlyingType == typeof(UInt64)) { return TypeCode.UInt64; } if (underlyingType == typeof(Boolean)) { return TypeCode.Boolean; } if (underlyingType == typeof(Char)) { return TypeCode.Char; } Contract.Assert(false, "Unknown underlying type."); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Enum", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } #endregion #region ToObject [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, sbyte value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EnumToObject(enumType.GetFullNameForEtw()); } #endif return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, short value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EnumToObject(enumType.GetFullNameForEtw()); } #endif return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, int value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EnumToObject(enumType.GetFullNameForEtw()); } #endif return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, byte value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EnumToObject(enumType.GetFullNameForEtw()); } #endif return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, ushort value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EnumToObject(enumType.GetFullNameForEtw()); } #endif return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, uint value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EnumToObject(enumType.GetFullNameForEtw()); } #endif return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, long value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EnumToObject(enumType.GetFullNameForEtw()); } #endif return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, ulong value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); #if !FEATURE_CORECLR && !MONO if (FrameworkEventSource.IsInitialized && FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.DynamicTypeUsage)) { FrameworkEventSource.Log.EnumToObject(enumType.GetFullNameForEtw()); } #endif return InternalBoxEnum(rtType, unchecked((long)value)); } [System.Security.SecuritySafeCritical] // auto-generated private static Object ToObject(Type enumType, char value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated private static Object ToObject(Type enumType, bool value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value ? 1 : 0); } #endregion } }
namespace Incoding.MvcContrib { #region << Using >> using System; using System.Web.Mvc; using System.Web.Routing; using Incoding.Block.IoC; using Incoding.Extensions; using Incoding.Maybe; using JetBrains.Annotations; #endregion public class IncodingHtmlHelper { #region Fields readonly HtmlHelper htmlHelper; #endregion ////ncrunch: no coverage start #region Constructors public IncodingHtmlHelper(HtmlHelper htmlHelper) { this.htmlHelper = htmlHelper; } #endregion static TagBuilder CreateScript(string id, HtmlType type, string src, MvcHtmlString content) { var routeValueDictionary = new RouteValueDictionary(new { type = type.ToLocalization() }); if (!string.IsNullOrWhiteSpace(src)) routeValueDictionary.Merge(new { src }); if (!string.IsNullOrWhiteSpace(id)) routeValueDictionary.Merge(new { id }); return CreateTag(HtmlTag.Script, content, routeValueDictionary); } static TagBuilder CreateInput(string value, string type, object attributes) { var routeValueDictionary = AnonymousHelper.ToDictionary(attributes); routeValueDictionary.Merge(new { value, type }); var input = CreateTag(HtmlTag.Input, MvcHtmlString.Empty, routeValueDictionary); return input; } internal static TagBuilder CreateTag(HtmlTag tag, MvcHtmlString content, RouteValueDictionary attributes) { var tagBuilder = new TagBuilder(tag.ToStringLower()); tagBuilder.InnerHtml = content.ReturnOrDefault(r => r.ToHtmlString(), string.Empty); tagBuilder.MergeAttributes(attributes, true); return tagBuilder; } // ReSharper disable ConvertToConstant.Global // ReSharper disable FieldCanBeMadeReadOnly.Global ////ncrunch: no coverage start #region Static Fields public static Selector DropDownTemplateId = "incodingDropDownTemplate".ToId(); public static JqueryAjaxOptions DropDownOption = new JqueryAjaxOptions(JqueryAjaxOptions.Default); public static BootstrapOfVersion BootstrapVersion = BootstrapOfVersion.v2; public static B Def_Label_Class = B.Col_xs_5; public static B Def_Control_Class = B.Col_xs_7; #endregion ////ncrunch: no coverage end // ReSharper restore FieldCanBeMadeReadOnly.Global // ReSharper restore ConvertToConstant.Global ////ncrunch: no coverage end #region Api Methods public MvcHtmlString Script([PathReference] string src) { var script = CreateScript(string.Empty, HtmlType.TextJavaScript, src, MvcHtmlString.Empty); return new MvcHtmlString(script.ToString()); } [Obsolete("Please use Template")] public MvcScriptTemplate<TModel> ScriptTemplate<TModel>(string id) { return new MvcScriptTemplate<TModel>(this.htmlHelper, id); } public MvcTemplate<TModel> Template<TModel>() { return new MvcTemplate<TModel>(this.htmlHelper); } public MvcHtmlString Link([PathReference] string href) { var tagBuilder = CreateTag(HtmlTag.Link, MvcHtmlString.Empty, new RouteValueDictionary()); tagBuilder.MergeAttribute(HtmlAttribute.Href.ToStringLower(), href); tagBuilder.MergeAttribute(HtmlAttribute.Rel.ToStringLower(), "stylesheet"); tagBuilder.MergeAttribute(HtmlAttribute.Type.ToStringLower(), HtmlType.TextCss.ToLocalization()); return new MvcHtmlString(tagBuilder.ToString()); } public MvcHtmlString Button(string value, object attributes = null) { var button = CreateTag(HtmlTag.Button, new MvcHtmlString(value), AnonymousHelper.ToDictionary(attributes)); return new MvcHtmlString(button.ToString()); } public MvcHtmlString Submit(string value, object attributes = null) { var submit = CreateInput(value, HtmlInputType.Submit.ToStringLower(), attributes); return new MvcHtmlString(submit.ToString(TagRenderMode.SelfClosing)); } public MvcHtmlString Img(string src, object attributes = null) { return Img(src, MvcHtmlString.Empty, attributes); } public MvcHtmlString Img(string src, MvcHtmlString content, object attributes = null) { var routeValueDictionary = AnonymousHelper.ToDictionary(attributes); routeValueDictionary.Merge(new { src }); var img = CreateTag(HtmlTag.Img, content, routeValueDictionary); return new MvcHtmlString(img.ToString()); } public MvcHtmlString Anchor(string href, string content, object attributes = null) { return Anchor(href, new MvcHtmlString(content), attributes); } public MvcHtmlString Anchor(string href, MvcHtmlString content, object attributes = null) { var routeValue = AnonymousHelper.ToDictionary(attributes); routeValue.Set("href", href); var a = CreateTag(HtmlTag.A, content, routeValue); return new MvcHtmlString(a.ToString()); } public MvcHtmlString Div(MvcHtmlString content, object attributes = null) { var div = CreateTag(HtmlTag.Div, content, AnonymousHelper.ToDictionary(attributes)); return new MvcHtmlString(div.ToString()); } public MvcHtmlString Div(string content, object attributes = null) { return Div(new MvcHtmlString(content), attributes); } public MvcHtmlString Span(MvcHtmlString content, object attributes = null) { var tag = CreateTag(HtmlTag.Span, content, AnonymousHelper.ToDictionary(attributes)); return new MvcHtmlString(tag.ToString()); } public MvcHtmlString Span(string content, object attributes = null) { return Span(new MvcHtmlString(content), attributes); } public MvcHtmlString I(object attributes = null) { var tag = CreateTag(HtmlTag.I, MvcHtmlString.Empty, AnonymousHelper.ToDictionary(attributes)); return new MvcHtmlString(tag.ToString()); } public MvcHtmlString P(MvcHtmlString content, object attributes = null) { var tag = CreateTag(HtmlTag.P, content, AnonymousHelper.ToDictionary(attributes)); return new MvcHtmlString(tag.ToString()); } public MvcHtmlString P(string content, object attributes = null) { return P(new MvcHtmlString(content), attributes); } public MvcHtmlString Ul(MvcHtmlString content, object attributes = null) { var tag = CreateTag(HtmlTag.Ul, content, AnonymousHelper.ToDictionary(attributes)); return new MvcHtmlString(tag.ToString()); } public MvcHtmlString Ul(string content, object attributes = null) { return Ul(new MvcHtmlString(content), attributes); } public MvcHtmlString Li(MvcHtmlString content, object attributes = null) { var tag = CreateTag(HtmlTag.Li, content, AnonymousHelper.ToDictionary(attributes)); return new MvcHtmlString(tag.ToString()); } public MvcHtmlString Li(string content, object attributes = null) { return Li(new MvcHtmlString(content), attributes); } public MvcHtmlString Tag(HtmlTag tag, MvcHtmlString content, object attributes = null) { var res = CreateTag(tag, content, AnonymousHelper.ToDictionary(attributes)); return new MvcHtmlString(res.ToString()); } public BeginTag BeginTag(HtmlTag tag, object attributes = null) { return new BeginTag(htmlHelper, tag, AnonymousHelper.ToDictionary(attributes)); } public MvcHtmlString Tag(HtmlTag tag, string content, object attributes = null) { return Tag(tag, new MvcHtmlString(content), attributes); } public MvcHtmlString File(string value, object attributes = null) { var file = CreateInput(value, HtmlInputType.File.ToStringLower(), attributes); return new MvcHtmlString(file.ToString(TagRenderMode.SelfClosing)); } public MvcHtmlString RenderDropDownTemplate() { var templateFactory = IoCFactory.Instance.TryResolve<ITemplateFactory>() ?? new TemplateHandlebarsFactory(); string template = templateFactory.GetDropDownTemplate(); return new MvcHtmlString(CreateScript("incodingDropDownTemplate", HtmlType.TextTemplate, string.Empty, new MvcHtmlString(template)).ToString()); } #endregion } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Text; using System.Collections; namespace NUnit.Framework.Constraints { /// <summary> /// Static methods used in creating messages /// </summary> public class MsgUtils { /// <summary> /// Static string used when strings are clipped /// </summary> private const string ELLIPSIS = "..."; /// <summary> /// Returns the representation of a type as used in NUnitLite. /// This is the same as Type.ToString() except for arrays, /// which are displayed with their declared sizes. /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string GetTypeRepresentation(object obj) { Array array = obj as Array; if (array == null) return string.Format("<{0}>", obj.GetType()); StringBuilder sb = new StringBuilder(); Type elementType = array.GetType(); int nest = 0; while (elementType.IsArray) { elementType = elementType.GetElementType(); ++nest; } sb.Append(elementType.ToString()); sb.Append('['); for (int r = 0; r < array.Rank; r++) { if (r > 0) sb.Append(','); sb.Append(array.GetLength(r)); } sb.Append(']'); while (--nest > 0) sb.Append("[]"); return string.Format("<{0}>", sb.ToString()); } /// <summary> /// Converts any control characters in a string /// to their escaped representation. /// </summary> /// <param name="s">The string to be converted</param> /// <returns>The converted string</returns> public static string EscapeControlChars(string s) { if (s != null) { StringBuilder sb = new StringBuilder(); foreach (char c in s) { switch (c) { //case '\'': // sb.Append("\\\'"); // break; //case '\"': // sb.Append("\\\""); // break; case '\\': sb.Append("\\\\"); break; case '\0': sb.Append("\\0"); break; case '\a': sb.Append("\\a"); break; case '\b': sb.Append("\\b"); break; case '\f': sb.Append("\\f"); break; case '\n': sb.Append("\\n"); break; case '\r': sb.Append("\\r"); break; case '\t': sb.Append("\\t"); break; case '\v': sb.Append("\\v"); break; case '\x0085': case '\x2028': case '\x2029': sb.Append(string.Format("\\x{0:X4}", (int)c)); break; default: sb.Append(c); break; } } s = sb.ToString(); } return s; } /// <summary> /// Return the a string representation for a set of indices into an array /// </summary> /// <param name="indices">Array of indices for which a string is needed</param> public static string GetArrayIndicesAsString(int[] indices) { StringBuilder sb = new StringBuilder(); sb.Append('['); for (int r = 0; r < indices.Length; r++) { if (r > 0) sb.Append(','); sb.Append(indices[r].ToString()); } sb.Append(']'); return sb.ToString(); } /// <summary> /// Get an array of indices representing the point in a enumerable, /// collection or array corresponding to a single int index into the /// collection. /// </summary> /// <param name="collection">The collection to which the indices apply</param> /// <param name="index">Index in the collection</param> /// <returns>Array of indices</returns> public static int[] GetArrayIndicesFromCollectionIndex(IEnumerable collection, int index) { Array array = collection as Array; int rank = array == null ? 1 : array.Rank; int[] result = new int[rank]; for (int r = rank; --r > 0; ) { int l = array.GetLength(r); result[r] = index % l; index /= l; } result[0] = index; return result; } /// <summary> /// Clip a string to a given length, starting at a particular offset, returning the clipped /// string with ellipses representing the removed parts /// </summary> /// <param name="s">The string to be clipped</param> /// <param name="maxStringLength">The maximum permitted length of the result string</param> /// <param name="clipStart">The point at which to start clipping</param> /// <returns>The clipped string</returns> public static string ClipString(string s, int maxStringLength, int clipStart) { int clipLength = maxStringLength; StringBuilder sb = new StringBuilder(); if (clipStart > 0) { clipLength -= ELLIPSIS.Length; sb.Append(ELLIPSIS); } if (s.Length - clipStart > clipLength) { clipLength -= ELLIPSIS.Length; sb.Append(s.Substring(clipStart, clipLength)); sb.Append(ELLIPSIS); } else if (clipStart > 0) sb.Append(s.Substring(clipStart)); else sb.Append(s); return sb.ToString(); } /// <summary> /// Clip the expected and actual strings in a coordinated fashion, /// so that they may be displayed together. /// </summary> /// <param name="expected"></param> /// <param name="actual"></param> /// <param name="maxDisplayLength"></param> /// <param name="mismatch"></param> public static void ClipExpectedAndActual(ref string expected, ref string actual, int maxDisplayLength, int mismatch) { // Case 1: Both strings fit on line int maxStringLength = Math.Max(expected.Length, actual.Length); if (maxStringLength <= maxDisplayLength) return; // Case 2: Assume that the tail of each string fits on line int clipLength = maxDisplayLength - ELLIPSIS.Length; int clipStart = maxStringLength - clipLength; // Case 3: If it doesn't, center the mismatch position if (clipStart > mismatch) clipStart = Math.Max(0, mismatch - clipLength / 2); expected = ClipString(expected, maxDisplayLength, clipStart); actual = ClipString(actual, maxDisplayLength, clipStart); } /// <summary> /// Shows the position two strings start to differ. Comparison /// starts at the start index. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The actual string</param> /// <param name="istart">The index in the strings at which comparison should start</param> /// <param name="ignoreCase">Boolean indicating whether case should be ignored</param> /// <returns>-1 if no mismatch found, or the index where mismatch found</returns> static public int FindMismatchPosition(string expected, string actual, int istart, bool ignoreCase) { int length = Math.Min(expected.Length, actual.Length); string s1 = ignoreCase ? expected.ToLower() : expected; string s2 = ignoreCase ? actual.ToLower() : actual; for (int i = istart; i < length; i++) { if (s1[i] != s2[i]) return i; } // // Strings have same content up to the length of the shorter string. // Mismatch occurs because string lengths are different, so show // that they start differing where the shortest string ends // if (expected.Length != actual.Length) return length; // // Same strings : We shouldn't get here // return -1; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Diagnostics; namespace System.DirectoryServices.ActiveDirectory { public class ActiveDirectorySubnet : IDisposable { private ActiveDirectorySite _site = null; private readonly string _name = null; internal readonly DirectoryContext context = null; private bool _disposed = false; internal bool existing = false; internal DirectoryEntry cachedEntry = null; public static ActiveDirectorySubnet FindByName(DirectoryContext context, string subnetName) { ValidateArgument(context, subnetName); // work with copy of the context context = new DirectoryContext(context); // bind to the rootdse to get the configurationnamingcontext DirectoryEntry de; try { de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext); string subnetdn = "CN=Subnets,CN=Sites," + config; de = DirectoryEntryManager.GetDirectoryEntry(context, subnetdn); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet, context.Name)); } try { ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=subnet)(objectCategory=subnet)(name=" + Utils.GetEscapedFilterValue(subnetName) + "))", new string[] { "distinguishedName" }, SearchScope.OneLevel, false, /* don't need paged search */ false /* don't need to cache result */); SearchResult srchResult = adSearcher.FindOne(); if (srchResult == null) { // no such subnet object Exception e = new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySubnet), subnetName); throw e; } else { string siteName = null; DirectoryEntry connectionEntry = srchResult.GetDirectoryEntry(); // try to get the site that this subnet lives in if (connectionEntry.Properties.Contains("siteObject")) { NativeComInterfaces.IAdsPathname pathCracker = (NativeComInterfaces.IAdsPathname)new NativeComInterfaces.Pathname(); // need to turn off the escaping for name pathCracker.EscapedMode = NativeComInterfaces.ADS_ESCAPEDMODE_OFF_EX; string tmp = (string)connectionEntry.Properties["siteObject"][0]; // escaping manipulation pathCracker.Set(tmp, NativeComInterfaces.ADS_SETTYPE_DN); string rdn = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF); Debug.Assert(rdn != null && Utils.Compare(rdn, 0, 3, "CN=", 0, 3) == 0); siteName = rdn.Substring(3); } // it is an existing subnet object ActiveDirectorySubnet subnet = null; if (siteName == null) subnet = new ActiveDirectorySubnet(context, subnetName, null, true); else subnet = new ActiveDirectorySubnet(context, subnetName, siteName, true); subnet.cachedEntry = connectionEntry; return subnet; } } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { // object is not found since we cannot even find the container in which to search throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySubnet), subnetName); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } finally { if (de != null) de.Dispose(); } } public ActiveDirectorySubnet(DirectoryContext context, string subnetName) { ValidateArgument(context, subnetName); // work with copy of the context context = new DirectoryContext(context); this.context = context; _name = subnetName; // bind to the rootdse to get the configurationnamingcontext DirectoryEntry de = null; try { de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext); string subnetn = "CN=Subnets,CN=Sites," + config; // bind to the subnet container de = DirectoryEntryManager.GetDirectoryEntry(context, subnetn); string rdn = "cn=" + _name; rdn = Utils.GetEscapedPath(rdn); cachedEntry = de.Children.Add(rdn, "subnet"); } catch (COMException e) { ExceptionHelper.GetExceptionFromCOMException(context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet, context.Name)); } finally { if (de != null) de.Dispose(); } } public ActiveDirectorySubnet(DirectoryContext context, string subnetName, string siteName) : this(context, subnetName) { if (siteName == null) throw new ArgumentNullException(nameof(siteName)); if (siteName.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); // validate that siteName is valid try { _site = ActiveDirectorySite.FindByName(this.context, siteName); } catch (ActiveDirectoryObjectNotFoundException) { throw new ArgumentException(SR.Format(SR.SiteNotExist, siteName), nameof(siteName)); } } internal ActiveDirectorySubnet(DirectoryContext context, string subnetName, string siteName, bool existing) { Debug.Assert(existing == true); this.context = context; _name = subnetName; if (siteName != null) { try { _site = ActiveDirectorySite.FindByName(context, siteName); } catch (ActiveDirectoryObjectNotFoundException) { throw new ArgumentException(SR.Format(SR.SiteNotExist, siteName), nameof(siteName)); } } this.existing = true; } public string Name { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); return _name; } } public ActiveDirectorySite Site { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); return _site; } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (value != null) { // check whether the site exists or not, you can not create a new site and set it to a subnet object with commit change to site object first if (!value.existing) throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted, value)); } _site = value; } } public string Location { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); try { if (cachedEntry.Properties.Contains("location")) return (string)cachedEntry.Properties["location"][0]; else return null; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); // if the value is null, it means that user wants to clear the value try { if (value == null) { if (cachedEntry.Properties.Contains("location")) cachedEntry.Properties["location"].Clear(); } else { cachedEntry.Properties["location"].Value = value; } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } public void Save() { if (_disposed) throw new ObjectDisposedException(GetType().Name); try { if (existing) { // check whether site has been changed or not if (_site == null) { // user wants to remove this subnet object from previous site if (cachedEntry.Properties.Contains("siteObject")) cachedEntry.Properties["siteObject"].Clear(); } else { // user configures this subnet object to a particular site cachedEntry.Properties["siteObject"].Value = _site.cachedEntry.Properties["distinguishedName"][0]; } cachedEntry.CommitChanges(); } else { if (Site != null) cachedEntry.Properties["siteObject"].Add(_site.cachedEntry.Properties["distinguishedName"][0]); cachedEntry.CommitChanges(); // the subnet has been created in the backend store existing = true; } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } public void Delete() { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (!existing) { throw new InvalidOperationException(SR.CannotDelete); } else { try { cachedEntry.Parent.Children.Remove(cachedEntry); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } public override string ToString() { if (_disposed) throw new ObjectDisposedException(GetType().Name); return Name; } public DirectoryEntry GetDirectoryEntry() { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (!existing) { throw new InvalidOperationException(SR.CannotGetObject); } else { return DirectoryEntryManager.GetDirectoryEntryInternal(context, cachedEntry.Path); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // free other state (managed objects) if (cachedEntry != null) cachedEntry.Dispose(); } // free your own state (unmanaged objects) _disposed = true; } private static void ValidateArgument(DirectoryContext context, string subnetName) { // basic validation first if (context == null) throw new ArgumentNullException(nameof(context)); // if target is not specified, then we determin the target from the logon credential, so if it is a local user context, it should fail if ((context.Name == null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); } // more validation for the context, if the target is not null, then it should be either forest name or server name if (context.Name != null) { // we only allow target to be forest, server name or ADAM config set if (!(context.isRootDomain() || context.isServer() || context.isADAMConfigSet())) throw new ArgumentException(SR.NotADOrADAM, nameof(context)); } if (subnetName == null) throw new ArgumentNullException(nameof(subnetName)); if (subnetName.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, nameof(subnetName)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.IO; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using System.Text; using System.Management.Automation.Host; using System.Collections.Concurrent; using System.Management.Automation.Internal; namespace System.Management.Automation.Runspaces { internal class PSSnapInTypeAndFormatErrors { public string psSnapinName; // only one of fullPath or formatTable or typeData or typeDefinition should be specified.. // typeData and isRemove should be used together internal PSSnapInTypeAndFormatErrors(string psSnapinName, string fullPath) { this.psSnapinName = psSnapinName; FullPath = fullPath; Errors = new ConcurrentBag<string>(); } internal PSSnapInTypeAndFormatErrors(string psSnapinName, FormatTable formatTable) { this.psSnapinName = psSnapinName; FormatTable = formatTable; Errors = new ConcurrentBag<string>(); } internal PSSnapInTypeAndFormatErrors(string psSnapinName, TypeData typeData, bool isRemove) { this.psSnapinName = psSnapinName; TypeData = typeData; IsRemove = isRemove; Errors = new ConcurrentBag<string>(); } internal PSSnapInTypeAndFormatErrors(string psSnapinName, ExtendedTypeDefinition typeDefinition) { this.psSnapinName = psSnapinName; FormatData = typeDefinition; Errors = new ConcurrentBag<string>(); } internal ExtendedTypeDefinition FormatData { get; } internal TypeData TypeData { get; } internal bool IsRemove { get; } internal string FullPath { get; } internal FormatTable FormatTable { get; } internal ConcurrentBag<string> Errors { get; set; } internal string PSSnapinName { get { return psSnapinName; } } internal bool FailToLoadFile; } internal static class FormatAndTypeDataHelper { private const string FileNotFound = "FileNotFound"; private const string CannotFindRegistryKey = "CannotFindRegistryKey"; private const string CannotFindRegistryKeyPath = "CannotFindRegistryKeyPath"; private const string EntryShouldBeMshXml = "EntryShouldBeMshXml"; private const string DuplicateFile = "DuplicateFile"; internal const string ValidationException = "ValidationException"; private static string GetBaseFolder(Collection<string> independentErrors) { return Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName); } private static string GetAndCheckFullFileName( string psSnapinName, HashSet<string> fullFileNameSet, string baseFolder, string baseFileName, Collection<string> independentErrors, ref bool needToRemoveEntry, bool checkFileExists) { string retValue = Path.IsPathRooted(baseFileName) ? baseFileName : Path.Combine(baseFolder, baseFileName); if (checkFileExists && !File.Exists(retValue)) { string error = StringUtil.Format(TypesXmlStrings.FileNotFound, psSnapinName, retValue); independentErrors.Add(error); return null; } if (fullFileNameSet.Contains(retValue)) { // Do not add Errors as we want loading of type/format files to be idempotent. // Just mark as Duplicate so the duplicate entry gets removed needToRemoveEntry = true; return null; } if (!retValue.EndsWith(".ps1xml", StringComparison.OrdinalIgnoreCase)) { string error = StringUtil.Format(TypesXmlStrings.EntryShouldBeMshXml, psSnapinName, retValue); independentErrors.Add(error); return null; } fullFileNameSet.Add(retValue); return retValue; } internal static void ThrowExceptionOnError( string errorId, Collection<string> independentErrors, Collection<PSSnapInTypeAndFormatErrors> PSSnapinFilesCollection, Category category) { Collection<string> errors = new Collection<string>(); if (independentErrors != null) { foreach (string error in independentErrors) { errors.Add(error); } } foreach (PSSnapInTypeAndFormatErrors PSSnapinFiles in PSSnapinFilesCollection) { foreach (string error in PSSnapinFiles.Errors) { errors.Add(error); } } if (errors.Count == 0) { return; } StringBuilder allErrors = new StringBuilder(); allErrors.Append('\n'); foreach (string error in errors) { allErrors.Append(error); allErrors.Append('\n'); } string message = string.Empty; if (category == Category.Types) { message = StringUtil.Format(ExtendedTypeSystem.TypesXmlError, allErrors.ToString()); } else if (category == Category.Formats) { message = StringUtil.Format(FormatAndOutXmlLoadingStrings.FormatLoadingErrors, allErrors.ToString()); } RuntimeException ex = new RuntimeException(message); ex.SetErrorId(errorId); throw ex; } internal static void ThrowExceptionOnError( string errorId, ConcurrentBag<string> errors, Category category) { if (errors.Count == 0) { return; } StringBuilder allErrors = new StringBuilder(); allErrors.Append('\n'); foreach (string error in errors) { allErrors.Append(error); allErrors.Append('\n'); } string message = string.Empty; if (category == Category.Types) { message = StringUtil.Format(ExtendedTypeSystem.TypesXmlError, allErrors.ToString()); } else if (category == Category.Formats) { message = StringUtil.Format(FormatAndOutXmlLoadingStrings.FormatLoadingErrors, allErrors.ToString()); } RuntimeException ex = new RuntimeException(message); ex.SetErrorId(errorId); throw ex; } internal enum Category { Types, Formats, } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial class SolutionCrawlerRegistrationService { private partial class WorkCoordinator { private abstract class AsyncWorkItemQueue<TKey> : IDisposable where TKey : class { private readonly object _gate; private readonly SemaphoreSlim _semaphore; private readonly Workspace _workspace; private readonly SolutionCrawlerProgressReporter _progressReporter; // map containing cancellation source for the item given out. private readonly Dictionary<object, CancellationTokenSource> _cancellationMap; public AsyncWorkItemQueue(SolutionCrawlerProgressReporter progressReporter, Workspace workspace) { _gate = new object(); _semaphore = new SemaphoreSlim(initialCount: 0); _cancellationMap = new Dictionary<object, CancellationTokenSource>(); _workspace = workspace; _progressReporter = progressReporter; } protected abstract int WorkItemCount_NoLock { get; } protected abstract void Dispose_NoLock(); protected abstract bool AddOrReplace_NoLock(WorkItem item); protected abstract bool TryTake_NoLock(TKey key, out WorkItem workInfo); protected abstract bool TryTakeAnyWork_NoLock(ProjectId preferableProjectId, ProjectDependencyGraph dependencyGraph, IDiagnosticAnalyzerService service, out WorkItem workItem); public bool HasAnyWork { get { lock (_gate) { return HasAnyWork_NoLock; } } } public void RemoveCancellationSource(object key) { lock (_gate) { // just remove cancellation token from the map. // the cancellation token might be passed out to other service // so don't call cancel on the source only because we are done using it. _cancellationMap.Remove(key); } } public virtual Task WaitAsync(CancellationToken cancellationToken) { return _semaphore.WaitAsync(cancellationToken); } public bool AddOrReplace(WorkItem item) { if (!HasAnyWork) { // first work is added. _progressReporter.Start(); } lock (_gate) { if (AddOrReplace_NoLock(item)) { // increase count _semaphore.Release(); return true; } return false; } } public void RequestCancellationOnRunningTasks() { List<CancellationTokenSource> cancellations; lock (_gate) { // request to cancel all running works cancellations = CancelAll_NoLock(); } RaiseCancellation_NoLock(cancellations); } public void Dispose() { List<CancellationTokenSource> cancellations; lock (_gate) { // here we don't need to care about progress reporter since // it will be only called when host is shutting down. // we do the below since we want to kill any pending tasks Dispose_NoLock(); cancellations = CancelAll_NoLock(); } RaiseCancellation_NoLock(cancellations); } private bool HasAnyWork_NoLock => WorkItemCount_NoLock > 0; protected Workspace Workspace => _workspace; private static void RaiseCancellation_NoLock(List<CancellationTokenSource> cancellations) { if (cancellations == null) { return; } // cancel can cause outer code to be run inlined, run it outside of the lock. cancellations.Do(s => s.Cancel()); } private List<CancellationTokenSource> CancelAll_NoLock() { // nothing to do if (_cancellationMap.Count == 0) { return null; } // make a copy var cancellations = _cancellationMap.Values.ToList(); // clear cancellation map _cancellationMap.Clear(); return cancellations; } protected void Cancel_NoLock(object key) { CancellationTokenSource source; if (_cancellationMap.TryGetValue(key, out source)) { source.Cancel(); _cancellationMap.Remove(key); } } public bool TryTake(TKey key, out WorkItem workInfo, out CancellationTokenSource source) { lock (_gate) { if (TryTake_NoLock(key, out workInfo)) { if (!HasAnyWork_NoLock) { // last work is done. _progressReporter.Stop(); } source = GetNewCancellationSource_NoLock(key); workInfo.AsyncToken.Dispose(); return true; } else { source = null; return false; } } } public bool TryTakeAnyWork( ProjectId preferableProjectId, ProjectDependencyGraph dependencyGraph, IDiagnosticAnalyzerService analyzerService, out WorkItem workItem, out CancellationTokenSource source) { lock (_gate) { // there must be at least one item in the map when this is called unless host is shutting down. if (TryTakeAnyWork_NoLock(preferableProjectId, dependencyGraph, analyzerService, out workItem)) { if (!HasAnyWork_NoLock) { // last work is done. _progressReporter.Stop(); } source = GetNewCancellationSource_NoLock(workItem.Key); workItem.AsyncToken.Dispose(); return true; } else { source = null; return false; } } } protected CancellationTokenSource GetNewCancellationSource_NoLock(object key) { Contract.Requires(!_cancellationMap.ContainsKey(key)); var source = new CancellationTokenSource(); _cancellationMap.Add(key, source); return source; } protected ProjectId GetBestProjectId_NoLock<T>( Dictionary<ProjectId, T> workQueue, ProjectId projectId, ProjectDependencyGraph dependencyGraph, IDiagnosticAnalyzerService analyzerService) { if (projectId != null) { if (workQueue.ContainsKey(projectId)) { return projectId; } // prefer project that directly depends on the given project and has diagnostics as next project to // process foreach (var dependingProjectId in dependencyGraph.GetProjectsThatDirectlyDependOnThisProject(projectId)) { if (workQueue.ContainsKey(dependingProjectId) && analyzerService?.ContainsDiagnostics(Workspace, dependingProjectId) == true) { return dependingProjectId; } } } // prefer a project that has diagnostics as next project to process. foreach (var pendingProjectId in workQueue.Keys) { if (analyzerService?.ContainsDiagnostics(Workspace, pendingProjectId) == true) { return pendingProjectId; } } // explicitly iterate so that we can use struct enumerator foreach (var pair in workQueue) { return pair.Key; } return Contract.FailWithReturn<ProjectId>("Shouldn't reach here"); } } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionSetSources { public class NamedParameterCompletionProviderTests : AbstractCSharpCompletionProviderTests { public NamedParameterCompletionProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture) { } internal override CompletionProvider CreateCompletionProvider() { return new NamedParameterCompletionProvider(); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SendEnterThroughToEditorTest() { const string markup = @" class Foo { public Foo(int a = 42) { } void Bar() { var b = new Foo($$ } }"; await VerifySendEnterThroughToEnterAsync(markup, "a:", sendThroughEnterOption: EnterKeyRule.Never, expected: false); await VerifySendEnterThroughToEnterAsync(markup, "a:", sendThroughEnterOption: EnterKeyRule.AfterFullyTypedWord, expected: true); await VerifySendEnterThroughToEnterAsync(markup, "a:", sendThroughEnterOption: EnterKeyRule.Always, expected: true); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitCharacterTest() { const string markup = @" class Foo { public Foo(int a = 42) { } void Bar() { var b = new Foo($$ } }"; await VerifyCommonCommitCharactersAsync(markup, textTypedSoFar: ""); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InObjectCreation() { var markup = @" class Foo { public Foo(int a = 42) { } void Bar() { var b = new Foo($$ } }"; await VerifyItemExistsAsync(markup, "a:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InBaseConstructor() { var markup = @" class Foo { public Foo(int a = 42) { } } class DogBed : Foo { public DogBed(int b) : base($$ } "; await VerifyItemExistsAsync(markup, "a:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InvocationExpression() { var markup = @" class Foo { void Bar(int a) { Bar($$ } } "; await VerifyItemExistsAsync(markup, "a:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InvocationExpressionAfterComma() { var markup = @" class Foo { void Bar(int a, string b) { Bar(b:"""", $$ } } "; await VerifyItemExistsAsync(markup, "a:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ElementAccessExpression() { var markup = @" class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } } class Program { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[$$ } } "; await VerifyItemExistsAsync(markup, "i:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PartialMethods() { var markup = @" partial class PartialClass { static partial void Foo(int declaring); static partial void Foo(int implementing) { } static void Caller() { Foo($$ } } "; await VerifyItemExistsAsync(markup, "declaring:"); await VerifyItemIsAbsentAsync(markup, "implementing:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterColon() { var markup = @" class Foo { void Bar(int a, string b) { Bar(a:$$ } } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(544292, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544292")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInCollectionInitializers() { var markup = @" using System.Collections.Generic; class Foo { void Bar(List<int> integers) { Bar(integers: new List<int> { 10, 11,$$ 12 }); } } "; await VerifyNoItemsExistAsync(markup); } [WorkItem(544191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544191")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FilteringOverloadsByCallSite() { var markup = @" class Class1 { void Test() { Foo(boolean:true, $$) } void Foo(string str = ""hello"", char character = 'a') { } void Foo(string str = ""hello"", bool boolean = false) { } } "; await VerifyItemExistsAsync(markup, "str:"); await VerifyItemIsAbsentAsync(markup, "character:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DontFilterYet() { var markup = @" class Class1 { void Test() { Foo(str:"""", $$) } void Foo(string str = ""hello"", char character = 'a') { } void Foo(string str = ""hello"", bool boolean = false) { } } "; await VerifyItemExistsAsync(markup, "boolean:"); await VerifyItemExistsAsync(markup, "character:"); } [WorkItem(544191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544191")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FilteringOverloadsByCallSiteComplex() { var markup = @" class Foo { void Test() { Bar m = new Bar(); Method(obj:m, $$ } void Method(Bar obj, int num = 23, string str = """") { } void Method(double dbl = double.MinValue, string str = """") { } void Method(int num = 1, bool b = false, string str = """") { } void Method(Bar obj, bool b = false, string str = """") { } } class Bar { } "; await VerifyItemExistsAsync(markup, "str:"); await VerifyItemExistsAsync(markup, "num:"); await VerifyItemExistsAsync(markup, "b:"); await VerifyItemIsAbsentAsync(markup, "dbl:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MethodOverloads() { var markup = @" class Foo { void Test() { object m = null; Method(m, $$ } void Method(object obj, int num = 23, string str = """") { } void Method(int num = 1, bool b = false, string str = """") { } void Method(object obj, bool b = false, string str = """") { } } "; await VerifyItemExistsAsync(markup, "str:"); await VerifyItemExistsAsync(markup, "num:"); await VerifyItemExistsAsync(markup, "b:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ExistingNamedParamsAreFilteredOut() { var markup = @" class Foo { void Test() { object m = null; Method(obj: m, str: """", $$); } void Method(object obj, int num = 23, string str = """") { } void Method(double dbl = double.MinValue, string str = """") { } void Method(int num = 1, bool b = false, string str = """") { } void Method(object obj, bool b = false, string str = """") { } } "; await VerifyItemExistsAsync(markup, "num:"); await VerifyItemExistsAsync(markup, "b:"); await VerifyItemIsAbsentAsync(markup, "obj:"); await VerifyItemIsAbsentAsync(markup, "str:"); } [WorkItem(529369, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529369")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VerbatimIdentifierNotAKeyword() { var markup = @" class Program { void Foo(int @integer) { Foo(@i$$ } } "; await VerifyItemExistsAsync(markup, "integer:"); } [WorkItem(544209, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544209")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DescriptionStringInMethodOverloads() { var markup = @" class Class1 { void Test() { Foo(boolean: true, $$) } void Foo(string obj = ""hello"") { } void Foo(bool boolean = false, Class1 obj = default(Class1)) { } } "; await VerifyItemExistsAsync(markup, "obj:", expectedDescriptionOrNull: $"({FeaturesResources.parameter}) Class1 obj = default(Class1)"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InDelegates() { var markup = @" public delegate void Del(string message); class Program { public static void DelegateMethod(string message) { System.Console.WriteLine(message); } static void Main(string[] args) { Del handler = DelegateMethod; handler($$ } }"; await VerifyItemExistsAsync(markup, "message:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InDelegateInvokeSyntax() { var markup = @" public delegate void Del(string message); class Program { public static void DelegateMethod(string message) { System.Console.WriteLine(message); } static void Main(string[] args) { Del handler = DelegateMethod; handler.Invoke($$ } }"; await VerifyItemExistsAsync(markup, "message:"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInComment() { var markup = @" public class Test { static void Main() { M(x: 0, //Hit ctrl-space at the end of this comment $$ y: 1); } static void M(int x, int y) { } } "; await VerifyNoItemsExistAsync(markup); } } }
// 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 Internal.Runtime.Augments; using System.Diagnostics; using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Runtime { public static class TypeLoaderExports { [RuntimeExport("GetThreadStaticsForDynamicType")] public static IntPtr GetThreadStaticsForDynamicType(int index) { IntPtr result = RuntimeImports.RhGetThreadLocalStorageForDynamicType(index, 0, 0); if (result != IntPtr.Zero) return result; int numTlsCells; int tlsStorageSize = RuntimeAugments.TypeLoaderCallbacks.GetThreadStaticsSizeForDynamicType(index, out numTlsCells); result = RuntimeImports.RhGetThreadLocalStorageForDynamicType(index, tlsStorageSize, numTlsCells); if (result == IntPtr.Zero) throw new OutOfMemoryException(); return result; } [RuntimeExport("ActivatorCreateInstanceAny")] public static unsafe void ActivatorCreateInstanceAny(ref object ptrToData, IntPtr pEETypePtr) { EETypePtr pEEType = new EETypePtr(pEETypePtr); if (pEEType.IsValueType) { // Nothing else to do for value types. return; } // For reference types, we need to: // 1- Allocate the new object // 2- Call its default ctor // 3- Update ptrToData to point to that newly allocated object ptrToData = RuntimeImports.RhNewObject(pEEType); Entry entry = LookupInCache(s_cache, pEETypePtr, pEETypePtr); if (entry == null) { entry = CacheMiss(pEETypePtr, pEETypePtr, SignatureKind.DefaultConstructor); } RawCalliHelper.Call(entry.Result, ptrToData); } // // Generic lookup cache // private class Entry { public IntPtr Context; public IntPtr Signature; public IntPtr Result; public IntPtr AuxResult; public Entry Next; } // Initialize the cache eagerly to avoid null checks. // Use array with just single element to make this pay-for-play. The actual cache will be allocated only // once the lazy lookups are actually needed. private static Entry[] s_cache; private static Lock s_lock; private static GCHandle s_previousCache; private volatile static IntPtr[] s_resolutionFunctionPointers; private static int s_nextResolutionFunctionPointerIndex; internal static void Initialize() { s_cache = new Entry[1]; s_resolutionFunctionPointers = new IntPtr[4]; s_nextResolutionFunctionPointerIndex = (int)SignatureKind.Count; } [RuntimeExport("GenericLookup")] public static IntPtr GenericLookup(IntPtr context, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); if (entry == null) { entry = CacheMiss(context, signature); } return entry.Result; } [RuntimeExport("GenericLookupAndCallCtor")] public static void GenericLookupAndCallCtor(Object arg, IntPtr context, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); if (entry == null) { entry = CacheMiss(context, signature); } RawCalliHelper.Call(entry.Result, arg); } [RuntimeExport("GenericLookupAndAllocObject")] public static Object GenericLookupAndAllocObject(IntPtr context, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); if (entry == null) { entry = CacheMiss(context, signature); } return RawCalliHelper.Call<Object>(entry.Result, entry.AuxResult); } [RuntimeExport("GenericLookupAndAllocArray")] public static Object GenericLookupAndAllocArray(IntPtr context, IntPtr arg, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); if (entry == null) { entry = CacheMiss(context, signature); } return RawCalliHelper.Call<Object>(entry.Result, entry.AuxResult, arg); } [RuntimeExport("GenericLookupAndCheckArrayElemType")] public static void GenericLookupAndCheckArrayElemType(IntPtr context, object arg, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); if (entry == null) { entry = CacheMiss(context, signature); } RawCalliHelper.Call(entry.Result, entry.AuxResult, arg); } [RuntimeExport("GenericLookupAndCast")] public static Object GenericLookupAndCast(Object arg, IntPtr context, IntPtr signature) { Entry entry = LookupInCache(s_cache, context, signature); if (entry == null) { entry = CacheMiss(context, signature); } return RawCalliHelper.Call<Object>(entry.Result, arg, entry.AuxResult); } public static unsafe IntPtr GetDelegateThunk(object delegateObj, int whichThunk) { Entry entry = LookupInCache(s_cache, delegateObj.m_pEEType, new IntPtr(whichThunk)); if (entry == null) { entry = CacheMiss(delegateObj.m_pEEType, new IntPtr(whichThunk), SignatureKind.GenericDelegateThunk, delegateObj); } return entry.Result; } public static unsafe IntPtr GVMLookupForSlot(object obj, RuntimeMethodHandle slot) { Entry entry = LookupInCache(s_cache, obj.m_pEEType, *(IntPtr*)&slot); if (entry == null) { entry = CacheMiss(obj.m_pEEType, *(IntPtr*)&slot, SignatureKind.GenericVirtualMethod); } return entry.Result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static IntPtr OpenInstanceMethodLookup(IntPtr openResolver, object obj) { Entry entry = LookupInCache(s_cache, obj.m_pEEType, openResolver); if (entry == null) { entry = CacheMiss(obj.m_pEEType, openResolver, SignatureKind.OpenInstanceResolver, obj); } return entry.Result; } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] private static Entry LookupInCache(Entry[] cache, IntPtr context, IntPtr signature) { int key = ((context.GetHashCode() >> 4) ^ signature.GetHashCode()) & (cache.Length - 1); Entry entry = cache[key]; while (entry != null) { if (entry.Context == context && entry.Signature == signature) break; entry = entry.Next; } return entry; } private enum SignatureKind { GenericDictionary, GenericVirtualMethod, OpenInstanceResolver, DefaultConstructor, GenericDelegateThunk, Count } internal static int RegisterResolutionFunction(IntPtr resolutionFunction) { if (s_lock == null) Interlocked.CompareExchange(ref s_lock, new Lock(), null); s_lock.Acquire(); try { int newResolutionFunctionId = s_nextResolutionFunctionPointerIndex; IntPtr[] resolutionFunctionPointers = null; if (newResolutionFunctionId < s_resolutionFunctionPointers.Length) { resolutionFunctionPointers = s_resolutionFunctionPointers; } else { resolutionFunctionPointers = new IntPtr[s_resolutionFunctionPointers.Length * 2]; Array.Copy(s_resolutionFunctionPointers, resolutionFunctionPointers, s_resolutionFunctionPointers.Length); s_resolutionFunctionPointers = resolutionFunctionPointers; } Volatile.Write(ref s_resolutionFunctionPointers[newResolutionFunctionId], resolutionFunction); s_nextResolutionFunctionPointerIndex++; return newResolutionFunctionId; } finally { s_lock.Release(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static IntPtr RuntimeCacheLookupInCache(IntPtr context, IntPtr signature, int registeredResolutionFunction, object contextObject, out IntPtr auxResult) { Entry entry = LookupInCache(s_cache, context, signature); if (entry == null) { entry = CacheMiss(context, signature, (SignatureKind)registeredResolutionFunction, contextObject); } auxResult = entry.AuxResult; return entry.Result; } private static unsafe Entry CacheMiss(IntPtr context, IntPtr signature, SignatureKind signatureKind = SignatureKind.GenericDictionary, object contextObject = null) { IntPtr result = IntPtr.Zero, auxResult = IntPtr.Zero; bool previouslyCached = false; // // Try to find the entry in the previous version of the cache that is kept alive by weak reference // if (s_previousCache.IsAllocated) { Entry[] previousCache = (Entry[])s_previousCache.Target; if (previousCache != null) { Entry previousEntry = LookupInCache(previousCache, context, signature); if (previousEntry != null) { result = previousEntry.Result; auxResult = previousEntry.AuxResult; previouslyCached = true; } } } // // Call into the type loader to compute the target // if (!previouslyCached) { switch (signatureKind) { case SignatureKind.GenericDictionary: result = RuntimeAugments.TypeLoaderCallbacks.GenericLookupFromContextAndSignature(context, signature, out auxResult); break; case SignatureKind.GenericVirtualMethod: result = Internal.Runtime.CompilerServices.GenericVirtualMethodSupport.GVMLookupForSlot(new RuntimeTypeHandle(new EETypePtr(context)), *(RuntimeMethodHandle*)&signature); break; case SignatureKind.OpenInstanceResolver: result = Internal.Runtime.CompilerServices.OpenMethodResolver.ResolveMethodWorker(signature, contextObject); break; case SignatureKind.DefaultConstructor: { result = RuntimeAugments.TypeLoaderCallbacks.TryGetDefaultConstructorForType(new RuntimeTypeHandle(new EETypePtr(context))); if (result == IntPtr.Zero) result = RuntimeAugments.GetFallbackDefaultConstructor(); } break; case SignatureKind.GenericDelegateThunk: result = RuntimeAugments.TypeLoaderCallbacks.GetDelegateThunk((Delegate)contextObject, (int)signature); break; default: result = RawCalliHelper.Call<IntPtr>(s_resolutionFunctionPointers[(int)signatureKind], context, signature, contextObject, out auxResult); break; } } // // Update the cache under the lock // if (s_lock == null) Interlocked.CompareExchange(ref s_lock, new Lock(), null); s_lock.Acquire(); try { // Avoid duplicate entries Entry existingEntry = LookupInCache(s_cache, context, signature); if (existingEntry != null) return existingEntry; // Resize cache as necessary Entry[] cache = ResizeCacheForNewEntryAsNecessary(); int key = ((context.GetHashCode() >> 4) ^ signature.GetHashCode()) & (cache.Length - 1); Entry newEntry = new Entry() { Context = context, Signature = signature, Result = result, AuxResult = auxResult, Next = cache[key] }; cache[key] = newEntry; return newEntry; } finally { s_lock.Release(); } } // // Parameters and state used by generic lookup cache resizing algorithm // private const int InitialCacheSize = 128; // MUST BE A POWER OF TWO private const int DefaultCacheSize = 1024; private const int MaximumCacheSize = 128 * 1024; private static long s_tickCountOfLastOverflow; private static int s_entries; private static bool s_roundRobinFlushing; private static Entry[] ResizeCacheForNewEntryAsNecessary() { Entry[] cache = s_cache; if (cache.Length < InitialCacheSize) { // Start with small cache size so that the cache entries used by startup one-time only initialization will get flushed soon return s_cache = new Entry[InitialCacheSize]; } int entries = s_entries++; // If the cache has spare space, we are done if (2 * entries < cache.Length) { if (s_roundRobinFlushing) { cache[2 * entries] = null; cache[2 * entries + 1] = null; } return cache; } // // Now, we have cache that is overflowing with the stuff. We need to decide whether to resize it or start flushing the old entries instead // // Start over counting the entries s_entries = 0; // See how long it has been since the last time the cache was overflowing long tickCount = Environment.TickCount64; long tickCountSinceLastOverflow = tickCount - s_tickCountOfLastOverflow; s_tickCountOfLastOverflow = tickCount; bool shrinkCache = false; bool growCache = false; if (cache.Length < DefaultCacheSize) { // If the cache have not reached the default size, just grow it without thinking about it much growCache = true; } else { if (tickCountSinceLastOverflow < cache.Length / 128) { // If the fill rate of the cache is faster than ~0.01ms per entry, grow it if (cache.Length < MaximumCacheSize) growCache = true; } else if (tickCountSinceLastOverflow > cache.Length * 16) { // If the fill rate of the cache is slower than 16ms per entry, shrink it if (cache.Length > DefaultCacheSize) shrinkCache = true; } // Otherwise, keep the current size and just keep flushing the entries round robin } if (growCache || shrinkCache) { s_roundRobinFlushing = false; // Keep the reference to the old cache in a weak handle. We will try to use to avoid // hitting the type loader until GC collects it. if (s_previousCache.IsAllocated) { s_previousCache.Target = cache; } else { s_previousCache = GCHandle.Alloc(cache, GCHandleType.Weak); } return s_cache = new Entry[shrinkCache ? (cache.Length / 2) : (cache.Length * 2)]; } else { s_roundRobinFlushing = true; return cache; } } } [System.Runtime.InteropServices.McgIntrinsicsAttribute] internal class RawCalliHelper { [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static T Call<T>(System.IntPtr pfn, IntPtr arg) { return default(T); } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static void Call(System.IntPtr pfn, Object arg) { } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static T Call<T>(System.IntPtr pfn, IntPtr arg1, IntPtr arg2) { return default(T); } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static T Call<T>(System.IntPtr pfn, IntPtr arg1, IntPtr arg2, object arg3, out IntPtr arg4) { arg4 = IntPtr.Zero; return default(T); } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static void Call(System.IntPtr pfn, IntPtr arg1, Object arg2) { } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static T Call<T>(System.IntPtr pfn, Object arg1, IntPtr arg2) { return default(T); } [MethodImplAttribute(MethodImplOptions.AggressiveInlining)] public static T Call<T>(IntPtr pfn, string[] arg0) { return default(T); } } }
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using ZXing.Common; using ZXing.QrCode.Internal; namespace ZXing.QrCode { /// <summary> /// This implementation can detect and decode QR Codes in an image. /// /// <author>Sean Owen</author> /// </summary> public class QRCodeReader : Reader { private static readonly ResultPoint[] NO_POINTS = new ResultPoint[0]; private readonly Decoder decoder = new Decoder(); /// <summary> /// Gets the decoder. /// </summary> /// <returns></returns> protected Decoder getDecoder() { return decoder; } /// <summary> /// Locates and decodes a QR code in an image. /// /// <returns>a String representing the content encoded by the QR code</returns> /// </summary> public Result decode(BinaryBitmap image) { return decode(image, null); } /// <summary> /// Locates and decodes a barcode in some format within an image. This method also accepts /// hints, each possibly associated to some data, which may help the implementation decode. /// </summary> /// <param name="image">image of barcode to decode</param> /// <param name="hints">passed as a <see cref="IDictionary{TKey, TValue}"/> from <see cref="DecodeHintType"/> /// to arbitrary data. The /// meaning of the data depends upon the hint type. The implementation may or may not do /// anything with these hints.</param> /// <returns> /// String which the barcode encodes /// </returns> public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints) { DecoderResult decoderResult; ResultPoint[] points; if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE)) { BitMatrix bits = extractPureBits(image.BlackMatrix); if (bits == null) return null; decoderResult = decoder.decode(bits, hints); points = NO_POINTS; } else { DetectorResult detectorResult = new Detector(image.BlackMatrix).detect(hints); if (detectorResult == null) return null; decoderResult = decoder.decode(detectorResult.Bits, hints); points = detectorResult.Points; } if (decoderResult == null) return null; Result result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.QR_CODE); IList<byte[]> byteSegments = decoderResult.ByteSegments; if (byteSegments != null) { result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments); } var ecLevel = decoderResult.ECLevel; if (ecLevel != null) { result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel); } return result; } /// <summary> /// Resets any internal state the implementation has after a decode, to prepare it /// for reuse. /// </summary> public void reset() { // do nothing } /// <summary> /// This method detects a code in a "pure" image -- that is, pure monochrome image /// which contains only an unrotated, unskewed, image of a code, with some white border /// around it. This is a specialized method that works exceptionally fast in this special /// case. /// /// <seealso cref="ZXing.PDF417.PDF417Reader.extractPureBits(BitMatrix)" /> /// <seealso cref="ZXing.Datamatrix.DataMatrixReader.extractPureBits(BitMatrix)" /> /// </summary> private static BitMatrix extractPureBits(BitMatrix image) { int[] leftTopBlack = image.getTopLeftOnBit(); int[] rightBottomBlack = image.getBottomRightOnBit(); if (leftTopBlack == null || rightBottomBlack == null) { return null; } float moduleSize; if (!QRCodeReader.moduleSize(leftTopBlack, image, out moduleSize)) return null; int top = leftTopBlack[1]; int bottom = rightBottomBlack[1]; int left = leftTopBlack[0]; int right = rightBottomBlack[0]; if (bottom - top != right - left) { // Special case, where bottom-right module wasn't black so we found something else in the last row // Assume it's a square, so use height as the width right = left + (bottom - top); } int matrixWidth = (int)Math.Round((right - left + 1) / moduleSize); int matrixHeight = (int)Math.Round((bottom - top + 1) / moduleSize); if (matrixWidth <= 0 || matrixHeight <= 0) { return null; } if (matrixHeight != matrixWidth) { // Only possibly decode square regions return null; } // Push in the "border" by half the module width so that we start // sampling in the middle of the module. Just in case the image is a // little off, this will help recover. int nudge = (int)(moduleSize / 2.0f); top += nudge; left += nudge; // Now just read off the bits BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight); for (int y = 0; y < matrixHeight; y++) { int iOffset = top + (int)(y * moduleSize); for (int x = 0; x < matrixWidth; x++) { if (image[left + (int)(x * moduleSize), iOffset]) { bits[x, y] = true; } } } return bits; } private static bool moduleSize(int[] leftTopBlack, BitMatrix image, out float msize) { int height = image.Height; int width = image.Width; int x = leftTopBlack[0]; int y = leftTopBlack[1]; bool inBlack = true; int transitions = 0; while (x < width && y < height) { if (inBlack != image[x, y]) { if (++transitions == 5) { break; } inBlack = !inBlack; } x++; y++; } if (x == width || y == height) { msize = 0.0f; return false; } msize = (x - leftTopBlack[0]) / 7.0f; return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Memoria.Assets; using Memoria.Prime; using Memoria.Prime.Exceptions; using Memoria.Prime.Text; using UnityEngine; namespace Memoria.Assets { public sealed class DialogBoxConstructor { public static void PhrasePreOpcodeSymbol(String text, Dialog dlg) { DialogBoxConstructor constructor = new DialogBoxConstructor(dlg, text); constructor.Construct(); } private readonly Dialog _dlg; private readonly StringBuilder _sb; private readonly Boolean _isJapanese; private readonly FF9StateGlobal _gameState; private readonly ETb _textEngine; private String _text; private Char[] _chars; private Int32 _choiseIndex; private DialogBoxConstructor(Dialog dlg, String text) { _dlg = dlg; _text = text; _chars = text.ToCharArray(); _sb = new StringBuilder(_chars.Length); _sb.Append(NGUIText.FF9WhiteColor); // Clear color _isJapanese = FF9StateSystem.Settings.CurrentLanguage == "Japanese"; _gameState = FF9StateSystem.Common.FF9; _textEngine = PersistenSingleton<EventEngine>.Instance?.eTb; _dlg.SignalNumber = ETb.gMesSignal; } private void Construct() { for (Int32 index = 0; index < _chars.Length; index++) { Int32 length = _chars.Length; Int32 left = length - index; Char ch = _chars[index]; if (ch == '[') { ParseOriginalTag(ref index, length); } else if (ch == '{') { FFIXTextTag tag = FFIXTextTag.TryRead(_chars, ref index, ref left); if (tag == null) { _sb.Append(ch); } else { index--; try { PerformMemoriaTag(ref index, tag); } catch (IndexOutOfRangeException ex) { Log.Error(ex, "Not enought arguments: {0}", tag); _sb.Append(tag); } catch (Exception ex) { Log.Error(ex, "Unexpected error: {0}", tag); _sb.Append(tag); } } } else { _sb.Append(ch); } } _dlg.SubPage.Add(_sb.ToString()); } private void PerformMemoriaTag(ref Int32 index, FFIXTextTag tag) { switch (tag.Code) { case FFIXTextTagCode.NoAnimation: _dlg.DialogAnimate.ShowWithoutAnimation = true; break; case FFIXTextTagCode.NoFocus: _dlg.FlagButtonInh = true; _dlg.FlagResetChoice = false; break; case FFIXTextTagCode.Flash: _dlg.TypeEffect = true; break; case FFIXTextTagCode.End: _dlg.EndMode = -1; break; case FFIXTextTagCode.DialogSize: OnStartSentense(tag.Param); break; case FFIXTextTagCode.LowerRight: _dlg.Tail = Dialog.TailPosition.LowerRight; break; case FFIXTextTagCode.LowerLeft: _dlg.Tail = Dialog.TailPosition.LowerLeft; break; case FFIXTextTagCode.UpperRight: _dlg.Tail = Dialog.TailPosition.UpperRight; break; case FFIXTextTagCode.UpperLeft: _dlg.Tail = Dialog.TailPosition.UpperLeft; break; case FFIXTextTagCode.LowerCenter: _dlg.Tail = Dialog.TailPosition.LowerCenter; break; case FFIXTextTagCode.UpperCenter: _dlg.Tail = Dialog.TailPosition.UpperCenter; break; case FFIXTextTagCode.LowerRightForce: _dlg.Tail = Dialog.TailPosition.LowerRightForce; break; case FFIXTextTagCode.LowerLeftForce: _dlg.Tail = Dialog.TailPosition.LowerLeftForce; break; case FFIXTextTagCode.UpperRightForce: _dlg.Tail = Dialog.TailPosition.UpperRightForce; break; case FFIXTextTagCode.UpperLeftForce: _dlg.Tail = Dialog.TailPosition.UpperLeftForce; break; case FFIXTextTagCode.DialogPosition: _dlg.Tail = Dialog.TailPosition.DialogPosition; break; case FFIXTextTagCode.Widths: OnWidthsTag(tag.Param); break; case FFIXTextTagCode.PreChoose: OnPreChoose(tag.Param); break; case FFIXTextTagCode.PreChooseMask: OnPreChooseMask(tag.Param); break; case FFIXTextTagCode.Time: OnTime(tag.Param[0]); break; case FFIXTextTagCode.Tab: OnTab(ref index); break; case FFIXTextTagCode.Icon: OnIcon(tag.Param[0]); break; case FFIXTextTagCode.IconEx: KeepIconEx(tag.Param[0]); break; case FFIXTextTagCode.Mobile: KeepMobileIcon(_sb, tag.Param[0]); break; case FFIXTextTagCode.Offset: OnDialogOffsetPositon(tag.Param); break; case FFIXTextTagCode.Zidane: OnCharacterName(0); break; case FFIXTextTagCode.Vivi: OnCharacterName(1); break; case FFIXTextTagCode.Dagger: OnCharacterName(2); break; case FFIXTextTagCode.Steiner: OnCharacterName(3); break; case FFIXTextTagCode.Fraya: OnCharacterName(4); break; case FFIXTextTagCode.Quina: OnCharacterName(5); break; case FFIXTextTagCode.Eiko: OnCharacterName(6); break; case FFIXTextTagCode.Amarant: OnCharacterName(7); break; case FFIXTextTagCode.Party: OnPartyMemberName(tag.Param[0] - 1); break; case FFIXTextTagCode.Variable: _sb.Append(tag); OnVariable(tag.Param[0]); break; case FFIXTextTagCode.Item: OnItemName(tag.Param[0]); break; case FFIXTextTagCode.Signal: _sb.Append(tag); OnSignal(tag.Param[0]); break; case FFIXTextTagCode.IncreaseSignal: _sb.Append(tag); OnIncreaseSignal(); OnTime(-1); break; case FFIXTextTagCode.IncreaseSignalEx: _sb.Append(tag); OnIncreaseSignal(); break; case FFIXTextTagCode.Position: _dlg.Position = new Vector2(tag.Param[0], tag.Param[1]); break; case FFIXTextTagCode.Text: OnTextVariable(tag.Param); break; case FFIXTextTagCode.Choice: _sb.Append(tag); OnTab(ref index); break; case FFIXTextTagCode.NewPage: _sb.Append(tag); OnNewPage(); break; default: { StringBuilder sb; if (NGUIText.ForceShowButton || !FF9StateSystem.MobilePlatform) sb = _sb; else sb = new StringBuilder(16); if (KeepKeyIcon(sb, tag.Code) || KeepKeyExIcon(sb, tag)) return; _sb.Append(tag); break; } } } private void ParseOriginalTag(ref Int32 index, Int32 length) { if (_chars[index + 5] == ']') { String a = new String(_chars, index, 6); if (a == "[" + NGUIText.NoAnimation + "]") { _dlg.DialogAnimate.ShowWithoutAnimation = true; index += 5; return; } if (a == "[" + NGUIText.NoFocus + "]") { _dlg.FlagButtonInh = true; _dlg.FlagResetChoice = false; index += 5; return; } if (a == "[" + NGUIText.FlashInh + "]") { _dlg.TypeEffect = true; index += 5; return; } if (a == "[" + NGUIText.EndSentence + "]") { _dlg.EndMode = -1; index += 5; return; } } Int32 newIndex = index; String text3 = new String(_chars, index, 5); if (text3 == "[" + NGUIText.StartSentense) { Int32[] allParametersFromTag = GetAllParametersFromTag(_chars, index, ref newIndex); OnStartSentense(allParametersFromTag); } else if (text3 == "[" + NGUIText.DialogTailPositon) { newIndex = Array.IndexOf(_chars, ']', index + 4); String text4 = new String(_chars, index + 6, newIndex - index - 6); String text5 = text4; switch (text5) { case "LOR": _dlg.Tail = Dialog.TailPosition.LowerRight; break; case "LOL": _dlg.Tail = Dialog.TailPosition.LowerLeft; break; case "UPR": _dlg.Tail = Dialog.TailPosition.UpperRight; break; case "UPL": _dlg.Tail = Dialog.TailPosition.UpperLeft; break; case "LOC": _dlg.Tail = Dialog.TailPosition.LowerCenter; break; case "UPC": _dlg.Tail = Dialog.TailPosition.UpperCenter; break; case "LORF": _dlg.Tail = Dialog.TailPosition.LowerRightForce; break; case "LOLF": _dlg.Tail = Dialog.TailPosition.LowerLeftForce; break; case "UPRF": _dlg.Tail = Dialog.TailPosition.UpperRightForce; break; case "UPLF": _dlg.Tail = Dialog.TailPosition.UpperLeftForce; break; case "DEFT": _dlg.Tail = Dialog.TailPosition.DialogPosition; break; } } else if (text3 == "[" + NGUIText.WidthInfo) { Int32[] allParametersFromTag2 = GetAllParametersFromTag(_chars, index, ref newIndex); OnWidthsTag(allParametersFromTag2); } else if (text3 == "[" + NGUIText.PreChoose) { Int32[] allParametersFromTag3 = GetAllParametersFromTag(_chars, index, ref newIndex); OnPreChoose(allParametersFromTag3); } else if (text3 == "[" + NGUIText.PreChooseMask) { Int32[] allParametersFromTag4 = GetAllParametersFromTag(_chars, index, ref newIndex); OnPreChooseMask(allParametersFromTag4); } else if (text3 == "[" + NGUIText.AnimationTime) { Int32 oneParameterFromTag = NGUIText.GetOneParameterFromTag(_chars, index, ref newIndex); OnTime(oneParameterFromTag); } else if (text3 == "[" + NGUIText.TextOffset) { Int32[] allParametersFromTag5 = GetAllParametersFromTag(_chars, index, ref newIndex); if (_dlg.SkipThisChoice(_choiseIndex)) { newIndex = _text.IndexOf('[' + NGUIText.TextOffset, newIndex, StringComparison.Ordinal); if (newIndex >= 0) { newIndex--; } } else if (allParametersFromTag5[0] == 18 && allParametersFromTag5[1] == 0) { _sb.Append(" "); } else { _sb.Append(text3); _sb.Append('='); _sb.Append(allParametersFromTag5[0]); _sb.Append(','); _sb.Append(allParametersFromTag5[1]); _sb.Append(']'); } _choiseIndex++; } else if ( text3 == "[" + NGUIText.CustomButtonIcon || text3 == "[" + NGUIText.ButtonIcon || text3 == "[" + NGUIText.JoyStickButtonIcon || text3 == "[" + NGUIText.KeyboardButtonIcon) { newIndex = Array.IndexOf(_chars, ']', index + 4); String text6 = new String(_chars, index + 6, newIndex - index - 6); if (!FF9StateSystem.MobilePlatform || text3 == "[" + NGUIText.JoyStickButtonIcon || text3 == "[" + NGUIText.KeyboardButtonIcon || NGUIText.ForceShowButton) { _sb.Append(text3); _sb.Append('='); _sb.Append(text6); _sb.Append("] "); } } else if (text3 == "[" + NGUIText.IconVar) { Int32 oneParameterFromTag2 = NGUIText.GetOneParameterFromTag(_chars, index, ref newIndex); OnIcon(oneParameterFromTag2); } else if (text3 == "[" + NGUIText.NewIcon) { Int32 oneParameterFromTag3 = NGUIText.GetOneParameterFromTag(_chars, index, ref newIndex); KeepIconEx(oneParameterFromTag3); } else if (text3 == "[" + NGUIText.MobileIcon) { Int32 oneParameterFromTag4 = NGUIText.GetOneParameterFromTag(_chars, index, ref newIndex); KeepMobileIcon(_sb, oneParameterFromTag4); } else if (text3 == "[" + NGUIText.DialogOffsetPositon) { Int32[] allParametersFromTag6 = GetAllParametersFromTag(_chars, index, ref newIndex); OnDialogOffsetPositon(allParametersFromTag6); } else if (NGUIText.nameKeywordList.Contains(text3.Remove(0, 1))) { String a2 = text3.Remove(0, 1); newIndex = Array.IndexOf(_chars, ']', index + 4); if (a2 == NGUIText.Zidane) { OnCharacterName(0); } else if (a2 == NGUIText.Vivi) { OnCharacterName(1); } else if (a2 == NGUIText.Dagger) { OnCharacterName(2); } else if (a2 == NGUIText.Steiner) { OnCharacterName(3); } else if (a2 == NGUIText.Fraya) { OnCharacterName(4); } else if (a2 == NGUIText.Quina) { OnCharacterName(5); } else if (a2 == NGUIText.Eiko) { OnCharacterName(6); } else if (a2 == NGUIText.Amarant) { OnCharacterName(7); } else if (a2 == NGUIText.Party1) { OnPartyMemberName(0); } else if (a2 == NGUIText.Party2) { OnPartyMemberName(1); } else if (a2 == NGUIText.Party3) { OnPartyMemberName(2); } else if (a2 == NGUIText.Party4) { OnPartyMemberName(3); } } else if (text3 == "[" + NGUIText.NumberVar) { Int32 num10 = 0; Int32 oneParameterFromTag5 = NGUIText.GetOneParameterFromTag(_chars, index, ref num10); OnVariable(oneParameterFromTag5); } else if (text3 == "[" + NGUIText.ItemNameVar) { Int32 oneParameterFromTag6 = NGUIText.GetOneParameterFromTag(_chars, index, ref newIndex); OnItemName(oneParameterFromTag6); } else if (text3 == "[" + NGUIText.Signal) { Int32 num11 = Array.IndexOf(_chars, ']', index + 4); String value2 = new String(_chars, index + 6, num11 - index - 6); Int32 signalNumber = Convert.ToInt32(value2); OnSignal(signalNumber); } else if (text3 == "[" + NGUIText.IncreaseSignal) { OnIncreaseSignal(); } else if (text3 == "[" + NGUIText.DialogAbsPosition) { Single[] allParameters = NGUIText.GetAllParameters(_chars, index, ref newIndex); _dlg.Position = new Vector2(allParameters[0], allParameters[1]); } else if (text3 == "[" + NGUIText.TextVar) { Int32[] allParametersFromTag7 = GetAllParametersFromTag(_chars, index, ref newIndex); OnTextVariable(allParametersFromTag7); } else if (text3 == "[" + NGUIText.Choose) { Int32 startIndex = Array.IndexOf(_chars, ']', index + 4); OnChoice(startIndex); } else if (text3 == "[" + NGUIText.NewPage) { OnNewPage(); } if (newIndex == index) { _sb.Append(_chars[index]); } else if (newIndex != -1) { index = newIndex; } else { index = length; } } private void OnNewPage() { _dlg.SubPage.Add(_sb.Evict()); _sb.Append(NGUIText.FF9WhiteColor); } private void OnChoice(Int32 startIndex) { if (_isJapanese) { Int32[] array2 = { -1 }; if (_dlg.DisableIndexes != null) { array2 = (_dlg.DisableIndexes.Count <= 0) ? array2 : _dlg.DisableIndexes.ToArray(); } _text = ProcessJapaneseChoose(_text, startIndex, array2); _chars = _text.ToArray(); } } private void OnTextVariable(Int32[] allParametersFromTag7) { _sb.Append(_textEngine.GetStringFromTable(Convert.ToUInt32(allParametersFromTag7[0]), Convert.ToUInt32(allParametersFromTag7[1]))); } private void OnIncreaseSignal() { _dlg.SignalNumber++; _dlg.SignalMode = 2; } private void OnSignal(Int32 signalNumber) { _dlg.SignalNumber = signalNumber; _dlg.SignalMode = 1; } private void OnItemName(Int32 oneParameterFromTag6) { _sb.Append("[C8B040][HSHD]"); _sb.Append(ETb.GetItemName(_textEngine.gMesValue[oneParameterFromTag6])); _sb.Append("[C8C8C8]"); } private void OnVariable(Int32 oneParameterFromTag5) { Int32 value = _textEngine.gMesValue[oneParameterFromTag5]; if (!_dlg.MessageValues.ContainsKey(oneParameterFromTag5)) { _dlg.MessageValues.Add(oneParameterFromTag5, value); } _dlg.MessageNeedUpdate = true; } private void OnStartSentense(Int32[] args) { Single width = args[0]; Int32 lineNumber = args[1]; if (width > 0f) width += 3f; if (width > _dlg.CaptionWidth) _dlg.Width = width; else _dlg.Width = _dlg.CaptionWidth; _dlg.LineNumber = lineNumber; } private void OnPartyMemberName(Int32 index) { Int32 partyPlayer = PersistenSingleton<EventEngine>.Instance.GetPartyPlayer(index); PLAYER player = _gameState.player[partyPlayer]; _sb.Append(player.name); } private void OnCharacterName(Int32 index) { _sb.Append(FF9StateSystem.Common.FF9.player[index].name); } private void OnDialogOffsetPositon(Int32[] allParametersFromTag6) { _dlg.OffsetPosition = new Vector3(allParametersFromTag6[0], allParametersFromTag6[1], allParametersFromTag6[2]); } internal static Boolean KeepKeyIcon(StringBuilder sb, FFIXTextTagCode tagCode) { switch (tagCode) { case FFIXTextTagCode.Up: sb.Append("[DBTN=UP] "); break; case FFIXTextTagCode.Down: sb.Append("[DBTN=DOWN] "); break; case FFIXTextTagCode.Left: sb.Append("[DBTN=LEFT] "); break; case FFIXTextTagCode.Right: sb.Append("[DBTN=RIGHT] "); break; case FFIXTextTagCode.Circle: sb.Append("[DBTN=CIRCLE] "); break; case FFIXTextTagCode.Cross: sb.Append("[DBTN=CROSS] "); break; case FFIXTextTagCode.Triangle: sb.Append("[DBTN=TRIANGLE] "); break; case FFIXTextTagCode.Square: sb.Append("[DBTN=SQUARE] "); break; case FFIXTextTagCode.R1: sb.Append("[DBTN=R1] "); break; case FFIXTextTagCode.R2: sb.Append("[DBTN=R2] "); break; case FFIXTextTagCode.L1: sb.Append("[DBTN=L1] "); break; case FFIXTextTagCode.L2: sb.Append("[DBTN=L2] "); break; case FFIXTextTagCode.Select: sb.Append("[DBTN=SELECT] "); break; case FFIXTextTagCode.Start: sb.Append("[DBTN=START] "); break; case FFIXTextTagCode.Pad: sb.Append("[DBTN=PAD] "); break; default: return false; } return true; } internal static Boolean KeepKeyExIcon(StringBuilder sb, FFIXTextTag tag) { switch (tag.Code) { case FFIXTextTagCode.UpEx: sb.Append("[CBTN=UP] "); break; case FFIXTextTagCode.DownEx: sb.Append("[CBTN=DOWN] "); break; case FFIXTextTagCode.LeftEx: sb.Append("[CBTN=LEFT] "); break; case FFIXTextTagCode.RightEx: sb.Append("[CBTN=RIGHT] "); break; case FFIXTextTagCode.CircleEx: sb.Append("[CBTN=CIRCLE] "); break; case FFIXTextTagCode.CrossEx: sb.Append("[CBTN=CROSS] "); break; case FFIXTextTagCode.TriangleEx: sb.Append("[CBTN=TRIANGLE] "); break; case FFIXTextTagCode.SquareEx: sb.Append("[CBTN=SQUARE] "); break; case FFIXTextTagCode.R1Ex: sb.Append("[CBTN=R1] "); break; case FFIXTextTagCode.R2Ex: sb.Append("[CBTN=R2] "); break; case FFIXTextTagCode.L1Ex: sb.Append("[CBTN=L1] "); break; case FFIXTextTagCode.L2Ex: sb.Append("[CBTN=L2] "); break; case FFIXTextTagCode.SelectEx: sb.Append("[CBTN=SELECT] "); break; case FFIXTextTagCode.StartEx: sb.Append("[CBTN=START] "); break; case FFIXTextTagCode.PadEx: sb.Append("[CBTN=PAD] "); break; default: return false; } return true; } internal static void KeepMobileIcon(StringBuilder sb, Int32 oneParameterFromTag4) { if (FF9StateSystem.MobilePlatform && !NGUIText.ForceShowButton) { sb.Append("[MOBI="); sb.Append(oneParameterFromTag4); sb.Append("] "); } } private void KeepIconEx(Int32 oneParameterFromTag3) { if ((_textEngine.gMesValue[0] & 1 << oneParameterFromTag3) > 0) { _sb.Append("[PNEW="); _sb.Append(oneParameterFromTag3); _sb.Append("] "); } } private void OnIcon(Int32 iconNumber) { switch (iconNumber) { case 34: _sb.Append("[sub]0[/sub]"); return; case 35: _sb.Append("[sub]1[/sub]"); return; case 39: _sb.Append("[sub]5[/sub]"); return; case 36: case 37: case 38: case 159: _sb.Append("[sup]"); _sb.Append(Localization.Get("Miss")); _sb.Append("[/sup]"); return; case 45: _sb.Append("[sub]/[/sub]"); break; case 160: _sb.Append("[sup]"); _sb.Append(Localization.Get("Death")); _sb.Append("[/sup]"); return; case 161: _sb.Append("[sup]"); _sb.Append(Localization.Get("Guard")); _sb.Append("[/sup]"); return; case 163: _sb.Append("[sup]"); _sb.Append(Localization.Get("MPCaption")); _sb.Append("[/sup]"); break; case 173: _sb.Append("9"); break; case 174: _sb.Append("/"); break; case 179: _sb.Append(NGUIText.FF9YellowColor); _sb.Append("[sup]"); _sb.Append(Localization.Get("Critical")); _sb.Append("[/sup]"); _sb.Append(NGUIText.FF9WhiteColor); break; default: _sb.Append("[ICON="); _sb.Append(iconNumber); _sb.Append("] "); break; } } private void OnTime(Int32 oneParameterFromTag) { if (oneParameterFromTag > 0) { _dlg.EndMode = oneParameterFromTag; _dlg.FlagButtonInh = true; } else if (oneParameterFromTag == -1) { _dlg.FlagButtonInh = true; } else { _dlg.FlagButtonInh = false; } } private void OnTab(ref Int32 index) { if (_dlg.SkipThisChoice(_choiseIndex)) { Int32 newIndex = _text.IndexOf("{Tab", index, StringComparison.Ordinal); if (newIndex >= 0) index = newIndex - 1; } else { _sb.Append(" "); } _choiseIndex++; } private void OnPreChooseMask(Int32[] allParametersFromTag4) { ETb.sChooseMask = ETb.sChooseMaskInit; _dlg.ChoiceNumber = Convert.ToInt32(allParametersFromTag4[0]); _dlg.CancelChoice = Convert.ToInt32(allParametersFromTag4[1]); _dlg.DefaultChoice = (ETb.sChoose < 0) ? 0 : ETb.sChoose; _dlg.LineNumber = ((_dlg.LineNumber >= (Single)_dlg.ChoiceNumber) ? _dlg.LineNumber : (_dlg.LineNumber + _dlg.ChoiceNumber)); _dlg.ChooseMask = ETb.sChooseMask; if (_dlg.DisableIndexes.Count > 0) { if (_dlg.DisableIndexes.Contains(_dlg.DefaultChoice) || !_dlg.ActiveIndexes.Contains(_dlg.DefaultChoice)) { _dlg.DefaultChoice = _dlg.ActiveIndexes.Min(); } if (_dlg.DisableIndexes.Contains(_dlg.CancelChoice) || !_dlg.ActiveIndexes.Contains(_dlg.CancelChoice)) { _dlg.CancelChoice = _dlg.ActiveIndexes.Max(); } } else { _dlg.DefaultChoice = (_dlg.DefaultChoice < _dlg.ChoiceNumber) ? _dlg.DefaultChoice : (_dlg.ChoiceNumber - 1); } _choiseIndex = 0; } private void OnPreChoose(Int32[] allParametersFromTag3) { ETb.sChooseMask = -1; _dlg.ChoiceNumber = Convert.ToInt32(allParametersFromTag3[0]); _dlg.DefaultChoice = (ETb.sChoose < 0) ? 0 : ETb.sChoose; _dlg.DefaultChoice = (_dlg.DefaultChoice < _dlg.ChoiceNumber) ? _dlg.DefaultChoice : (_dlg.ChoiceNumber - 1); Int32 num9 = Convert.ToInt32(allParametersFromTag3[1]); _dlg.CancelChoice = (num9 <= -1) ? (_dlg.ChoiceNumber - 1) : num9; } private void OnWidthsTag(Int32[] allParametersFromTag2) { Int32 num5 = 0; while (num5 + 2 < allParametersFromTag2.Length) { Int32 num6 = 0; Int32 num7 = allParametersFromTag2[num5]; Int32 num8 = allParametersFromTag2[num5 + 1]; if (_dlg.DisableIndexes.Contains(num7 - 1)) { num8 = 0; } List<Int32> list = new List<Int32>(); Boolean flag2 = false; while (allParametersFromTag2[num5 + 2 + num6] != -1) { list.Add(allParametersFromTag2[num5 + 2 + num6]); flag2 = true; num6++; } if (num6 == 0) { num6 = 1; } num5 += 2 + num6; if (flag2) { num5++; } num8 += (Int32)NGUIText.GetDialogWidthFromSpecialOpcode(list, _textEngine, _dlg.PhraseLabel); if (_dlg.OriginalWidth < num8) { _dlg.Width = num8; } } } public static Int32[] GetAllParametersFromTag(Char[] fullText, Int32 currentIndex, ref Int32 closingBracket) { closingBracket = Array.IndexOf(fullText, ']', currentIndex + 4); String text = new String(fullText, currentIndex + 6, closingBracket - currentIndex - 6); String[] array = text.Split(','); return Array.ConvertAll(array, Int32.Parse); } // Not supported for Memoria Tags public static String ProcessJapaneseChoose(String text, Int32 startIndex, Int32[] disableChoice) { Int32 endSentenceIndex = text.IndexOf('[' + NGUIText.EndSentence, startIndex + 1, StringComparison.Ordinal); Int32 sentenceLength = endSentenceIndex - startIndex; if (sentenceLength <= 0) { Int32 timeIndex = text.IndexOf("[TIME=-1]", startIndex + 1, StringComparison.Ordinal); sentenceLength = timeIndex - startIndex; } String sentence = text.Substring(startIndex + 1, sentenceLength); String[] lines = sentence.Split('\n'); StringBuilder sb = new StringBuilder(sentence.Length); for (Int32 i = 0; i < lines.Length; i++) { String line = lines[i]; Boolean replacePadding = true; for (Int32 k = 0; k < disableChoice.Length; k++) { if (i == disableChoice[k]) { replacePadding = false; break; } } if (replacePadding) { sb.Append(line.Replace(" ", " ")); if (i + 1 < lines.Length) sb.Append('\n'); } } return text.Replace(sentence, sb.ToString()); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace swagger { using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// This client that can be used to manage Azure Search services and API /// keys. /// /// ASd /// /// - ASd /// - qawe /// /// </summary> public partial class SearchManagementClient : ServiceClient<SearchManagementClient>, ISearchManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.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> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft Azure /// subscription. /// The subscription ID forms part of the URI for every service call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// The client API version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IQueryKeysOperations. /// </summary> public virtual IQueryKeysOperations QueryKeys { get; private set; } /// <summary> /// Gets the IServicesOperations. /// </summary> public virtual IServicesOperations Services { get; private set; } /// <summary> /// Initializes a new instance of the SearchManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SearchManagementClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the SearchManagementClient 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> protected SearchManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the SearchManagementClient 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> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected SearchManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SearchManagementClient 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> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected SearchManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SearchManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SearchManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SearchManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </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> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SearchManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SearchManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SearchManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SearchManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </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> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SearchManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { QueryKeys = new QueryKeysOperations(this); Services = new ServicesOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2015-02-28"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// // 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 Hyak.Common; using Microsoft.WindowsAzure.Management.RemoteApp.Models; namespace Microsoft.WindowsAzure.Management.RemoteApp.Models { /// <summary> /// The collection details. /// </summary> public partial class Collection { private CollectionAclLevel _aclLevel; /// <summary> /// Optional. Application ACL level (Collection or Application) /// </summary> public CollectionAclLevel AclLevel { get { return this._aclLevel; } set { this._aclLevel = value; } } private ActiveDirectoryConfig _adInfo; /// <summary> /// Optional. The domain join details for this collection. /// </summary> public ActiveDirectoryConfig AdInfo { get { return this._adInfo; } set { this._adInfo = value; } } private string _customRdpProperty; /// <summary> /// Optional. Optional customer-defined RDP properties of the /// collection. /// </summary> public string CustomRdpProperty { get { return this._customRdpProperty; } set { this._customRdpProperty = value; } } private string _description; /// <summary> /// Optional. The description of the collection. /// </summary> public string Description { get { return this._description; } set { this._description = value; } } private IList<string> _dnsServers; /// <summary> /// Optional. List of the DNS Servers. /// </summary> public IList<string> DnsServers { get { return this._dnsServers; } set { this._dnsServers = value; } } private string _lastErrorCode; /// <summary> /// Optional. The last operation error code on this collection. /// </summary> public string LastErrorCode { get { return this._lastErrorCode; } set { this._lastErrorCode = value; } } private DateTime _lastModifiedTimeUtc; /// <summary> /// Optional. UTC Date time of the last modification of this collection. /// </summary> public DateTime LastModifiedTimeUtc { get { return this._lastModifiedTimeUtc; } set { this._lastModifiedTimeUtc = value; } } private int _maxSessions; /// <summary> /// Optional. The maximum number of concurrent users allowed for this /// collection. /// </summary> public int MaxSessions { get { return this._maxSessions; } set { this._maxSessions = value; } } private CollectionMode _mode; /// <summary> /// Optional. The collection mode. /// </summary> public CollectionMode Mode { get { return this._mode; } set { this._mode = value; } } private string _name; /// <summary> /// Required. The collection name. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private OfficeType _officeType; /// <summary> /// Optional. If the template image for this collection includes Office /// this will specify the type. /// </summary> public OfficeType OfficeType { get { return this._officeType; } set { this._officeType = value; } } private string _planName; /// <summary> /// Required. The plan name associated with this collection. /// </summary> public string PlanName { get { return this._planName; } set { this._planName = value; } } private bool _readyForPublishing; /// <summary> /// Optional. A flag denoting if this collection is ready for /// publishing operations. /// </summary> public bool ReadyForPublishing { get { return this._readyForPublishing; } set { this._readyForPublishing = value; } } private string _region; /// <summary> /// Optional. The region where the collection is deployed. /// </summary> public string Region { get { return this._region; } set { this._region = value; } } private int _sessionWarningThreshold; /// <summary> /// Optional. The end-user session limit warning threshold. Reaching /// or crossing this threshold will cause a capacity warning message /// to be shown in the management portal. /// </summary> public int SessionWarningThreshold { get { return this._sessionWarningThreshold; } set { this._sessionWarningThreshold = value; } } private string _status; /// <summary> /// Optional. The collection status. /// </summary> public string Status { get { return this._status; } set { this._status = value; } } private string _subnetName; /// <summary> /// Optional. The subnet name of the customer created Azure VNet. /// </summary> public string SubnetName { get { return this._subnetName; } set { this._subnetName = value; } } private string _templateImageName; /// <summary> /// Optional. The name of the template image associated with this /// collection. /// </summary> public string TemplateImageName { get { return this._templateImageName; } set { this._templateImageName = value; } } private bool _trialOnly; /// <summary> /// Optional. Trial-only collections can be used only during the trial /// period of your subscription. When the trial expires or you /// activate your subscription, these collections will be permanently /// disabled. /// </summary> public bool TrialOnly { get { return this._trialOnly; } set { this._trialOnly = value; } } private CollectionType _type; /// <summary> /// Optional. The collection type. /// </summary> public CollectionType Type { get { return this._type; } set { this._type = value; } } private string _vNetName; /// <summary> /// Optional. The VNet name associated with this collection. /// </summary> public string VNetName { get { return this._vNetName; } set { this._vNetName = value; } } /// <summary> /// Initializes a new instance of the Collection class. /// </summary> public Collection() { this.DnsServers = new LazyList<string>(); } /// <summary> /// Initializes a new instance of the Collection class with required /// arguments. /// </summary> public Collection(string name, string planName) : this() { if (name == null) { throw new ArgumentNullException("name"); } if (planName == null) { throw new ArgumentNullException("planName"); } this.Name = name; this.PlanName = planName; } } }
/* * REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application * * The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists. * * OpenAPI spec version: v1 * * */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using HETSAPI.Models; using HETSAPI.ViewModels; namespace HETSAPI.Services.Impl { /// <summary> /// /// </summary> public class AttachmentService : IAttachmentService { private readonly DbAppContext _context; /// <summary> /// Create a service and set the database context /// </summary> public AttachmentService(DbAppContext context) { _context = context; } /// <summary> /// /// </summary> /// <param name="items"></param> /// <response code="201">Attachment created</response> public virtual IActionResult AttachmentsBulkPostAsync(Attachment[] items) { if (items == null) { return new BadRequestResult(); } foreach (Attachment item in items) { // determine if this is an insert or an update bool exists = _context.Attachments.Any(a => a.Id == item.Id); if (exists) { _context.Update(item); } else { _context.Add(item); } } // Save the changes _context.SaveChanges(); return new NoContentResult(); } /// <summary> /// /// </summary> /// <response code="200">OK</response> public virtual IActionResult AttachmentsGetAsync() { var result = _context.Attachments.ToList(); return new ObjectResult(result); } /// <summary> /// /// </summary> /// <param name="id">id of Attachment to delete</param> /// <response code="200">OK</response> /// <response code="404">Attachment not found</response> public virtual IActionResult AttachmentsIdDeletePostAsync(int id) { var exists = _context.Attachments.Any(a => a.Id == id); if (exists) { var item = _context.Attachments.First(a => a.Id == id); if (item != null) { _context.Attachments.Remove(item); // Save the changes _context.SaveChanges(); } return new ObjectResult(item); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// Returns the binary file component of an attachment /// </summary> /// <param name="id">Attachment Id</param> /// <response code="200">OK</response> /// <response code="404">Attachment not found in system</response> public virtual IActionResult AttachmentsIdDownloadGetAsync(int id) { var exists = _context.Attachments.Any(a => a.Id == id); if (exists) { var attachment = _context.Attachments.First(a => a.Id == id); // // MOTI has requested that files be stored in the database. // var result = new FileContentResult(attachment.FileContents, "application/octet-stream"); result.FileDownloadName = attachment.FileName; return result; } else { return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <param name="id">id of Attachment to fetch</param> /// <response code="200">OK</response> /// <response code="404">Attachment not found</response> public virtual IActionResult AttachmentsIdGetAsync(int id) { var exists = _context.Attachments.Any(a => a.Id == id); if (exists) { var result = _context.Attachments.First(a => a.Id == id); return new ObjectResult(result); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <param name="id">id of Attachment to fetch</param> /// <param name="item"></param> /// <response code="200">OK</response> /// <response code="404">Attachment not found</response> public virtual IActionResult AttachmentsIdPutAsync(int id, Attachment item) { var exists = _context.Attachments.Any(a => a.Id == id); if (exists && id == item.Id) { _context.Attachments.Update(item); // Save the changes _context.SaveChanges(); return new ObjectResult(item); } else { // record not found return new StatusCodeResult(404); } } /// <summary> /// /// </summary> /// <param name="item"></param> /// <response code="201">Attachment created</response> public virtual IActionResult AttachmentsPostAsync(Attachment item) { var exists = _context.Attachments.Any(a => a.Id == item.Id); if (exists) { _context.Attachments.Update(item); } else { // record not found _context.Attachments.Add(item); } // Save the changes _context.SaveChanges(); return new ObjectResult(item); } } }
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Runtime.InteropServices; using Platform.Runtime.Interop; namespace Platform.Network.Time { [StructLayout(LayoutKind.Explicit)] internal struct NtpByteOctuple { [FieldOffset(0)] public BigEndianByteQuad FirstQuad; [FieldOffset(4)] public BigEndianByteQuad SecondQuad; public static NtpByteOctuple FromTimeSpan(TimeSpan timeSpan) { var retval = new NtpByteOctuple(); var milliseconds = (ulong)timeSpan.TotalMilliseconds; var intpart = (uint)(milliseconds / 1000L); var fractpart = (uint)(((milliseconds % 1000L) * 0x100000000L) / 1000L); retval.FirstQuad = BigEndianByteQuad.FromUInt32(intpart); retval.SecondQuad = BigEndianByteQuad.FromUInt32(fractpart); retval.ToTimeSpan(); return retval; } public static NtpByteOctuple FromDateTime(DateTime dateTime) { var referenceTime = new DateTime(1900, 1, 1, 0, 0, 0); var timeSpan = dateTime.ToUniversalTime() - referenceTime; return FromTimeSpan(timeSpan); } public TimeSpan ToTimeSpan() { ulong intpart = 0; ulong fractpart = 0; intpart = FirstQuad.ToUInt32(); fractpart = SecondQuad.ToUInt32(); var milliseconds = intpart * 1000 + (fractpart * 1000) / 0x100000000UL; return TimeSpan.FromMilliseconds((double)milliseconds); } public DateTime ToDateTime() { var time = new DateTime(1900, 1, 1, 0, 0, 0); time += ToTimeSpan(); time = DateTime.SpecifyKind(time, DateTimeKind.Utc); return time; } } public enum NtpLeapIndicator { NoWarning = 0, // 0 - No warning LastMinute61 = 1, // 1 - Last minute has 61 seconds LastMinute59 = 2, // 2 - Last minute has 59 seconds Alarm = 3 // 3 - Alarm condition (clock not synchronized) } //Mode field values public enum NtpMode { SymmetricActive = 1, // 1 - Symmetric active SymmetricPassive = 2, // 2 - Symmetric pasive Client = 3, // 3 - Client Server = 4, // 4 - Server Broadcast = 5, // 5 - Broadcast Unknown = 6 // 0, 6, 7 - Reserved } // Stratum field values public enum NtpStratum { Unspecified = 0, // 0 - unspecified or unavailable PrimaryReference = 1, // 1 - primary reference (e.g. radio-clock) SecondaryReference, // 2-15 - secondary reference (via NTP or SNTP) Reserved // 16-255 - reserved } [StructLayout(LayoutKind.Explicit)] public struct NtpPacket { public const int DefaultPort = 123; public static TimeSpan CalculateRoundTripDelay(NtpPacket resultPacket, DateTime resultTime) { return (resultTime - resultPacket.OriginateTimeSpamp) - (resultPacket.ReceiveTimeSpamp - resultPacket.TransmitTimeSpamp); } public static TimeSpan CalculateLocalClockOffset(NtpPacket resultPacket, DateTime resultTime) { return TimeSpan.FromTicks(((resultPacket.ReceiveTimeSpamp - resultPacket.OriginateTimeSpamp) + (resultPacket.TransmitTimeSpamp - resultTime)).Ticks / 2); } [FieldOffset(0)] private byte headerByte1; /// <summary> /// LeapIndicator /// </summary> public NtpLeapIndicator LeapIndicator { get { var x = (byte)(headerByte1 >> 6); if (x > 3) { x = 3; } return (NtpLeapIndicator)x; } set { var x = (byte)(((byte)value) << 6); headerByte1 = (byte)((headerByte1 & 0x3F) | x); } } /// <summary> /// VersionNumber /// </summary> public int VersionNumber { get { // Bits 3 - 5 var x = (byte)((this.headerByte1 & 0x38) >> 3); return x; } set { byte x; x = (byte)(((byte)value) << 3); headerByte1 = (byte)((headerByte1 & 0xC7) | x); } } /// <summary> /// Mode /// </summary> public NtpMode Mode { get { var x = (byte)(headerByte1 & 0x7); if (x > 5) { x = 5; } return (NtpMode)x; } set { var x = (byte)value; headerByte1 = (byte)((headerByte1 & 0xF8) | x); } } /// <summary> /// Stratum /// </summary> public NtpStratum Stratum { get { return (NtpStratum)stratum; } set { stratum = (byte)value; } } /// <summary> /// <see cref="Stratum"/> /// </summary> [FieldOffset(1)] private byte stratum; /// <summary> /// Poll /// </summary> public int PollInterval { get { return (int)pollInterval; } set { pollInterval = (sbyte)value; } } /// <summary> /// <see cref="PollInterval"/> /// </summary> [FieldOffset(2)] private sbyte pollInterval; /// <summary> /// Precision /// </summary> public int Precision { get { return (int)precision; } set { precision = (sbyte)value; } } /// <summary> /// <see cref="Precision"/> /// </summary> [FieldOffset(3)] private sbyte precision; /// <summary> /// RootDelay /// </summary> public TimeSpan RootDelay { get { return rootDelay.ToTimeSpan(); } set { rootDelay.SetFrom(value); } } [FieldOffset(4)] private BigEndianByteQuad rootDelay; /// <summary> /// RootDelay /// </summary> public TimeSpan RootDisperson { get { var temp = 0; temp = (((((rootDispersion.Byte1 << 8) + rootDispersion.Byte2) << 8) + rootDispersion.Byte3) << 8) + rootDispersion.Byte4; return TimeSpan.FromMilliseconds(1000 * (((double)temp) / 0x10000)); } set { var milliseconds = value.TotalMilliseconds; milliseconds /= 1000; milliseconds *= 0x10000; var x = (int)milliseconds; rootDispersion.Byte4 = (byte)(x & 0xf); rootDispersion.Byte3 = (byte)((x >> 8) & 0xf); rootDispersion.Byte2 = (byte)((x >> 16) & 0xf); rootDispersion.Byte1 = (byte)((x >> 24) & 0xf); } } [FieldOffset(8)] private BigEndianByteQuad rootDispersion; /// <summary> /// ReferenceId /// </summary> public string ReferenceId { get { string val = ""; switch (this.Stratum) { case NtpStratum.Unspecified: goto case NtpStratum.PrimaryReference; case NtpStratum.PrimaryReference: val = new StringBuilder().Append((char)referenceId.Byte1) .Append((char)referenceId.Byte2) .Append((char)referenceId.Byte3) .Append((char)referenceId.Byte4).ToString(); break; case NtpStratum.SecondaryReference: switch (VersionNumber) { case 3: // Version 3, Reference ID is an IPv4 address var address = $"{this.referenceId.Byte1}.{this.referenceId.Byte2}.{this.referenceId.Byte3}.{this.referenceId.Byte4}"; try { var host = Dns.GetHostEntry(address); val = host.HostName + " (" + address + ")"; } catch (Exception) { val = "N/A"; } break; case 4: // Version 4, Reference ID is the timestamp of last update /*DateTime time = ComputeDate(GetMilliSeconds(offReferenceID)); // Take care of the time zone TimeSpan offspan = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now); val = (time + offspan).ToString(); * */ val = ""; break; default: val = "N/A"; break; } break; } return val; } } [FieldOffset(12)] private BigEndianByteQuad referenceId; /// <summary> /// ReferenceTimeSpamp /// </summary> public DateTime ReferenceTimeSpamp { get { return referenceTimeSpamp.ToDateTime().ToLocalTime(); } set { referenceTimeSpamp = NtpByteOctuple.FromDateTime(value); } } /// <summary> /// <see cref="ReferenceTimeSpamp"/> /// </summary> [FieldOffset(16)] private NtpByteOctuple referenceTimeSpamp; /// <summary> /// OriginateTimeSpamp /// </summary> public DateTime OriginateTimeSpamp { get { return originateTimeSpamp.ToDateTime().ToLocalTime(); } set { originateTimeSpamp = NtpByteOctuple.FromDateTime(value); } } /// <summary> /// <see cref="OriginateTimeSpamp"/> /// </summary> [FieldOffset(24)] private NtpByteOctuple originateTimeSpamp; /// <summary> /// ReceiveTimeSpamp /// </summary> public DateTime ReceiveTimeSpamp { get { return receiveTimeSpamp.ToDateTime().ToLocalTime(); } set { receiveTimeSpamp = NtpByteOctuple.FromDateTime(value); } } /// <summary> /// <see cref="ReceiveTimeSpamp"/> /// </summary> [FieldOffset(32)] private NtpByteOctuple receiveTimeSpamp; /// <summary> /// TransmitTimeSpamp /// </summary> public DateTime TransmitTimeSpamp { get { return transmitTimeSpamp.ToDateTime().ToLocalTime(); } set { transmitTimeSpamp = NtpByteOctuple.FromDateTime(value); } } /// <summary> /// <see cref="TransmitTimeSpamp"/> /// </summary> [FieldOffset(40)] private NtpByteOctuple transmitTimeSpamp; public byte[] ToRawByteArray() { return MarshalUtils.RawSerialize(this); } public static NtpPacket ParseRawByteArray(byte[] array) { var retval = MarshalUtils.RawDeserialize<NtpPacket>(array); return retval; } public static NtpPacket ReadCurrentTime(string serverName) { return ReadPacket(serverName, DefaultPort); } public static NtpPacket ReadPacket(string serverName, int port) { IPAddress ipAddress; var udpClient = new UdpClient(); udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000); if (IPAddress.TryParse(serverName, out ipAddress)) { udpClient.Connect(ipAddress, port); } else { udpClient.Connect(serverName, port); } using (udpClient) { return ReadPacket(udpClient); } } public static NtpPacket ReadPacket(UdpClient udpClient) { var packet = new NtpPacket(); packet.VersionNumber = 4; packet.Mode = NtpMode.Client; packet.TransmitTimeSpamp = DateTime.Now; return ReadPacket(udpClient, packet); } public static NtpPacket ReadPacket(UdpClient udpClient, NtpPacket packet) { var remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); byte[] data = null; for (int i = 0; i < 5; i++) { data = packet.ToRawByteArray(); udpClient.Send(data, data.Length); try { data = udpClient.Receive(ref remoteEndPoint); break; } catch (SocketException) { continue; } } if (data == null) { throw new TimeoutException(); } var resultPacket = NtpPacket.ParseRawByteArray(data); return resultPacket; } } }
namespace Ocelot.AcceptanceTests { using Microsoft.AspNetCore.Http; using Ocelot.Configuration.File; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using TestStack.BDDfy; using Xunit; public class HeaderTests : IDisposable { private int _count; private readonly Steps _steps; private readonly ServiceHandler _serviceHandler; public HeaderTests() { _serviceHandler = new ServiceHandler(); _steps = new Steps(); } [Fact] public void should_transform_upstream_header() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51871, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, UpstreamHeaderTransform = new Dictionary<string,string> { {"Laz", "D, GP"} } } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51871", "/", 200, "Laz")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .And(x => _steps.GivenIAddAHeader("Laz", "D")) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("GP")) .BDDfy(); } [Fact] public void should_transform_downstream_header() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51871, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, DownstreamHeaderTransform = new Dictionary<string,string> { {"Location", "http://www.bbc.co.uk/, http://ocelot.com/"} } } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51871", "/", 200, "Location", "http://www.bbc.co.uk/")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseHeaderIs("Location", "http://ocelot.com/")) .BDDfy(); } [Fact] public void should_fix_issue_190() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 6773, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, DownstreamHeaderTransform = new Dictionary<string,string> { {"Location", "http://localhost:6773, {BaseUrl}"} }, HttpHandlerOptions = new FileHttpHandlerOptions { AllowAutoRedirect = false } } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:6773", "/", 302, "Location", "http://localhost:6773/pay/Receive")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Redirect)) .And(x => _steps.ThenTheResponseHeaderIs("Location", "http://localhost:5000/pay/Receive")) .BDDfy(); } [Fact] public void should_fix_issue_205() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 6773, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, DownstreamHeaderTransform = new Dictionary<string,string> { {"Location", "{DownstreamBaseUrl}, {BaseUrl}"} }, HttpHandlerOptions = new FileHttpHandlerOptions { AllowAutoRedirect = false } } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:6773", "/", 302, "Location", "http://localhost:6773/pay/Receive")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Redirect)) .And(x => _steps.ThenTheResponseHeaderIs("Location", "http://localhost:5000/pay/Receive")) .BDDfy(); } [Fact] public void should_fix_issue_417() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 6773, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, DownstreamHeaderTransform = new Dictionary<string,string> { {"Location", "{DownstreamBaseUrl}, {BaseUrl}"} }, HttpHandlerOptions = new FileHttpHandlerOptions { AllowAutoRedirect = false } } }, GlobalConfiguration = new FileGlobalConfiguration { BaseUrl = "http://anotherapp.azurewebsites.net" } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:6773", "/", 302, "Location", "http://localhost:6773/pay/Receive")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.Redirect)) .And(x => _steps.ThenTheResponseHeaderIs("Location", "http://anotherapp.azurewebsites.net/pay/Receive")) .BDDfy(); } [Fact] public void request_should_reuse_cookies_with_cookie_container() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/sso/{everything}", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 6774, } }, UpstreamPathTemplate = "/sso/{everything}", UpstreamHttpMethod = new List<string> { "Get", "Post", "Options" }, HttpHandlerOptions = new FileHttpHandlerOptions { UseCookieContainer = true } } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:6774", "/sso/test", 200)) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .And(x => _steps.WhenIGetUrlOnTheApiGateway("/sso/test")) .And(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseHeaderIs("Set-Cookie", "test=0; path=/")) .And(x => _steps.GivenIAddCookieToMyRequest("test=1; path=/")) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/sso/test")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .BDDfy(); } [Fact] public void request_should_have_own_cookies_no_cookie_container() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/sso/{everything}", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 6775, } }, UpstreamPathTemplate = "/sso/{everything}", UpstreamHttpMethod = new List<string> { "Get", "Post", "Options" }, HttpHandlerOptions = new FileHttpHandlerOptions { UseCookieContainer = false } } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:6775", "/sso/test", 200)) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .And(x => _steps.WhenIGetUrlOnTheApiGateway("/sso/test")) .And(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseHeaderIs("Set-Cookie", "test=0; path=/")) .And(x => _steps.GivenIAddCookieToMyRequest("test=1; path=/")) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/sso/test")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .BDDfy(); } [Fact] public void issue_474_should_not_put_spaces_in_header() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 52866, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:52866", "/", 200, "Accept")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .And(x => _steps.GivenIAddAHeader("Accept", "text/html,application/xhtml+xml,application/xml;")) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("text/html,application/xhtml+xml,application/xml;")) .BDDfy(); } [Fact] public void issue_474_should_put_spaces_in_header() { var configuration = new FileConfiguration { ReRoutes = new List<FileReRoute> { new FileReRoute { DownstreamPathTemplate = "/", DownstreamScheme = "http", DownstreamHostAndPorts = new List<FileHostAndPort> { new FileHostAndPort { Host = "localhost", Port = 51874, } }, UpstreamPathTemplate = "/", UpstreamHttpMethod = new List<string> { "Get" }, } } }; this.Given(x => x.GivenThereIsAServiceRunningOn("http://localhost:51874", "/", 200, "Accept")) .And(x => _steps.GivenThereIsAConfiguration(configuration)) .And(x => _steps.GivenOcelotIsRunning()) .And(x => _steps.GivenIAddAHeader("Accept", "text/html")) .And(x => _steps.GivenIAddAHeader("Accept", "application/xhtml+xml")) .And(x => _steps.GivenIAddAHeader("Accept", "application/xml")) .When(x => _steps.WhenIGetUrlOnTheApiGateway("/")) .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => _steps.ThenTheResponseBodyShouldBe("text/html, application/xhtml+xml, application/xml")) .BDDfy(); } private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode) { _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, context => { if (_count == 0) { context.Response.Cookies.Append("test", "0"); _count++; context.Response.StatusCode = statusCode; return Task.CompletedTask; } if (context.Request.Cookies.TryGetValue("test", out var cookieValue) || context.Request.Headers.TryGetValue("Set-Cookie", out var headerValue)) { if (cookieValue == "0" || headerValue == "test=1; path=/") { context.Response.StatusCode = statusCode; return Task.CompletedTask; } } context.Response.StatusCode = 500; return Task.CompletedTask; }); } private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode, string headerKey) { _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, async context => { if (context.Request.Headers.TryGetValue(headerKey, out var values)) { var result = values.First(); context.Response.StatusCode = statusCode; await context.Response.WriteAsync(result); } }); } private void GivenThereIsAServiceRunningOn(string baseUrl, string basePath, int statusCode, string headerKey, string headerValue) { _serviceHandler.GivenThereIsAServiceRunningOn(baseUrl, basePath, context => { context.Response.OnStarting(() => { context.Response.Headers.Add(headerKey, headerValue); context.Response.StatusCode = statusCode; return Task.CompletedTask; }); return Task.CompletedTask; }); } public void Dispose() { _serviceHandler?.Dispose(); _steps.Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //----------------------------------------------------------------------------- // // Description: // This is a base abstract class for PackagePart. This is a part of the // Packaging Layer // //----------------------------------------------------------------------------- using System; using System.IO; using System.Collections; using System.Collections.Generic; // For List <> using System.Diagnostics; // For Debug.Assert namespace System.IO.Packaging { /// <summary> /// This class represents the a PackagePart within a container. /// This is a part of the Packaging Layer APIs /// </summary> public abstract class PackagePart { //------------------------------------------------------ // // Public Constructors // //------------------------------------------------------ #region Protected Constructor /// <summary> /// Protected constructor for the abstract Base class. /// This is the current contract between the subclass and the base class /// If we decide some registration mechanism then this might change /// /// You should use this constructor in the rare case when you do not have /// the content type information related to this part and would prefer to /// obtain it later as required. /// /// These parts have the CompressionOption as NotCompressed by default. /// /// NOTE : If you are using this constructor from your subclass or passing a null /// for the content type parameter, be sure to implement the GetContentTypeCore /// method, as that will be called to get the content type value. This is provided /// to enable lazy initialization of the ContentType property. /// /// </summary> /// <param name="package">Package in which this part is being created</param> /// <param name="partUri">uri of the part</param> /// <exception cref="ArgumentNullException">If parameter "package" is null</exception> /// <exception cref="ArgumentNullException">If parameter "partUri" is null</exception> protected PackagePart(Package package, Uri partUri) : this(package, partUri, null, CompressionOption.NotCompressed) { } /// <summary> /// Protected constructor for the abstract Base class. /// This is the current contract between the subclass and the base class /// If we decide some registration mechanism then this might change /// /// These parts have the CompressionOption as NotCompressed by default. /// /// NOTE : If you are using this constructor from your subclass or passing a null /// for the content type parameter, be sure to implement the GetContentTypeCore /// method, as that will be called to get the content type value. This is provided /// to enable lazy initialization of the ContentType property. /// /// </summary> /// <param name="package">Package in which this part is being created</param> /// <param name="partUri">uri of the part</param> /// <param name="contentType">Content Type of the part, can be null if the value /// is unknown at the time of construction. However the value has to be made /// available anytime the ContentType property is called. A null value only indicates /// that the value will be provided later. Every PackagePart must have a valid /// Content Type</param> /// <exception cref="ArgumentNullException">If parameter "package" is null</exception> /// <exception cref="ArgumentNullException">If parameter "partUri" is null</exception> /// <exception cref="ArgumentException">If parameter "partUri" does not conform to the valid partUri syntax</exception> protected PackagePart(Package package, Uri partUri, string contentType) : this(package, partUri, contentType, CompressionOption.NotCompressed) { } /// <summary> /// Protected constructor for the abstract Base class. /// This is the current contract between the subclass and the base class /// If we decide some registration mechanism then this might change /// /// NOTE : If you are using this constructor from your subclass or passing a null /// for the content type parameter, be sure to implement the GetContentTypeCore /// method, as that will be called to get the content type value. This is provided /// to enable lazy initialization of the ContentType property. /// /// </summary> /// <param name="package">Package in which this part is being created</param> /// <param name="partUri">uri of the part</param> /// <param name="contentType">Content Type of the part, can be null if the value /// is unknown at the time of construction. However the value has to be made /// available anytime the ContentType property is called. A null value only indicates /// that the value will be provided later. Every PackagePart must have a valid /// Content Type</param> /// <param name="compressionOption">compression option for this part</param> /// <exception cref="ArgumentNullException">If parameter "package" is null</exception> /// <exception cref="ArgumentNullException">If parameter "partUri" is null</exception> /// <exception cref="ArgumentOutOfRangeException">If CompressionOption enumeration [compressionOption] does not have one of the valid values</exception> /// <exception cref="ArgumentException">If parameter "partUri" does not conform to the valid partUri syntax</exception> protected PackagePart(Package package, Uri partUri, string contentType, CompressionOption compressionOption) { if (package == null) throw new ArgumentNullException("package"); if (partUri == null) throw new ArgumentNullException("partUri"); Package.ThrowIfCompressionOptionInvalid(compressionOption); _uri = PackUriHelper.ValidatePartUri(partUri); _container = package; if (contentType == null) _contentType = null; else _contentType = new ContentType(contentType); _requestedStreams = null; _compressionOption = compressionOption; _isRelationshipPart = PackUriHelper.IsRelationshipPartUri(partUri); } #endregion Protected Constructor //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties /// <summary> /// The Uri for this PackagePart. It is always relative to the Package Root /// The PackagePart properties can not be accessed if the parent container is closed. /// </summary> /// <value></value> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> public Uri Uri { get { CheckInvalidState(); return _uri; } } /// <summary> /// The Content type of the stream that is represented by this part. /// The PackagePart properties can not be accessed if the parent container is closed. /// The content type value can be provided by the underlying physical format /// implementation at the time of creation of the Part object ( constructor ) or /// We can initialize it in a lazy manner when the ContentType property is called /// called for the first time by calling the GetContentTypeCore method. /// Note: This method GetContentTypeCore() is only for lazy initialization of the Content /// type value and will only be called once. There is no way to change the content type of /// the part once it has been assigned. /// </summary> /// <value>Content Type of the Part [can never return null] </value> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="InvalidOperationException">If the subclass fails to provide a non-null content type value.</exception> public string ContentType { get { CheckInvalidState(); if (_contentType == null) { //Lazy initialization for the content type string contentType = GetContentTypeCore(); if (contentType == null) { // We have seen this bug in the past and have said that this should be // treated as exception. If we get a null content type, it's an error. // We want to throw this exception so that anyone sub-classing this class // should not be setting the content type to null. Its like any other // parameter validation. This is the only place we can validate it. We // throw an ArgumentNullException, when the content type is set to null // in the constructor. // // We cannot get rid of this exception. At most, we can change it to // Debug.Assert. But then client code will see an Assert if they make // a mistake and that is also not desirable. // // PackagePart is a public API. throw new InvalidOperationException(SR.NullContentTypeProvided); } _contentType = new ContentType(contentType); } return _contentType.ToString(); } } /// <summary> /// The parent container for this PackagePart /// The PackagePart properties can not be accessed if the parent container is closed. /// </summary> /// <value></value> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> public Package Package { get { CheckInvalidState(); return _container; } } /// <summary> /// CompressionOption class that was provided as a parameter during the original CreatePart call. /// The PackagePart properties can not be accessed if the parent container is closed. /// </summary> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> public CompressionOption CompressionOption { get { CheckInvalidState(); return _compressionOption; } } #endregion Public Properties //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods #region Content Type Method /// <summary> /// Custom Implementation for the GetContentType Method /// This method should only be implemented by those physical format implementors where /// the value for the content type cannot be provided at the time of construction of /// Part object and if calculating the content type value is a non-trivial or costly /// operation. The return value has to be a valid ContentType. This method will be used in /// real corner cases. The most common usage should be to provide the content type in the /// constructor. /// This method is only for lazy initialization of the Content type value and will only /// be called once. There is no way to change the content type of the part once it is /// assigned. /// </summary> /// <returns>Content type for the Part</returns> /// <exception cref="NotSupportedException">By default, this method throws a NotSupportedException. If a subclass wants to /// initialize the content type for a PackagePart in a lazy manner they must override this method.</exception> protected virtual string GetContentTypeCore() { throw new NotSupportedException(SR.GetContentTypeCoreNotImplemented); } #endregion Content Type Method #region Stream Methods /// <summary> /// Returns the underlying stream that is represented by this part /// with the default FileMode and FileAccess /// Note: If you are requesting a stream for a relationship part and /// at the same time using relationship APIs to manipulate relationships, /// the final persisted data will depend on which data gets flushed last. /// </summary> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the subclass fails to provide a non-null stream object</exception> public Stream GetStream() { CheckInvalidState(); return GetStream(FileMode.OpenOrCreate, _container.FileOpenAccess); } /// <summary> /// Returns the underlying stream in the specified mode and the /// default FileAccess /// Note: If you are requesting a stream for a relationship part for editing /// and at the same time using relationship APIs to manipulate relationships, /// the final persisted data will depend on which data gets flushed last. /// </summary> /// <param name="mode"></param> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="ArgumentOutOfRangeException">If FileMode enumeration [mode] does not have one of the valid values</exception> /// <exception cref="IOException">If FileAccess.Read is provided and FileMode values are any of the following - /// FileMode.Create, FileMode.CreateNew, FileMode.Truncate, FileMode.Append</exception> /// <exception cref="IOException">If the mode and access for the Package and the Stream are not compatible</exception> /// <exception cref="IOException">If the subclass fails to provide a non-null stream object</exception> public Stream GetStream(FileMode mode) { CheckInvalidState(); return GetStream(mode, _container.FileOpenAccess); } /// <summary> /// Returns the underlying stream that is represented by this part /// in the specified mode with the access. /// Note: If you are requesting a stream for a relationship part and /// at the same time using relationship APIs to manipulate relationships, /// the final persisted data will depend on which data gets flushed last. /// </summary> /// <param name="mode"></param> /// <param name="access"></param> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="ArgumentOutOfRangeException">If FileMode enumeration [mode] does not have one of the valid values</exception> /// <exception cref="ArgumentOutOfRangeException">If FileAccess enumeration [access] does not have one of the valid values</exception> /// <exception cref="IOException">If FileAccess.Read is provided and FileMode values are any of the following - /// FileMode.Create, FileMode.CreateNew, FileMode.Truncate, FileMode.Append</exception> /// <exception cref="IOException">If the mode and access for the Package and the Stream are not compatible</exception> /// <exception cref="IOException">If the subclass fails to provide a non-null stream object</exception> public Stream GetStream(FileMode mode, FileAccess access) { CheckInvalidState(); ThrowIfOpenAccessModesAreIncompatible(mode, access); if (mode == FileMode.CreateNew) throw new ArgumentException(SR.CreateNewNotSupported); if (mode == FileMode.Truncate) throw new ArgumentException(SR.TruncateNotSupported); Stream s = GetStreamCore(mode, access); if (s == null) throw new IOException(SR.NullStreamReturned); //Detect if any stream implementations are returning all three //properties - CanSeek, CanWrite and CanRead as false. Such a //stream should be pretty much useless. And as per current programming //practice, these properties are all false, when the stream has been //disposed. Debug.Assert(!IsStreamClosed(s)); //Lazy init if (_requestedStreams == null) _requestedStreams = new List<Stream>(); //Default capacity is 4 //Delete all the closed streams from the _requestedStreams list. //Each time a new stream is handed out, we go through the list //to clean up streams that were handed out and have been closed. //Thus those stream can be garbage collected and we will avoid //keeping around stream objects that have been disposed CleanUpRequestedStreamsList(); _requestedStreams.Add(s); return s; } /// <summary> /// Custom Implementation for the GetSream Method /// </summary> /// <param name="mode"></param> /// <param name="access"></param> /// <returns></returns> protected abstract Stream GetStreamCore(FileMode mode, FileAccess access); #endregion Stream Methods #region PackageRelationship Methods /// <summary> /// Adds a relationship to this PackagePart with the Target PackagePart specified as the Uri /// Initial and trailing spaces in the name of the PackageRelationship are trimmed. /// </summary> /// <param name="targetUri"></param> /// <param name="targetMode">Enumeration indicating the base uri for the target uri</param> /// <param name="relationshipType">PackageRelationship type, having uri like syntax that is used to /// uniquely identify the role of the relationship</param> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is readonly, it cannot be modified</exception> /// <exception cref="ArgumentNullException">If parameter "targetUri" is null</exception> /// <exception cref="ArgumentNullException">If parameter "relationshipType" is null</exception> /// <exception cref="ArgumentOutOfRangeException">If parameter "targetMode" enumeration does not have a valid value</exception> /// <exception cref="ArgumentException">If TargetMode is TargetMode.Internal and the targetUri is an absolute Uri </exception> /// <exception cref="ArgumentException">If relationship is being targeted to a relationship part</exception> public PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType) { return CreateRelationship(targetUri, targetMode, relationshipType, null); } /// <summary> /// Adds a relationship to this PackagePart with the Target PackagePart specified as the Uri /// Initial and trailing spaces in the name of the PackageRelationship are trimmed. /// </summary> /// <param name="targetUri"></param> /// <param name="targetMode">Enumeration indicating the base uri for the target uri</param> /// <param name="relationshipType">PackageRelationship type, having uri like syntax that is used to /// uniquely identify the role of the relationship</param> /// <param name="id">String that conforms to the xsd:ID datatype. Unique across the source's /// relationships. Null is OK (ID will be generated). An empty string is an invalid XML ID.</param> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is readonly, it cannot be modified</exception> /// <exception cref="ArgumentNullException">If parameter "targetUri" is null</exception> /// <exception cref="ArgumentNullException">If parameter "relationshipType" is null</exception> /// <exception cref="ArgumentOutOfRangeException">If parameter "targetMode" enumeration does not have a valid value</exception> /// <exception cref="ArgumentException">If TargetMode is TargetMode.Internal and the targetUri is an absolute Uri </exception> /// <exception cref="ArgumentException">If relationship is being targeted to a relationship part</exception> /// <exception cref="System.Xml.XmlException">If parameter "id" is not a valid Xsd Id</exception> /// <exception cref="System.Xml.XmlException">If an id is provided in the method, and its not unique</exception> public PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType, String id) { CheckInvalidState(); _container.ThrowIfReadOnly(); EnsureRelationships(); //All parameter validation is done in the following method return _relationships.Add(targetUri, targetMode, relationshipType, id); } /// <summary> /// Deletes a relationship from the PackagePart. This is done based on the /// relationship's ID. The target PackagePart is not affected by this operation. /// </summary> /// <param name="id">The ID of the relationship to delete. An invalid ID will not /// throw an exception, but nothing will be deleted.</param> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is readonly, it cannot be modified</exception> /// <exception cref="ArgumentNullException">If parameter "id" is null</exception> /// <exception cref="System.Xml.XmlException">If parameter "id" is not a valid Xsd Id</exception> public void DeleteRelationship(string id) { CheckInvalidState(); _container.ThrowIfReadOnly(); if (id == null) throw new ArgumentNullException("id"); InternalRelationshipCollection.ThrowIfInvalidXsdId(id); EnsureRelationships(); _relationships.Delete(id); } /// <summary> /// Returns a collection of all the Relationships that are /// owned by this PackagePart /// </summary> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is write only, no information can be retrieved from it</exception> public PackageRelationshipCollection GetRelationships() { //All the validations for dispose and file access are done in the //GetRelationshipsHelper method. return GetRelationshipsHelper(null); } /// <summary> /// Returns a collection of filtered Relationships that are /// owned by this PackagePart /// The relationshipType string is compared with the type of the relationships /// in a case sensitive and culture ignorant manner. /// </summary> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is write only, no information can be retrieved from it</exception> /// <exception cref="ArgumentNullException">If parameter "relationshipType" is null</exception> /// <exception cref="ArgumentException">If parameter "relationshipType" is an empty string</exception> public PackageRelationshipCollection GetRelationshipsByType(string relationshipType) { //These checks are made in the GetRelationshipsHelper as well, but we make them //here as we need to perform parameter validation CheckInvalidState(); _container.ThrowIfWriteOnly(); if (relationshipType == null) throw new ArgumentNullException("relationshipType"); InternalRelationshipCollection.ThrowIfInvalidRelationshipType(relationshipType); return GetRelationshipsHelper(relationshipType); } /// <summary> /// Retrieve a relationship per ID. /// </summary> /// <param name="id">The relationship ID.</param> /// <returns>The relationship with ID 'id' or throw an exception if not found.</returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is write only, no information can be retrieved from it</exception> /// <exception cref="ArgumentNullException">If parameter "id" is null</exception> /// <exception cref="System.Xml.XmlException">If parameter "id" is not a valid Xsd Id</exception> /// <exception cref="InvalidOperationException">If the requested relationship does not exist in the Package</exception> public PackageRelationship GetRelationship(string id) { //All the validations for dispose and file access are done in the //GetRelationshipHelper method. PackageRelationship returnedRelationship = GetRelationshipHelper(id); if (returnedRelationship == null) throw new InvalidOperationException(SR.PackagePartRelationshipDoesNotExist); else return returnedRelationship; } /// <summary> /// Returns whether there is a relationship with the specified ID. /// </summary> /// <param name="id">The relationship ID.</param> /// <returns>true iff a relationship with ID 'id' is defined on this source.</returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is write only, no information can be retrieved from it</exception> /// <exception cref="ArgumentNullException">If parameter "id" is null</exception> /// <exception cref="System.Xml.XmlException">If parameter "id" is not a valid Xsd Id</exception> public bool RelationshipExists(string id) { //All the validations for dispose and file access are done in the //GetRelationshipHelper method. return (GetRelationshipHelper(id) != null); } #endregion PackageRelationship Methods #endregion Public Methods //------------------------------------------------------ // // Public Events // //------------------------------------------------------ // None //------------------------------------------------------ // // Internal Constructors // //------------------------------------------------------ // None //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties internal bool IsRelationshipPart { get { return _isRelationshipPart; } } //This property can be set to indicate if the part has been deleted internal bool IsDeleted { get { return _deleted; } set { _deleted = value; } } //This property can be set to indicate if the part has been deleted internal bool IsClosed { get { return _disposed; } } /// <summary> /// This property returns the content type of the part /// as a validated strongly typed ContentType object /// </summary> internal ContentType ValidatedContentType { get { return _contentType; } } #endregion Internal Properties //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods //Delete all the relationships for this part internal void ClearRelationships() { if (_relationships != null) _relationships.Clear(); } //Flush all the streams that are currently opened for this part and the relationships for this part //Note: This method is never be called on a deleted part internal void Flush() { Debug.Assert(_deleted != true, "PackagePart.Flush should never be called on a deleted part"); if (_requestedStreams != null) { foreach (Stream s in _requestedStreams) { // Streams in this list are never set to null, so we do not need to check for // stream being null; However it could be closed by some external code. In that case // this property (CanWrite) will still be accessible and we can check to see // whether we can call flush or no. if (s.CanWrite) s.Flush(); } } // Relationships for this part should have been flushed earlier in the Package.Flush method. } //Close all the streams that are open for this part. internal void Close() { if (!_disposed) { try { if (_requestedStreams != null) { //Adding this extra check here to optimize delete operation //Everytime we delete a part we close it before deleting to //ensure that its deleted in a valid state. However, we do not //need to persist any changes if the part is being deleted. if (!_deleted) { foreach (Stream s in _requestedStreams) { s.Dispose(); } } _requestedStreams.Clear(); } // Relationships for this part should have been flushed/closed earlier in the Package.Close method. } finally { _requestedStreams = null; //InternalRelationshipCollection is not required any more _relationships = null; //Once the container is closed there is no way to get to the stream or any other part //in the container. _container = null; //We do not need to explicitly call GC.SuppressFinalize(this) _disposed = true; } } } /// <summary> /// write the relationships part /// </summary> /// <remarks> /// </remarks> internal void FlushRelationships() { Debug.Assert(_deleted != true, "PackagePart.FlushRelationsips should never be called on a deleted part"); // flush relationships if (_relationships != null && _container.FileOpenAccess != FileAccess.Read) { _relationships.Flush(); } } internal void CloseRelationships() { if (!_deleted) { //Flush the relationships for this part. FlushRelationships(); } } #endregion Internal Methods //------------------------------------------------------ // // Internal Events // //------------------------------------------------------ // None //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods // lazy init private void EnsureRelationships() { if (_relationships == null) { // check here ThrowIfRelationship(); // obtain the relationships from the PackageRelationship part (if available) _relationships = new InternalRelationshipCollection(this); } } //Make sure that the access modes for the container and the part are compatible private void ThrowIfOpenAccessModesAreIncompatible(FileMode mode, FileAccess access) { Package.ThrowIfFileModeInvalid(mode); Package.ThrowIfFileAccessInvalid(access); //Creating a part using a readonly stream. if (access == FileAccess.Read && (mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate || mode == FileMode.Append)) throw new IOException(SR.UnsupportedCombinationOfModeAccess); //Incompatible access modes between container and part stream. if ((_container.FileOpenAccess == FileAccess.Read && access != FileAccess.Read) || (_container.FileOpenAccess == FileAccess.Write && access != FileAccess.Write)) throw new IOException(SR.ContainerAndPartModeIncompatible); } //Check if the part is in an invalid state private void CheckInvalidState() { ThrowIfPackagePartDeleted(); ThrowIfParentContainerClosed(); } //If the parent container is closed then the operations on this part like getting stream make no sense private void ThrowIfParentContainerClosed() { if (_container == null) throw new InvalidOperationException(SR.ParentContainerClosed); } //If the part has been deleted then we throw private void ThrowIfPackagePartDeleted() { if (_deleted == true) throw new InvalidOperationException(SR.PackagePartDeleted); } // some operations are invalid if we are a relationship part private void ThrowIfRelationship() { if (IsRelationshipPart) throw new InvalidOperationException(SR.RelationshipPartsCannotHaveRelationships); } /// <summary> /// Retrieve a relationship per ID. /// </summary> /// <param name="id">The relationship ID.</param> /// <returns>The relationship with ID 'id' or null if not found.</returns> private PackageRelationship GetRelationshipHelper(string id) { CheckInvalidState(); _container.ThrowIfWriteOnly(); if (id == null) throw new ArgumentNullException("id"); InternalRelationshipCollection.ThrowIfInvalidXsdId(id); EnsureRelationships(); return _relationships.GetRelationship(id); } /// <summary> /// Returns a collection of all the Relationships that are /// owned by this PackagePart, based on the filter string /// </summary> /// <returns></returns> private PackageRelationshipCollection GetRelationshipsHelper(string filterString) { CheckInvalidState(); _container.ThrowIfWriteOnly(); EnsureRelationships(); //Internally null is used to indicate that no filter string was specified and //and all the relationships should be returned. return new PackageRelationshipCollection(_relationships, filterString); } //Deletes all the streams that have been closed from the _requestedStreams list. private void CleanUpRequestedStreamsList() { if (_requestedStreams != null) { for (int i = _requestedStreams.Count - 1; i >= 0; i--) { if (IsStreamClosed(_requestedStreams[i])) _requestedStreams.RemoveAt(i); } } } //Detect if the stream has been closed. //When a stream is closed the three flags - CanSeek, CanRead and CanWrite //return false. These properties do not throw ObjectDisposedException. //So we rely on the values of these properties to determine if a stream //has been closed. private bool IsStreamClosed(Stream s) { return !s.CanRead && !s.CanSeek && !s.CanWrite; } #endregion Private Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Members private PackUriHelper.ValidatedPartUri _uri; private Package _container; private ContentType _contentType; private List<Stream> _requestedStreams; private InternalRelationshipCollection _relationships; private CompressionOption _compressionOption = CompressionOption.NotCompressed; private bool _disposed; private bool _deleted; private bool _isRelationshipPart; #endregion Private Members } }
#region --- License --- /* Copyright (c) 2006-2008 the OpenTK team. * See license.txt for license info * * Contributions by Andy Gill. */ #endregion #region --- Using Directives --- using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Reflection; using System.Diagnostics; using System.Reflection.Emit; #endregion namespace OpenTK.Graphics.OpenGL { /// <summary> /// OpenGL bindings for .NET, implementing the full OpenGL API, including extensions. /// </summary> /// <remarks> /// <para> /// This class contains all OpenGL enums and functions defined in the latest OpenGL specification. /// The official .spec files can be found at: http://opengl.org/registry/. /// </para> /// <para> A valid OpenGL context must be created before calling any OpenGL function.</para> /// <para> /// Use the GL.Load and GL.LoadAll methods to prepare function entry points prior to use. To maintain /// cross-platform compatibility, this must be done for both core and extension functions. The GameWindow /// and the GLControl class will take care of this automatically. /// </para> /// <para> /// You can use the GL.SupportsExtension method to check whether any given category of extension functions /// exists in the current OpenGL context. Keep in mind that different OpenGL contexts may support different /// extensions, and under different entry points. Always check if all required extensions are still supported /// when changing visuals or pixel formats. /// </para> /// <para> /// You may retrieve the entry point for an OpenGL function using the GL.GetDelegate method. /// </para> /// </remarks> /// <see href="http://opengl.org/registry/"/> public sealed partial class GL : GraphicsBindingsBase { #region --- Fields --- internal const string Library = "opengl32.dll"; static SortedList<string, bool> AvailableExtensions = new SortedList<string, bool>(); static readonly object sync_root = new object(); #endregion #region --- Constructor --- static GL() { } #endregion #region --- Public Members --- /// <summary> /// Loads all OpenGL entry points (core and extension). /// This method is provided for compatibility purposes with older OpenTK versions. /// </summary> [Obsolete("If you are using a context constructed outside of OpenTK, create a new GraphicsContext and pass your context handle to it. Otherwise, there is no need to call this method.")] public static void LoadAll() { new GL().LoadEntryPoints(); } #endregion #region --- Protected Members --- /// <summary> /// Returns a synchronization token unique for the GL class. /// </summary> protected override object SyncRoot { get { return sync_root; } } #endregion #region --- GL Overloads --- #pragma warning disable 3019 #pragma warning disable 1591 #pragma warning disable 1572 #pragma warning disable 1573 // Note: Mono 1.9.1 truncates StringBuilder results (for 'out string' parameters). // We work around this issue by doubling the StringBuilder capacity. #region public static void Color[34]() overloads public static void Color3(System.Drawing.Color color) { GL.Color3(color.R, color.G, color.B); } public static void Color4(System.Drawing.Color color) { GL.Color4(color.R, color.G, color.B, color.A); } public static void Color3(Vector3 color) { GL.Color3(color.X, color.Y, color.Z); } public static void Color4(Vector4 color) { GL.Color4(color.X, color.Y, color.Z, color.W); } public static void Color4(Color4 color) { GL.Color4(color.R, color.G, color.B, color.A); } #endregion #region public static void ClearColor() overloads public static void ClearColor(System.Drawing.Color color) { GL.ClearColor(color.R / 255.0f, color.G / 255.0f, color.B / 255.0f, color.A / 255.0f); } public static void ClearColor(Color4 color) { GL.ClearColor(color.R, color.G, color.B, color.A); } #endregion #region public static void BlendColor() overloads public static void BlendColor(System.Drawing.Color color) { GL.BlendColor(color.R / 255.0f, color.G / 255.0f, color.B / 255.0f, color.A / 255.0f); } public static void BlendColor(Color4 color) { GL.BlendColor(color.R, color.G, color.B, color.A); } #endregion #region public static void Material() overloads public static void Material(MaterialFace face, MaterialParameter pname, Vector4 @params) { unsafe { Material(face, pname, (float*)&@params.X); } } public static void Material(MaterialFace face, MaterialParameter pname, Color4 @params) { unsafe { GL.Material(face, pname, (float*)&@params); } } #endregion #region public static void Light() overloads public static void Light(LightName name, LightParameter pname, Vector4 @params) { unsafe { GL.Light(name, pname, (float*)&@params.X); } } public static void Light(LightName name, LightParameter pname, Color4 @params) { unsafe { GL.Light(name, pname, (float*)&@params); } } #endregion #region Normal|RasterPos|Vertex|TexCoord|Rotate|Scale|Translate|*Matrix public static void Normal3(Vector3 normal) { GL.Normal3(normal.X, normal.Y, normal.Z); } public static void RasterPos2(Vector2 pos) { GL.RasterPos2(pos.X, pos.Y); } public static void RasterPos3(Vector3 pos) { GL.RasterPos3(pos.X, pos.Y, pos.Z); } public static void RasterPos4(Vector4 pos) { GL.RasterPos4(pos.X, pos.Y, pos.Z, pos.W); } public static void Vertex2(Vector2 v) { GL.Vertex2(v.X, v.Y); } public static void Vertex3(Vector3 v) { GL.Vertex3(v.X, v.Y, v.Z); } public static void Vertex4(Vector4 v) { GL.Vertex4(v.X, v.Y, v.Z, v.W); } public static void TexCoord2(Vector2 v) { GL.TexCoord2(v.X, v.Y); } public static void TexCoord3(Vector3 v) { GL.TexCoord3(v.X, v.Y, v.Z); } public static void TexCoord4(Vector4 v) { GL.TexCoord4(v.X, v.Y, v.Z, v.W); } public static void Rotate(Single angle, Vector3 axis) { GL.Rotate((Single)angle, axis.X, axis.Y, axis.Z); } public static void Scale(Vector3 scale) { GL.Scale(scale.X, scale.Y, scale.Z); } public static void Translate(Vector3 trans) { GL.Translate(trans.X, trans.Y, trans.Z); } public static void MultMatrix(ref Matrix4 mat) { unsafe { fixed (Single* m_ptr = &mat.Row0.X) { GL.MultMatrix((Single*)m_ptr); } } } public static void LoadMatrix(ref Matrix4 mat) { unsafe { fixed (Single* m_ptr = &mat.Row0.X) { GL.LoadMatrix((Single*)m_ptr); } } } public static void LoadTransposeMatrix(ref Matrix4 mat) { unsafe { fixed (Single* m_ptr = &mat.Row0.X) { GL.LoadTransposeMatrix((Single*)m_ptr); } } } public static void MultTransposeMatrix(ref Matrix4 mat) { unsafe { fixed (Single* m_ptr = &mat.Row0.X) { GL.MultTransposeMatrix((Single*)m_ptr); } } } public static void UniformMatrix4(int location, bool transpose, ref Matrix4 matrix) { unsafe { fixed (float* matrix_ptr = &matrix.Row0.X) { GL.UniformMatrix4(location, 1, transpose, matrix_ptr); } } } public static void Normal3(Vector3d normal) { GL.Normal3(normal.X, normal.Y, normal.Z); } public static void RasterPos2(Vector2d pos) { GL.RasterPos2(pos.X, pos.Y); } public static void RasterPos3(Vector3d pos) { GL.RasterPos3(pos.X, pos.Y, pos.Z); } public static void RasterPos4(Vector4d pos) { GL.RasterPos4(pos.X, pos.Y, pos.Z, pos.W); } public static void Vertex2(Vector2d v) { GL.Vertex2(v.X, v.Y); } public static void Vertex3(Vector3d v) { GL.Vertex3(v.X, v.Y, v.Z); } public static void Vertex4(Vector4d v) { GL.Vertex4(v.X, v.Y, v.Z, v.W); } public static void TexCoord2(Vector2d v) { GL.TexCoord2(v.X, v.Y); } public static void TexCoord3(Vector3d v) { GL.TexCoord3(v.X, v.Y, v.Z); } public static void TexCoord4(Vector4d v) { GL.TexCoord4(v.X, v.Y, v.Z, v.W); } public static void Rotate(double angle, Vector3d axis) { GL.Rotate((double)angle, axis.X, axis.Y, axis.Z); } public static void Scale(Vector3d scale) { GL.Scale(scale.X, scale.Y, scale.Z); } public static void Translate(Vector3d trans) { GL.Translate(trans.X, trans.Y, trans.Z); } public static void MultMatrix(ref Matrix4d mat) { unsafe { fixed (Double* m_ptr = &mat.Row0.X) { GL.MultMatrix((Double*)m_ptr); } } } public static void LoadMatrix(ref Matrix4d mat) { unsafe { fixed (Double* m_ptr = &mat.Row0.X) { GL.LoadMatrix((Double*)m_ptr); } } } public static void LoadTransposeMatrix(ref Matrix4d mat) { unsafe { fixed (Double* m_ptr = &mat.Row0.X) { GL.LoadTransposeMatrix((Double*)m_ptr); } } } public static void MultTransposeMatrix(ref Matrix4d mat) { unsafe { fixed (Double* m_ptr = &mat.Row0.X) { GL.MultTransposeMatrix((Double*)m_ptr); } } } #region Uniform [CLSCompliant(false)] public static void Uniform2(int location, ref Vector2 vector) { GL.Uniform2(location, vector.X, vector.Y); } [CLSCompliant(false)] public static void Uniform3(int location, ref Vector3 vector) { GL.Uniform3(location, vector.X, vector.Y, vector.Z); } [CLSCompliant(false)] public static void Uniform4(int location, ref Vector4 vector) { GL.Uniform4(location, vector.X, vector.Y, vector.Z, vector.W); } public static void Uniform2(int location, Vector2 vector) { GL.Uniform2(location, vector.X, vector.Y); } public static void Uniform3(int location, Vector3 vector) { GL.Uniform3(location, vector.X, vector.Y, vector.Z); } public static void Uniform4(int location, Vector4 vector) { GL.Uniform4(location, vector.X, vector.Y, vector.Z, vector.W); } public static void Uniform4(int location, Color4 color) { GL.Uniform4(location, color.R, color.G, color.B, color.A); } public static void Uniform4(int location, Quaternion quaternion) { GL.Uniform4(location, quaternion.X, quaternion.Y, quaternion.Z, quaternion.W); } #endregion #endregion #region Shaders #region GetActiveAttrib public static string GetActiveAttrib(int program, int index, out int size, out ActiveAttribType type) { int length; GetProgram(program, OpenTK.Graphics.OpenGL.ProgramParameter.ActiveAttributeMaxLength, out length); StringBuilder sb = new StringBuilder(length == 0 ? 1 : length * 2); GetActiveAttrib(program, index, sb.Capacity, out length, out size, out type, sb); return sb.ToString(); } #endregion #region GetActiveUniform public static string GetActiveUniform(int program, int uniformIndex, out int size, out ActiveUniformType type) { int length; GetProgram(program, OpenTK.Graphics.OpenGL.ProgramParameter.ActiveUniformMaxLength, out length); StringBuilder sb = new StringBuilder(length == 0 ? 1 : length); GetActiveUniform(program, uniformIndex, sb.Capacity, out length, out size, out type, sb); return sb.ToString(); } #endregion #region GetActiveUniformName public static string GetActiveUniformName(int program, int uniformIndex) { int length; GetProgram(program, OpenTK.Graphics.OpenGL.ProgramParameter.ActiveUniformMaxLength, out length); StringBuilder sb = new StringBuilder(length == 0 ? 1 : length * 2); GetActiveUniformName(program, uniformIndex, sb.Capacity, out length, sb); return sb.ToString(); } #endregion #region GetActiveUniformBlockName public static string GetActiveUniformBlockName(int program, int uniformIndex) { int length; GetProgram(program, OpenTK.Graphics.OpenGL.ProgramParameter.ActiveUniformBlockMaxNameLength, out length); StringBuilder sb = new StringBuilder(length == 0 ? 1 : length * 2); GetActiveUniformBlockName(program, uniformIndex, sb.Capacity, out length, sb); return sb.ToString(); } #endregion #region public static void ShaderSource(Int32 shader, System.String @string) public static void ShaderSource(Int32 shader, System.String @string) { unsafe { int length = @string.Length; GL.ShaderSource((UInt32)shader, 1, new string[] { @string }, &length); } } #endregion #region public static string GetShaderInfoLog(Int32 shader) public static string GetShaderInfoLog(Int32 shader) { string info; GetShaderInfoLog(shader, out info); return info; } #endregion #region public static void GetShaderInfoLog(Int32 shader, out string info) public static void GetShaderInfoLog(Int32 shader, out string info) { unsafe { int length; GL.GetShader(shader, ShaderParameter.InfoLogLength, out length); if (length == 0) { info = String.Empty; return; } StringBuilder sb = new StringBuilder(length * 2); GL.GetShaderInfoLog((UInt32)shader, sb.Capacity, &length, sb); info = sb.ToString(); } } #endregion #region public static string GetProgramInfoLog(Int32 program) public static string GetProgramInfoLog(Int32 program) { string info; GetProgramInfoLog(program, out info); return info; } #endregion #region public static void GetProgramInfoLog(Int32 program, out string info) public static void GetProgramInfoLog(Int32 program, out string info) { unsafe { int length; GL.GetProgram(program, OpenTK.Graphics.OpenGL.ProgramParameter.InfoLogLength, out length); if (length == 0) { info = String.Empty; return; } StringBuilder sb = new StringBuilder(length * 2); GL.GetProgramInfoLog((UInt32)program, sb.Capacity, &length, sb); info = sb.ToString(); } } #endregion #endregion #region public static void PointParameter(PointSpriteCoordOriginParameter param) /// <summary> /// Helper function that defines the coordinate origin of the Point Sprite. /// </summary> /// <param name="param"> /// A OpenTK.Graphics.OpenGL.GL.PointSpriteCoordOriginParameter token, /// denoting the origin of the Point Sprite. /// </param> public static void PointParameter(PointSpriteCoordOriginParameter param) { GL.PointParameter(PointParameterName.PointSpriteCoordOrigin, (int)param); } #endregion #region VertexAttrib|MultiTexCoord [CLSCompliant(false)] public static void VertexAttrib2(Int32 index, ref Vector2 v) { GL.VertexAttrib2(index, v.X, v.Y); } [CLSCompliant(false)] public static void VertexAttrib3(Int32 index, ref Vector3 v) { GL.VertexAttrib3(index, v.X, v.Y, v.Z); } [CLSCompliant(false)] public static void VertexAttrib4(Int32 index, ref Vector4 v) { GL.VertexAttrib4(index, v.X, v.Y, v.Z, v.W); } public static void VertexAttrib2(Int32 index, Vector2 v) { GL.VertexAttrib2(index, v.X, v.Y); } public static void VertexAttrib3(Int32 index, Vector3 v) { GL.VertexAttrib3(index, v.X, v.Y, v.Z); } public static void VertexAttrib4(Int32 index, Vector4 v) { GL.VertexAttrib4(index, v.X, v.Y, v.Z, v.W); } public static void MultiTexCoord2(TextureUnit target, ref Vector2 v) { GL.MultiTexCoord2(target, v.X, v.Y); } public static void MultiTexCoord3(TextureUnit target, ref Vector3 v) { GL.MultiTexCoord3(target, v.X, v.Y, v.Z); } public static void MultiTexCoord4(TextureUnit target, ref Vector4 v) { GL.MultiTexCoord4(target, v.X, v.Y, v.Z, v.W); } [CLSCompliant(false)] public static void VertexAttrib2(Int32 index, ref Vector2d v) { GL.VertexAttrib2(index, v.X, v.Y); } [CLSCompliant(false)] public static void VertexAttrib3(Int32 index, ref Vector3d v) { GL.VertexAttrib3(index, v.X, v.Y, v.Z); } [CLSCompliant(false)] public static void VertexAttrib4(Int32 index, ref Vector4d v) { GL.VertexAttrib4(index, v.X, v.Y, v.Z, v.W); } public static void VertexAttrib2(Int32 index, Vector2d v) { GL.VertexAttrib2(index, v.X, v.Y); } public static void VertexAttrib3(Int32 index, Vector3d v) { GL.VertexAttrib3(index, v.X, v.Y, v.Z); } public static void VertexAttrib4(Int32 index, Vector4d v) { GL.VertexAttrib4(index, v.X, v.Y, v.Z, v.W); } public static void MultiTexCoord2(TextureUnit target, ref Vector2d v) { GL.MultiTexCoord2(target, v.X, v.Y); } public static void MultiTexCoord3(TextureUnit target, ref Vector3d v) { GL.MultiTexCoord3(target, v.X, v.Y, v.Z); } public static void MultiTexCoord4(TextureUnit target, ref Vector4d v) { GL.MultiTexCoord4(target, v.X, v.Y, v.Z, v.W); } #endregion #region Rect public static void Rect(System.Drawing.RectangleF rect) { GL.Rect(rect.Left, rect.Top, rect.Right, rect.Bottom); } public static void Rect(System.Drawing.Rectangle rect) { GL.Rect(rect.Left, rect.Top, rect.Right, rect.Bottom); } [CLSCompliant(false)] public static void Rect(ref System.Drawing.RectangleF rect) { GL.Rect(rect.Left, rect.Top, rect.Right, rect.Bottom); } [CLSCompliant(false)] public static void Rect(ref System.Drawing.Rectangle rect) { GL.Rect(rect.Left, rect.Top, rect.Right, rect.Bottom); } #endregion #region public static int GenTexture() public static int GenTexture() { int id; GenTextures(1, out id); return id; } #endregion #region DeleteTexture public static void DeleteTexture(int id) { DeleteTextures(1, ref id); } [CLSCompliant(false)] public static void DeleteTexture(uint id) { DeleteTextures(1, ref id); } #endregion #region [Vertex|Normal|Index|Color|FogCoord|VertexAttrib]Pointer public static void VertexPointer(int size, VertexPointerType type, int stride, int offset) { VertexPointer(size, type, stride, (IntPtr)offset); } public static void NormalPointer(NormalPointerType type, int stride, int offset) { NormalPointer(type, stride, (IntPtr)offset); } public static void IndexPointer(IndexPointerType type, int stride, int offset) { IndexPointer(type, stride, (IntPtr)offset); } public static void ColorPointer(int size, ColorPointerType type, int stride, int offset) { ColorPointer(size, type, stride, (IntPtr)offset); } public static void FogCoordPointer(FogPointerType type, int stride, int offset) { FogCoordPointer(type, stride, (IntPtr)offset); } public static void EdgeFlagPointer(int stride, int offset) { EdgeFlagPointer(stride, (IntPtr)offset); } public static void TexCoordPointer(int size, TexCoordPointerType type, int stride, int offset) { TexCoordPointer(size, type, stride, (IntPtr)offset); } public static void VertexAttribPointer(int index, int size, VertexAttribPointerType type, bool normalized, int stride, int offset) { VertexAttribPointer(index, size, type, normalized, stride, (IntPtr)offset); } #endregion #region DrawElements public static void DrawElements(BeginMode mode, int count, DrawElementsType type, int offset) { DrawElements(mode, count, type, new IntPtr(offset)); } #endregion #region Get[Float|Double] public static void GetFloat(GetPName pname, out Vector2 vector) { unsafe { fixed (Vector2* ptr = &vector) GetFloat(pname, (float*)ptr); } } public static void GetFloat(GetPName pname, out Vector3 vector) { unsafe { fixed (Vector3* ptr = &vector) GetFloat(pname, (float*)ptr); } } public static void GetFloat(GetPName pname, out Vector4 vector) { unsafe { fixed (Vector4* ptr = &vector) GetFloat(pname, (float*)ptr); } } public static void GetFloat(GetPName pname, out Matrix4 matrix) { unsafe { fixed (Matrix4* ptr = &matrix) GetFloat(pname, (float*)ptr); } } public static void GetDouble(GetPName pname, out Vector2d vector) { unsafe { fixed (Vector2d* ptr = &vector) GetDouble(pname, (double*)ptr); } } public static void GetDouble(GetPName pname, out Vector3d vector) { unsafe { fixed (Vector3d* ptr = &vector) GetDouble(pname, (double*)ptr); } } public static void GetDouble(GetPName pname, out Vector4d vector) { unsafe { fixed (Vector4d* ptr = &vector) GetDouble(pname, (double*)ptr); } } public static void GetDouble(GetPName pname, out Matrix4d matrix) { unsafe { fixed (Matrix4d* ptr = &matrix) GetDouble(pname, (double*)ptr); } } #endregion #region Viewport public static void Viewport(System.Drawing.Size size) { GL.Viewport(0, 0, size.Width, size.Height); } public static void Viewport(System.Drawing.Point location, System.Drawing.Size size) { GL.Viewport(location.X, location.Y, size.Width, size.Height); } public static void Viewport(System.Drawing.Rectangle rectangle) { GL.Viewport(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height); } #if NO_SYSDRAWING public static void Viewport(OpenTK.Point location, OpenTK.Size size) { GL.Viewport(location.X, location.Y, size.Width, size.Height); } public static void Viewport(OpenTK.Rectangle rectangle) { GL.Viewport(rectangle.X, rectangle.Y, rectangle.Width, rectangle.Height); } #endif #endregion #region TexEnv public static void TexEnv(TextureEnvTarget target, TextureEnvParameter pname, System.Drawing.Color color) { Color4 c = new Color4(color.R, color.G, color.B, color.A); unsafe { TexEnv(target, pname, &c.R); } } public static void TexEnv(TextureEnvTarget target, TextureEnvParameter pname, Color4 color) { unsafe { TexEnv(target, pname, &color.R); } } #endregion #region Obsolete [AutoGenerated(Category = "Version11Deprecated", Version = "1.1", EntryPoint = "glDisableClientState")] [Obsolete("Use DisableClientState(ArrayCap) instead.")] public static void DisableClientState(OpenTK.Graphics.OpenGL.EnableCap array) { DisableClientState((ArrayCap)array); } [AutoGenerated(Category = "Version11Deprecated", Version = "1.1", EntryPoint = "glEnableClientState")] [Obsolete("Use EnableClientState(ArrayCap) instead.")] public static void EnableClientState(OpenTK.Graphics.OpenGL.EnableCap array) { EnableClientState((ArrayCap)array); } [AutoGenerated(Category = "ArbUniformBufferObject", Version = "2.0", EntryPoint = "glGetActiveUniformsiv")] [Obsolete("Use GetActiveUniforms(..., ActiveUniformParameter, ...) instead.")] public static void GetActiveUniforms(Int32 program, Int32 uniformCount, Int32[] uniformIndices, ArbUniformBufferObject pname, [OutAttribute] Int32[] @params) { GetActiveUniforms(program, uniformCount, uniformIndices, (ActiveUniformParameter)pname, @params); } [AutoGenerated(Category = "ArbUniformBufferObject", Version = "2.0", EntryPoint = "glGetActiveUniformsiv")] [Obsolete("Use GetActiveUniforms(..., ActiveUniformParameter, ...) instead.")] public static void GetActiveUniforms(Int32 program, Int32 uniformCount, ref Int32 uniformIndices, ArbUniformBufferObject pname, [OutAttribute] out Int32 @params) { GetActiveUniforms(program, uniformCount, ref uniformIndices, (ActiveUniformParameter)pname, out @params); } [System.CLSCompliant(false)] [AutoGenerated(Category = "ArbUniformBufferObject", Version = "2.0", EntryPoint = "glGetActiveUniformsiv")] [Obsolete("Use GetActiveUniforms(..., ActiveUniformParameter, ...) instead.")] public static unsafe void GetActiveUniforms(Int32 program, Int32 uniformCount, Int32* uniformIndices, ArbUniformBufferObject pname, [OutAttribute] Int32* @params) { GetActiveUniforms(program, uniformCount, uniformIndices, (ActiveUniformParameter)pname, @params); } [System.CLSCompliant(false)] [AutoGenerated(Category = "ArbUniformBufferObject", Version = "2.0", EntryPoint = "glGetActiveUniformsiv")] [Obsolete("Use GetActiveUniforms(..., ActiveUniformParameter, ...) instead.")] public static void GetActiveUniforms(UInt32 program, Int32 uniformCount, UInt32[] uniformIndices, ArbUniformBufferObject pname, [OutAttribute] Int32[] @params) { GetActiveUniforms(program, uniformCount, uniformIndices, (ActiveUniformParameter)pname, @params); } [System.CLSCompliant(false)] [AutoGenerated(Category = "ArbUniformBufferObject", Version = "2.0", EntryPoint = "glGetActiveUniformsiv")] [Obsolete("Use GetActiveUniforms(..., ActiveUniformParameter, ...) instead.")] public static void GetActiveUniforms(UInt32 program, Int32 uniformCount, ref UInt32 uniformIndices, ArbUniformBufferObject pname, [OutAttribute] out Int32 @params) { GetActiveUniforms(program, uniformCount, ref uniformIndices, (ActiveUniformParameter)pname, out @params); } [System.CLSCompliant(false)] [AutoGenerated(Category = "ArbUniformBufferObject", Version = "2.0", EntryPoint = "glGetActiveUniformsiv")] [Obsolete("Use GetActiveUniforms(..., ActiveUniformParameter, ...) instead.")] public static unsafe void GetActiveUniforms(UInt32 program, Int32 uniformCount, UInt32* uniformIndices, ArbUniformBufferObject pname, [OutAttribute] Int32* @params) { GetActiveUniforms(program, uniformCount, uniformIndices, (ActiveUniformParameter)pname, @params); } public static partial class Arb { [AutoGenerated(Category = "ArbGeometryShader4", Version = "3.0", EntryPoint = "glProgramParameteriARB")] [Obsolete("Use ProgramParameter(..., AssemblyProgramParameterArb, ...) instead.")] public static void ProgramParameter(Int32 program, ArbGeometryShader4 pname, Int32 value) { ProgramParameter(program, (AssemblyProgramParameterArb)pname, value); } [AutoGenerated(Category = "ArbGeometryShader4", Version = "3.0", EntryPoint = "glProgramParameteriARB")] [Obsolete("Use ProgramParameter(..., AssemblyProgramParameterArb, ...) instead.")] [CLSCompliant(false)] public static void ProgramParameter(UInt32 program, ArbGeometryShader4 pname, Int32 value) { ProgramParameter(program, (AssemblyProgramParameterArb)pname, value); } } public static partial class Ext { [AutoGenerated(Category = "EXT_geometry_shader4", Version = "2.0", EntryPoint = "glProgramParameteriEXT")] [Obsolete("Use ProgramParameter(..., AssemblyProgramParameterArb, ...) instead.")] public static void ProgramParameter(Int32 program, ExtGeometryShader4 pname, Int32 value) { ProgramParameter(program, (AssemblyProgramParameterArb)pname, value); } [AutoGenerated(Category = "ArbGeometryShader4", Version = "3.0", EntryPoint = "glProgramParameteriARB")] [Obsolete("Use ProgramParameter(..., AssemblyProgramParameterArb, ...) instead.")] [CLSCompliant(false)] public static void ProgramParameter(UInt32 program, ExtGeometryShader4 pname, Int32 value) { ProgramParameter(program, (AssemblyProgramParameterArb)pname, value); } } #endregion #pragma warning restore 3019 #pragma warning restore 1591 #pragma warning restore 1572 #pragma warning restore 1573 #endregion } public delegate void DebugProcAmd(int id, AmdDebugOutput category, AmdDebugOutput severity, IntPtr length, string message, IntPtr userParam); public delegate void DebugProcArb(int id, ArbDebugOutput category, ArbDebugOutput severity, IntPtr length, string message, IntPtr userParam); }
using System; using System.Collections.Generic; using System.Text; namespace Entitas { /// Use pool.CreateEntity() to create a new entity and /// pool.DestroyEntity() to destroy it. /// You can add, replace and remove IComponent to an entity. public partial class Entity { /// Occurs when a component gets added. /// All event handlers will be removed when /// the entity gets destroyed by the pool. public event EntityChanged OnComponentAdded; /// Occurs when a component gets removed. /// All event handlers will be removed when /// the entity gets destroyed by the pool. public event EntityChanged OnComponentRemoved; /// Occurs when a component gets replaced. /// All event handlers will be removed when /// the entity gets destroyed by the pool. public event ComponentReplaced OnComponentReplaced; /// Occurs when an entity gets released and is not retained anymore. /// All event handlers will be removed when /// the entity gets destroyed by the pool. public event EntityReleased OnEntityReleased; public delegate void EntityChanged( Entity entity, int index, IComponent component ); public delegate void ComponentReplaced( Entity entity, int index, IComponent previousComponent, IComponent newComponent ); public delegate void EntityReleased(Entity entity); /// The total amount of components an entity can possibly have. public int totalComponents { get { return _totalComponents; } } /// Each entity has its own unique creationIndex which will be set by /// the pool when you create the entity. public int creationIndex { get { return _creationIndex; } } /// The pool manages the state of an entity. /// Active entities are enabled, destroyed entities are not. public bool isEnabled { get { return _isEnabled; } } /// componentPools is set by the pool which created the entity and /// is used to reuse removed components. /// Removed components will be pushed to the componentPool. /// Use entity.CreateComponent(index, type) to get a new or /// reusable component from the componentPool. /// Use entity.GetComponentPool(index) to get a componentPool for /// a specific component index. public Stack<IComponent>[] componentPools { get { return _componentPools; } } /// The poolMetaData is set by the pool which created the entity and /// contains information about the pool. /// It's used to provide better error messages. public PoolMetaData poolMetaData { get { return _poolMetaData; } } internal int _creationIndex; internal bool _isEnabled = true; readonly int _totalComponents; readonly IComponent[] _components; readonly Stack<IComponent>[] _componentPools; readonly PoolMetaData _poolMetaData; IComponent[] _componentsCache; int[] _componentIndicesCache; string _toStringCache; /// Use pool.CreateEntity() to create a new entity and /// pool.DestroyEntity() to destroy it. public Entity(int totalComponents, Stack<IComponent>[] componentPools, PoolMetaData poolMetaData = null) { _totalComponents = totalComponents; _components = new IComponent[totalComponents]; _componentPools = componentPools; if(poolMetaData != null) { _poolMetaData = poolMetaData; } else { // If pool.CreateEntity() was used to create the entity, // we will never end up here. // This is a fallback when entities are created manually. var componentNames = new string[totalComponents]; for(int i = 0; i < componentNames.Length; i++) { componentNames[i] = i.ToString(); } _poolMetaData = new PoolMetaData( "No Pool", componentNames, null ); } } /// Adds a component at the specified index. /// You can only have one component at an index. /// Each component type must have its own constant index. /// The prefered way is to use the /// generated methods from the code generator. public Entity AddComponent(int index, IComponent component) { if(!_isEnabled) { throw new EntityIsNotEnabledException( "Cannot add component '" + _poolMetaData.componentNames[index] + "' to " + this + "!" ); } if(HasComponent(index)) { throw new EntityAlreadyHasComponentException( index, "Cannot add component '" + _poolMetaData.componentNames[index] + "' to " + this + "!", "You should check if an entity already has the component " + "before adding it or use entity.ReplaceComponent()." ); } _components[index] = component; _componentsCache = null; _componentIndicesCache = null; _toStringCache = null; if(OnComponentAdded != null) { OnComponentAdded(this, index, component); } return this; } /// Removes a component at the specified index. /// You can only remove a component at an index if it exists. /// The prefered way is to use the /// generated methods from the code generator. public Entity RemoveComponent(int index) { if(!_isEnabled) { throw new EntityIsNotEnabledException( "Cannot remove component '" + _poolMetaData.componentNames[index] + "' from " + this + "!" ); } if(!HasComponent(index)) { throw new EntityDoesNotHaveComponentException( index, "Cannot remove component '" + _poolMetaData.componentNames[index] + "' from " + this + "!", "You should check if an entity has the component" + "before removing it." ); } replaceComponent(index, null); return this; } /// Replaces an existing component at the specified index /// or adds it if it doesn't exist yet. /// The prefered way is to use the /// generated methods from the code generator. public Entity ReplaceComponent(int index, IComponent component) { if(!_isEnabled) { throw new EntityIsNotEnabledException( "Cannot replace component '" + _poolMetaData.componentNames[index] + "' on " + this + "!" ); } if(HasComponent(index)) { replaceComponent(index, component); } else if(component != null) { AddComponent(index, component); } return this; } void replaceComponent(int index, IComponent replacement) { var previousComponent = _components[index]; if(replacement != previousComponent) { _components[index] = replacement; _componentsCache = null; if(replacement != null) { if(OnComponentReplaced != null) { OnComponentReplaced( this, index, previousComponent, replacement ); } } else { _componentIndicesCache = null; _toStringCache = null; if(OnComponentRemoved != null) { OnComponentRemoved(this, index, previousComponent); } } GetComponentPool(index).Push(previousComponent); } else { if(OnComponentReplaced != null) { OnComponentReplaced( this, index, previousComponent, replacement ); } } } /// Returns a component at the specified index. /// You can only get a component at an index if it exists. /// The prefered way is to use the /// generated methods from the code generator. public IComponent GetComponent(int index) { if(!HasComponent(index)) { throw new EntityDoesNotHaveComponentException( index, "Cannot get component '" + _poolMetaData.componentNames[index] + "' from " + this + "!", "You should check if an entity has the component" + "before getting it." ); } return _components[index]; } /// Returns all added components. public IComponent[] GetComponents() { if(_componentsCache == null) { var components = EntitasCache.GetIComponentList(); for(int i = 0; i < _components.Length; i++) { var component = _components[i]; if(component != null) { components.Add(component); } } _componentsCache = components.ToArray(); EntitasCache.PushIComponentList(components); } return _componentsCache; } /// Returns all indices of added components. public int[] GetComponentIndices() { if(_componentIndicesCache == null) { var indices = EntitasCache.GetIntList(); for(int i = 0; i < _components.Length; i++) { if(_components[i] != null) { indices.Add(i); } } _componentIndicesCache = indices.ToArray(); EntitasCache.PushIntList(indices); } return _componentIndicesCache; } /// Determines whether this entity has a component /// at the specified index. public bool HasComponent(int index) { return _components[index] != null; } /// Determines whether this entity has components /// at all the specified indices. public bool HasComponents(int[] indices) { for(int i = 0; i < indices.Length; i++) { if(_components[indices[i]] == null) { return false; } } return true; } /// Determines whether this entity has a component /// at any of the specified indices. public bool HasAnyComponent(int[] indices) { for(int i = 0; i < indices.Length; i++) { if(_components[indices[i]] != null) { return true; } } return false; } /// Removes all components. public void RemoveAllComponents() { _toStringCache = null; for(int i = 0; i < _components.Length; i++) { if(_components[i] != null) { replaceComponent(i, null); } } } /// Returns the componentPool for the specified component index. /// componentPools is set by the pool which created the entity and /// is used to reuse removed components. /// Removed components will be pushed to the componentPool. /// Use entity.CreateComponent(index, type) to get a new or /// reusable component from the componentPool. public Stack<IComponent> GetComponentPool(int index) { var componentPool = _componentPools[index]; if(componentPool == null) { componentPool = new Stack<IComponent>(); _componentPools[index] = componentPool; } return componentPool; } /// Returns a new or reusable component from the componentPool /// for the specified component index. public IComponent CreateComponent(int index, Type type) { var componentPool = GetComponentPool(index); return componentPool.Count > 0 ? componentPool.Pop() : (IComponent)Activator.CreateInstance(type); } /// Returns a new or reusable component from the componentPool /// for the specified component index. public T CreateComponent<T>(int index) where T : new() { var componentPool = GetComponentPool(index); return componentPool.Count > 0 ? (T)componentPool.Pop() : new T(); } #if ENTITAS_FAST_AND_UNSAFE /// Returns the number of objects that retain this entity. public int retainCount { get { return _retainCount; } } int _retainCount; #else /// Returns the number of objects that retain this entity. public int retainCount { get { return owners.Count; } } /// Returns all the objects that retain this entity. public readonly HashSet<object> owners = new HashSet<object>(); #endif /// Retains the entity. An owner can only retain the same entity once. /// Retain/Release is part of AERC (Automatic Entity Reference Counting) /// and is used internally to prevent pooling retained entities. /// If you use retain manually you also have to /// release it manually at some point. public Entity Retain(object owner) { #if ENTITAS_FAST_AND_UNSAFE _retainCount += 1; #else if(!owners.Add(owner)) { throw new EntityIsAlreadyRetainedByOwnerException(this, owner); } #endif _toStringCache = null; return this; } /// Releases the entity. An owner can only release an entity /// if it retains it. /// Retain/Release is part of AERC (Automatic Entity Reference Counting) /// and is used internally to prevent pooling retained entities. /// If you use retain manually you also have to /// release it manually at some point. public void Release(object owner) { #if ENTITAS_FAST_AND_UNSAFE _retainCount -= 1; if(_retainCount == 0) { #else if(!owners.Remove(owner)) { throw new EntityIsNotRetainedByOwnerException(this, owner); } if(owners.Count == 0) { #endif _toStringCache = null; if(OnEntityReleased != null) { OnEntityReleased(this); } } } // This method is used internally. Don't call it yourself. // Use pool.DestroyEntity(entity); internal void destroy() { _isEnabled = false; RemoveAllComponents(); OnComponentAdded = null; OnComponentReplaced = null; OnComponentRemoved = null; } // Do not call this method manually. This method is called by the pool. internal void removeAllOnEntityReleasedHandlers() { OnEntityReleased = null; } /// Returns a cached string to describe the entity /// with the following format: /// Entity_{creationIndex}(*{retainCount})({list of components}) public override string ToString() { if(_toStringCache == null) { var sb = new StringBuilder() .Append("Entity_") .Append(_creationIndex) .Append("(*") .Append(retainCount) .Append(")") .Append("("); const string separator = ", "; var components = GetComponents(); var lastSeparator = components.Length - 1; for(int i = 0; i < components.Length; i++) { sb.Append( components[i].GetType().Name.RemoveComponentSuffix() ); if(i < lastSeparator) { sb.Append(separator); } } sb.Append(")"); _toStringCache = sb.ToString(); } return _toStringCache; } } public class EntityAlreadyHasComponentException : EntitasException { public EntityAlreadyHasComponentException( int index, string message, string hint ) : base( message + "\nEntity already has a component at index " + index + "!", hint ) { } } public class EntityDoesNotHaveComponentException : EntitasException { public EntityDoesNotHaveComponentException( int index, string message, string hint ) : base( message + "\nEntity does not have a component at index " + index + "!", hint ) { } } public class EntityIsNotEnabledException : EntitasException { public EntityIsNotEnabledException(string message) : base( message + "\nEntity is not enabled!", "The entity has already been destroyed. " + "You cannot modify destroyed entities." ) { } } public class EntityEqualityComparer : IEqualityComparer<Entity> { public static readonly EntityEqualityComparer comparer = new EntityEqualityComparer(); public bool Equals(Entity x, Entity y) { return x == y; } public int GetHashCode(Entity obj) { return obj._creationIndex; } } public class EntityIsAlreadyRetainedByOwnerException : EntitasException { public EntityIsAlreadyRetainedByOwnerException( Entity entity, object owner ) : base( "'" + owner + "' cannot retain " + entity + "!\n" + "Entity is already retained by this object!", "The entity must be released by this object first." ) { } } public class EntityIsNotRetainedByOwnerException : EntitasException { public EntityIsNotRetainedByOwnerException(Entity entity, object owner) : base( "'" + owner + "' cannot release " + entity + "!\n" + "Entity is not retained by this object!", "An entity can only be released from objects that retain it." ) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using MailGun.Data; namespace MailGun.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("00000000000000_CreateIdentitySchema")] partial class CreateIdentitySchema { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.0.0-rc3") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("MailGun.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.HasOne("MailGun.Models.ApplicationUser") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.HasOne("MailGun.Models.ApplicationUser") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany("Users") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("MailGun.Models.ApplicationUser") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Xunit; namespace System.IO.Tests { public class FileSystemWatcherTests : FileSystemWatcherTest { private static void ValidateDefaults(FileSystemWatcher watcher, string path, string filter) { Assert.Equal(false, watcher.EnableRaisingEvents); Assert.Equal(filter, watcher.Filter); Assert.Equal(false, watcher.IncludeSubdirectories); Assert.Equal(8192, watcher.InternalBufferSize); Assert.Equal(NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName, watcher.NotifyFilter); Assert.Equal(path, watcher.Path); } [Fact] public void FileSystemWatcher_NewFileInfoAction_TriggersNothing() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var file = new TempFile(Path.Combine(testDirectory.Path, "file"))) using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path))) { Action action = () => new FileInfo(file.Path); ExpectEvent(watcher, 0, action, expectedPath: file.Path); } } [Fact] public void FileSystemWatcher_FileInfoGetter_TriggersNothing() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var file = new TempFile(Path.Combine(testDirectory.Path, "file"))) using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path))) { FileAttributes res; Action action = () => res = new FileInfo(file.Path).Attributes; ExpectEvent(watcher, 0, action, expectedPath: file.Path); } } [Fact] public void FileSystemWatcher_EmptyAction_TriggersNothing() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var file = new TempFile(Path.Combine(testDirectory.Path, "file"))) using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path))) { Action action = () => { }; ExpectEvent(watcher, 0, action, expectedPath: file.Path); } } [Fact] public void FileSystemWatcher_ctor() { string path = String.Empty; string pattern = "*.*"; using (FileSystemWatcher watcher = new FileSystemWatcher()) ValidateDefaults(watcher, path, pattern); } [Fact] public void FileSystemWatcher_ctor_path() { string path = @"."; string pattern = "*.*"; using (FileSystemWatcher watcher = new FileSystemWatcher(path)) ValidateDefaults(watcher, path, pattern); } [Fact] public void FileSystemWatcher_ctor_path_pattern() { string path = @"."; string pattern = "honey.jar"; using (FileSystemWatcher watcher = new FileSystemWatcher(path, pattern)) ValidateDefaults(watcher, path, pattern); } [Fact] public void FileSystemWatcher_ctor_InvalidStrings() { using (var testDirectory = new TempDirectory(GetTestFilePath())) { // Null filter Assert.Throws<ArgumentNullException>("filter", () => new FileSystemWatcher(testDirectory.Path, null)); // Null path Assert.Throws<ArgumentNullException>("path", () => new FileSystemWatcher(null)); Assert.Throws<ArgumentNullException>("path", () => new FileSystemWatcher(null, "*")); // Empty path Assert.Throws<ArgumentException>("path", () => new FileSystemWatcher(string.Empty)); Assert.Throws<ArgumentException>("path", () => new FileSystemWatcher(string.Empty, "*")); // Invalid directory Assert.Throws<ArgumentException>("path", () => new FileSystemWatcher(GetTestFilePath())); Assert.Throws<ArgumentException>("path", () => new FileSystemWatcher(GetTestFilePath(), "*")); } } [Fact] public void FileSystemWatcher_Changed() { using (FileSystemWatcher watcher = new FileSystemWatcher()) { var handler = new FileSystemEventHandler((o, e) => { }); // add / remove watcher.Changed += handler; watcher.Changed -= handler; // shouldn't throw watcher.Changed -= handler; } } [Fact] public void FileSystemWatcher_Created() { using (FileSystemWatcher watcher = new FileSystemWatcher()) { var handler = new FileSystemEventHandler((o, e) => { }); // add / remove watcher.Created += handler; watcher.Created -= handler; // shouldn't throw watcher.Created -= handler; } } [Fact] public void FileSystemWatcher_Deleted() { using (FileSystemWatcher watcher = new FileSystemWatcher()) { var handler = new FileSystemEventHandler((o, e) => { }); // add / remove watcher.Deleted += handler; watcher.Deleted -= handler; // shouldn't throw watcher.Deleted -= handler; } } [Fact] public void FileSystemWatcher_Disposed() { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Dispose(); watcher.Dispose(); // shouldn't throw Assert.Throws<ObjectDisposedException>(() => watcher.EnableRaisingEvents = true); } [Fact] public void FileSystemWatcher_EnableRaisingEvents() { using (var testDirectory = new TempDirectory(GetTestFilePath())) { FileSystemWatcher watcher = new FileSystemWatcher(testDirectory.Path); Assert.Equal(false, watcher.EnableRaisingEvents); watcher.EnableRaisingEvents = true; Assert.Equal(true, watcher.EnableRaisingEvents); watcher.EnableRaisingEvents = false; Assert.Equal(false, watcher.EnableRaisingEvents); } } [Fact] public void FileSystemWatcher_Error() { using (FileSystemWatcher watcher = new FileSystemWatcher()) { var handler = new ErrorEventHandler((o, e) => { }); // add / remove watcher.Error += handler; watcher.Error -= handler; // shouldn't throw watcher.Error -= handler; } } [Fact] public void FileSystemWatcher_Filter() { FileSystemWatcher watcher = new FileSystemWatcher(); Assert.Equal("*.*", watcher.Filter); // Null and empty should be mapped to "*.*" watcher.Filter = null; Assert.Equal("*.*", watcher.Filter); watcher.Filter = String.Empty; Assert.Equal("*.*", watcher.Filter); watcher.Filter = " "; Assert.Equal(" ", watcher.Filter); watcher.Filter = "\0"; Assert.Equal("\0", watcher.Filter); watcher.Filter = "\n"; Assert.Equal("\n", watcher.Filter); watcher.Filter = "abc.dll"; Assert.Equal("abc.dll", watcher.Filter); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || // expect no change for OrdinalIgnoreCase-equal strings RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // expect no change for OrdinalIgnoreCase-equal strings // it's unclear why desktop does this but preserve it for compat watcher.Filter = "ABC.DLL"; Assert.Equal("abc.dll", watcher.Filter); } // We can make this setting by first changing to another value then back. watcher.Filter = null; watcher.Filter = "ABC.DLL"; Assert.Equal("ABC.DLL", watcher.Filter); } [Fact] public void FileSystemWatcher_IncludeSubdirectories() { FileSystemWatcher watcher = new FileSystemWatcher(); Assert.Equal(false, watcher.IncludeSubdirectories); watcher.IncludeSubdirectories = true; Assert.Equal(true, watcher.IncludeSubdirectories); watcher.IncludeSubdirectories = false; Assert.Equal(false, watcher.IncludeSubdirectories); } [Fact] public void FileSystemWatcher_InternalBufferSize() { FileSystemWatcher watcher = new FileSystemWatcher(); Assert.Equal(8192, watcher.InternalBufferSize); watcher.InternalBufferSize = 20000; Assert.Equal(20000, watcher.InternalBufferSize); watcher.InternalBufferSize = int.MaxValue; Assert.Equal(int.MaxValue, watcher.InternalBufferSize); // FSW enforces a minimum value of 4096 watcher.InternalBufferSize = 0; Assert.Equal(4096, watcher.InternalBufferSize); watcher.InternalBufferSize = -1; Assert.Equal(4096, watcher.InternalBufferSize); watcher.InternalBufferSize = int.MinValue; Assert.Equal(4096, watcher.InternalBufferSize); watcher.InternalBufferSize = 4095; Assert.Equal(4096, watcher.InternalBufferSize); } [Fact] public void FileSystemWatcher_NotifyFilter() { FileSystemWatcher watcher = new FileSystemWatcher(); Assert.Equal(NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName, watcher.NotifyFilter); var notifyFilters = Enum.GetValues(typeof(NotifyFilters)).Cast<NotifyFilters>(); foreach (NotifyFilters filterValue in notifyFilters) { watcher.NotifyFilter = filterValue; Assert.Equal(filterValue, watcher.NotifyFilter); } var allFilters = notifyFilters.Aggregate((mask, flag) => mask | flag); watcher.NotifyFilter = allFilters; Assert.Equal(allFilters, watcher.NotifyFilter); // This doesn't make sense, but it is permitted. watcher.NotifyFilter = 0; Assert.Equal((NotifyFilters)0, watcher.NotifyFilter); // These throw InvalidEnumException on desktop, but ArgumentException on K Assert.Throws<ArgumentException>(() => watcher.NotifyFilter = (NotifyFilters)(-1)); Assert.Throws<ArgumentException>(() => watcher.NotifyFilter = (NotifyFilters)int.MinValue); Assert.Throws<ArgumentException>(() => watcher.NotifyFilter = (NotifyFilters)int.MaxValue); Assert.Throws<ArgumentException>(() => watcher.NotifyFilter = allFilters + 1); // Simulate a bit added to the flags Assert.Throws<ArgumentException>(() => watcher.NotifyFilter = allFilters | (NotifyFilters)((int)notifyFilters.Max() << 1)); } [Fact] public void FileSystemWatcher_OnChanged() { using (TestFileSystemWatcher watcher = new TestFileSystemWatcher()) { bool eventOccurred = false; object obj = null; FileSystemEventArgs actualArgs = null, expectedArgs = new FileSystemEventArgs(WatcherChangeTypes.Changed, "directory", "file"); watcher.Changed += (o, e) => { eventOccurred = true; obj = o; actualArgs = e; }; watcher.CallOnChanged(expectedArgs); Assert.True(eventOccurred, "Event should be invoked"); Assert.Equal(watcher, obj); Assert.Equal(expectedArgs, actualArgs); } } [Fact] public void FileSystemWatcher_OnCreated() { using (TestFileSystemWatcher watcher = new TestFileSystemWatcher()) { bool eventOccurred = false; object obj = null; FileSystemEventArgs actualArgs = null, expectedArgs = new FileSystemEventArgs(WatcherChangeTypes.Created, "directory", "file"); watcher.Created += (o, e) => { eventOccurred = true; obj = o; actualArgs = e; }; watcher.CallOnCreated(expectedArgs); Assert.True(eventOccurred, "Event should be invoked"); Assert.Equal(watcher, obj); Assert.Equal(expectedArgs, actualArgs); } } [Fact] [PlatformSpecific(PlatformID.OSX | PlatformID.Windows)] public void FileSystemWatcher_OnCreatedWithMismatchedCasingGivesExpectedFullPath() { using (var dir = new TempDirectory(GetTestFilePath())) using (var fsw = new FileSystemWatcher(dir.Path)) { AutoResetEvent are = new AutoResetEvent(false); string fullPath = Path.Combine(dir.Path.ToUpper(), "Foo.txt"); fsw.Created += (o, e) => { Assert.True(fullPath.Equals(e.FullPath, StringComparison.OrdinalIgnoreCase)); are.Set(); }; fsw.EnableRaisingEvents = true; using (var file = new TempFile(fullPath)) { ExpectEvent(are, "created"); } } } [Fact] public void FileSystemWatcher_OnDeleted() { using (TestFileSystemWatcher watcher = new TestFileSystemWatcher()) { bool eventOccurred = false; object obj = null; FileSystemEventArgs actualArgs = null, expectedArgs = new FileSystemEventArgs(WatcherChangeTypes.Deleted, "directory", "file"); watcher.Deleted += (o, e) => { eventOccurred = true; obj = o; actualArgs = e; }; watcher.CallOnDeleted(expectedArgs); Assert.True(eventOccurred, "Event should be invoked"); Assert.Equal(watcher, obj); Assert.Equal(expectedArgs, actualArgs); } } [Fact] public void FileSystemWatcher_OnError() { using (TestFileSystemWatcher watcher = new TestFileSystemWatcher()) { bool eventOccurred = false; object obj = null; ErrorEventArgs actualArgs = null, expectedArgs = new ErrorEventArgs(new Exception()); watcher.Error += (o, e) => { eventOccurred = true; obj = o; actualArgs = e; }; watcher.CallOnError(expectedArgs); Assert.True(eventOccurred, "Event should be invoked"); Assert.Equal(watcher, obj); Assert.Equal(expectedArgs, actualArgs); } } [Fact] public void FileSystemWatcher_OnRenamed() { using (TestFileSystemWatcher watcher = new TestFileSystemWatcher()) { bool eventOccurred = false; object obj = null; RenamedEventArgs actualArgs = null, expectedArgs = new RenamedEventArgs(WatcherChangeTypes.Renamed, "directory", "file", "oldFile"); watcher.Renamed += (o, e) => { eventOccurred = true; obj = o; actualArgs = e; }; watcher.CallOnRenamed(expectedArgs); Assert.True(eventOccurred, "Event should be invoked"); Assert.Equal(watcher, obj); Assert.Equal(expectedArgs, actualArgs); } } [Fact] [PlatformSpecific(PlatformID.Windows)] // Unix FSW don't trigger on a file rename. public void FileSystemWatcher_Windows_OnRenameGivesExpectedFullPath() { using (var dir = new TempDirectory(GetTestFilePath())) using (var file = new TempFile(Path.Combine(dir.Path, "file"))) using (var fsw = new FileSystemWatcher(dir.Path)) { AutoResetEvent eventOccurred = WatchRenamed(fsw); string newPath = Path.Combine(dir.Path, "newPath"); fsw.Renamed += (o, e) => { Assert.Equal(e.OldFullPath, file.Path); Assert.Equal(e.FullPath, newPath); }; fsw.EnableRaisingEvents = true; File.Move(file.Path, newPath); ExpectEvent(eventOccurred, "renamed"); } } [Fact] public void FileSystemWatcher_Path() { FileSystemWatcher watcher = new FileSystemWatcher(); Assert.Equal(String.Empty, watcher.Path); watcher.Path = null; Assert.Equal(String.Empty, watcher.Path); watcher.Path = "."; Assert.Equal(".", watcher.Path); watcher.Path = ".."; Assert.Equal("..", watcher.Path); string currentDir = Path.GetFullPath(".").TrimEnd('.', Path.DirectorySeparatorChar); watcher.Path = currentDir; Assert.Equal(currentDir, watcher.Path); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || // expect no change for OrdinalIgnoreCase-equal strings RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { watcher.Path = currentDir.ToUpperInvariant(); Assert.Equal(currentDir, watcher.Path); watcher.Path = currentDir.ToLowerInvariant(); Assert.Equal(currentDir, watcher.Path); } // expect a change for same "full-path" but different string path, FSW does not normalize string currentDirRelative = currentDir + Path.DirectorySeparatorChar + "." + Path.DirectorySeparatorChar + "." + Path.DirectorySeparatorChar + "." + Path.DirectorySeparatorChar + "."; watcher.Path = currentDirRelative; Assert.Equal(currentDirRelative, watcher.Path); // FSW starts with String.Empty and will ignore setting this if it is already set, // but if you set it after some other valid string has been set it will throw. Assert.Throws<ArgumentException>(() => watcher.Path = String.Empty); // Non-existent path Assert.Throws<ArgumentException>(() => watcher.Path = GetTestFilePath()); // Web path Assert.Throws<ArgumentException>(() => watcher.Path = "http://localhost"); // File protocol Assert.Throws<ArgumentException>(() => watcher.Path = "file:///" + currentDir.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); } [Fact] public void FileSystemWatcher_Renamed() { using (FileSystemWatcher watcher = new FileSystemWatcher()) { var handler = new RenamedEventHandler((o, e) => { }); // add / remove watcher.Renamed += handler; watcher.Renamed -= handler; // shouldn't throw watcher.Renamed -= handler; } } [Fact] [PlatformSpecific(PlatformID.Linux)] [OuterLoop] public void FileSystemWatcher_CreateManyConcurrentInstances() { int maxUserInstances = int.Parse(File.ReadAllText("/proc/sys/fs/inotify/max_user_instances")); var watchers = new List<FileSystemWatcher>(); using (var dir = new TempDirectory(GetTestFilePath())) { try { Assert.Throws<IOException>(() => { // Create enough inotify instances to exceed the number of allowed watches for (int i = 0; i <= maxUserInstances; i++) { watchers.Add(new FileSystemWatcher(dir.Path) { EnableRaisingEvents = true }); } }); } finally { foreach (FileSystemWatcher watcher in watchers) { watcher.Dispose(); } } } } [Fact] [PlatformSpecific(PlatformID.Linux)] public void FileSystemWatcher_CreateManyConcurrentWatches() { int maxUserWatches = int.Parse(File.ReadAllText("/proc/sys/fs/inotify/max_user_watches")); using (var dir = new TempDirectory(GetTestFilePath())) using (var watcher = new FileSystemWatcher(dir.Path) { IncludeSubdirectories = true, NotifyFilter = NotifyFilters.FileName }) { Action action = () => { // Create enough directories to exceed the number of allowed watches for (int i = 0; i <= maxUserWatches; i++) { Directory.CreateDirectory(Path.Combine(dir.Path, i.ToString())); } }; Action cleanup = () => { for (int i = 0; i <= maxUserWatches; i++) { Directory.Delete(Path.Combine(dir.Path, i.ToString())); } }; ExpectError(watcher, action, cleanup); // Make sure existing watches still work even after we've had one or more failures Action createAction = () => File.WriteAllText(Path.Combine(dir.Path, Path.GetRandomFileName()), "text"); Action createCleanup = () => File.Delete(Path.Combine(dir.Path, Path.GetRandomFileName())); ExpectEvent(watcher, WatcherChangeTypes.Created, createAction, createCleanup); } } [Fact] public void FileSystemWatcher_StopCalledOnBackgroundThreadDoesNotDeadlock() { // Check the case where Stop or Dispose (they do the same thing) is called from // a FSW event callback and make sure we don't Thread.Join to deadlock using (var dir = new TempDirectory(GetTestFilePath())) { FileSystemWatcher watcher = new FileSystemWatcher(); AutoResetEvent are = new AutoResetEvent(false); FileSystemEventHandler callback = (sender, arg) => { watcher.Dispose(); are.Set(); }; // Attach the FSW to the existing structure watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size; watcher.Changed += callback; using (var file = File.Create(Path.Combine(dir.Path, "testfile.txt"))) { watcher.EnableRaisingEvents = true; // Change the nested file and verify we get the changed event byte[] bt = new byte[4096]; file.Write(bt, 0, bt.Length); file.Flush(); } ExpectEvent(are, "deleted"); } } [Fact] public void FileSystemWatcher_WatchingAliasedFolderResolvesToRealPathWhenWatching() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir"))) using (var fsw = new FileSystemWatcher(dir.Path)) { AutoResetEvent are = WatchCreated(fsw); fsw.Filter = "*"; fsw.EnableRaisingEvents = true; using (var temp = new TempDirectory(Path.Combine(dir.Path, "foo"))) { ExpectEvent(are, "created"); } } } } }
// 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 SubtractInt64() { var test = new SimpleBinaryOpTest__SubtractInt64(); 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__SubtractInt64 { private const int VectorSize = 16; private const int ElementCount = VectorSize / sizeof(Int64); private static Int64[] _data1 = new Int64[ElementCount]; private static Int64[] _data2 = new Int64[ElementCount]; private static Vector128<Int64> _clsVar1; private static Vector128<Int64> _clsVar2; private Vector128<Int64> _fld1; private Vector128<Int64> _fld2; private SimpleBinaryOpTest__DataTable<Int64> _dataTable; static SimpleBinaryOpTest__SubtractInt64() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__SubtractInt64() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int64>(_data1, _data2, new Int64[ElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.Subtract( Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.Subtract( Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.Subtract( Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int64*)(_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<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Subtract), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(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<Int64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int64>>(_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((Int64*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int64*)(_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((Int64*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int64*)(_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__SubtractInt64(); 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<Int64> left, Vector128<Int64> right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[ElementCount]; Int64[] inArray2 = new Int64[ElementCount]; Int64[] outArray = new Int64[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, 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 = "") { Int64[] inArray1 = new Int64[ElementCount]; Int64[] inArray2 = new Int64[ElementCount]; Int64[] outArray = new Int64[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { if ((long)(left[0] - right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((long)(left[i] - right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Subtract)}<Int64>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// File delete // For StringBuilder using System; using System.Collections.Specialized; using System.Configuration; using System.Data; using System.Data.OleDb; using System.IO; using System.Security.Permissions; using NUnit.Framework; namespace Xsd2Db.Data.Test { /// <summary> /// This class contains tests that involve a database connection. /// </summary> [TestFixture] public class JetTest : Common { /// <summary> /// /// </summary> public JetTest() : base("jet_test") { } /// <summary> /// Returns a properly formatted connection string. /// </summary> /// <returns>A properly formatted connection string</returns> public override IDbConnection Connection() { return new OleDbConnection(JetDataSchemaAdapter.GetConnectionString(Catalog)); } /// <summary> /// /// </summary> /// <param name="exception"></param> /// <param name="commandText"></param> public override void ValidateExceptionOnDuplicateInsert(Exception exception, string commandText) { OleDbException theException = exception as OleDbException; Assertion.AssertNotNull(String.Format("Expected an OLE DB Exception for '{0}'! Received {1} '{2}'", commandText, exception.GetType(), exception.Message), theException); Assertion.Assert(String.Format("Unexpected Exception!\r\n\tException : '{0}'\r\n\tFor Query : '{1}'", theException.Message, commandText), theException.ErrorCode == -2147467259); } /// <summary> /// /// </summary> /// <param name="exception"></param> /// <param name="commandText"></param> public override void ValidateExceptionOnBadForeignKeyInsert(Exception exception, string commandText) { OleDbException theException = exception as OleDbException; Assertion.AssertNotNull(String.Format("Expected an OLEDB Exception for '{0}'! Received {1} '{2}'", commandText, exception.GetType(), exception.Message), theException); Assertion.Assert(String.Format("Unexpected Exception!\r\n\tException : '{0}'\r\n\tFor Query : '{1}'", theException.Message, commandText), theException.ErrorCode == -2147467259); } /// <summary> /// Test to see what happens if the user tries to create a schema /// definition script for a null data set. /// </summary> [Test] [ExpectedException(typeof (ArgumentNullException))] public void TestNullDataSet() { DataSchemaAdapter creator = new JetDataSchemaAdapter(); creator.Create((DataSet) null, false); } /// <summary> /// Test to see what happens if the user tries to create a schema /// definition script for an unnamed data set. /// </summary> [Test] [ExpectedException(typeof (ArgumentException))] public void TestUnnamedDataSet() { DataSchemaAdapter creator = new JetDataSchemaAdapter(); creator.Create(new DataSet(String.Empty), false); } /// <summary> /// Test to see what happens if the user tries to get a schema /// creation script for a dataSet containing a table that has /// no columns. /// </summary> [Test] public void TestNoColumns1() { DataSet ds = new DataSet(Catalog); ds.Tables.Add("empty_table"); DataSchemaAdapter creator = new JetDataSchemaAdapter(); creator.Create(ds, false); } /// <summary> /// Test to see what happens if the user tries to get a schema /// creation script for a dataSet containing a table that has /// no columns. The schema is loaded from a file. /// </summary> [Test] public void TestNoColumns2() { string name = "TestNoColumns2"; string file = String.Format("{0}.xsd", name); DataSet ds = new DataSet(Catalog); ds.Tables.Add("empty_table_1"); ds.Tables.Add("empty_table_2"); ds.WriteXmlSchema(file); ds.Dispose(); ds = new DataSet(); ds.ReadXmlSchema(file); DataSchemaAdapter creator = new JetDataSchemaAdapter(); creator.Create(ds, false); } /// <summary> /// Tests the creation (and subsequent removal) of a database. /// </summary> [Test] public void CreateEmptyDB() { Helper.Print("\n---\n--- Starting CreateEmptyDB\n---\n"); DataSchemaAdapter creator = new JetDataSchemaAdapter(); DataSet dataSet = new DataSet(this.Catalog); creator.Create(dataSet, true); Assertion.Assert(File.Exists(JetDataSchemaAdapter.GetPath(this.Catalog))); // // Can we open it? // using (IDbConnection connection = Connection()) { connection.Open(); } } /// <summary> /// Perform some basic insertion tests using primary and foreign /// key constraints. /// </summary> [Test] [ReflectionPermission(SecurityAction.LinkDemand, Unrestricted=true)] public void RelationTest1() { Helper.Print("\n---\n--- Starting RelationTest1\n---\n"); DataSet ds = base.MakeDataSet(); base.DoRelationTest(ds, new JetDataSchemaAdapter()); } /// <summary> /// Perform some basic insertion tests using primary and foreign /// key constraints. /// </summary> [Test] [ReflectionPermission(SecurityAction.LinkDemand, Unrestricted=true)] public void RelationTest2() { Helper.Print("\n---\n--- Starting RelationTest2\n---\n"); string file = "RelationTestFromFile.xsd"; using (DataSet ds = MakeDataSet()) { ds.WriteXmlSchema(file); ds.Dispose(); } using (DataSet ds = new DataSet()) { ds.ReadXmlSchema(file); ds.DataSetName = this.Catalog; DoRelationTest(ds, new JetDataSchemaAdapter()); } } /// <summary> /// Tests the creation (and subsequent removal) of a database. /// </summary> [Test] // AS: this test fails with the message // "'abstract_element_definition__slot__members__abstract_element_definition' // is not a valid name. Make sure that it // 'abstract_element_definition__slot__members__abstract_element_definition' is not a // valid name. Make sure that it does not include invalid characters or punctuation // and that it is not too long. public void CreateFromOntology() { Helper.Print("\n---\n--- Starting CreateFromOntology\n---\n"); DataSchemaAdapter creator = new JetDataSchemaAdapter(); DataSet dataSet = new DataSet(this.Catalog); string xsdFile = ((NameValueCollection) ConfigurationSettings.GetConfig("Xsd2Db.Data.Test"))["ObjectModelXsd"]; if (xsdFile == null || xsdFile.Length == 0) xsdFile = "../Common/DataSchemaAdapter/Test/ObjectModel.xsd"; dataSet.ReadXmlSchema(xsdFile); dataSet.DataSetName = this.Catalog; creator.Create(dataSet, true); Assertion.Assert(File.Exists(JetDataSchemaAdapter.GetPath(this.Catalog))); // // Can we open it? // using (IDbConnection connection = Connection()) { connection.Open(); } } /// <summary> /// /// </summary> [SetUp] public void SetUp() { CleanUp(); } /// <summary> /// Cleanup code to ensure that the tests don't leave anything /// behind in the database. /// </summary> [TearDown] public void TearDown() { CleanUp(); } /// <summary> /// /// </summary> public void CleanUp() { File.Delete(JetDataSchemaAdapter.GetPath(Catalog)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace System.IO { /// <summary>Provides an implementation of FileSystem for Unix systems.</summary> internal sealed partial class UnixFileSystem : FileSystem { public override int MaxPath { get { return Interop.Sys.MaxPath; } } public override int MaxDirectoryPath { get { return Interop.Sys.MaxPath; } } public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent) { return new UnixFileStream(fullPath, mode, access, share, bufferSize, options, parent); } public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite) { // The destination path may just be a directory into which the file should be copied. // If it is, append the filename from the source onto the destination directory if (DirectoryExists(destFullPath)) { destFullPath = Path.Combine(destFullPath, Path.GetFileName(sourceFullPath)); } // Copy the contents of the file from the source to the destination, creating the destination in the process using (var src = new FileStream(sourceFullPath, FileMode.Open, FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, FileOptions.None)) using (var dst = new FileStream(destFullPath, overwrite ? FileMode.Create : FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, FileStream.DefaultBufferSize, FileOptions.None)) { Interop.CheckIo(Interop.Sys.CopyFile(src.SafeFileHandle, dst.SafeFileHandle)); } } public override void MoveFile(string sourceFullPath, string destFullPath) { // The desired behavior for Move(source, dest) is to not overwrite the destination file // if it exists. Since rename(source, dest) will replace the file at 'dest' if it exists, // link/unlink are used instead. Note that the Unix FileSystemWatcher will treat a Move // as a Creation and Deletion instead of a Rename and thus differ from Windows. if (Interop.Sys.Link(sourceFullPath, destFullPath) < 0) { // If link fails, we can fall back to doing a full copy, but we'll only do so for // cases where we expect link could fail but such a copy could succeed. We don't // want to do so for all errors, because the copy could incur a lot of cost // even if we know it'll eventually fail, e.g. EROFS means that the source file // system is read-only and couldn't support the link being added, but if it's // read-only, then the move should fail any way due to an inability to delete // the source file. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EXDEV || // rename fails across devices / mount points errorInfo.Error == Interop.Error.EPERM || // permissions might not allow creating hard links even if a copy would work errorInfo.Error == Interop.Error.EOPNOTSUPP || // links aren't supported by the source file system errorInfo.Error == Interop.Error.EMLINK) // too many hard links to the source file { CopyFile(sourceFullPath, destFullPath, overwrite: false); } else { // The operation failed. Within reason, try to determine which path caused the problem // so we can throw a detailed exception. string path = null; bool isDirectory = false; if (errorInfo.Error == Interop.Error.ENOENT) { if (!Directory.Exists(Path.GetDirectoryName(destFullPath))) { // The parent directory of destFile can't be found. // Windows distinguishes between whether the directory or the file isn't found, // and throws a different exception in these cases. We attempt to approximate that // here; there is a race condition here, where something could change between // when the error occurs and our checks, but it's the best we can do, and the // worst case in such a race condition (which could occur if the file system is // being manipulated concurrently with these checks) is that we throw a // FileNotFoundException instead of DirectoryNotFoundexception. path = destFullPath; isDirectory = true; } else { path = sourceFullPath; } } else if (errorInfo.Error == Interop.Error.EEXIST) { path = destFullPath; } throw Interop.GetExceptionForIoErrno(errorInfo, path, isDirectory); } } DeleteFile(sourceFullPath); } public override void DeleteFile(string fullPath) { if (Interop.Sys.Unlink(fullPath) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); // ENOENT means it already doesn't exist; nop if (errorInfo.Error != Interop.Error.ENOENT) { if (errorInfo.Error == Interop.Error.EISDIR) errorInfo = Interop.Error.EACCES.Info(); throw Interop.GetExceptionForIoErrno(errorInfo, fullPath); } } } public override void CreateDirectory(string fullPath) { // NOTE: This logic is primarily just carried forward from Win32FileSystem.CreateDirectory. int length = fullPath.Length; // We need to trim the trailing slash or the code will try to create 2 directories of the same name. if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath)) { length--; } // For paths that are only // or /// if (length == 2 && PathInternal.IsDirectorySeparator(fullPath[1])) { throw new IOException(SR.Format(SR.IO_CannotCreateDirectory, fullPath)); } // We can save a bunch of work if the directory we want to create already exists. if (DirectoryExists(fullPath)) { return; } // Attempt to figure out which directories don't exist, and only create the ones we need. bool somepathexists = false; Stack<string> stackDir = new Stack<string>(); int lengthRoot = PathInternal.GetRootLength(fullPath); if (length > lengthRoot) { int i = length - 1; while (i >= lengthRoot && !somepathexists) { string dir = fullPath.Substring(0, i + 1); if (!DirectoryExists(dir)) // Create only the ones missing { stackDir.Push(dir); } else { somepathexists = true; } while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i])) { i--; } i--; } } int count = stackDir.Count; if (count == 0 && !somepathexists) { string root = Directory.InternalGetDirectoryRoot(fullPath); if (!DirectoryExists(root)) { throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true); } return; } // Create all the directories int result = 0; Interop.ErrorInfo firstError = default(Interop.ErrorInfo); string errorString = fullPath; while (stackDir.Count > 0) { string name = stackDir.Pop(); if (name.Length >= MaxDirectoryPath) { throw new PathTooLongException(SR.IO_PathTooLong); } // The mkdir command uses 0777 by default (it'll be AND'd with the process umask internally). // We do the same. result = Interop.Sys.MkDir(name, (int)Interop.Sys.Permissions.Mask); if (result < 0 && firstError.Error == 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); // While we tried to avoid creating directories that don't // exist above, there are a few cases that can fail, e.g. // a race condition where another process or thread creates // the directory first, or there's a file at the location. if (errorInfo.Error != Interop.Error.EEXIST) { firstError = errorInfo; } else if (FileExists(name) || (!DirectoryExists(name, out errorInfo) && errorInfo.Error == Interop.Error.EACCES)) { // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw. firstError = errorInfo; errorString = name; } } } // Only throw an exception if creating the exact directory we wanted failed to work correctly. if (result < 0 && firstError.Error != 0) { throw Interop.GetExceptionForIoErrno(firstError, errorString, isDirectory: true); } } public override void MoveDirectory(string sourceFullPath, string destFullPath) { if (Interop.Sys.Rename(sourceFullPath, destFullPath) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); switch (errorInfo.Error) { case Interop.Error.EACCES: // match Win32 exception throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), errorInfo.RawErrno); default: throw Interop.GetExceptionForIoErrno(errorInfo, sourceFullPath, isDirectory: true); } } } public override void RemoveDirectory(string fullPath, bool recursive) { var di = new DirectoryInfo(fullPath); if (!di.Exists) { throw Interop.GetExceptionForIoErrno(Interop.Error.ENOENT.Info(), fullPath, isDirectory: true); } RemoveDirectoryInternal(di, recursive, throwOnTopLevelDirectoryNotFound: true); } private void RemoveDirectoryInternal(DirectoryInfo directory, bool recursive, bool throwOnTopLevelDirectoryNotFound) { Exception firstException = null; if ((directory.Attributes & FileAttributes.ReparsePoint) != 0) { DeleteFile(directory.FullName); return; } if (recursive) { try { foreach (string item in EnumeratePaths(directory.FullName, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both)) { if (!ShouldIgnoreDirectory(Path.GetFileName(item))) { try { var childDirectory = new DirectoryInfo(item); if (childDirectory.Exists) { RemoveDirectoryInternal(childDirectory, recursive, throwOnTopLevelDirectoryNotFound: false); } else { DeleteFile(item); } } catch (Exception exc) { if (firstException != null) { firstException = exc; } } } } } catch (Exception exc) { if (firstException != null) { firstException = exc; } } if (firstException != null) { throw firstException; } } if (Interop.Sys.RmDir(directory.FullName) < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); switch (errorInfo.Error) { case Interop.Error.EACCES: case Interop.Error.EPERM: case Interop.Error.EROFS: case Interop.Error.EISDIR: throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, directory.FullName)); // match Win32 exception case Interop.Error.ENOENT: if (!throwOnTopLevelDirectoryNotFound) { return; } goto default; default: throw Interop.GetExceptionForIoErrno(errorInfo, directory.FullName, isDirectory: true); } } } public override bool DirectoryExists(string fullPath) { Interop.ErrorInfo ignored; return DirectoryExists(fullPath, out ignored); } private static bool DirectoryExists(string fullPath, out Interop.ErrorInfo errorInfo) { return FileExists(fullPath, Interop.Sys.FileTypes.S_IFDIR, out errorInfo); } public override bool FileExists(string fullPath) { Interop.ErrorInfo ignored; return FileExists(fullPath, Interop.Sys.FileTypes.S_IFREG, out ignored); } private static bool FileExists(string fullPath, int fileType, out Interop.ErrorInfo errorInfo) { Debug.Assert(fileType == Interop.Sys.FileTypes.S_IFREG || fileType == Interop.Sys.FileTypes.S_IFDIR); Interop.Sys.FileStatus fileinfo; errorInfo = default(Interop.ErrorInfo); // First use stat, as we want to follow symlinks. If that fails, it could be because the symlink // is broken, we don't have permissions, etc., in which case fall back to using LStat to evaluate // based on the symlink itself. if (Interop.Sys.Stat(fullPath, out fileinfo) < 0 && Interop.Sys.LStat(fullPath, out fileinfo) < 0) { errorInfo = Interop.Sys.GetLastErrorInfo(); return false; } // Something exists at this path. If the caller is asking for a directory, return true if it's // a directory and false for everything else. If the caller is asking for a file, return false for // a directory and true for everything else. return (fileType == Interop.Sys.FileTypes.S_IFDIR) == ((fileinfo.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR); } public override IEnumerable<string> EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { return new FileSystemEnumerable<string>(path, searchPattern, searchOption, searchTarget, (p, _) => p); } public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { switch (searchTarget) { case SearchTarget.Files: return new FileSystemEnumerable<FileInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => new FileInfo(path, null)); case SearchTarget.Directories: return new FileSystemEnumerable<DirectoryInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => new DirectoryInfo(path, null)); default: return new FileSystemEnumerable<FileSystemInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => isDir ? (FileSystemInfo)new DirectoryInfo(path, null) : (FileSystemInfo)new FileInfo(path, null)); } } private sealed class FileSystemEnumerable<T> : IEnumerable<T> { private readonly PathPair _initialDirectory; private readonly string _searchPattern; private readonly SearchOption _searchOption; private readonly bool _includeFiles; private readonly bool _includeDirectories; private readonly Func<string, bool, T> _translateResult; private IEnumerator<T> _firstEnumerator; internal FileSystemEnumerable( string userPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget, Func<string, bool, T> translateResult) { // Basic validation of the input path if (userPath == null) { throw new ArgumentNullException("path"); } if (string.IsNullOrWhiteSpace(userPath)) { throw new ArgumentException(SR.Argument_EmptyPath, "path"); } // Validate and normalize the search pattern. If after doing so it's empty, // matching Win32 behavior we can skip all additional validation and effectively // return an empty enumerable. searchPattern = NormalizeSearchPattern(searchPattern); if (searchPattern.Length > 0) { PathHelpers.CheckSearchPattern(searchPattern); PathHelpers.ThrowIfEmptyOrRootedPath(searchPattern); // If the search pattern contains any paths, make sure we factor those into // the user path, and then trim them off. int lastSlash = searchPattern.LastIndexOf(Path.DirectorySeparatorChar); if (lastSlash >= 0) { if (lastSlash >= 1) { userPath = Path.Combine(userPath, searchPattern.Substring(0, lastSlash)); } searchPattern = searchPattern.Substring(lastSlash + 1); } string fullPath = Path.GetFullPath(userPath); // Store everything for the enumerator _initialDirectory = new PathPair(userPath, fullPath); _searchPattern = searchPattern; _searchOption = searchOption; _includeFiles = (searchTarget & SearchTarget.Files) != 0; _includeDirectories = (searchTarget & SearchTarget.Directories) != 0; _translateResult = translateResult; } // Open the first enumerator so that any errors are propagated synchronously. _firstEnumerator = Enumerate(); } public IEnumerator<T> GetEnumerator() { return Interlocked.Exchange(ref _firstEnumerator, null) ?? Enumerate(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private IEnumerator<T> Enumerate() { return Enumerate( _initialDirectory.FullPath != null ? OpenDirectory(_initialDirectory.FullPath) : null); } private IEnumerator<T> Enumerate(Microsoft.Win32.SafeHandles.SafeDirectoryHandle dirHandle) { if (dirHandle == null) { // Empty search yield break; } Debug.Assert(!dirHandle.IsInvalid); Debug.Assert(!dirHandle.IsClosed); // Maintain a stack of the directories to explore, in the case of SearchOption.AllDirectories // Lazily-initialized only if we find subdirectories that will be explored. Stack<PathPair> toExplore = null; PathPair dirPath = _initialDirectory; while (dirHandle != null) { try { // Read each entry from the enumerator Interop.Sys.DirectoryEntry dirent; while (Interop.Sys.ReadDir(dirHandle, out dirent) == 0) { // Get from the dir entry whether the entry is a file or directory. // We classify everything as a file unless we know it to be a directory. bool isDir; if (dirent.InodeType == Interop.Sys.NodeType.DT_DIR) { // We know it's a directory. isDir = true; } else if (dirent.InodeType == Interop.Sys.NodeType.DT_LNK || dirent.InodeType == Interop.Sys.NodeType.DT_UNKNOWN) { // It's a symlink or unknown: stat to it to see if we can resolve it to a directory. // If we can't (e.g. symlink to a file, broken symlink, etc.), we'll just treat it as a file. Interop.ErrorInfo errnoIgnored; isDir = DirectoryExists(Path.Combine(dirPath.FullPath, dirent.InodeName), out errnoIgnored); } else { // Otherwise, treat it as a file. This includes regular files, FIFOs, etc. isDir = false; } // Yield the result if the user has asked for it. In the case of directories, // always explore it by pushing it onto the stack, regardless of whether // we're returning directories. if (isDir) { if (!ShouldIgnoreDirectory(dirent.InodeName)) { string userPath = null; if (_searchOption == SearchOption.AllDirectories) { if (toExplore == null) { toExplore = new Stack<PathPair>(); } userPath = Path.Combine(dirPath.UserPath, dirent.InodeName); toExplore.Push(new PathPair(userPath, Path.Combine(dirPath.FullPath, dirent.InodeName))); } if (_includeDirectories && Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0) { yield return _translateResult(userPath ?? Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/true); } } } else if (_includeFiles && Interop.Sys.FnMatch(_searchPattern, dirent.InodeName, Interop.Sys.FnMatchFlags.FNM_NONE) == 0) { yield return _translateResult(Path.Combine(dirPath.UserPath, dirent.InodeName), /*isDirectory*/false); } } } finally { // Close the directory enumerator dirHandle.Dispose(); dirHandle = null; } if (toExplore != null && toExplore.Count > 0) { // Open the next directory. dirPath = toExplore.Pop(); dirHandle = OpenDirectory(dirPath.FullPath); } } } private static string NormalizeSearchPattern(string searchPattern) { if (searchPattern == "." || searchPattern == "*.*") { searchPattern = "*"; } else if (PathHelpers.EndsInDirectorySeparator(searchPattern)) { searchPattern += "*"; } return searchPattern; } private static Microsoft.Win32.SafeHandles.SafeDirectoryHandle OpenDirectory(string fullPath) { Microsoft.Win32.SafeHandles.SafeDirectoryHandle handle = Interop.Sys.OpenDir(fullPath); if (handle.IsInvalid) { throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), fullPath, isDirectory: true); } return handle; } } /// <summary>Determines whether the specified directory name should be ignored.</summary> /// <param name="name">The name to evaluate.</param> /// <returns>true if the name is "." or ".."; otherwise, false.</returns> private static bool ShouldIgnoreDirectory(string name) { return name == "." || name == ".."; } public override string GetCurrentDirectory() { return Interop.Sys.GetCwd(); } public override void SetCurrentDirectory(string fullPath) { Interop.CheckIo(Interop.Sys.ChDir(fullPath), fullPath); } public override FileAttributes GetAttributes(string fullPath) { return new FileInfo(fullPath, null).Attributes; } public override void SetAttributes(string fullPath, FileAttributes attributes) { new FileInfo(fullPath, null).Attributes = attributes; } public override DateTimeOffset GetCreationTime(string fullPath) { return new FileInfo(fullPath, null).CreationTime; } public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory) { IFileSystemObject info = asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); info.CreationTime = time; } public override DateTimeOffset GetLastAccessTime(string fullPath) { return new FileInfo(fullPath, null).LastAccessTime; } public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory) { IFileSystemObject info = asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); info.LastAccessTime = time; } public override DateTimeOffset GetLastWriteTime(string fullPath) { return new FileInfo(fullPath, null).LastWriteTime; } public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory) { IFileSystemObject info = asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); info.LastWriteTime = time; } public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory) { return asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); } } }
using Lucene.Net.Index; using Lucene.Net.Store; using Lucene.Net.Util; using Lucene.Net.Util.Packed; using System; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Codecs.BlockTerms { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Selects every Nth term as and index term, and hold term /// bytes (mostly) fully expanded in memory. This terms index /// supports seeking by ord. See /// <see cref="VariableGapTermsIndexWriter"/> for a more memory efficient /// terms index that does not support seeking by ord. /// <para/> /// @lucene.experimental /// </summary> public class FixedGapTermsIndexWriter : TermsIndexWriterBase { protected IndexOutput m_output; /// <summary>Extension of terms index file</summary> internal readonly static string TERMS_INDEX_EXTENSION = "tii"; internal readonly static string CODEC_NAME = "SIMPLE_STANDARD_TERMS_INDEX"; internal readonly static int VERSION_START = 0; internal readonly static int VERSION_APPEND_ONLY = 1; internal readonly static int VERSION_CHECKSUM = 1000; // 4.x "skipped" trunk's monotonic addressing: give any user a nice exception internal readonly static int VERSION_CURRENT = VERSION_CHECKSUM; private readonly int termIndexInterval; private readonly IList<SimpleFieldWriter> fields = new List<SimpleFieldWriter>(); private readonly FieldInfos fieldInfos; // unread public FixedGapTermsIndexWriter(SegmentWriteState state) { string indexFileName = IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, TERMS_INDEX_EXTENSION); termIndexInterval = state.TermIndexInterval; m_output = state.Directory.CreateOutput(indexFileName, state.Context); bool success = false; try { fieldInfos = state.FieldInfos; WriteHeader(m_output); m_output.WriteInt32(termIndexInterval); success = true; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(m_output); } } } private void WriteHeader(IndexOutput output) { CodecUtil.WriteHeader(output, CODEC_NAME, VERSION_CURRENT); } public override FieldWriter AddField(FieldInfo field, long termsFilePointer) { //System.out.println("FGW: addFfield=" + field.name); SimpleFieldWriter writer = new SimpleFieldWriter(this, field, termsFilePointer); fields.Add(writer); return writer; } /// <summary> /// NOTE: if your codec does not sort in unicode code /// point order, you must override this method, to simply /// return <c>indexedTerm.Length</c>. /// </summary> protected virtual int IndexedTermPrefixLength(BytesRef priorTerm, BytesRef indexedTerm) { // As long as codec sorts terms in unicode codepoint // order, we can safely strip off the non-distinguishing // suffix to save RAM in the loaded terms index. int idxTermOffset = indexedTerm.Offset; int priorTermOffset = priorTerm.Offset; int limit = Math.Min(priorTerm.Length, indexedTerm.Length); for (int byteIdx = 0; byteIdx < limit; byteIdx++) { if (priorTerm.Bytes[priorTermOffset + byteIdx] != indexedTerm.Bytes[idxTermOffset + byteIdx]) { return byteIdx + 1; } } return Math.Min(1 + priorTerm.Length, indexedTerm.Length); } private class SimpleFieldWriter : FieldWriter { private readonly FixedGapTermsIndexWriter outerInstance; internal readonly FieldInfo fieldInfo; internal int numIndexTerms; internal readonly long indexStart; internal readonly long termsStart; internal long packedIndexStart; internal long packedOffsetsStart; private long numTerms; // TODO: we could conceivably make a PackedInts wrapper // that auto-grows... then we wouldn't force 6 bytes RAM // per index term: private short[] termLengths; private int[] termsPointerDeltas; private long lastTermsPointer; private long totTermLength; private readonly BytesRef lastTerm = new BytesRef(); internal SimpleFieldWriter(FixedGapTermsIndexWriter outerInstance, FieldInfo fieldInfo, long termsFilePointer) { this.outerInstance = outerInstance; this.fieldInfo = fieldInfo; indexStart = outerInstance.m_output.GetFilePointer(); termsStart = lastTermsPointer = termsFilePointer; termLengths = EMPTY_INT16S; termsPointerDeltas = EMPTY_INT32S; } public override bool CheckIndexTerm(BytesRef text, TermStats stats) { // First term is first indexed term: //System.output.println("FGW: checkIndexTerm text=" + text.utf8ToString()); if (0 == (numTerms++ % outerInstance.termIndexInterval)) { return true; } else { if (0 == numTerms % outerInstance.termIndexInterval) { // save last term just before next index term so we // can compute wasted suffix lastTerm.CopyBytes(text); } return false; } } public override void Add(BytesRef text, TermStats stats, long termsFilePointer) { int indexedTermLength = outerInstance.IndexedTermPrefixLength(lastTerm, text); //System.out.println("FGW: add text=" + text.utf8ToString() + " " + text + " fp=" + termsFilePointer); // write only the min prefix that shows the diff // against prior term outerInstance.m_output.WriteBytes(text.Bytes, text.Offset, indexedTermLength); if (termLengths.Length == numIndexTerms) { termLengths = ArrayUtil.Grow(termLengths); } if (termsPointerDeltas.Length == numIndexTerms) { termsPointerDeltas = ArrayUtil.Grow(termsPointerDeltas); } // save delta terms pointer termsPointerDeltas[numIndexTerms] = (int)(termsFilePointer - lastTermsPointer); lastTermsPointer = termsFilePointer; // save term length (in bytes) Debug.Assert(indexedTermLength <= short.MaxValue); termLengths[numIndexTerms] = (short)indexedTermLength; totTermLength += indexedTermLength; lastTerm.CopyBytes(text); numIndexTerms++; } public override void Finish(long termsFilePointer) { // write primary terms dict offsets packedIndexStart = outerInstance.m_output.GetFilePointer(); PackedInt32s.Writer w = PackedInt32s.GetWriter(outerInstance.m_output, numIndexTerms, PackedInt32s.BitsRequired(termsFilePointer), PackedInt32s.DEFAULT); // relative to our indexStart long upto = 0; for (int i = 0; i < numIndexTerms; i++) { upto += termsPointerDeltas[i]; w.Add(upto); } w.Finish(); packedOffsetsStart = outerInstance.m_output.GetFilePointer(); // write offsets into the byte[] terms w = PackedInt32s.GetWriter(outerInstance.m_output, 1 + numIndexTerms, PackedInt32s.BitsRequired(totTermLength), PackedInt32s.DEFAULT); upto = 0; for (int i = 0; i < numIndexTerms; i++) { w.Add(upto); upto += termLengths[i]; } w.Add(upto); w.Finish(); // our referrer holds onto us, while other fields are // being written, so don't tie up this RAM: termLengths = null; termsPointerDeltas = null; } } protected override void Dispose(bool disposing) { if (disposing) { if (m_output != null) { bool success = false; try { long dirStart = m_output.GetFilePointer(); int fieldCount = fields.Count; int nonNullFieldCount = 0; for (int i = 0; i < fieldCount; i++) { SimpleFieldWriter field = fields[i]; if (field.numIndexTerms > 0) { nonNullFieldCount++; } } m_output.WriteVInt32(nonNullFieldCount); for (int i = 0; i < fieldCount; i++) { SimpleFieldWriter field = fields[i]; if (field.numIndexTerms > 0) { m_output.WriteVInt32(field.fieldInfo.Number); m_output.WriteVInt32(field.numIndexTerms); m_output.WriteVInt64(field.termsStart); m_output.WriteVInt64(field.indexStart); m_output.WriteVInt64(field.packedIndexStart); m_output.WriteVInt64(field.packedOffsetsStart); } } WriteTrailer(dirStart); CodecUtil.WriteFooter(m_output); success = true; } finally { if (success) { IOUtils.Dispose(m_output); } else { IOUtils.DisposeWhileHandlingException(m_output); } m_output = null; } } } } private void WriteTrailer(long dirStart) { m_output.WriteInt64(dirStart); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.AppEngine.V1.Snippets { using Google.Api.Gax; using Google.LongRunning; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedDomainMappingsClientSnippets { /// <summary>Snippet for ListDomainMappings</summary> public void ListDomainMappingsRequestObject() { // Snippet: ListDomainMappings(ListDomainMappingsRequest, CallSettings) // Create client DomainMappingsClient domainMappingsClient = DomainMappingsClient.Create(); // Initialize request argument(s) ListDomainMappingsRequest request = new ListDomainMappingsRequest { Parent = "", }; // Make the request PagedEnumerable<ListDomainMappingsResponse, DomainMapping> response = domainMappingsClient.ListDomainMappings(request); // Iterate over all response items, lazily performing RPCs as required foreach (DomainMapping item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListDomainMappingsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (DomainMapping item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<DomainMapping> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (DomainMapping item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListDomainMappingsAsync</summary> public async Task ListDomainMappingsRequestObjectAsync() { // Snippet: ListDomainMappingsAsync(ListDomainMappingsRequest, CallSettings) // Create client DomainMappingsClient domainMappingsClient = await DomainMappingsClient.CreateAsync(); // Initialize request argument(s) ListDomainMappingsRequest request = new ListDomainMappingsRequest { Parent = "", }; // Make the request PagedAsyncEnumerable<ListDomainMappingsResponse, DomainMapping> response = domainMappingsClient.ListDomainMappingsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((DomainMapping item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListDomainMappingsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (DomainMapping item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<DomainMapping> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (DomainMapping item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetDomainMapping</summary> public void GetDomainMappingRequestObject() { // Snippet: GetDomainMapping(GetDomainMappingRequest, CallSettings) // Create client DomainMappingsClient domainMappingsClient = DomainMappingsClient.Create(); // Initialize request argument(s) GetDomainMappingRequest request = new GetDomainMappingRequest { Name = "", }; // Make the request DomainMapping response = domainMappingsClient.GetDomainMapping(request); // End snippet } /// <summary>Snippet for GetDomainMappingAsync</summary> public async Task GetDomainMappingRequestObjectAsync() { // Snippet: GetDomainMappingAsync(GetDomainMappingRequest, CallSettings) // Additional: GetDomainMappingAsync(GetDomainMappingRequest, CancellationToken) // Create client DomainMappingsClient domainMappingsClient = await DomainMappingsClient.CreateAsync(); // Initialize request argument(s) GetDomainMappingRequest request = new GetDomainMappingRequest { Name = "", }; // Make the request DomainMapping response = await domainMappingsClient.GetDomainMappingAsync(request); // End snippet } /// <summary>Snippet for CreateDomainMapping</summary> public void CreateDomainMappingRequestObject() { // Snippet: CreateDomainMapping(CreateDomainMappingRequest, CallSettings) // Create client DomainMappingsClient domainMappingsClient = DomainMappingsClient.Create(); // Initialize request argument(s) CreateDomainMappingRequest request = new CreateDomainMappingRequest { Parent = "", DomainMapping = new DomainMapping(), OverrideStrategy = DomainOverrideStrategy.UnspecifiedDomainOverrideStrategy, }; // Make the request Operation<DomainMapping, OperationMetadataV1> response = domainMappingsClient.CreateDomainMapping(request); // Poll until the returned long-running operation is complete Operation<DomainMapping, OperationMetadataV1> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result DomainMapping result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<DomainMapping, OperationMetadataV1> retrievedResponse = domainMappingsClient.PollOnceCreateDomainMapping(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result DomainMapping retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateDomainMappingAsync</summary> public async Task CreateDomainMappingRequestObjectAsync() { // Snippet: CreateDomainMappingAsync(CreateDomainMappingRequest, CallSettings) // Additional: CreateDomainMappingAsync(CreateDomainMappingRequest, CancellationToken) // Create client DomainMappingsClient domainMappingsClient = await DomainMappingsClient.CreateAsync(); // Initialize request argument(s) CreateDomainMappingRequest request = new CreateDomainMappingRequest { Parent = "", DomainMapping = new DomainMapping(), OverrideStrategy = DomainOverrideStrategy.UnspecifiedDomainOverrideStrategy, }; // Make the request Operation<DomainMapping, OperationMetadataV1> response = await domainMappingsClient.CreateDomainMappingAsync(request); // Poll until the returned long-running operation is complete Operation<DomainMapping, OperationMetadataV1> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result DomainMapping result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<DomainMapping, OperationMetadataV1> retrievedResponse = await domainMappingsClient.PollOnceCreateDomainMappingAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result DomainMapping retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateDomainMapping</summary> public void UpdateDomainMappingRequestObject() { // Snippet: UpdateDomainMapping(UpdateDomainMappingRequest, CallSettings) // Create client DomainMappingsClient domainMappingsClient = DomainMappingsClient.Create(); // Initialize request argument(s) UpdateDomainMappingRequest request = new UpdateDomainMappingRequest { Name = "", DomainMapping = new DomainMapping(), UpdateMask = new FieldMask(), }; // Make the request Operation<DomainMapping, OperationMetadataV1> response = domainMappingsClient.UpdateDomainMapping(request); // Poll until the returned long-running operation is complete Operation<DomainMapping, OperationMetadataV1> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result DomainMapping result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<DomainMapping, OperationMetadataV1> retrievedResponse = domainMappingsClient.PollOnceUpdateDomainMapping(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result DomainMapping retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateDomainMappingAsync</summary> public async Task UpdateDomainMappingRequestObjectAsync() { // Snippet: UpdateDomainMappingAsync(UpdateDomainMappingRequest, CallSettings) // Additional: UpdateDomainMappingAsync(UpdateDomainMappingRequest, CancellationToken) // Create client DomainMappingsClient domainMappingsClient = await DomainMappingsClient.CreateAsync(); // Initialize request argument(s) UpdateDomainMappingRequest request = new UpdateDomainMappingRequest { Name = "", DomainMapping = new DomainMapping(), UpdateMask = new FieldMask(), }; // Make the request Operation<DomainMapping, OperationMetadataV1> response = await domainMappingsClient.UpdateDomainMappingAsync(request); // Poll until the returned long-running operation is complete Operation<DomainMapping, OperationMetadataV1> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result DomainMapping result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<DomainMapping, OperationMetadataV1> retrievedResponse = await domainMappingsClient.PollOnceUpdateDomainMappingAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result DomainMapping retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteDomainMapping</summary> public void DeleteDomainMappingRequestObject() { // Snippet: DeleteDomainMapping(DeleteDomainMappingRequest, CallSettings) // Create client DomainMappingsClient domainMappingsClient = DomainMappingsClient.Create(); // Initialize request argument(s) DeleteDomainMappingRequest request = new DeleteDomainMappingRequest { Name = "", }; // Make the request Operation<Empty, OperationMetadataV1> response = domainMappingsClient.DeleteDomainMapping(request); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadataV1> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadataV1> retrievedResponse = domainMappingsClient.PollOnceDeleteDomainMapping(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteDomainMappingAsync</summary> public async Task DeleteDomainMappingRequestObjectAsync() { // Snippet: DeleteDomainMappingAsync(DeleteDomainMappingRequest, CallSettings) // Additional: DeleteDomainMappingAsync(DeleteDomainMappingRequest, CancellationToken) // Create client DomainMappingsClient domainMappingsClient = await DomainMappingsClient.CreateAsync(); // Initialize request argument(s) DeleteDomainMappingRequest request = new DeleteDomainMappingRequest { Name = "", }; // Make the request Operation<Empty, OperationMetadataV1> response = await domainMappingsClient.DeleteDomainMappingAsync(request); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadataV1> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadataV1> retrievedResponse = await domainMappingsClient.PollOnceDeleteDomainMappingAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } } }
/*---------------------------------------------------------------- // Copyright (C) 2007 Fengart //----------------------------------------------------------------*/ using System; namespace MonkeyOthello.Engines.V2.AI { public class EndSolve : BaseSolve { private const int highestScore = Constants.HighestScore; private uint RegionParity; public int BestMove { get { return bestMove; } } public int Nodes { get { return nodes; } } public EndSolve() : base() { } public int NoParEndSolve(ChessType[] board, int alpha, int beta, ChessType color, int empties, int discdiff, int prevmove) { int score = -highestScore; ChessType oppcolor = 2 - color; int sqnum = -1, j, j1; int eval; Empties em, old_em; nodes++; for (old_em = EmHead, em = old_em.Succ; em != null; old_em = em, em = em.Succ) { sqnum = em.Square; j = RuleUtils.DoFlips(board, sqnum, color, oppcolor); if (j > 0) { board[sqnum] = color; old_em.Succ = em.Succ; if (empties == 2) { j1 = RuleUtils.CountFlips(board, EmHead.Succ.Square, oppcolor, color); if (j1 > 0)// { eval = discdiff + 2 * (j - j1); } else //pass { j1 = RuleUtils.CountFlips(board, EmHead.Succ.Square, color, oppcolor); eval = discdiff + 2 * j; if (j1 > 0)// { eval += 2 * (j1 + 1); } else {//both pass if (eval >= 0) eval += 2; } } } else { eval = -NoParEndSolve(board, -beta, -alpha, oppcolor, empties - 1, -discdiff - 2 * j - 1, sqnum); } RuleUtils.UndoFlips(board, j, oppcolor); board[sqnum] = ChessType.EMPTY; old_em.Succ = em; //purning if (eval > score) { score = eval; if (empties == searchDepth) { bestMove = sqnum; } if (eval > alpha) { if (eval >= beta) { // purning return score; } alpha = eval; } } } } if (score == -highestScore) { if (empties == searchDepth) { bestMove = MVPASS; } if (prevmove == 0) { if (discdiff > 0) return discdiff + empties; if (discdiff < 0) return discdiff - empties; return 0; } else return -NoParEndSolve(board, -beta, -alpha, oppcolor, empties, -discdiff, 0); } return score; } public int ParEndSolve(ChessType[] board, int alpha, int beta, ChessType color, int empties, int discdiff, int prevmove) { int score = -highestScore; ChessType oppcolor = 2 - color; int sqnum = -1; int j; int eval; Empties em, old_em; int holepar; // nodes++; for (old_em = EmHead, em = old_em.Succ; em != null; old_em = em, em = em.Succ) { holepar = em.HoleId; holepar = em.Square; holepar = em.HoleId; sqnum = em.Square; j = RuleUtils.DoFlips(board, sqnum, color, oppcolor); if (j > 0) { // board[sqnum] = color; // RegionParity ^= (uint)holepar; // old_em.Succ = em.Succ; if (empties <= 1 + Constants.Use_Parity) { eval = -NoParEndSolve(board, -beta, -alpha, oppcolor, empties - 1, -discdiff - 2 * j - 1, sqnum); } else { eval = -ParEndSolve(board, -beta, -alpha, oppcolor, empties - 1, -discdiff - 2 * j - 1, sqnum); } // RuleUtils.UndoFlips(board, j, oppcolor); RegionParity ^= (uint)holepar; board[sqnum] = ChessType.EMPTY; old_em.Succ = em; if (eval > score) { score = eval; //========================================= if (empties == searchDepth) { bestMove = sqnum; //StaticMethod.UpdateMessage(score, nodes,sqnum); // StaticMethod.UpdateThinkingMove(sqnum); } if (eval > alpha) { if (eval >= beta) { return score; } alpha = eval; } } } } if (score == -highestScore) { if (empties == searchDepth) { bestMove = MVPASS; } if (prevmove == 0) { if (discdiff > 0) return discdiff + empties; if (discdiff < 0) return discdiff - empties; return 0; } else return -ParEndSolve(board, -beta, -alpha, oppcolor, empties, -discdiff, 0); } return score; } public int FastestFirstEndSolve(ChessType[] board, int alpha, int beta, ChessType color, int empties, int discdiff, int prevmove) { int i, j; int score = -highestScore; ChessType oppcolor = 2 - color; int sqnum = -1; int ev; int flipped; int moves, mobility; int best_value, best_index; Empties em, old_em; Empties[] move_ptr = new Empties[64]; int holepar; int[] goodness = new int[64]; moves = 0; nodes++; for (old_em = EmHead, em = old_em.Succ; em != null; old_em = em, em = em.Succ) { sqnum = em.Square; flipped = RuleUtils.DoFlips(board, sqnum, color, oppcolor); if (flipped > 0) { board[sqnum] = color; old_em.Succ = em.Succ; mobility = count_mobility(board, oppcolor); RuleUtils.UndoFlips(board, flipped, oppcolor); old_em.Succ = em; board[sqnum] = ChessType.EMPTY; move_ptr[moves] = em; goodness[moves] = -mobility; moves++; } } if (moves != 0) { for (i = 0; i < moves; i++) { best_value = goodness[i]; best_index = i; for (j = i + 1; j < moves; j++) if (goodness[j] > best_value) { best_value = goodness[j]; best_index = j; } em = move_ptr[best_index]; move_ptr[best_index] = move_ptr[i]; goodness[best_index] = goodness[i]; sqnum = em.Square; holepar = em.HoleId; j = RuleUtils.DoFlips(board, sqnum, color, oppcolor); board[sqnum] = color; RegionParity ^= (uint)holepar; em.Pred.Succ = em.Succ; if (em.Succ != null) em.Succ.Pred = em.Pred; if (empties <= Constants.Fastest_First + 1) ev = -ParEndSolve(board, -beta, -alpha, oppcolor, empties - 1, -discdiff - 2 * j - 1, sqnum); else ev = -FastestFirstEndSolve(board, -beta, -alpha, oppcolor, empties - 1, -discdiff - 2 * j - 1, sqnum); RuleUtils.UndoFlips(board, j, oppcolor); RegionParity ^= (uint)holepar; board[sqnum] = ChessType.EMPTY; em.Pred.Succ = em; if (em.Succ != null) em.Succ.Pred = em; if (ev > score) { score = ev; if (empties == searchDepth) { bestMove = sqnum; } if (ev > alpha) { if (ev >= beta) return score; alpha = ev; } } } } else { if (prevmove == 0) { if (discdiff > 0) return discdiff + empties; if (discdiff < 0) return discdiff - empties; return 0; } else /* I pass: */ score = -FastestFirstEndSolve(board, -beta, -alpha, oppcolor, empties, -discdiff, 0); if (empties == searchDepth) { bestMove = MVPASS; } } return score; } public int Solve(ChessType[] board, int alpha, int beta, ChessType color, int empties, int discdiff, int prevmove) { RegionParity = 0; for (int i = 10; i <= 80; i++) { RegionParity ^= HoleId[i]; } searchDepth = empties; nodes = 0; if (empties > Constants.Fastest_First) return FastestFirstEndSolve(board, alpha, beta, color, empties, discdiff, prevmove); else { if (empties <= Constants.Use_Parity) return NoParEndSolve(board, alpha, beta, color, empties, discdiff, prevmove); else return ParEndSolve(board, alpha, beta, color, empties, discdiff, prevmove); } } } }
// <copyright> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> namespace System.ServiceModel.Description { using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Runtime; using System.Text; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using WsdlNS = System.Web.Services.Description; internal static class WsdlHelper { public static WsdlNS.ServiceDescription GetSingleWsdl(MetadataSet metadataSet) { if (metadataSet.MetadataSections.Count < 1) { return null; } List<WsdlNS.ServiceDescription> wsdls = new List<WsdlNS.ServiceDescription>(); List<XmlSchema> xsds = new List<XmlSchema>(); foreach (MetadataSection section in metadataSet.MetadataSections) { if (section.Metadata is WsdlNS.ServiceDescription) { wsdls.Add((WsdlNS.ServiceDescription)section.Metadata); } if (section.Metadata is XmlSchema) { xsds.Add((XmlSchema)section.Metadata); } } VerifyContractNamespace(wsdls); WsdlNS.ServiceDescription singleWsdl = GetSingleWsdl(CopyServiceDescriptionCollection(wsdls)); // Inline XML schemas foreach (XmlSchema schema in xsds) { XmlSchema newSchema = CloneXsd(schema); RemoveSchemaLocations(newSchema); singleWsdl.Types.Schemas.Add(newSchema); } return singleWsdl; } private static void RemoveSchemaLocations(XmlSchema schema) { foreach (XmlSchemaObject schemaObject in schema.Includes) { XmlSchemaExternal external = schemaObject as XmlSchemaExternal; if (external != null) { external.SchemaLocation = null; } } } private static WsdlNS.ServiceDescription GetSingleWsdl(List<WsdlNS.ServiceDescription> wsdls) { // Use WSDL that has the contracts as the base for single WSDL WsdlNS.ServiceDescription singleWsdl = wsdls.First(wsdl => wsdl.PortTypes.Count > 0); if (singleWsdl == null) { singleWsdl = new WsdlNS.ServiceDescription(); } else { singleWsdl.Types.Schemas.Clear(); singleWsdl.Imports.Clear(); } Dictionary<XmlQualifiedName, XmlQualifiedName> bindingReferenceChanges = new Dictionary<XmlQualifiedName, XmlQualifiedName>(); foreach (WsdlNS.ServiceDescription wsdl in wsdls) { if (wsdl != singleWsdl) { MergeWsdl(singleWsdl, wsdl, bindingReferenceChanges); } } EnsureSingleNamespace(singleWsdl, bindingReferenceChanges); return singleWsdl; } private static List<WsdlNS.ServiceDescription> CopyServiceDescriptionCollection(List<WsdlNS.ServiceDescription> wsdls) { List<WsdlNS.ServiceDescription> newWsdls = new List<WsdlNS.ServiceDescription>(); foreach (WsdlNS.ServiceDescription wsdl in wsdls) { newWsdls.Add(CloneWsdl(wsdl)); } return newWsdls; } private static void MergeWsdl(WsdlNS.ServiceDescription singleWsdl, WsdlNS.ServiceDescription wsdl, Dictionary<XmlQualifiedName, XmlQualifiedName> bindingReferenceChanges) { if (wsdl.Services.Count > 0) { singleWsdl.Name = wsdl.Name; } foreach (WsdlNS.Binding binding in wsdl.Bindings) { string uniqueBindingName = NamingHelper.GetUniqueName(binding.Name, WsdlHelper.IsBindingNameUsed, singleWsdl.Bindings); if (binding.Name != uniqueBindingName) { bindingReferenceChanges.Add( new XmlQualifiedName(binding.Name, binding.ServiceDescription.TargetNamespace), new XmlQualifiedName(uniqueBindingName, singleWsdl.TargetNamespace)); UpdatePolicyKeys(binding, uniqueBindingName, wsdl); binding.Name = uniqueBindingName; } singleWsdl.Bindings.Add(binding); } foreach (object extension in wsdl.Extensions) { singleWsdl.Extensions.Add(extension); } foreach (WsdlNS.Message message in wsdl.Messages) { singleWsdl.Messages.Add(message); } foreach (WsdlNS.Service service in wsdl.Services) { singleWsdl.Services.Add(service); } foreach (string warning in wsdl.ValidationWarnings) { singleWsdl.ValidationWarnings.Add(warning); } } private static void UpdatePolicyKeys(WsdlNS.Binding binding, string newBindingName, WsdlNS.ServiceDescription wsdl) { string oldBindingName = binding.Name; // policy IEnumerable<XmlElement> bindingPolicies = FindAllElements(wsdl.Extensions, MetadataStrings.WSPolicy.Elements.Policy); string policyIdStringPrefixFormat = "{0}_"; foreach (XmlElement policyElement in bindingPolicies) { XmlNode policyId = policyElement.Attributes.GetNamedItem(MetadataStrings.Wsu.Attributes.Id, MetadataStrings.Wsu.NamespaceUri); string policyIdString = policyId.Value; string policyIdStringWithOldBindingName = string.Format(CultureInfo.InvariantCulture, policyIdStringPrefixFormat, oldBindingName); string policyIdStringWithNewBindingName = string.Format(CultureInfo.InvariantCulture, policyIdStringPrefixFormat, newBindingName); if (policyId != null && policyIdString != null && policyIdString.StartsWith(policyIdStringWithOldBindingName, StringComparison.Ordinal)) { policyId.Value = policyIdStringWithNewBindingName + policyIdString.Substring(policyIdStringWithOldBindingName.Length); } } // policy reference UpdatePolicyReference(binding.Extensions, oldBindingName, newBindingName); foreach (WsdlNS.OperationBinding operationBinding in binding.Operations) { UpdatePolicyReference(operationBinding.Extensions, oldBindingName, newBindingName); if (operationBinding.Input != null) { UpdatePolicyReference(operationBinding.Input.Extensions, oldBindingName, newBindingName); } if (operationBinding.Output != null) { UpdatePolicyReference(operationBinding.Output.Extensions, oldBindingName, newBindingName); } foreach (WsdlNS.FaultBinding fault in operationBinding.Faults) { UpdatePolicyReference(fault.Extensions, oldBindingName, newBindingName); } } } private static void UpdatePolicyReference(WsdlNS.ServiceDescriptionFormatExtensionCollection extensions, string oldBindingName, string newBindingName) { IEnumerable<XmlElement> bindingPolicyReferences = FindAllElements(extensions, MetadataStrings.WSPolicy.Elements.PolicyReference); string policyReferencePrefixFormat = "#{0}_"; foreach (XmlElement policyReferenceElement in bindingPolicyReferences) { XmlNode policyReference = policyReferenceElement.Attributes.GetNamedItem(MetadataStrings.WSPolicy.Attributes.URI); string policyReferenceValue = policyReference.Value; string policyReferenceValueWithOldBindingName = string.Format(CultureInfo.InvariantCulture, policyReferencePrefixFormat, oldBindingName); string policyReferenceValueWithNewBindingName = string.Format(CultureInfo.InvariantCulture, policyReferencePrefixFormat, newBindingName); if (policyReference != null && policyReferenceValue != null && policyReferenceValue.StartsWith(policyReferenceValueWithOldBindingName, StringComparison.Ordinal)) { policyReference.Value = policyReferenceValueWithNewBindingName + policyReference.Value.Substring(policyReferenceValueWithOldBindingName.Length); } } } private static IEnumerable<XmlElement> FindAllElements(WsdlNS.ServiceDescriptionFormatExtensionCollection extensions, string elementName) { List<XmlElement> policyReferences = new List<XmlElement>(); for (int i = 0; i < extensions.Count; i++) { XmlElement element = extensions[i] as XmlElement; if (element != null && element.LocalName == elementName) { policyReferences.Add(element); } } return policyReferences; } private static void VerifyContractNamespace(List<WsdlNS.ServiceDescription> wsdls) { IEnumerable<WsdlNS.ServiceDescription> contractWsdls = wsdls.Where(serviceDescription => serviceDescription.PortTypes.Count > 0); if (contractWsdls.Count() > 1) { IEnumerable<string> namespaces = contractWsdls.Select<WsdlNS.ServiceDescription, string>(wsdl => wsdl.TargetNamespace); string contractNamespaces = string.Join(", ", namespaces); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SingleWsdlNotGenerated, contractNamespaces))); } } private static void EnsureSingleNamespace(WsdlNS.ServiceDescription wsdl, Dictionary<XmlQualifiedName, XmlQualifiedName> bindingReferenceChanges) { string targetNamespace = wsdl.TargetNamespace; foreach (WsdlNS.Binding binding in wsdl.Bindings) { if (binding.Type.Namespace != targetNamespace) { binding.Type = new XmlQualifiedName(binding.Type.Name, targetNamespace); } } foreach (WsdlNS.PortType portType in wsdl.PortTypes) { foreach (WsdlNS.Operation operation in portType.Operations) { WsdlNS.OperationInput messageInput = operation.Messages.Input; if (messageInput != null && messageInput.Message.Namespace != targetNamespace) { messageInput.Message = new XmlQualifiedName(messageInput.Message.Name, targetNamespace); } WsdlNS.OperationOutput messageOutput = operation.Messages.Output; if (messageOutput != null && messageOutput.Message.Namespace != targetNamespace) { messageOutput.Message = new XmlQualifiedName(messageOutput.Message.Name, targetNamespace); } foreach (WsdlNS.OperationFault fault in operation.Faults) { if (fault.Message.Namespace != targetNamespace) { fault.Message = new XmlQualifiedName(fault.Message.Name, targetNamespace); } } } } foreach (WsdlNS.Service service in wsdl.Services) { foreach (WsdlNS.Port port in service.Ports) { XmlQualifiedName newPortBinding; if (bindingReferenceChanges.TryGetValue(port.Binding, out newPortBinding)) { port.Binding = newPortBinding; } else if (port.Binding.Namespace != targetNamespace) { port.Binding = new XmlQualifiedName(port.Binding.Name, targetNamespace); } } } } private static bool IsBindingNameUsed(string name, object collection) { WsdlNS.BindingCollection bindings = (WsdlNS.BindingCollection)collection; foreach (WsdlNS.Binding binding in bindings) { if (binding.Name == name) { return true; } } return false; } private static WsdlNS.ServiceDescription CloneWsdl(WsdlNS.ServiceDescription originalWsdl) { Fx.Assert(originalWsdl != null, "originalWsdl must not be null"); WsdlNS.ServiceDescription newWsdl; using (MemoryStream memoryStream = new MemoryStream()) { originalWsdl.Write(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); newWsdl = WsdlNS.ServiceDescription.Read(memoryStream); } return newWsdl; } private static XmlSchema CloneXsd(XmlSchema originalXsd) { Fx.Assert(originalXsd != null, "originalXsd must not be null"); XmlSchema newXsd; using (MemoryStream memoryStream = new MemoryStream()) { originalXsd.Write(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); newXsd = XmlSchema.Read(memoryStream, null); } return newXsd; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Mono.Debugger.Cli { public sealed class CommandArguments { internal CommandArguments(IEnumerable<string> args) { _args = args; _enum = args.GetEnumerator(); } private readonly IEnumerable<string> _args; private readonly IEnumerator<string> _enum; public bool HasArguments { get { return _args.Count() > 0; } } public bool NextBoolean(bool? def = null) { if (!_enum.MoveNext()) { if (def != null) return (bool)def; throw MissingArgument(); } bool value; if (bool.TryParse(_enum.Current, out value)) return value; throw InvalidFormat(); } public char NextChar(char? def = null) { if (!_enum.MoveNext()) { if (def != null) return (char)def; throw MissingArgument(); } char value; if (char.TryParse(_enum.Current, out value)) return value; throw InvalidFormat(); } public byte NextByte(byte? def = null) { if (!_enum.MoveNext()) { if (def != null) return (byte)def; throw MissingArgument(); } byte value; if (byte.TryParse(_enum.Current, out value)) return value; throw InvalidFormat(); } public sbyte NextSByte(sbyte? def = null) { if (!_enum.MoveNext()) { if (def != null) return (sbyte)def; throw MissingArgument(); } if (!_enum.MoveNext()) throw MissingArgument(); sbyte value; if (sbyte.TryParse(_enum.Current, out value)) return value; throw InvalidFormat(); } public ushort NextUInt16(ushort? def = null) { if (!_enum.MoveNext()) { if (def != null) return (ushort)def; throw MissingArgument(); } ushort value; if (ushort.TryParse(_enum.Current, out value)) return value; throw InvalidFormat(); } public short NextInt16(short? def = null) { if (!_enum.MoveNext()) { if (def != null) return (short)def; throw MissingArgument(); } if (!_enum.MoveNext()) throw MissingArgument(); short value; if (short.TryParse(_enum.Current, out value)) return value; throw InvalidFormat(); } public uint NextUInt32(uint? def = null) { if (!_enum.MoveNext()) { if (def != null) return (uint)def; throw MissingArgument(); } uint value; if (uint.TryParse(_enum.Current, out value)) return value; throw InvalidFormat(); } public int NextInt32(int? def = null) { if (!_enum.MoveNext()) { if (def != null) return (int)def; throw MissingArgument(); } int value; if (int.TryParse(_enum.Current, out value)) return value; throw InvalidFormat(); } public ulong NextUInt64(ulong? def = null) { if (!_enum.MoveNext()) { if (def != null) return (ulong)def; throw MissingArgument(); } ulong value; if (ulong.TryParse(_enum.Current, out value)) return value; throw InvalidFormat(); } public long NextInt64(long? def = null) { if (!_enum.MoveNext()) { if (def != null) return (long)def; throw MissingArgument(); } long value; if (long.TryParse(_enum.Current, out value)) return value; throw InvalidFormat(); } public float NextSingle(float? def = null) { if (!_enum.MoveNext()) { if (def != null) return (float)def; throw MissingArgument(); } float value; if (float.TryParse(_enum.Current, out value)) return value; throw InvalidFormat(); } public double NextDouble(double? def = null) { if (!_enum.MoveNext()) { if (def != null) return (double)def; throw MissingArgument(); } double value; if (double.TryParse(_enum.Current, out value)) return value; throw InvalidFormat(); } public decimal NextDecimal(decimal? def = null) { if (!_enum.MoveNext()) { if (def != null) return (decimal)def; throw MissingArgument(); } decimal value; if (decimal.TryParse(_enum.Current, out value)) return value; throw InvalidFormat(); } public string NextString(string def = null) { if (!_enum.MoveNext()) { if (def != null) return def; throw MissingArgument(); } var current = _enum.Current; // Special case for quoted strings... if (current.StartsWith("\"")) { while (!current.EndsWith("\"")) current += " " + NextString(); // Skip the last space and quotation mark. return current.Substring(1, current.Length - 2); } return current; } public T NextEnum<T>(T? def = null) where T : struct { if (!typeof(T).IsEnum) throw new ArgumentException("Type T is not an enum."); T value; if (Enum.TryParse(NextString(def != null ? def.ToString() : null), true, out value)) return value; throw InvalidFormat(); } private static Exception MissingArgument() { return new CommandArgumentException("Missing command argument."); } private static Exception InvalidFormat() { return new CommandArgumentException("Incorrectly formatted argument."); } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using TABS_UserControls.resources.code.BAL; using System.Data.SqlTypes; using TABS_UserControls.resources.code.DAL; namespace TABS_UserControls.usercontrols { public partial class postedit_jobs : System.Web.UI.UserControl { UserClass userlogic = new UserClass(); SchoolClass schoologic = new SchoolClass(); ProfileClass profilelogic = new ProfileClass(); SchoolManagerClass manage = new SchoolManagerClass(); tabs_admin adminlogic = new tabs_admin(); JobClass joblogic = new JobClass(); int jobid, userid, schoolid; protected void Page_Init(object sender, EventArgs e) { try { jobid = Convert.ToInt32(Request.QueryString["job"]); } catch { jobid = 0; } try { userid = Convert.ToInt32(Session["userid"].ToString()); } catch { userid = 0; } try { schoolid = userlogic.getSchoolByUserId(userid)[0].schoolid; } catch { schoolid = 0; } // debug //jobid = 8; //userid = 1; //schoolid = 1069; } protected void Page_Load(object sender, EventArgs e) { if (jobid != 0) { // This is a Existing if (!Page.IsPostBack) { ddlCountry.DataSource = adminlogic.getCountry(); ddlCountry.DataBind(); ddlCountry.Items.FindByText("USA").Selected = true; ddlState.DataSource = manage.getStatesByCountryId(Convert.ToInt16(ddlCountry.SelectedValue)); ddlState.DataBind(); ddlSchool.DataSource = schoologic.getSchools(); ddlSchool.DataBind(); chxListJob.DataSource = joblogic.getJobTypes(); chxListJob.DataBind(); rdoCalendar.DataSource = joblogic.GetCalendarYearTypes(); rdoCalendar.DataBind(); this.DisplayExistingJob(jobid); } } else { // This is a new Job if (!Page.IsPostBack) { ddlCountry.DataSource = adminlogic.getCountry(); ddlCountry.DataBind(); ddlCountry.Items.FindByText("USA").Selected = true; ddlState.DataSource = manage.getStatesByCountryId(Convert.ToInt16(ddlCountry.SelectedValue)); ddlState.DataBind(); ddlSchool.DataSource = schoologic.getSchools(); ddlSchool.DataBind(); chxListJob.DataSource = joblogic.getJobTypes(); chxListJob.DataBind(); rdoCalendar.DataSource = joblogic.GetCalendarYearTypes(); rdoCalendar.DataBind(); ddlCategory.DataSource = joblogic.GetJobCategories(); ddlCategory.DataBind(); ddlSalary.DataSource = joblogic.GetJobSalaries(); ddlSalary.DataBind(); chxBenefits.DataSource = joblogic.getBenefits(); chxBenefits.DataBind(); } } } protected void DisplayExistingJob(int jobid) { TABS_UserControls.resources.code.DAL.JobsDataset._tabs_JobsRow row = joblogic.getSchoolJobByJobId(jobid)[0]; postDate.Text = row.PostingDate.ToString(); expireDate.Text = row.ExpirationDate.ToString(); jobtitle.Text = row.JobTitle.ToString(); ddlSchool.Items.FindByValue(row.SchoolId.ToString()).Selected = true; txtPerson.Text = row.ContactName.ToString(); txtEmail.Text = row.ContactEmail.ToString(); chxHideEmail.Checked = row.HideContactEmail; chxHidePerson.Checked = row.HideContactName; chxHideSchool.Checked = row.HideSchool; DataTable jobTypes = joblogic.getJobTypesByJobId(jobid); foreach (DataRow dr in jobTypes.Rows) { chxListJob.Items.FindByValue(dr["JobTypeId"].ToString()).Selected = true; } DataTable jobCal = joblogic.getCalendarYearsByJobId(jobid); foreach (DataRow dr2 in jobCal.Rows) { rdoCalendar.Items.FindByValue(dr2["CalendarYearTypeId"].ToString()).Selected = true; } ddlCategory.DataSource = joblogic.GetJobCategories(); ddlCategory.DataBind(); ddlCategory.Items.FindByValue(row.JobCategoryId.ToString()).Selected = true; txtStartDate.Text = row.ExpirationDate.ToString(); ddlSalary.DataSource = joblogic.GetJobSalaries(); ddlSalary.DataBind(); ddlSalary.Items.FindByValue(row.SalaryId.ToString()).Selected = true; txtDesc.Text = row.JobDescription.ToString(); txtReq.Text = row.JobRequirements.ToString(); chxBenefits.DataSource = joblogic.getBenefits(); chxBenefits.DataBind(); DataTable jobBenefit = joblogic.getJobBenefitsById(jobid); foreach (DataRow dr2 in jobBenefit.Rows) { chxBenefits.Items.FindByValue(dr2["JobBenefitId"].ToString()).Selected = true; } DataTable jobApp = joblogic.getJobAppliesByJobId(jobid); DataTable personDT = new DataTable(); JobsDataset._tabs_JobContactInformationRow controw = null; for (int i = 0; i < jobApp.Rows.Count; i++) { int applyId = Convert.ToInt32(jobApp.Rows[i]["JobApplyMethodId"].ToString()); personDT = joblogic.getJobContactInfoById(Convert.ToInt32(jobApp.Rows[i]["JobsToJobApplyMethodId"].ToString())); controw = (JobsDataset._tabs_JobContactInformationRow)personDT.Rows[0]; switch (applyId) { case 1: chxRegular.Checked = true; txtAttnReg.Text = controw.ContactName; txtAdd1.Text = controw.StreetAddress1; txtAdd2.Text = controw.StreetAddress2; txtCity.Text = controw.City; txtZip.Text = controw.Zipcode; ddlCountry.Items.FindByValue(controw.CountryId.ToString()).Selected = true; ddlState.Items.FindByValue(controw.StateId.ToString()).Selected = true; break; case 2: chxFax.Checked = true; txtAttnFax.Text = controw.ContactName; txtFaxNumber.Text = controw.FaxNumber; break; case 3: chxEmail.Checked = true; txtContactName.Text = controw.ContactName; txtEmail2.Text = controw.EmailAddress; break; case 4: chxOnline.Checked = true; txtUrl.Text = controw.URL; break; default: break; } } //if (jobApp.Rows.Count > 0) //{ // DataTable personDT = joblogic.getJobContactInfoById(Convert.ToInt32(jobApp.Rows[0]["JobsToJobApplyMethodId"].ToString())); // if (personDT.Rows.Count > 0) // { // TABS_UserControls.resources.code.DAL.JobsDataset._tabs_JobContactInformationRow controw = (TABS_UserControls.resources.code.DAL.JobsDataset._tabs_JobContactInformationRow)personDT.Rows[0]; // txtAttnReg.Text = controw.ContactName; // txtAdd1.Text = controw.StreetAddress1; // txtAdd2.Text = controw.StreetAddress2; // txtCity.Text = controw.City; // txtZip.Text = controw.Zipcode; // ddlCountry.Items.FindByValue(controw.CountryId.ToString()).Selected = true; // ddlState.Items.FindByValue(controw.StateId.ToString()).Selected = true; // txtAttnFax.Text = controw.ContactName; // txtFaxNumber.Text = controw.FaxNumber; // txtContactName.Text = controw.ContactName; // txtEmail2.Text = controw.EmailAddress; // txtUrl.Text = controw.URL; // } //} txtInstructions.Text = row.SpecificInstructions.ToString(); } protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e) { ddlState.DataSource = manage.getStatesByCountryId(Convert.ToInt32(ddlCountry.SelectedValue)); ddlState.DataBind(); } protected void btnSubmit_Click(object sender, EventArgs e) { try { jobid = Convert.ToInt32(Request.QueryString["job"]); } catch { jobid = 0; } try { userid = Convert.ToInt32(Session["userid"].ToString()); } catch { userid = 0; } try { schoolid = userlogic.getSchoolByUserId(userid)[0].schoolid; } catch { schoolid = 0; } if (jobid > 0) { this.updatedJob(); } else { this.saveJob(); } } protected void updatedJob() { // delete key relationships DataTable jobApp = joblogic.getJobAppliesByJobId(jobid); for(int i=0; i< jobApp.Rows.Count; i++) { int applyid = Convert.ToInt32(jobApp.Rows[i]["JobsToJobApplyMethodId"].ToString()); joblogic.deleteJobRelationships(jobid, applyid); } DateTime startDate; //int salaryId; // catch non req fields if (String.IsNullOrEmpty(txtStartDate.Text)) { startDate = (DateTime)SqlDateTime.Null; } else { startDate = Convert.ToDateTime(txtStartDate.Text); } // Update //joblogic.updateJobs(jobid, Convert.ToInt32(ddlCategory.SelectedValue), Convert.ToInt32(ddlSalary.SelectedValue), Convert.ToDateTime(postDate.Text), Convert.ToDateTime(expireDate.Text), jobtitle.Text, schoolid, txtPerson.Text, txtEmail.Text, chxHidePerson.Checked, chxHideEmail.Checked, Convert.ToDateTime(txtStartDate.Text), txtDesc.Text, txtReq.Text, txtInstructions.Text, txtCalOther.Text, chxHideSchool.Checked); joblogic.updateJobs(jobid, Convert.ToInt32(ddlCategory.SelectedValue), Convert.ToInt32(ddlSalary.SelectedValue), Convert.ToDateTime(postDate.Text), Convert.ToDateTime(expireDate.Text), jobtitle.Text, schoolid, txtPerson.Text, txtEmail.Text, chxHidePerson.Checked, chxHideEmail.Checked, startDate, txtDesc.Text, txtReq.Text, txtInstructions.Text, txtCalOther.Text, chxHideSchool.Checked); for (int x = 0; x < chxListJob.Items.Count; x++) { if (chxListJob.Items[x].Selected) { joblogic.insertJobTypes(jobid, Convert.ToInt32(chxListJob.Items[x].Value)); } } for (int c = 0; c < rdoCalendar.Items.Count; c++) { if (rdoCalendar.Items[c].Selected) { joblogic.insertJobCalendars(jobid, Convert.ToInt32(rdoCalendar.Items[c].Value)); } } for (int b = 0; b < chxBenefits.Items.Count; b++) { if (chxBenefits.Items[b].Selected) { joblogic.insertJobBenefits(jobid, Convert.ToInt32(chxBenefits.Items[b].Value), chxBenefits.Items[b].Text); } } int val = 1; if (chxRegular.Checked) { val = joblogic.insertJobApplyMethods(jobid, 1); joblogic.insertJobApplyContact(val, txtAttnReg.Text, txtAdd1.Text, txtAdd2.Text, txtCity.Text, Convert.ToInt32(ddlState.SelectedValue), Convert.ToInt32(ddlCountry.SelectedValue), txtZip.Text, txtFaxNumber.Text, txtEmail2.Text, txtUrl.Text); } if (chxEmail.Checked) { val = joblogic.insertJobApplyMethods(jobid, 3); joblogic.insertJobApplyContact(val, txtContactName.Text, txtAdd1.Text, txtAdd2.Text, txtCity.Text, Convert.ToInt32(ddlState.SelectedValue), Convert.ToInt32(ddlCountry.SelectedValue), txtZip.Text, txtFaxNumber.Text, txtEmail2.Text, txtUrl.Text); } if (chxFax.Checked) { val = joblogic.insertJobApplyMethods(jobid, 2); joblogic.insertJobApplyContact(val, txtAttnFax.Text, txtAdd1.Text, txtAdd2.Text, txtCity.Text, Convert.ToInt32(ddlState.SelectedValue), Convert.ToInt32(ddlCountry.SelectedValue), txtZip.Text, txtFaxNumber.Text, txtEmail2.Text, txtUrl.Text); } if (chxOnline.Checked) { val = joblogic.insertJobApplyMethods(jobid, 4); joblogic.insertJobApplyContact(val, txtAttnReg.Text, txtAdd1.Text, txtAdd2.Text, txtCity.Text, Convert.ToInt32(ddlState.SelectedValue), Convert.ToInt32(ddlCountry.SelectedValue), txtZip.Text, txtFaxNumber.Text, txtEmail2.Text, txtUrl.Text); } Response.Redirect("/for-schools/post-edit-jobs.aspx"); } protected void saveJob() { DateTime startDate; //int salaryId; // catch non req fields if (String.IsNullOrEmpty(txtStartDate.Text)) { startDate = (DateTime)SqlDateTime.Null; } else { startDate = Convert.ToDateTime(txtStartDate.Text); } // Insert int retVal = joblogic.insertJob(Convert.ToInt32(ddlCategory.SelectedValue), Convert.ToInt32(ddlSalary.SelectedValue), Convert.ToDateTime(postDate.Text), Convert.ToDateTime(expireDate.Text), jobtitle.Text, schoolid, txtPerson.Text, txtEmail.Text, chxHidePerson.Checked, chxHideEmail.Checked, startDate, txtDesc.Text, txtReq.Text, txtInstructions.Text, txtCalOther.Text, chxHideSchool.Checked); DataTable jobApp = joblogic.getJobAppliesByJobId(retVal); for (int x = 0; x < chxListJob.Items.Count; x++) { if (chxListJob.Items[x].Selected) { joblogic.insertJobTypes(retVal, Convert.ToInt32(chxListJob.Items[x].Value)); } } for (int c = 0; c < rdoCalendar.Items.Count; c++) { if (rdoCalendar.Items[c].Selected) { joblogic.insertJobCalendars(retVal, Convert.ToInt32(rdoCalendar.Items[c].Value)); } } for (int b = 0; b < chxBenefits.Items.Count; b++) { if (chxBenefits.Items[b].Selected) { joblogic.insertJobBenefits(retVal, Convert.ToInt32(chxBenefits.Items[b].Value), chxBenefits.Items[b].Text); } } int val = 1; if (chxRegular.Checked) { val = joblogic.insertJobApplyMethods(retVal, 1); joblogic.insertJobApplyContact(val, txtAttnReg.Text, txtAdd1.Text, txtAdd2.Text, txtCity.Text, Convert.ToInt32(ddlState.SelectedValue), Convert.ToInt32(ddlCountry.SelectedValue), txtZip.Text, txtFaxNumber.Text, txtEmail2.Text, txtUrl.Text); } if (chxEmail.Checked) { val = joblogic.insertJobApplyMethods(retVal, 3); joblogic.insertJobApplyContact(val, txtContactName.Text, txtAdd1.Text, txtAdd2.Text, txtCity.Text, Convert.ToInt32(ddlState.SelectedValue), Convert.ToInt32(ddlCountry.SelectedValue), txtZip.Text, txtFaxNumber.Text, txtEmail2.Text, txtUrl.Text); } if (chxFax.Checked) { val = joblogic.insertJobApplyMethods(retVal, 2); joblogic.insertJobApplyContact(val, txtAttnFax.Text, txtAdd1.Text, txtAdd2.Text, txtCity.Text, Convert.ToInt32(ddlState.SelectedValue), Convert.ToInt32(ddlCountry.SelectedValue), txtZip.Text, txtFaxNumber.Text, txtEmail2.Text, txtUrl.Text); } if (chxOnline.Checked) { val = joblogic.insertJobApplyMethods(retVal, 4); joblogic.insertJobApplyContact(val, txtAttnReg.Text, txtAdd1.Text, txtAdd2.Text, txtCity.Text, Convert.ToInt32(ddlState.SelectedValue), Convert.ToInt32(ddlCountry.SelectedValue), txtZip.Text, txtFaxNumber.Text, txtEmail2.Text, txtUrl.Text); } Response.Redirect("/for-schools/post-edit-jobs.aspx"); } protected void chxRegular_CheckedChanged(object sender, EventArgs e) { if (warining1.Visible == false) { warining1.Visible = true; warining2.Visible = true; warining3.Visible = true; warining4.Visible = true; warining5.Visible = true; warining6.Visible = true; warining7.Visible = false; warining8.Visible = false; warining9.Visible = false; warining10.Visible = false; warining11.Visible = false; } else { warining1.Visible = false; warining2.Visible = false; warining3.Visible = false; warining4.Visible = false; warining5.Visible = false; warining6.Visible = false; warining7.Visible = false; warining8.Visible = false; warining9.Visible = false; warining10.Visible = false; warining11.Visible = false; } } protected void chxFax_CheckedChanged(object sender, EventArgs e) { if (warining7.Visible == false) { warining1.Visible = false; warining2.Visible = false; warining3.Visible = false; warining4.Visible = false; warining5.Visible = false; warining6.Visible = false; warining7.Visible = true; warining8.Visible = true; warining9.Visible = false; warining10.Visible = false; warining11.Visible = false; } else { warining1.Visible = false; warining2.Visible = false; warining3.Visible = false; warining4.Visible = false; warining5.Visible = false; warining6.Visible = false; warining7.Visible = false; warining8.Visible = false; warining9.Visible = false; warining10.Visible = false; warining11.Visible = false; } } protected void chxEmail_CheckedChanged(object sender, EventArgs e) { if (warining9.Visible == false) { warining1.Visible = false; warining2.Visible = false; warining3.Visible = false; warining4.Visible = false; warining5.Visible = false; warining6.Visible = false; warining7.Visible = false; warining8.Visible = false; warining9.Visible = true; warining10.Visible = true; warining11.Visible = false; } else { warining1.Visible = false; warining2.Visible = false; warining3.Visible = false; warining4.Visible = false; warining5.Visible = false; warining6.Visible = false; warining7.Visible = false; warining8.Visible = false; warining9.Visible = false; warining10.Visible = false; warining11.Visible = false; } } protected void chxOnline_CheckedChanged(object sender, EventArgs e) { if (warining11.Visible == false) { warining1.Visible = false; warining2.Visible = false; warining3.Visible = false; warining4.Visible = false; warining5.Visible = false; warining6.Visible = false; warining7.Visible = false; warining8.Visible = false; warining9.Visible = false; warining10.Visible = false; warining11.Visible = true; } else { warining1.Visible = false; warining2.Visible = false; warining3.Visible = false; warining4.Visible = false; warining5.Visible = false; warining6.Visible = false; warining7.Visible = false; warining8.Visible = false; warining9.Visible = false; warining10.Visible = false; warining11.Visible = false; } } } }
/* * 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. */ #pragma warning disable 649 #pragma warning disable 169 namespace Apache.Ignite.Core.Tests.Compute { using System; using System.Collections.Generic; using System.Linq; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Test for task and job adapter. /// </summary> public class TaskAdapterTest : AbstractTaskTest { /// <summary> /// Constructor. /// </summary> public TaskAdapterTest() : base(false) { } /// <summary> /// Constructor. /// </summary> /// <param name="fork">Fork flag.</param> protected TaskAdapterTest(bool fork) : base(fork) { } /// <summary> /// Test for task adapter. /// </summary> [Test] public void TestTaskAdapter() { Assert.AreEqual(3, Grid1.GetCluster().GetNodes().Count); HashSet<Guid> allNodes = new HashSet<Guid>(); for (int i = 0; i < 20 && allNodes.Count < GetServerCount(); i++) { HashSet<Guid> res = Grid1.GetCompute().Execute(new TestSplitTask(), 1); Assert.AreEqual(1, res.Count); allNodes.UnionWith(res); } Assert.AreEqual(GetServerCount(), allNodes.Count); HashSet<Guid> res2 = Grid1.GetCompute().Execute<int, Guid, HashSet<Guid>>(typeof(TestSplitTask), 3); Assert.IsTrue(res2.Count > 0); Grid1.GetCompute().Execute(new TestSplitTask(), 100); Assert.AreEqual(GetServerCount(), allNodes.Count); } /// <summary> /// Test for job adapter. /// </summary> [Test] public void TestSerializableJobAdapter() { for (int i = 0; i < 10; i++) { bool res = Grid1.GetCompute().Execute(new TestJobAdapterTask(), true); Assert.IsTrue(res); } } /// <summary> /// Test for job adapter. /// </summary> [Test] public void TestBinarizableJobAdapter() { for (int i = 0; i < 10; i++) { bool res = Grid1.GetCompute().Execute(new TestJobAdapterTask(), false); Assert.IsTrue(res); } } /** <inheritDoc /> */ override protected void GetBinaryTypeConfigurations(ICollection<BinaryTypeConfiguration> portTypeCfgs) { portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableJob))); } /// <summary> /// Test task. /// </summary> public class TestSplitTask : ComputeTaskSplitAdapter<int, Guid, HashSet<Guid>> { [InstanceResource] private readonly IIgnite _ignite; /** <inheritDoc /> */ override protected ICollection<IComputeJob<Guid>> Split(int gridSize, int arg) { Assert.AreEqual(_ignite.GetCluster().GetNodes().Count(x => !x.IsClient), gridSize); int jobsNum = arg; Assert.IsTrue(jobsNum > 0); var jobs = new List<IComputeJob<Guid>>(jobsNum); for (int i = 0; i < jobsNum; i++) jobs.Add(new NodeIdJob()); return jobs; } /** <inheritDoc /> */ override public HashSet<Guid> Reduce(IList<IComputeJobResult<Guid>> results) { HashSet<Guid> nodes = new HashSet<Guid>(); foreach (var res in results) { Guid id = res.Data; Assert.NotNull(id); nodes.Add(id); } return nodes; } } /// <summary> /// Test task. /// </summary> public class TestJobAdapterTask : ComputeTaskSplitAdapter<bool, bool, bool> { /** <inheritDoc /> */ override protected ICollection<IComputeJob<bool>> Split(int gridSize, bool arg) { bool serializable = arg; ICollection<IComputeJob<bool>> jobs = new List<IComputeJob<bool>>(1); if (serializable) jobs.Add(new SerializableJob(100, "str")); else jobs.Add(new BinarizableJob(100, "str")); return jobs; } /** <inheritDoc /> */ override public bool Reduce(IList<IComputeJobResult<bool>> results) { Assert.AreEqual(1, results.Count); Assert.IsTrue(results[0].Data); return true; } } /// <summary> /// Test job. /// </summary> [Serializable] public class NodeIdJob : IComputeJob<Guid> { [InstanceResource] private IIgnite _grid = null; /** <inheritDoc /> */ public Guid Execute() { Assert.NotNull(_grid); return _grid.GetCluster().GetLocalNode().Id; } /** <inheritDoc /> */ public void Cancel() { // No-op. } } /// <summary> /// Test serializable job. /// </summary> [Serializable] public class SerializableJob : ComputeJobAdapter<bool> { [InstanceResource] private IIgnite _grid = null; public SerializableJob(params object[] args) : base(args) { // No-op. } /** <inheritDoc /> */ override public bool Execute() { Assert.IsFalse(IsCancelled()); Cancel(); Assert.IsTrue(IsCancelled()); Assert.NotNull(_grid); int arg1 = GetArgument<int>(0); Assert.AreEqual(100, arg1); string arg2 = GetArgument<string>(1); Assert.AreEqual("str", arg2); return true; } } /// <summary> /// Test binary job. /// </summary> public class BinarizableJob : ComputeJobAdapter<bool> { [InstanceResource] private IIgnite _grid; public BinarizableJob(params object[] args) : base(args) { // No-op. } /** <inheritDoc /> */ override public bool Execute() { Assert.IsFalse(IsCancelled()); Cancel(); Assert.IsTrue(IsCancelled()); Assert.NotNull(_grid); int arg1 = GetArgument<int>(0); Assert.AreEqual(100, arg1); string arg2 = GetArgument<string>(1); Assert.AreEqual("str", arg2); return true; } } } }
using System; using System.IO; /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 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 end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "Ant" and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * This package is based on the work done by Keiron Liddle, Aftex Software * <keiron@aftexsw.com> to whom the Ant project is very grateful for his * great code. */ namespace Org.BouncyCastle.Apache.Bzip2 { /** * An input stream that decompresses from the BZip2 format (with the file * header chars) to be read as any other stream. * * @author <a href="mailto:keiron@aftexsw.com">Keiron Liddle</a> * * <b>NB:</b> note this class has been modified to read the leading BZ from the * start of the BZIP2 stream to make it compatible with other PGP programs. */ public class CBZip2InputStream : Stream { private static void Cadvise() { //System.out.Println("CRC Error"); //throw new CCoruptionError(); } private static void BadBGLengths() { Cadvise(); } private static void BitStreamEOF() { Cadvise(); } private static void CompressedStreamEOF() { Cadvise(); } private void MakeMaps() { int i; nInUse = 0; for (i = 0; i < 256; i++) { if (inUse[i]) { seqToUnseq[nInUse] = (char) i; unseqToSeq[i] = (char) nInUse; nInUse++; } } } /* index of the last char in the block, so the block size == last + 1. */ private int last; /* index in zptr[] of original string after sorting. */ private int origPtr; /* always: in the range 0 .. 9. The current block size is 100000 * this number. */ private int blockSize100k; private bool blockRandomised; private int bsBuff; private int bsLive; private CRC mCrc = new CRC(); private bool[] inUse = new bool[256]; private int nInUse; private char[] seqToUnseq = new char[256]; private char[] unseqToSeq = new char[256]; private char[] selector = new char[BZip2Constants.MAX_SELECTORS]; private char[] selectorMtf = new char[BZip2Constants.MAX_SELECTORS]; private int[] tt; private char[] ll8; /* freq table collected to save a pass over the data during decompression. */ private int[] unzftab = new int[256]; private int[][] limit = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); private int[][] basev = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); private int[][] perm = InitIntArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); private int[] minLens = new int[BZip2Constants.N_GROUPS]; private Stream bsStream; private bool streamEnd = false; private int currentChar = -1; private const int START_BLOCK_STATE = 1; private const int RAND_PART_A_STATE = 2; private const int RAND_PART_B_STATE = 3; private const int RAND_PART_C_STATE = 4; private const int NO_RAND_PART_A_STATE = 5; private const int NO_RAND_PART_B_STATE = 6; private const int NO_RAND_PART_C_STATE = 7; private int currentState = START_BLOCK_STATE; private int storedBlockCRC, storedCombinedCRC; private int computedBlockCRC, computedCombinedCRC; int i2, count, chPrev, ch2; int i, tPos; int rNToGo = 0; int rTPos = 0; int j2; char z; public CBZip2InputStream(Stream zStream) { ll8 = null; tt = null; BsSetStream(zStream); Initialize(); InitBlock(); SetupBlock(); } internal static int[][] InitIntArray(int n1, int n2) { int[][] a = new int[n1][]; for (int k = 0; k < n1; ++k) { a[k] = new int[n2]; } return a; } internal static char[][] InitCharArray(int n1, int n2) { char[][] a = new char[n1][]; for (int k = 0; k < n1; ++k) { a[k] = new char[n2]; } return a; } public override int ReadByte() { if (streamEnd) { return -1; } else { int retChar = currentChar; switch (currentState) { case START_BLOCK_STATE: break; case RAND_PART_A_STATE: break; case RAND_PART_B_STATE: SetupRandPartB(); break; case RAND_PART_C_STATE: SetupRandPartC(); break; case NO_RAND_PART_A_STATE: break; case NO_RAND_PART_B_STATE: SetupNoRandPartB(); break; case NO_RAND_PART_C_STATE: SetupNoRandPartC(); break; default: break; } return retChar; } } private void Initialize() { char magic3, magic4; magic3 = BsGetUChar(); magic4 = BsGetUChar(); if (magic3 != 'B' && magic4 != 'Z') { throw new IOException("Not a BZIP2 marked stream"); } magic3 = BsGetUChar(); magic4 = BsGetUChar(); if (magic3 != 'h' || magic4 < '1' || magic4 > '9') { BsFinishedWithStream(); streamEnd = true; return; } SetDecompressStructureSizes(magic4 - '0'); computedCombinedCRC = 0; } private void InitBlock() { char magic1, magic2, magic3, magic4; char magic5, magic6; magic1 = BsGetUChar(); magic2 = BsGetUChar(); magic3 = BsGetUChar(); magic4 = BsGetUChar(); magic5 = BsGetUChar(); magic6 = BsGetUChar(); if (magic1 == 0x17 && magic2 == 0x72 && magic3 == 0x45 && magic4 == 0x38 && magic5 == 0x50 && magic6 == 0x90) { Complete(); return; } if (magic1 != 0x31 || magic2 != 0x41 || magic3 != 0x59 || magic4 != 0x26 || magic5 != 0x53 || magic6 != 0x59) { BadBlockHeader(); streamEnd = true; return; } storedBlockCRC = BsGetInt32(); if (BsR(1) == 1) { blockRandomised = true; } else { blockRandomised = false; } // currBlockNo++; GetAndMoveToFrontDecode(); mCrc.InitialiseCRC(); currentState = START_BLOCK_STATE; } private void EndBlock() { computedBlockCRC = mCrc.GetFinalCRC(); /* A bad CRC is considered a fatal error. */ if (storedBlockCRC != computedBlockCRC) { CrcError(); } computedCombinedCRC = (computedCombinedCRC << 1) | (int)(((uint)computedCombinedCRC) >> 31); computedCombinedCRC ^= computedBlockCRC; } private void Complete() { storedCombinedCRC = BsGetInt32(); if (storedCombinedCRC != computedCombinedCRC) { CrcError(); } BsFinishedWithStream(); streamEnd = true; } private static void BlockOverrun() { Cadvise(); } private static void BadBlockHeader() { Cadvise(); } private static void CrcError() { Cadvise(); } private void BsFinishedWithStream() { try { if (this.bsStream != null) { this.bsStream.Close(); this.bsStream = null; } } catch { //ignore } } private void BsSetStream(Stream f) { bsStream = f; bsLive = 0; bsBuff = 0; } private int BsR(int n) { int v; while (bsLive < n) { int zzi; char thech = '\0'; try { thech = (char) bsStream.ReadByte(); } catch (IOException) { CompressedStreamEOF(); } if (thech == '\uffff') { CompressedStreamEOF(); } zzi = thech; bsBuff = (bsBuff << 8) | (zzi & 0xff); bsLive += 8; } v = (bsBuff >> (bsLive - n)) & ((1 << n) - 1); bsLive -= n; return v; } private char BsGetUChar() { return (char) BsR(8); } private int BsGetint() { int u = 0; u = (u << 8) | BsR(8); u = (u << 8) | BsR(8); u = (u << 8) | BsR(8); u = (u << 8) | BsR(8); return u; } private int BsGetIntVS(int numBits) { return (int) BsR(numBits); } private int BsGetInt32() { return (int) BsGetint(); } private void HbCreateDecodeTables(int[] limit, int[] basev, int[] perm, char[] length, int minLen, int maxLen, int alphaSize) { int pp, i, j, vec; pp = 0; for (i = minLen; i <= maxLen; i++) { for (j = 0; j < alphaSize; j++) { if (length[j] == i) { perm[pp] = j; pp++; } } } for (i = 0; i < BZip2Constants.MAX_CODE_LEN; i++) { basev[i] = 0; } for (i = 0; i < alphaSize; i++) { basev[length[i] + 1]++; } for (i = 1; i < BZip2Constants.MAX_CODE_LEN; i++) { basev[i] += basev[i - 1]; } for (i = 0; i < BZip2Constants.MAX_CODE_LEN; i++) { limit[i] = 0; } vec = 0; for (i = minLen; i <= maxLen; i++) { vec += (basev[i + 1] - basev[i]); limit[i] = vec - 1; vec <<= 1; } for (i = minLen + 1; i <= maxLen; i++) { basev[i] = ((limit[i - 1] + 1) << 1) - basev[i]; } } private void RecvDecodingTables() { char[][] len = InitCharArray(BZip2Constants.N_GROUPS, BZip2Constants.MAX_ALPHA_SIZE); int i, j, t, nGroups, nSelectors, alphaSize; int minLen, maxLen; bool[] inUse16 = new bool[16]; /* Receive the mapping table */ for (i = 0; i < 16; i++) { if (BsR(1) == 1) { inUse16[i] = true; } else { inUse16[i] = false; } } for (i = 0; i < 256; i++) { inUse[i] = false; } for (i = 0; i < 16; i++) { if (inUse16[i]) { for (j = 0; j < 16; j++) { if (BsR(1) == 1) { inUse[i * 16 + j] = true; } } } } MakeMaps(); alphaSize = nInUse + 2; /* Now the selectors */ nGroups = BsR(3); nSelectors = BsR(15); for (i = 0; i < nSelectors; i++) { j = 0; while (BsR(1) == 1) { j++; } selectorMtf[i] = (char) j; } /* Undo the MTF values for the selectors. */ { char[] pos = new char[BZip2Constants.N_GROUPS]; char tmp, v; for (v = '\0'; v < nGroups; v++) { pos[v] = v; } for (i = 0; i < nSelectors; i++) { v = selectorMtf[i]; tmp = pos[v]; while (v > 0) { pos[v] = pos[v - 1]; v--; } pos[0] = tmp; selector[i] = tmp; } } /* Now the coding tables */ for (t = 0; t < nGroups; t++) { int curr = BsR(5); for (i = 0; i < alphaSize; i++) { while (BsR(1) == 1) { if (BsR(1) == 0) { curr++; } else { curr--; } } len[t][i] = (char) curr; } } /* Create the Huffman decoding tables */ for (t = 0; t < nGroups; t++) { minLen = 32; maxLen = 0; for (i = 0; i < alphaSize; i++) { if (len[t][i] > maxLen) { maxLen = len[t][i]; } if (len[t][i] < minLen) { minLen = len[t][i]; } } HbCreateDecodeTables(limit[t], basev[t], perm[t], len[t], minLen, maxLen, alphaSize); minLens[t] = minLen; } } private void GetAndMoveToFrontDecode() { char[] yy = new char[256]; int i, j, nextSym, limitLast; int EOB, groupNo, groupPos; limitLast = BZip2Constants.baseBlockSize * blockSize100k; origPtr = BsGetIntVS(24); RecvDecodingTables(); EOB = nInUse + 1; groupNo = -1; groupPos = 0; /* Setting up the unzftab entries here is not strictly necessary, but it does save having to do it later in a separate pass, and so saves a block's worth of cache misses. */ for (i = 0; i <= 255; i++) { unzftab[i] = 0; } for (i = 0; i <= 255; i++) { yy[i] = (char) i; } last = -1; { int zt, zn, zvec, zj; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.G_SIZE; } groupPos--; zt = selector[groupNo]; zn = minLens[zt]; zvec = BsR(zn); while (zvec > limit[zt][zn]) { zn++; { { while (bsLive < 1) { int zzi; char thech = '\0'; try { thech = (char) bsStream.ReadByte(); } catch (IOException) { CompressedStreamEOF(); } if (thech == '\uffff') { CompressedStreamEOF(); } zzi = thech; bsBuff = (bsBuff << 8) | (zzi & 0xff); bsLive += 8; } } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; } zvec = (zvec << 1) | zj; } nextSym = perm[zt][zvec - basev[zt][zn]]; } while (true) { if (nextSym == EOB) { break; } if (nextSym == BZip2Constants.RUNA || nextSym == BZip2Constants.RUNB) { char ch; int s = -1; int N = 1; do { if (nextSym == BZip2Constants.RUNA) { s = s + (0 + 1) * N; } else if (nextSym == BZip2Constants.RUNB) { s = s + (1 + 1) * N; } N = N * 2; { int zt, zn, zvec, zj; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.G_SIZE; } groupPos--; zt = selector[groupNo]; zn = minLens[zt]; zvec = BsR(zn); while (zvec > limit[zt][zn]) { zn++; { { while (bsLive < 1) { int zzi; char thech = '\0'; try { thech = (char) bsStream.ReadByte(); } catch (IOException) { CompressedStreamEOF(); } if (thech == '\uffff') { CompressedStreamEOF(); } zzi = thech; bsBuff = (bsBuff << 8) | (zzi & 0xff); bsLive += 8; } } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; } zvec = (zvec << 1) | zj; } nextSym = perm[zt][zvec - basev[zt][zn]]; } } while (nextSym == BZip2Constants.RUNA || nextSym == BZip2Constants.RUNB); s++; ch = seqToUnseq[yy[0]]; unzftab[ch] += s; while (s > 0) { last++; ll8[last] = ch; s--; } if (last >= limitLast) { BlockOverrun(); } continue; } else { char tmp; last++; if (last >= limitLast) { BlockOverrun(); } tmp = yy[nextSym - 1]; unzftab[seqToUnseq[tmp]]++; ll8[last] = seqToUnseq[tmp]; /* This loop is hammered during decompression, hence the unrolling. for (j = nextSym-1; j > 0; j--) yy[j] = yy[j-1]; */ j = nextSym - 1; for (; j > 3; j -= 4) { yy[j] = yy[j - 1]; yy[j - 1] = yy[j - 2]; yy[j - 2] = yy[j - 3]; yy[j - 3] = yy[j - 4]; } for (; j > 0; j--) { yy[j] = yy[j - 1]; } yy[0] = tmp; { int zt, zn, zvec, zj; if (groupPos == 0) { groupNo++; groupPos = BZip2Constants.G_SIZE; } groupPos--; zt = selector[groupNo]; zn = minLens[zt]; zvec = BsR(zn); while (zvec > limit[zt][zn]) { zn++; { { while (bsLive < 1) { int zzi; char thech = '\0'; try { thech = (char) bsStream.ReadByte(); } catch (IOException) { CompressedStreamEOF(); } zzi = thech; bsBuff = (bsBuff << 8) | (zzi & 0xff); bsLive += 8; } } zj = (bsBuff >> (bsLive - 1)) & 1; bsLive--; } zvec = (zvec << 1) | zj; } nextSym = perm[zt][zvec - basev[zt][zn]]; } continue; } } } private void SetupBlock() { int[] cftab = new int[257]; char ch; cftab[0] = 0; for (i = 1; i <= 256; i++) { cftab[i] = unzftab[i - 1]; } for (i = 1; i <= 256; i++) { cftab[i] += cftab[i - 1]; } for (i = 0; i <= last; i++) { ch = (char) ll8[i]; tt[cftab[ch]] = i; cftab[ch]++; } cftab = null; tPos = tt[origPtr]; count = 0; i2 = 0; ch2 = 256; /* not a char and not EOF */ if (blockRandomised) { rNToGo = 0; rTPos = 0; SetupRandPartA(); } else { SetupNoRandPartA(); } } private void SetupRandPartA() { if (i2 <= last) { chPrev = ch2; ch2 = ll8[tPos]; tPos = tt[tPos]; if (rNToGo == 0) { rNToGo = BZip2Constants.rNums[rTPos]; rTPos++; if (rTPos == 512) { rTPos = 0; } } rNToGo--; ch2 ^= (int) ((rNToGo == 1) ? 1 : 0); i2++; currentChar = ch2; currentState = RAND_PART_B_STATE; mCrc.UpdateCRC(ch2); } else { EndBlock(); InitBlock(); SetupBlock(); } } private void SetupNoRandPartA() { if (i2 <= last) { chPrev = ch2; ch2 = ll8[tPos]; tPos = tt[tPos]; i2++; currentChar = ch2; currentState = NO_RAND_PART_B_STATE; mCrc.UpdateCRC(ch2); } else { EndBlock(); InitBlock(); SetupBlock(); } } private void SetupRandPartB() { if (ch2 != chPrev) { currentState = RAND_PART_A_STATE; count = 1; SetupRandPartA(); } else { count++; if (count >= 4) { z = ll8[tPos]; tPos = tt[tPos]; if (rNToGo == 0) { rNToGo = BZip2Constants.rNums[rTPos]; rTPos++; if (rTPos == 512) { rTPos = 0; } } rNToGo--; z ^= (char)((rNToGo == 1) ? 1 : 0); j2 = 0; currentState = RAND_PART_C_STATE; SetupRandPartC(); } else { currentState = RAND_PART_A_STATE; SetupRandPartA(); } } } private void SetupRandPartC() { if (j2 < (int) z) { currentChar = ch2; mCrc.UpdateCRC(ch2); j2++; } else { currentState = RAND_PART_A_STATE; i2++; count = 0; SetupRandPartA(); } } private void SetupNoRandPartB() { if (ch2 != chPrev) { currentState = NO_RAND_PART_A_STATE; count = 1; SetupNoRandPartA(); } else { count++; if (count >= 4) { z = ll8[tPos]; tPos = tt[tPos]; currentState = NO_RAND_PART_C_STATE; j2 = 0; SetupNoRandPartC(); } else { currentState = NO_RAND_PART_A_STATE; SetupNoRandPartA(); } } } private void SetupNoRandPartC() { if (j2 < (int) z) { currentChar = ch2; mCrc.UpdateCRC(ch2); j2++; } else { currentState = NO_RAND_PART_A_STATE; i2++; count = 0; SetupNoRandPartA(); } } private void SetDecompressStructureSizes(int newSize100k) { if (!(0 <= newSize100k && newSize100k <= 9 && 0 <= blockSize100k && blockSize100k <= 9)) { // throw new IOException("Invalid block size"); } blockSize100k = newSize100k; if (newSize100k == 0) { return; } int n = BZip2Constants.baseBlockSize * newSize100k; ll8 = new char[n]; tt = new int[n]; } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { int c = -1; int k; for (k = 0; k < count; ++k) { c = ReadByte(); if (c == -1) break; buffer[k + offset] = (byte)c; } return k; } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long value) { } public override void Write(byte[] buffer, int offset, int count) { } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { } } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Net.Sockets; using System.IO; using System.Runtime.InteropServices; namespace EmergeTk { public class CometClient : Surface { private static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(CometClient)); static byte[] XMLPolicyBytes = Encoding.ASCII.GetBytes(CometServer.XMLPolicy); //UTF8Encoding.GetBytes(XMLPolicy); //Encoding.ASCIIEncoding.GetBytes(XMLPolicy); string url; NameValueCollection querystring; Dictionary<string, string> headers = new Dictionary<string, string>(), cookies = new Dictionary<string,string>(); Socket s; Context context; ICometWriter writer; static CometClient() { //ASCIIEncoding a = new ASCIIEncoding(); //XMLPolicyBytes = a.GetBytes(XMLPolicy); } public CometClient(Socket s) { this.s = s; } public bool Connected { get { return s.Connected; } } public string CacheKey { get { return url; } } public Context Context { get { return context; } set { context = value; } } public Dictionary<string, string> Headers { get { return headers; } } public Dictionary<string, string> Cookies { get { return cookies; } } protected NetworkStream ns; protected BufferedStream bs; protected StreamReader sr; protected StreamWriter sw; public void Setup() { log.Debug("setting up comet client"); ns = new NetworkStream(s, FileAccess.ReadWrite); bs = new BufferedStream(ns); sr = new StreamReader(ns); sw = new StreamWriter(bs); log.Debug("parsing request "); if( ! parseRequest() ) return; log.Debug("reading headers"); readHeaders(); log.Debug("done reading headers"); if( querystring == null || querystring["sid"] == null ) return; context = Context.GetContext(querystring["sid"], CacheKey); if (context != null) { log.Debug("found context for ", querystring["sid"] ); this.Context = context; writer.Context = context; context.ConnectComet(this); } else { Write("alert('Comet lost context.');"); Shutdown(); } writeSuccess(); } public void Shutdown() { log.Debug("shutting socket down"); ns.Close(); s.Close(); if (Context != null) { Context.DisconnectComet(); } } public bool parseRequest() { log.Debug("in parse request"); //char[] data = new char[1]; //while( sr.ReadBlock( data, 0, 1 ) > 0 ) // log.Debug(data); String request = sr.ReadLine(); log.Debug( "parsing request", request, request == "<policy-file-request/>\0" ); if( request == "<policy-file-request/>\0" ) { //writer = new FlashCometWriter(sw,ns); log.Debug("is a policy file request" ); s.Send(XMLPolicyBytes); s.Close(); log.Debug("done sending request"); //throw new Exception("reading policy headers"); return false; } string[] tokens = request.Split(new char[] { ' ' }); log.Debug("parsing request", request, tokens ); if( tokens.Length > 1 && tokens[1].Length > 1 ) { url = tokens[1].Substring(1); if( url.IndexOf('?') > -1 ) { querystring = System.Web.HttpUtility.ParseQueryString( url.Substring( url.IndexOf('?') + 1 ) ); } } if( querystring == null ) { log.Error("no querystring was found for a comet connect request"); return false; } if (querystring["flash"] == "1" ) { writer = new FlashCometWriter(sw,ns); StateObject so = new StateObject(); so.workSocket = s; s.BeginReceive(so.buffer,0,so.buffer.Length, SocketFlags.None, new AsyncCallback(Receive), so); } else { writer = new HtmlCometWriter(sw); writer.Context = context; } return true; } string lastInput; int sameCount = 0; public void Receive(IAsyncResult ar) { StateObject so = ar.AsyncState as StateObject; if (!so.workSocket.Connected) { return; } try { int length; for (length = 0; length < so.buffer.Length; length++) { if (so.buffer[length] == 0) break; } string input = new string(Encoding.ASCII.GetChars(so.buffer, 0, length)); if (input == lastInput) { sameCount++; } else { sameCount = 0; lastInput = input; } so.workSocket.EndReceive(ar); if ( !so.workSocket.Connected || sameCount > 10 ) { context.Unregister(); Shutdown(); return; } Dictionary<string,object> data = (Dictionary<string,object>)JSON.Default.Decode( input ); log.Debug( "recevied data", data ); so.buffer.Initialize(); so.workSocket.BeginReceive(so.buffer, 0, so.buffer.Length, SocketFlags.None, new AsyncCallback(Receive), so); if( data != null ) context.Transform( (string)data["id"], (string)data["evt"], (string)data["arg"] ); } catch( Exception e ) { log.Error("Error receiving data", Util.BuildExceptionOutput(e) ); } } public void readHeaders() { try { String line; while ((line = sr.ReadLine()) != null && line != "") { string[] tokens = line.Split(new char[] { ':' }); String name = tokens[0].Trim(); String value = ""; for (int i = 1; i < tokens.Length; i++) { value += tokens[i].Trim(); if (i < tokens.Length - 1) tokens[i] += ":"; } headers[name] = value; if (name == "Cookie") { string[] cookieTokens = value.Split(new char[] { '=', ';' },StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < cookieTokens.Length; i += 2) { string cookieName = cookieTokens[i].Trim(); string cookieValue = cookieTokens[i+1].Trim(); cookies[cookieName] = cookieValue; } } } } catch( Exception e ) { log.Error("Error Reading headers: " + Util.BuildExceptionOutput(e ) ); } } public virtual void writeSuccess() { writer.WriteSuccess(); } public override void Write(string data) { if( sb == null ) sb = new StringBuilder(); sb.Append( data ); } StringBuilder sb; public override void End () { base.End (); writer.Write( sb.ToString().Replace(@"\",@"\\") ); sb = new StringBuilder(); } // State object for reading client data asynchronously public class StateObject { // Client socket. public Socket workSocket = null; // Size of receive buffer. public const int BufferSize = 1024; // Receive buffer. public byte[] buffer = new byte[BufferSize]; // Received data string. public StringBuilder sb = new StringBuilder(); } } }
using System; using GuruComponents.Netrix.HtmlFormatting.Elements; namespace GuruComponents.Netrix.XmlDesigner { /// <summary> /// This class is used to store information about the way the formatter treats an element. /// </summary> /// <remarks> /// It is used internally to control the formatting behavior. Externally it is used to provide such information for plug-in modules. /// </remarks> public class XmlTagInfo : ITagInfo { private string _tagName; private string _ns; private WhiteSpaceType _inner; private WhiteSpaceType _following; private FormattingFlags _flags; private ElementType _type; /// <summary> /// The type of element controls the generel formatting behavior. /// </summary> public ElementType Type { get { return _type; } } /// <summary> /// Determines how to format this kind of element. /// </summary> public FormattingFlags Flags { get { return _flags; } } /// <summary> /// Determines how significant are whitespaces following this element. /// </summary> public WhiteSpaceType FollowingWhiteSpaceType { get { return _following; } } /// <summary> /// Determines how significant are whitespaces within this element. /// </summary> public WhiteSpaceType InnerWhiteSpaceType { get { return _inner; } } /// <summary> /// The element has to treated as comment. /// </summary> public bool IsComment { get { return (_flags & FormattingFlags.Comment) == 0 == false; } } /// <summary> /// The element is an inline element. /// </summary> public bool IsInline { get { return (_flags & FormattingFlags.Inline) == 0 == false; } } /// <summary> /// The element has to be treated as pure XML. /// </summary> public bool IsXml { get { return (_flags & FormattingFlags.Xml) == 0 == false; } } /// <summary> /// The element does not has an end tag, e.g. it is not a container. /// </summary> public bool NoEndTag { get { return (_flags & FormattingFlags.NoEndTag) == 0 == false; } } /// <summary> /// The element does not being indented, even if it starts at a new line. /// </summary> public bool NoIndent { get { if ((_flags & FormattingFlags.NoIndent) == 0) { return NoEndTag; } else { return true; } } } /// <summary> /// The element is supposed to preserve its content. /// </summary> public bool PreserveContent { get { return (_flags & FormattingFlags.PreserveContent) == 0 == false; } } /// <summary> /// The tag name of the element. /// </summary> public string TagName { get { if (_ns != null && _ns != String.Empty) return String.Concat(_ns, ":", _tagName); else return _tagName; } } /// <summary> /// The tag name of the element. /// </summary> public string Namespace { get { return _ns; } set { _ns = value; } } /// <overloads/> /// <summary> /// Creates a new tag info with basic parameters. /// </summary> /// <param name="tagName"></param> /// <param name="flags"></param> public XmlTagInfo(string tagName, FormattingFlags flags) : this(tagName, flags, WhiteSpaceType.CarryThrough, WhiteSpaceType.CarryThrough, ElementType.Other) { } /// <summary> /// Creates a new tag info with basic parameters. /// </summary> /// <param name="tagName"></param> /// <param name="flags"></param> /// <param name="type"></param> public XmlTagInfo(string tagName, FormattingFlags flags, ElementType type) : this(tagName, flags, WhiteSpaceType.CarryThrough, WhiteSpaceType.CarryThrough, type) { } /// <summary> /// Creates a new tag info with basic parameters. /// </summary> /// <param name="tagName"></param> /// <param name="flags"></param> /// <param name="innerWhiteSpace"></param> /// <param name="followingWhiteSpace"></param> public XmlTagInfo(string tagName, FormattingFlags flags, WhiteSpaceType innerWhiteSpace, WhiteSpaceType followingWhiteSpace) : this(tagName, flags, innerWhiteSpace, followingWhiteSpace, ElementType.Other) { } /// <summary> /// Creates a new tag info with basic parameters. /// </summary> /// <param name="tagName"></param> /// <param name="flags"></param> /// <param name="innerWhiteSpace"></param> /// <param name="followingWhiteSpace"></param> /// <param name="type"></param> public XmlTagInfo(string tagName, FormattingFlags flags, WhiteSpaceType innerWhiteSpace, WhiteSpaceType followingWhiteSpace, ElementType type) { if (tagName.IndexOf(":") != -1) { string[] parsed = tagName.Split(':'); _tagName = parsed[1]; _ns = parsed[0]; } else { _tagName = tagName; } _inner = innerWhiteSpace; _following = followingWhiteSpace; _flags = flags; _type = type; } /// <summary> /// Creates a new tag info with basic parameters. /// </summary> /// <param name="newTagName"></param> /// <param name="info"></param> public XmlTagInfo(string newTagName, ITagInfo info) { _tagName = newTagName; _inner = info.InnerWhiteSpaceType; _following = info.FollowingWhiteSpaceType; _flags = info.Flags; _type = info.Type; } /// <summary> /// Informs that a element can carry another one. /// </summary> /// <remarks> /// This method always returns true. Classes derive from <see cref="TagInfo"/> may /// overwrite it to control the behavior of complex elements. /// </remarks> /// <param name="info"></param> /// <returns></returns> public virtual bool CanContainTag(ITagInfo info) { return true; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics.Contracts; using System.Collections.Generic; namespace System.Globalization { internal partial class CalendarData { private bool LoadCalendarDataFromSystem(String localeName, CalendarId calendarId) { bool ret = true; uint useOverrides = this.bUseUserOverrides ? 0 : CAL_NOUSEROVERRIDE; // // Windows doesn't support some calendars right now, so remap those. // switch (calendarId) { case CalendarId.JAPANESELUNISOLAR: // Data looks like Japanese calendarId = CalendarId.JAPAN; break; case CalendarId.JULIAN: // Data looks like gregorian US case CalendarId.CHINESELUNISOLAR: // Algorithmic, so actual data is irrelevent case CalendarId.SAKA: // reserved to match Office but not implemented in our code, so data is irrelevent case CalendarId.LUNAR_ETO_CHN: // reserved to match Office but not implemented in our code, so data is irrelevent case CalendarId.LUNAR_ETO_KOR: // reserved to match Office but not implemented in our code, so data is irrelevent case CalendarId.LUNAR_ETO_ROKUYOU: // reserved to match Office but not implemented in our code, so data is irrelevent case CalendarId.KOREANLUNISOLAR: // Algorithmic, so actual data is irrelevent case CalendarId.TAIWANLUNISOLAR: // Algorithmic, so actual data is irrelevent calendarId = CalendarId.GREGORIAN_US; break; } // // Special handling for some special calendar due to OS limitation. // This includes calendar like Taiwan calendar, UmAlQura calendar, etc. // CheckSpecialCalendar(ref calendarId, ref localeName); // Numbers ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_ITWODIGITYEARMAX | useOverrides, out this.iTwoDigitYearMax); // Strings ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_SCALNAME, out this.sNativeName); ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_SMONTHDAY | useOverrides, out this.sMonthDay); // String Arrays // Formats ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SSHORTDATE, LOCALE_SSHORTDATE | useOverrides, out this.saShortDates); ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SLONGDATE, LOCALE_SLONGDATE | useOverrides, out this.saLongDates); // Get the YearMonth pattern. ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SYEARMONTH, LOCALE_SYEARMONTH, out this.saYearMonths); // Day & Month Names // These are all single calType entries, 1 per day, so we have to make 7 or 13 calls to collect all the names // Day // Note that we're off-by-one since managed starts on sunday and windows starts on monday ret &= GetCalendarDayInfo(localeName, calendarId, CAL_SDAYNAME7, out this.saDayNames); ret &= GetCalendarDayInfo(localeName, calendarId, CAL_SABBREVDAYNAME7, out this.saAbbrevDayNames); // Month names ret &= GetCalendarMonthInfo(localeName, calendarId, CAL_SMONTHNAME1, out this.saMonthNames); ret &= GetCalendarMonthInfo(localeName, calendarId, CAL_SABBREVMONTHNAME1, out this.saAbbrevMonthNames); // // The following LCTYPE are not supported in some platforms. If the call fails, // don't return a failure. // GetCalendarDayInfo(localeName, calendarId, CAL_SSHORTESTDAYNAME7, out this.saSuperShortDayNames); // Gregorian may have genitive month names if (calendarId == CalendarId.GREGORIAN) { GetCalendarMonthInfo(localeName, calendarId, CAL_SMONTHNAME1 | CAL_RETURN_GENITIVE_NAMES, out this.saMonthGenitiveNames); GetCalendarMonthInfo(localeName, calendarId, CAL_SABBREVMONTHNAME1 | CAL_RETURN_GENITIVE_NAMES, out this.saAbbrevMonthGenitiveNames); } // Calendar Parts Names // This doesn't get always get localized names for gregorian (not available in windows < 7) // so: eg: coreclr on win < 7 won't get these CallEnumCalendarInfo(localeName, calendarId, CAL_SERASTRING, 0, out this.saEraNames); CallEnumCalendarInfo(localeName, calendarId, CAL_SABBREVERASTRING, 0, out this.saAbbrevEraNames); // // Calendar Era Info // Note that calendar era data (offsets, etc) is hard coded for each calendar since this // data is implementation specific and not dynamic (except perhaps Japanese) // // Clean up the escaping of the formats this.saShortDates = CultureData.ReescapeWin32Strings(this.saShortDates); this.saLongDates = CultureData.ReescapeWin32Strings(this.saLongDates); this.saYearMonths = CultureData.ReescapeWin32Strings(this.saYearMonths); this.sMonthDay = CultureData.ReescapeWin32String(this.sMonthDay); return ret; } // Get native two digit year max internal static int GetTwoDigitYearMax(CalendarId calendarId) { int twoDigitYearMax = -1; if (!CallGetCalendarInfoEx(null, calendarId, (uint)CAL_ITWODIGITYEARMAX, out twoDigitYearMax)) { twoDigitYearMax = -1; } return twoDigitYearMax; } internal static CalendarData GetCalendarData(CalendarId calendarId) { // // Get a calendar. // Unfortunately we depend on the locale in the OS, so we need a locale // no matter what. So just get the appropriate calendar from the // appropriate locale here // // Get a culture name // TODO: NLS Arrowhead Arrowhead - note that this doesn't handle the new calendars (lunisolar, etc) String culture = CalendarIdToCultureName(calendarId); // Return our calendar return CultureInfo.GetCultureInfo(culture).m_cultureData.GetCalendar(calendarId); } // Call native side to figure out which calendars are allowed internal static int GetCalendars(String localeName, bool useUserOverride, CalendarId[] calendars) { EnumCalendarsData data = new EnumCalendarsData(); data.userOverride = 0; data.calendars = new LowLevelList<int>(); // First call GetLocaleInfo if necessary if (useUserOverride) { // They want user overrides, see if the user calendar matches the input calendar int userCalendar = Interop.mincore.GetLocaleInfoExInt(localeName, LOCALE_ICALENDARTYPE); // If we got a default, then use it as the first calendar if (userCalendar != 0) { data.userOverride = userCalendar; data.calendars.Add(userCalendar); } } GCHandle contextHandle = GCHandle.Alloc(data); try { EnumCalendarInfoExExCallback callback = new EnumCalendarInfoExExCallback(EnumCalendarsCallback); Interop.mincore_private.LParamCallbackContext context = new Interop.mincore_private.LParamCallbackContext(); context.lParam = (IntPtr)contextHandle; // Now call the enumeration API. Work is done by our callback function Interop.mincore_private.EnumCalendarInfoExEx(callback, localeName, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, context); } finally { contextHandle.Free(); } // Copy to the output array for (int i = 0; i < Math.Min(calendars.Length, data.calendars.Count); i++) calendars[i] = (CalendarId)data.calendars[i]; // Now we have a list of data, return the count return data.calendars.Count; } private static bool SystemSupportsTaiwaneseCalendar() { string data; // Taiwanese calendar get listed as one of the optional zh-TW calendars only when having zh-TW UI return CallGetCalendarInfoEx("zh-TW", CalendarId.TAIWAN, CAL_SCALNAME, out data); } // PAL Layer ends here const uint CAL_RETURN_NUMBER = 0x20000000; const uint CAL_RETURN_GENITIVE_NAMES = 0x10000000; const uint CAL_NOUSEROVERRIDE = 0x80000000; const uint CAL_SCALNAME = 0x00000002; const uint CAL_SMONTHDAY = 0x00000038; const uint CAL_SSHORTDATE = 0x00000005; const uint CAL_SLONGDATE = 0x00000006; const uint CAL_SYEARMONTH = 0x0000002f; const uint CAL_SDAYNAME7 = 0x0000000d; const uint CAL_SABBREVDAYNAME7 = 0x00000014; const uint CAL_SMONTHNAME1 = 0x00000015; const uint CAL_SABBREVMONTHNAME1 = 0x00000022; const uint CAL_SSHORTESTDAYNAME7 = 0x00000037; const uint CAL_SERASTRING = 0x00000004; const uint CAL_SABBREVERASTRING = 0x00000039; const uint CAL_ICALINTVALUE = 0x00000001; const uint CAL_ITWODIGITYEARMAX = 0x00000030; const uint ENUM_ALL_CALENDARS = 0xffffffff; const uint LOCALE_SSHORTDATE = 0x0000001F; const uint LOCALE_SLONGDATE = 0x00000020; const uint LOCALE_SYEARMONTH = 0x00001006; const uint LOCALE_ICALENDARTYPE = 0x00001009; private static String CalendarIdToCultureName(CalendarId calendarId) { switch (calendarId) { case CalendarId.GREGORIAN_US: return "fa-IR"; // "fa-IR" Iran case CalendarId.JAPAN: return "ja-JP"; // "ja-JP" Japan case CalendarId.TAIWAN: return "zh-TW"; // zh-TW Taiwan case CalendarId.KOREA: return "ko-KR"; // "ko-KR" Korea case CalendarId.HIJRI: case CalendarId.GREGORIAN_ARABIC: case CalendarId.UMALQURA: return "ar-SA"; // "ar-SA" Saudi Arabia case CalendarId.THAI: return "th-TH"; // "th-TH" Thailand case CalendarId.HEBREW: return "he-IL"; // "he-IL" Israel case CalendarId.GREGORIAN_ME_FRENCH: return "ar-DZ"; // "ar-DZ" Algeria case CalendarId.GREGORIAN_XLIT_ENGLISH: case CalendarId.GREGORIAN_XLIT_FRENCH: return "ar-IQ"; // "ar-IQ"; Iraq default: // Default to gregorian en-US break; } return "en-US"; } //////////////////////////////////////////////////////////////////////// // // For calendars like Gregorain US/Taiwan/UmAlQura, they are not available // in all OS or all localized versions of OS. // If OS does not support these calendars, we will fallback by using the // appropriate fallback calendar and locale combination to retrieve data from OS. // // Parameters: // __deref_inout pCalendarInt: // Pointer to the calendar ID. This will be updated to new fallback calendar ID if needed. // __in_out pLocaleNameStackBuffer // Pointer to the StackSString object which holds the locale name to be checked. // This will be updated to new fallback locale name if needed. // //////////////////////////////////////////////////////////////////////// private static void CheckSpecialCalendar(ref CalendarId calendar, ref string localeName) { string data; // Gregorian-US isn't always available in the OS, however it is the same for all locales switch (calendar) { case CalendarId.GREGORIAN_US: // See if this works if (!CallGetCalendarInfoEx(localeName, calendar, CAL_SCALNAME, out data)) { // Failed, set it to a locale (fa-IR) that's alway has Gregorian US available in the OS localeName = "fa-IR"; } // See if that works if (!CallGetCalendarInfoEx(localeName, calendar, CAL_SCALNAME, out data)) { // Failed again, just use en-US with the gregorian calendar localeName = "en-US"; calendar = CalendarId.GREGORIAN; } break; case CalendarId.TAIWAN: // Taiwan calendar data is not always in all language version of OS due to Geopolical reasons. // It is only available in zh-TW localized versions of Windows. // Let's check if OS supports it. If not, fallback to Greogrian localized for Taiwan calendar. if (!SystemSupportsTaiwaneseCalendar()) { calendar = CalendarId.GREGORIAN; } break; } } private static bool CallGetCalendarInfoEx(string localeName, CalendarId calendar, uint calType, out int data) { return (Interop.mincore.GetCalendarInfoEx(localeName, (uint)calendar, IntPtr.Zero, calType | CAL_RETURN_NUMBER, IntPtr.Zero, 0, out data) != 0); } private static unsafe bool CallGetCalendarInfoEx(string localeName, CalendarId calendar, uint calType, out string data) { const int BUFFER_LENGTH = 80; // The maximum size for values returned from GetCalendarInfoEx is 80 characters. char* buffer = stackalloc char[BUFFER_LENGTH]; int ret = Interop.mincore.GetCalendarInfoEx(localeName, (uint)calendar, IntPtr.Zero, calType, (IntPtr)buffer, BUFFER_LENGTH, IntPtr.Zero); if (ret > 0) { if (buffer[ret - 1] == '\0') { ret--; // don't include the null termination in the string } data = new string(buffer, 0, ret); return true; } data = ""; return false; } // Context for EnumCalendarInfoExEx callback. class EnumData { public string userOverride; public LowLevelList<string> strings; } // EnumCalendarInfoExEx callback itself. static unsafe bool EnumCalendarInfoCallback(IntPtr lpCalendarInfoString, uint calendar, IntPtr pReserved, Interop.mincore_private.LParamCallbackContext contextHandle) { EnumData context = (EnumData)((GCHandle)contextHandle.lParam).Target; try { string calendarInfo = new string((char*)lpCalendarInfoString); // If we had a user override, check to make sure this differs if (context.userOverride != calendarInfo) context.strings.Add(calendarInfo); return true; } catch (Exception) { return false; } } private static unsafe bool CallEnumCalendarInfo(string localeName, CalendarId calendar, uint calType, uint lcType, out string[] data) { EnumData context = new EnumData(); context.userOverride = null; context.strings = new LowLevelList<string>(); // First call GetLocaleInfo if necessary if (((lcType != 0) && ((lcType & CAL_NOUSEROVERRIDE) == 0)) && // Get user locale, see if it matches localeName. // Note that they should match exactly, including letter case GetUserDefaultLocaleName() == localeName) { // They want user overrides, see if the user calendar matches the input calendar CalendarId userCalendar = (CalendarId)Interop.mincore.GetLocaleInfoExInt(localeName, LOCALE_ICALENDARTYPE); // If the calendars were the same, see if the locales were the same if (userCalendar == calendar) { // They matched, get the user override since locale & calendar match string res = Interop.mincore.GetLocaleInfoEx(localeName, lcType); // if it succeeded remember the override for the later callers if (res != "") { // Remember this was the override (so we can look for duplicates later in the enum function) context.userOverride = res; // Add to the result strings. context.strings.Add(res); } } } GCHandle contextHandle = GCHandle.Alloc(context); try { EnumCalendarInfoExExCallback callback = new EnumCalendarInfoExExCallback(EnumCalendarInfoCallback); Interop.mincore_private.LParamCallbackContext ctx = new Interop.mincore_private.LParamCallbackContext(); ctx.lParam = (IntPtr)contextHandle; // Now call the enumeration API. Work is done by our callback function Interop.mincore_private.EnumCalendarInfoExEx(callback, localeName, (uint)calendar, null, calType, ctx); } finally { contextHandle.Free(); } // Now we have a list of data, fail if we didn't find anything. if (context.strings.Count == 0) { data = null; return false; } string[] output = context.strings.ToArray(); if (calType == CAL_SABBREVERASTRING || calType == CAL_SERASTRING) { // Eras are enumerated backwards. (oldest era name first, but // Japanese calendar has newest era first in array, and is only // calendar with multiple eras) Array.Reverse(output, 0, output.Length); } data = output; return true; } //////////////////////////////////////////////////////////////////////// // // Get the native day names // // NOTE: There's a disparity between .Net & windows day orders, the input day should // start with Sunday // // Parameters: // OUT pOutputStrings The output string[] value. // //////////////////////////////////////////////////////////////////////// static bool GetCalendarDayInfo(string localeName, CalendarId calendar, uint calType, out string[] outputStrings) { bool result = true; // // We'll need a new array of 7 items // string[] results = new string[7]; // Get each one of them for (int i = 0; i < 7; i++, calType++) { result &= CallGetCalendarInfoEx(localeName, calendar, calType, out results[i]); // On the first iteration we need to go from CAL_SDAYNAME7 to CAL_SDAYNAME1, so subtract 7 before the ++ happens // This is because the framework starts on sunday and windows starts on monday when counting days if (i == 0) calType -= 7; } outputStrings = results; return result; } //////////////////////////////////////////////////////////////////////// // // Get the native month names // // Parameters: // OUT pOutputStrings The output string[] value. // //////////////////////////////////////////////////////////////////////// static bool GetCalendarMonthInfo(string localeName, CalendarId calendar, uint calType, out string[] outputStrings) { // // We'll need a new array of 13 items // string[] results = new string[13]; // Get each one of them for (int i = 0; i < 13; i++, calType++) { if (!CallGetCalendarInfoEx(localeName, calendar, calType, out results[i])) results[i] = ""; } outputStrings = results; return true; } // // struct to help our calendar data enumaration callback // class EnumCalendarsData { public int userOverride; // user override value (if found) public LowLevelList<int> calendars; // list of calendars found so far } static bool EnumCalendarsCallback(IntPtr lpCalendarInfoString, uint calendar, IntPtr reserved, Interop.mincore_private.LParamCallbackContext cxt) { EnumCalendarsData context = (EnumCalendarsData)((GCHandle)cxt.lParam).Target; try { // If we had a user override, check to make sure this differs if (context.userOverride != calendar) context.calendars.Add((int)calendar); return true; } catch (Exception) { return false; } } private static unsafe String GetUserDefaultLocaleName() { const int LOCALE_NAME_MAX_LENGTH = 85; const uint LOCALE_SNAME = 0x0000005c; const string LOCALE_NAME_USER_DEFAULT = null; int result; char* localeName = stackalloc char[LOCALE_NAME_MAX_LENGTH]; result = Interop.mincore.GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SNAME, localeName, LOCALE_NAME_MAX_LENGTH); return result <= 0 ? "" : new String(localeName, 0, result - 1); // exclude the null termination } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.CloudProfiler.v2 { /// <summary>The CloudProfiler Service.</summary> public class CloudProfilerService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v2"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public CloudProfilerService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public CloudProfilerService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Projects = new ProjectsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "cloudprofiler"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://cloudprofiler.googleapis.com/"; #else "https://cloudprofiler.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://cloudprofiler.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Available OAuth 2.0 scopes for use with the Stackdriver Profiler API.</summary> public class Scope { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; /// <summary> /// View and write monitoring data for all of your Google and third-party Cloud and API projects /// </summary> public static string Monitoring = "https://www.googleapis.com/auth/monitoring"; /// <summary>Publish metric data to your Google Cloud projects</summary> public static string MonitoringWrite = "https://www.googleapis.com/auth/monitoring.write"; } /// <summary>Available OAuth 2.0 scope constants for use with the Stackdriver Profiler API.</summary> public static class ScopeConstants { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; /// <summary> /// View and write monitoring data for all of your Google and third-party Cloud and API projects /// </summary> public const string Monitoring = "https://www.googleapis.com/auth/monitoring"; /// <summary>Publish metric data to your Google Cloud projects</summary> public const string MonitoringWrite = "https://www.googleapis.com/auth/monitoring.write"; } /// <summary>Gets the Projects resource.</summary> public virtual ProjectsResource Projects { get; } } /// <summary>A base abstract class for CloudProfiler requests.</summary> public abstract class CloudProfilerBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new CloudProfilerBaseServiceRequest instance.</summary> protected CloudProfilerBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes CloudProfiler parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "projects" collection of methods.</summary> public class ProjectsResource { private const string Resource = "projects"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ProjectsResource(Google.Apis.Services.IClientService service) { this.service = service; Profiles = new ProfilesResource(service); } /// <summary>Gets the Profiles resource.</summary> public virtual ProfilesResource Profiles { get; } /// <summary>The "profiles" collection of methods.</summary> public class ProfilesResource { private const string Resource = "profiles"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ProfilesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// CreateProfile creates a new profile resource in the online mode. The server ensures that the new /// profiles are created at a constant rate per deployment, so the creation request may hang for some time /// until the next profile session is available. The request may fail with ABORTED error if the creation is /// not available within ~1m, the response will indicate the duration of the backoff the client should take /// before attempting creating a profile again. The backoff duration is returned in google.rpc.RetryInfo /// extension on the response status. To a gRPC client, the extension will be return as a binary-serialized /// proto in the trailing metadata item named "google.rpc.retryinfo-bin". /// </summary> /// <param name="body">The body of the request.</param> /// <param name="parent">Parent project to create the profile in.</param> public virtual CreateRequest Create(Google.Apis.CloudProfiler.v2.Data.CreateProfileRequest body, string parent) { return new CreateRequest(service, body, parent); } /// <summary> /// CreateProfile creates a new profile resource in the online mode. The server ensures that the new /// profiles are created at a constant rate per deployment, so the creation request may hang for some time /// until the next profile session is available. The request may fail with ABORTED error if the creation is /// not available within ~1m, the response will indicate the duration of the backoff the client should take /// before attempting creating a profile again. The backoff duration is returned in google.rpc.RetryInfo /// extension on the response status. To a gRPC client, the extension will be return as a binary-serialized /// proto in the trailing metadata item named "google.rpc.retryinfo-bin". /// </summary> public class CreateRequest : CloudProfilerBaseServiceRequest<Google.Apis.CloudProfiler.v2.Data.Profile> { /// <summary>Constructs a new Create request.</summary> public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudProfiler.v2.Data.CreateProfileRequest body, string parent) : base(service) { Parent = parent; Body = body; InitParameters(); } /// <summary>Parent project to create the profile in.</summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudProfiler.v2.Data.CreateProfileRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "create"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v2/{+parent}/profiles"; /// <summary>Initializes Create parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+$", }); } } /// <summary> /// CreateOfflineProfile creates a new profile resource in the offline mode. The client provides the profile /// to create along with the profile bytes, the server records it. /// </summary> /// <param name="body">The body of the request.</param> /// <param name="parent">Parent project to create the profile in.</param> public virtual CreateOfflineRequest CreateOffline(Google.Apis.CloudProfiler.v2.Data.Profile body, string parent) { return new CreateOfflineRequest(service, body, parent); } /// <summary> /// CreateOfflineProfile creates a new profile resource in the offline mode. The client provides the profile /// to create along with the profile bytes, the server records it. /// </summary> public class CreateOfflineRequest : CloudProfilerBaseServiceRequest<Google.Apis.CloudProfiler.v2.Data.Profile> { /// <summary>Constructs a new CreateOffline request.</summary> public CreateOfflineRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudProfiler.v2.Data.Profile body, string parent) : base(service) { Parent = parent; Body = body; InitParameters(); } /// <summary>Parent project to create the profile in.</summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudProfiler.v2.Data.Profile Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "createOffline"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v2/{+parent}/profiles:createOffline"; /// <summary>Initializes CreateOffline parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+$", }); } } /// <summary> /// UpdateProfile updates the profile bytes and labels on the profile resource created in the online mode. /// Updating the bytes for profiles created in the offline mode is currently not supported: the profile /// content must be provided at the time of the profile creation. /// </summary> /// <param name="body">The body of the request.</param> /// <param name="name">Output only. Opaque, server-assigned, unique ID for this profile.</param> public virtual PatchRequest Patch(Google.Apis.CloudProfiler.v2.Data.Profile body, string name) { return new PatchRequest(service, body, name); } /// <summary> /// UpdateProfile updates the profile bytes and labels on the profile resource created in the online mode. /// Updating the bytes for profiles created in the offline mode is currently not supported: the profile /// content must be provided at the time of the profile creation. /// </summary> public class PatchRequest : CloudProfilerBaseServiceRequest<Google.Apis.CloudProfiler.v2.Data.Profile> { /// <summary>Constructs a new Patch request.</summary> public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudProfiler.v2.Data.Profile body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary>Output only. Opaque, server-assigned, unique ID for this profile.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary> /// Field mask used to specify the fields to be overwritten. Currently only profile_bytes and labels /// fields are supported by UpdateProfile, so only those fields can be specified in the mask. When no /// mask is provided, all fields are overwritten. /// </summary> [Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)] public virtual object UpdateMask { get; set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudProfiler.v2.Data.Profile Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "patch"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "PATCH"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v2/{+name}"; /// <summary>Initializes Patch parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/profiles/[^/]+$", }); RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter { Name = "updateMask", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } } namespace Google.Apis.CloudProfiler.v2.Data { /// <summary> /// CreateProfileRequest describes a profile resource online creation request. The deployment field must be /// populated. The profile_type specifies the list of profile types supported by the agent. The creation call will /// hang until a profile of one of these types needs to be collected. /// </summary> public class CreateProfileRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. Deployment details.</summary> [Newtonsoft.Json.JsonPropertyAttribute("deployment")] public virtual Deployment Deployment { get; set; } /// <summary>Required. One or more profile types that the agent is capable of providing.</summary> [Newtonsoft.Json.JsonPropertyAttribute("profileType")] public virtual System.Collections.Generic.IList<string> ProfileType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Deployment contains the deployment identification information.</summary> public class Deployment : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Labels identify the deployment within the user universe and same target. Validation regex for label names: /// `^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$`. Value for an individual label must be &amp;lt;= 512 bytes, the total /// size of all label names and values must be &amp;lt;= 1024 bytes. Label named "language" can be used to /// record the programming language of the profiled deployment. The standard choices for the value include /// "java", "go", "python", "ruby", "nodejs", "php", "dotnet". For deployments running on Google Cloud Platform, /// "zone" or "region" label should be present describing the deployment location. An example of a zone is /// "us-central1-a", an example of a region is "us-central1" or "us-central". /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("labels")] public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; } /// <summary>Project ID is the ID of a cloud project. Validation regex: `^a-z{4,61}[a-z0-9]$`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("projectId")] public virtual string ProjectId { get; set; } /// <summary> /// Target is the service name used to group related deployments: * Service name for App Engine Flex / Standard. /// * Cluster and container name for GKE. * User-specified string for direct Compute Engine profiling (e.g. /// Java). * Job name for Dataflow. Validation regex: `^[a-z]([-a-z0-9_.]{0,253}[a-z0-9])?$`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("target")] public virtual string Target { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Profile resource.</summary> public class Profile : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Deployment this profile corresponds to.</summary> [Newtonsoft.Json.JsonPropertyAttribute("deployment")] public virtual Deployment Deployment { get; set; } /// <summary> /// Duration of the profiling session. Input (for the offline mode) or output (for the online mode). The field /// represents requested profiling duration. It may slightly differ from the effective profiling duration, which /// is recorded in the profile data, in case the profiling can't be stopped immediately (e.g. in case stopping /// the profiling is handled asynchronously). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("duration")] public virtual object Duration { get; set; } /// <summary> /// Input only. Labels associated to this specific profile. These labels will get merged with the deployment /// labels for the final data set. See documentation on deployment labels for validation rules and limits. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("labels")] public virtual System.Collections.Generic.IDictionary<string, string> Labels { get; set; } /// <summary>Output only. Opaque, server-assigned, unique ID for this profile.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary> /// Input only. Profile bytes, as a gzip compressed serialized proto, the format is /// https://github.com/google/pprof/blob/master/proto/profile.proto. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("profileBytes")] public virtual string ProfileBytes { get; set; } /// <summary> /// Type of profile. For offline mode, this must be specified when creating the profile. For online mode it is /// assigned and returned by the server. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("profileType")] public virtual string ProfileType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; namespace System.Linq.Expressions { /// <summary> /// Represents a named parameter expression. /// </summary> [DebuggerTypeProxy(typeof(Expression.ParameterExpressionProxy))] public class ParameterExpression : Expression { private readonly string _name; internal ParameterExpression(string name) { _name = name; } internal static ParameterExpression Make(Type type, string name, bool isByRef) { if (isByRef) { return new ByRefParameterExpression(type, name); } else { if (!type.GetTypeInfo().IsEnum) { switch (type.GetTypeCode()) { case TypeCode.Boolean: return new PrimitiveParameterExpression<Boolean>(name); case TypeCode.Byte: return new PrimitiveParameterExpression<Byte>(name); case TypeCode.Char: return new PrimitiveParameterExpression<Char>(name); case TypeCode.DateTime: return new PrimitiveParameterExpression<DateTime>(name); case TypeCode.Decimal: return new PrimitiveParameterExpression<Decimal>(name); case TypeCode.Double: return new PrimitiveParameterExpression<Double>(name); case TypeCode.Int16: return new PrimitiveParameterExpression<Int16>(name); case TypeCode.Int32: return new PrimitiveParameterExpression<Int32>(name); case TypeCode.Int64: return new PrimitiveParameterExpression<Int64>(name); case TypeCode.Object: // common reference types which we optimize go here. Of course object is in // the list, the others are driven by profiling of various workloads. This list // should be kept short. if (type == typeof(object)) { return new ParameterExpression(name); } else if (type == typeof(Exception)) { return new PrimitiveParameterExpression<Exception>(name); } else if (type == typeof(object[])) { return new PrimitiveParameterExpression<object[]>(name); } break; case TypeCode.SByte: return new PrimitiveParameterExpression<SByte>(name); case TypeCode.Single: return new PrimitiveParameterExpression<Single>(name); case TypeCode.String: return new PrimitiveParameterExpression<String>(name); case TypeCode.UInt16: return new PrimitiveParameterExpression<UInt16>(name); case TypeCode.UInt32: return new PrimitiveParameterExpression<UInt32>(name); case TypeCode.UInt64: return new PrimitiveParameterExpression<UInt64>(name); } } } return new TypedParameterExpression(type, name); } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public override Type Type { get { return typeof(object); } } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.Parameter; } } /// <summary> /// The Name of the parameter or variable. /// </summary> public string Name { get { return _name; } } /// <summary> /// Indicates that this ParameterExpression is to be treated as a ByRef parameter. /// </summary> public bool IsByRef { get { return GetIsByRef(); } } internal virtual bool GetIsByRef() { return false; } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitParameter(this); } } /// <summary> /// Specialized subclass to avoid holding onto the byref flag in a /// parameter expression. This version always holds onto the expression /// type explicitly and therefore derives from TypedParameterExpression. /// </summary> internal sealed class ByRefParameterExpression : TypedParameterExpression { internal ByRefParameterExpression(Type type, string name) : base(type, name) { } internal override bool GetIsByRef() { return true; } } /// <summary> /// Specialized subclass which holds onto the type of the expression for /// uncommon types. /// </summary> internal class TypedParameterExpression : ParameterExpression { private readonly Type _paramType; internal TypedParameterExpression(Type type, string name) : base(name) { _paramType = type; } public sealed override Type Type { get { return _paramType; } } } /// <summary> /// Generic type to avoid needing explicit storage for primitive data types /// which are commonly used. /// </summary> internal sealed class PrimitiveParameterExpression<T> : ParameterExpression { internal PrimitiveParameterExpression(string name) : base(name) { } public sealed override Type Type { get { return typeof(T); } } } public partial class Expression { /// <summary> /// Creates a <see cref="ParameterExpression" /> node that can be used to identify a parameter or a variable in an expression tree. /// </summary> /// <param name="type">The type of the parameter or variable.</param> /// <returns>A <see cref="ParameterExpression" /> node with the specified name and type.</returns> public static ParameterExpression Parameter(Type type) { return Parameter(type, null); } /// <summary> /// Creates a <see cref="ParameterExpression" /> node that can be used to identify a parameter or a variable in an expression tree. /// </summary> /// <param name="type">The type of the parameter or variable.</param> /// <returns>A <see cref="ParameterExpression" /> node with the specified name and type.</returns> public static ParameterExpression Variable(Type type) { return Variable(type, null); } /// <summary> /// Creates a <see cref="ParameterExpression" /> node that can be used to identify a parameter or a variable in an expression tree. /// </summary> /// <param name="type">The type of the parameter or variable.</param> /// <param name="name">The name of the parameter or variable, used for debugging or pretty printing purpose only.</param> /// <returns>A <see cref="ParameterExpression" /> node with the specified name and type.</returns> public static ParameterExpression Parameter(Type type, string name) { ContractUtils.RequiresNotNull(type, nameof(type)); if (type == typeof(void)) { throw Error.ArgumentCannotBeOfTypeVoid(); } bool byref = type.IsByRef; if (byref) { type = type.GetElementType(); } return ParameterExpression.Make(type, name, byref); } /// <summary> /// Creates a <see cref="ParameterExpression" /> node that can be used to identify a parameter or a variable in an expression tree. /// </summary> /// <param name="type">The type of the parameter or variable.</param> /// <param name="name">The name of the parameter or variable, used for debugging or pretty printing purpose only.</param> /// <returns>A <see cref="ParameterExpression" /> node with the specified name and type.</returns> public static ParameterExpression Variable(Type type, string name) { ContractUtils.RequiresNotNull(type, nameof(type)); if (type == typeof(void)) throw Error.ArgumentCannotBeOfTypeVoid(); if (type.IsByRef) throw Error.TypeMustNotBeByRef(); return ParameterExpression.Make(type, name, false); } } }
namespace AngleSharp.Io { using AngleSharp.Common; using AngleSharp.Dom; using AngleSharp.Text; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Threading; using System.Threading.Tasks; /// <summary> /// The default (ready-to-use) HTTP requester. /// </summary> public sealed class DefaultHttpRequester : BaseRequester { #region Constants private const Int32 BufferSize = 4096; private static readonly String? Version = typeof(DefaultHttpRequester).Assembly.GetCustomAttribute<AssemblyFileVersionAttribute>()?.Version; private static readonly String AgentName = "AngleSharp/" + Version; #endregion #region Fields private TimeSpan _timeOut; private readonly Action<HttpWebRequest> _setup; private readonly Dictionary<String, String> _headers; #endregion #region ctor /// <summary> /// Constructs a default HTTP requester with the information presented /// in the info object. /// </summary> /// <param name="userAgent">The user-agent name to use, if any.</param> /// <param name="setup">An optional setup function for the HttpWebRequest object.</param> public DefaultHttpRequester(String? userAgent = null, Action<HttpWebRequest>? setup = null) { _timeOut = new TimeSpan(0, 0, 0, 45); _setup = setup ?? ((HttpWebRequest r) => { }); _headers = new Dictionary<String, String> { { HeaderNames.UserAgent, userAgent ?? AgentName }, { HeaderNames.AcceptEncoding, "gzip, deflate" } }; } #endregion #region Properties /// <summary> /// Gets the used headers. /// </summary> public IDictionary<String, String> Headers => _headers; /// <summary> /// Gets or sets the timeout value. /// </summary> public TimeSpan Timeout { get => _timeOut; set => _timeOut = value; } #endregion #region Methods /// <summary> /// Checks if the given protocol is supported. /// </summary> /// <param name="protocol"> /// The protocol to check for, e.g. http. /// </param> /// <returns> /// True if the protocol is supported, otherwise false. /// </returns> public override Boolean SupportsProtocol(String protocol) => protocol.IsOneOf(ProtocolNames.Http, ProtocolNames.Https); /// <summary> /// Performs an asynchronous http request that can be cancelled. /// </summary> /// <param name="request">The options to consider.</param> /// <param name="cancellationToken"> /// The token for cancelling the task. /// </param> /// <returns> /// The task that will eventually give the response data. /// </returns> protected override async Task<IResponse?> PerformRequestAsync(Request request, CancellationToken cancellationToken) { var cts = new CancellationTokenSource(_timeOut); var cache = new RequestState(request, _headers, _setup); using (cancellationToken.Register(cts.Cancel)) { return await cache.RequestAsync(cts.Token).ConfigureAwait(false); } } #endregion #region Transport private sealed class RequestState { private static MethodInfo? _serverString; private readonly CookieContainer _cookies; private readonly IDictionary<String, String> _headers; private readonly HttpWebRequest _http; private readonly Request _request; private readonly Byte[] _buffer; public RequestState(Request request, IDictionary<String, String> headers, Action<HttpWebRequest> setup) { _cookies = new CookieContainer(); _headers = headers; _request = request; _http = (HttpWebRequest)WebRequest.Create(request.Address); _http.CookieContainer = _cookies; _http.Method = request.Method.ToString().ToUpperInvariant(); _buffer = new Byte[BufferSize]; SetHeaders(); SetCookies(); AllowCompression(); DisableAutoRedirect(); setup.Invoke(_http); } public async Task<IResponse?> RequestAsync(CancellationToken cancellationToken) { cancellationToken.Register(_http.Abort); if (_request.Method == HttpMethod.Post || _request.Method == HttpMethod.Put) { var target = await _http.GetRequestStreamAsync().ConfigureAwait(false); SendRequest(target); } WebResponse? response; try { response = await _http.GetResponseAsync().ConfigureAwait(false); } catch (WebException ex) { response = ex.Response; } RaiseConnectionLimit(_http); return GetResponse(response as HttpWebResponse); } private void SendRequest(Stream target) { var source = _request.Content; while (source != null) { var length = source.Read(_buffer, 0, BufferSize); if (length == 0) { break; } target.Write(_buffer, 0, length); } } [return: NotNullIfNotNull("response")] private DefaultResponse? GetResponse(HttpWebResponse? response) { if (response != null) { var originalCookies = _cookies.GetCookies(_request.Address!); var newCookies = _cookies.GetCookies(response.ResponseUri); var cookies = newCookies.OfType<Cookie>().Except(originalCookies.OfType<Cookie>()).ToArray(); var headers = response.Headers.AllKeys.Select(m => new { Key = m, Value = response.Headers[m] }); var result = new DefaultResponse { Content = response.GetResponseStream(), StatusCode = response.StatusCode, Address = Url.Convert(response.ResponseUri) }; foreach (var header in headers) { result.Headers.Add(header.Key, header.Value); } if (cookies.Length > 0) { var strings = cookies.Select(Stringify); result.Headers[HeaderNames.SetCookie] = String.Join(", ", strings); } return result; } return null; } /// <summary> /// Dirty workaround to re-obtain the string representation of the cookie /// for the set-cookie header. Uses the internal ToServerString method and /// falls back to the ordinary ToString. /// </summary> private static String Stringify(Cookie cookie) { if (_serverString is null) { var methods = typeof(Cookie).GetMethods(); var func = methods.FirstOrDefault(m => m.Name is "ToServerString"); _serverString = func ?? methods.First(m => m.Name is "ToString"); } return _serverString.Invoke(cookie, null)!.ToString()!; } /// <summary> /// Dirty dirty workaround since the webrequester itself is already /// quite stupid, but the one here (for the PCL) is really not the /// way things should be programmed ... /// </summary> private void AddHeader(String key, String value) { if (key.Is(HeaderNames.Accept)) { _http.Accept = value; } else if (key.Is(HeaderNames.ContentType)) { _http.ContentType = value; } else if (key.Is(HeaderNames.Expect)) { _http.Expect = value; } else if (key.Is(HeaderNames.Date)) { _http.Date = DateTime.Parse(value, CultureInfo.InvariantCulture); } else if (key.Is(HeaderNames.Host)) { _http.Host = value; } else if (key.Is(HeaderNames.IfModifiedSince)) { _http.IfModifiedSince = DateTime.Parse(value, CultureInfo.InvariantCulture); } else if (key.Is(HeaderNames.Referer)) { _http.Referer = value; } else if (key.Is(HeaderNames.UserAgent)) { _http.UserAgent = value; } else if (!key.Is(HeaderNames.Connection) && !key.Is(HeaderNames.Range) && !key.Is(HeaderNames.ContentLength) && !key.Is(HeaderNames.TransferEncoding)) { _http.Headers[key] = value; } } private void SetCookies() { var cookieHeader = _request.Headers.GetOrDefault(HeaderNames.Cookie, String.Empty); _cookies.SetCookies(_http.RequestUri, cookieHeader.Replace(';', ',').Replace("$", "")); } private void SetHeaders() { foreach (var header in _headers) { AddHeader(header.Key, header.Value); } foreach (var header in _request.Headers) { if (!header.Key.Is(HeaderNames.Cookie)) { AddHeader(header.Key, header.Value); } } } private void AllowCompression() { _http.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } private void DisableAutoRedirect() { _http.AllowAutoRedirect = false; } } private static void RaiseConnectionLimit(HttpWebRequest http) { http.ServicePoint.ConnectionLimit = 1024; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using Internal.Runtime.CompilerServices; #pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)' #if BIT64 using nuint = System.UInt64; #else using nuint = System.UInt32; #endif namespace System { /// <summary> /// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed /// or native memory, or to memory allocated on the stack. It is type- and memory-safe. /// </summary> [DebuggerTypeProxy(typeof(SpanDebugView<>))] [DebuggerDisplay("{DebuggerDisplay,nq}")] [NonVersionable] public readonly ref struct Span<T> { /// <summary>A byref or a native ptr.</summary> internal readonly ByReference<T> _pointer; /// <summary>The number of elements this Span contains.</summary> #if PROJECTN [Bound] #endif private readonly int _length; /// <summary> /// Creates a new span over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData())); _length = array.Length; } /// <summary> /// Creates a new span over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the span.</param> /// <param name="length">The number of items in the span.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null /// reference (Nothing in Visual Basic).</exception> /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[] array, int start, int length) { if (array == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); _pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start)); _length = length; } /// <summary> /// Creates a new span over the target unmanaged buffer. Clearly this /// is quite dangerous, because we are creating arbitrarily typed T's /// out of a void*-typed block of memory. And the length is not checked. /// But if this creation is correct, then all subsequent uses are correct. /// </summary> /// <param name="pointer">An unmanaged pointer to memory.</param> /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="length"/> is negative. /// </exception> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe Span(void* pointer, int length) { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); if (length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer)); _length = length; } /// <summary> /// Create a new span over a portion of a regular managed object. This can be useful /// if part of a managed object represents a "fixed array." This is dangerous because neither the /// <paramref name="length"/> is checked, nor <paramref name="obj"/> being null, nor the fact that /// "rawPointer" actually lies within <paramref name="obj"/>. /// </summary> /// <param name="obj">The managed object that contains the data to span over.</param> /// <param name="objectData">A reference to data within that object.</param> /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] [EditorBrowsable(EditorBrowsableState.Never)] public static Span<T> DangerousCreate(object obj, ref T objectData, int length) => new Span<T>(ref objectData, length); // Constructor for internal use only. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Span(ref T ptr, int length) { Debug.Assert(length >= 0); _pointer = new ByReference<T>(ref ptr); _length = length; } //Debugger Display = {T[length]} private string DebuggerDisplay => string.Format("{{{0}[{1}]}}", typeof(T).Name, _length); /// <summary> /// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element /// would have been stored. Such a reference can be used for pinning but must never be dereferenced. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] [EditorBrowsable(EditorBrowsableState.Never)] internal ref T DangerousGetPinnableReference() { return ref _pointer.Value; } /// <summary> /// The number of items in the span. /// </summary> public int Length { [NonVersionable] get { return _length; } } /// <summary> /// Returns true if Length is 0. /// </summary> public bool IsEmpty { [NonVersionable] get { return _length == 0; } } /// <summary> /// Returns a reference to specified element of the Span. /// </summary> /// <param name="index"></param> /// <returns></returns> /// <exception cref="System.IndexOutOfRangeException"> /// Thrown when index less than 0 or index greater than or equal to Length /// </exception> public ref T this[int index] { #if PROJECTN [BoundsChecking] get { return ref Unsafe.Add(ref _pointer.Value, index); } #else [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] get { if ((uint)index >= (uint)_length) ThrowHelper.ThrowIndexOutOfRangeException(); return ref Unsafe.Add(ref _pointer.Value, index); } #endif } /// <summary> /// Clears the contents of this span. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) { Span.ClearWithReferences(ref Unsafe.As<T, IntPtr>(ref _pointer.Value), (nuint)_length * (nuint)(Unsafe.SizeOf<T>() / sizeof(nuint))); } else { Span.ClearWithoutReferences(ref Unsafe.As<T, byte>(ref _pointer.Value), (nuint)_length * (nuint)Unsafe.SizeOf<T>()); } } /// <summary> /// Fills the contents of this span with the given value. /// </summary> public void Fill(T value) { if (Unsafe.SizeOf<T>() == 1) { uint length = (uint)_length; if (length == 0) return; T tmp = value; // Avoid taking address of the "value" argument. It would regress performance of the loop below. Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref _pointer.Value), Unsafe.As<T, byte>(ref tmp), length); } else { // Do all math as nuint to avoid unnecessary 64->32->64 bit integer truncations nuint length = (uint)_length; if (length == 0) return; ref T r = ref DangerousGetPinnableReference(); // TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16 nuint elementSize = (uint)Unsafe.SizeOf<T>(); nuint i = 0; for (; i < (length & ~(nuint)7); i += 8) { Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 4) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 5) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 6) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 7) * elementSize) = value; } if (i < (length & ~(nuint)3)) { Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value; Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value; i += 4; } for (; i < length; i++) { Unsafe.AddByteOffset<T>(ref r, i * elementSize) = value; } } } /// <summary> /// Copies the contents of this span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// </summary> /// <param name="destination">The span to copy items into.</param> /// <exception cref="System.ArgumentException"> /// Thrown when the destination Span is shorter than the source Span. /// </exception> public void CopyTo(Span<T> destination) { if (!TryCopyTo(destination)) ThrowHelper.ThrowArgumentException_DestinationTooShort(); } /// <summary> /// Copies the contents of this span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// </summary> /// <param name="destination">The span to copy items into.</param> /// <returns>If the destination span is shorter than the source span, this method /// return false and no data is written to the destination.</returns> public bool TryCopyTo(Span<T> destination) { if ((uint)_length > (uint)destination.Length) return false; Span.CopyTo<T>(ref destination._pointer.Value, ref _pointer.Value, _length); return true; } /// <summary> /// Returns true if left and right point at the same memory and have the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public static bool operator ==(Span<T> left, Span<T> right) { return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value); } /// <summary> /// Returns false if left and right point at the same memory and have the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public static bool operator !=(Span<T> left, Span<T> right) => !(left == right); /// <summary> /// This method is not supported as spans cannot be boxed. To compare two spans, use operator==. /// <exception cref="System.NotSupportedException"> /// Always thrown by this method. /// </exception> /// </summary> [Obsolete("Equals() on Span will always throw an exception. Use == instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) { throw new NotSupportedException(SR.NotSupported_CannotCallEqualsOnSpan); } /// <summary> /// This method is not supported as spans cannot be boxed. /// <exception cref="System.NotSupportedException"> /// Always thrown by this method. /// </exception> /// </summary> [Obsolete("GetHashCode() on Span will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException(SR.NotSupported_CannotCallGetHashCodeOnSpan); } /// <summary> /// Returns a <see cref="String"/> with the name of the type and the number of elements /// </summary> public override string ToString() => "System.Span[" + Length.ToString() + "]"; /// <summary> /// Defines an implicit conversion of an array to a <see cref="Span{T}"/> /// </summary> public static implicit operator Span<T>(T[] array) => array != null ? new Span<T>(array) : default; /// <summary> /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Span{T}"/> /// </summary> public static implicit operator Span<T>(ArraySegment<T> arraySegment) => arraySegment.Array != null ? new Span<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count) : default; /// <summary> /// Defines an implicit conversion of a <see cref="Span{T}"/> to a <see cref="ReadOnlySpan{T}"/> /// </summary> public static implicit operator ReadOnlySpan<T>(Span<T> span) => new ReadOnlySpan<T>(ref span._pointer.Value, span._length); /// <summary> /// Forms a slice out of the given span, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start) { if ((uint)start > (uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start); } /// <summary> /// Forms a slice out of the given span, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); return new Span<T>(ref Unsafe.Add(ref _pointer.Value, start), length); } /// <summary> /// Copies the contents of this span into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public T[] ToArray() { if (_length == 0) return Array.Empty<T>(); var destination = new T[_length]; Span.CopyTo<T>(ref Unsafe.As<byte, T>(ref destination.GetRawSzArrayData()), ref _pointer.Value, _length); return destination; } // <summary> /// Returns an empty <see cref="Span{T}"/> /// </summary> public static Span<T> Empty => default(Span<T>); /// <summary>Gets an enumerator for this span.</summary> public Enumerator GetEnumerator() => new Enumerator(this); /// <summary>Enumerates the elements of a <see cref="Span{T}"/>.</summary> public ref struct Enumerator { /// <summary>The span being enumerated.</summary> private readonly Span<T> _span; /// <summary>The next index to yield.</summary> private int _index; /// <summary>Initialize the enumerator.</summary> /// <param name="span">The span to enumerate.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(Span<T> span) { _span = span; _index = -1; } /// <summary>Advances the enumerator to the next element of the span.</summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { int index = _index + 1; if (index < _span.Length) { _index = index; return true; } return false; } /// <summary>Gets the element at the current position of the enumerator.</summary> public ref T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => ref _span[_index]; } } } }
namespace AutoMapper.Configuration { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Execution; public class MappingExpression : MappingExpression<object, object>, IMappingExpression { public MappingExpression(TypePair types, MemberList memberList) : base(memberList, types.SourceType, types.DestinationType) { } public new IMappingExpression ReverseMap() => (IMappingExpression) base.ReverseMap(); public new IMappingExpression Substitute(Func<object, object> substituteFunc) => (IMappingExpression) base.Substitute(substituteFunc); public new IMappingExpression ConstructUsingServiceLocator() => (IMappingExpression)base.ConstructUsingServiceLocator(); public void ForAllMembers(Action<IMemberConfigurationExpression> memberOptions) => base.ForAllMembers(opts => memberOptions((IMemberConfigurationExpression)opts)); void IMappingExpression.ConvertUsing<TTypeConverter>() { ConvertUsing(typeof(TTypeConverter)); } public void ConvertUsing(Type typeConverterType) { var interfaceType = typeof(ITypeConverter<,>).MakeGenericType(Types.SourceType, Types.DestinationType); var convertMethodType = interfaceType.IsAssignableFrom(typeConverterType) ? interfaceType : typeConverterType; var converter = new DeferredInstantiatedConverter(convertMethodType, typeConverterType.BuildCtor<object>( context => typeof(ITypeConverter<,>).MakeGenericType(context.SourceType, context.DestinationType))); TypeMapActions.Add(tm => tm.UseCustomMapper(converter.Convert)); } public void As(Type typeOverride) => TypeMapActions.Add(tm => tm.DestinationTypeOverride = typeOverride); public void ForAllOtherMembers(Action<IMemberConfigurationExpression> memberOptions) { base.ForAllOtherMembers(o => memberOptions((IMemberConfigurationExpression)o)); } public IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions) => (IMappingExpression)base.ForMember(name, c => memberOptions((IMemberConfigurationExpression)c)); public new IMappingExpression ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions) => (IMappingExpression)base.ForSourceMember(sourceMemberName, memberOptions); public new IMappingExpression Include(Type otherSourceType, Type otherDestinationType) => (IMappingExpression)base.Include(otherSourceType, otherDestinationType); public new IMappingExpression IgnoreAllPropertiesWithAnInaccessibleSetter() => (IMappingExpression)base.IgnoreAllPropertiesWithAnInaccessibleSetter(); public new IMappingExpression IgnoreAllSourcePropertiesWithAnInaccessibleSetter() => (IMappingExpression)base.IgnoreAllSourcePropertiesWithAnInaccessibleSetter(); public new IMappingExpression IncludeBase(Type sourceBase, Type destinationBase) => (IMappingExpression)base.IncludeBase(sourceBase, destinationBase); public new IMappingExpression BeforeMap(Action<object, object> beforeFunction) => (IMappingExpression)base.BeforeMap(beforeFunction); public new IMappingExpression BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<object, object> => (IMappingExpression)base.BeforeMap<TMappingAction>(); public new IMappingExpression AfterMap(Action<object, object> afterFunction) => (IMappingExpression)base.AfterMap(afterFunction); public new IMappingExpression AfterMap<TMappingAction>() where TMappingAction : IMappingAction<object, object> => (IMappingExpression)base.AfterMap<TMappingAction>(); public new IMappingExpression ConstructUsing(Func<object, object> ctor) => (IMappingExpression)base.ConstructUsing(ctor); public new IMappingExpression ConstructUsing(Func<ResolutionContext, object> ctor) => (IMappingExpression)base.ConstructUsing(ctor); public IMappingExpression ConstructProjectionUsing(LambdaExpression ctor) { var func = ctor.Compile(); TypeMapActions.Add(tm => tm.ConstructExpression = ctor); return ConstructUsing(ctxt => func.DynamicInvoke(ctxt.SourceValue)); } public new IMappingExpression MaxDepth(int depth) => (IMappingExpression)base.MaxDepth(depth); public new IMappingExpression ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<object>> paramOptions) => (IMappingExpression)base.ForCtorParam(ctorParamName, paramOptions); public new IMappingExpression PreserveReferences() => (IMappingExpression)base.PreserveReferences(); protected override IMemberConfiguration CreateMemberConfigurationExpression<TMember>(IMemberAccessor member, Type sourceType) { return new MemberConfigurationExpression(member, sourceType); } protected override MappingExpression<object, object> CreateReverseMapExpression() { return new MappingExpression(new TypePair(DestinationType, SourceType), MemberList.Source); } private class MemberConfigurationExpression : MemberConfigurationExpression<object, object>, IMemberConfigurationExpression { public MemberConfigurationExpression(IMemberAccessor destinationMember, Type sourceType) : base(destinationMember, sourceType) { } } } public class MappingExpression<TSource, TDestination> : IMappingExpression<TSource, TDestination>, ITypeMapConfiguration { private readonly List<IMemberConfiguration> _memberConfigurations = new List<IMemberConfiguration>(); private readonly List<SourceMappingExpression> _sourceMemberConfigurations = new List<SourceMappingExpression>(); private readonly List<CtorParamConfigurationExpression<TSource>> _ctorParamConfigurations = new List<CtorParamConfigurationExpression<TSource>>(); private MappingExpression<TDestination, TSource> _reverseMap; private Action<IMemberConfigurationExpression<TSource, object>> _allMemberOptions; private Func<IMemberAccessor, bool> _memberFilter; public MappingExpression(MemberList memberList) { MemberList = memberList; Types = new TypePair(typeof(TSource), typeof(TDestination)); } public MappingExpression(MemberList memberList, Type sourceType, Type destinationType) { MemberList = memberList; Types = new TypePair(sourceType, destinationType); } public MemberList MemberList { get; } public TypePair Types { get; } public Type SourceType => Types.SourceType; public Type DestinationType => Types.DestinationType; public ITypeMapConfiguration ReverseTypeMap => _reverseMap; protected List<Action<TypeMap>> TypeMapActions { get; } = new List<Action<TypeMap>>(); public IMappingExpression<TSource, TDestination> PreserveReferences() { TypeMapActions.Add(tm => tm.EnablePreserveReferences()); return this; } protected virtual IMemberConfiguration CreateMemberConfigurationExpression<TMember>(IMemberAccessor member, Type sourceType) { return new MemberConfigurationExpression<TSource, TMember>(member, sourceType); } protected virtual MappingExpression<TDestination, TSource> CreateReverseMapExpression() { return new MappingExpression<TDestination, TSource>(MemberList.Source, DestinationType, SourceType); } public IMappingExpression<TSource, TDestination> ForMember<TMember>(Expression<Func<TDestination, TMember>> destinationMember, Action<IMemberConfigurationExpression<TSource, TMember>> memberOptions) { var memberInfo = ReflectionHelper.FindProperty(destinationMember); IMemberAccessor destProperty = memberInfo.ToMemberAccessor(); ForDestinationMember(destProperty, memberOptions); return this; } public IMappingExpression<TSource, TDestination> ForMember(string name, Action<IMemberConfigurationExpression<TSource, object>> memberOptions) { var member = DestinationType.GetFieldOrProperty(name); ForDestinationMember(member.ToMemberAccessor(), memberOptions); return this; } public void ForAllOtherMembers(Action<IMemberConfigurationExpression<TSource, object>> memberOptions) { _allMemberOptions = memberOptions; _memberFilter = m => _memberConfigurations.All(c=>c.DestinationMember.MemberInfo != m.MemberInfo); } public void ForAllMembers(Action<IMemberConfigurationExpression<TSource, object>> memberOptions) { _allMemberOptions = memberOptions; _memberFilter = _ => true; } public IMappingExpression<TSource, TDestination> IgnoreAllPropertiesWithAnInaccessibleSetter() { var properties = DestinationType.GetDeclaredProperties().Where(pm => pm.HasAnInaccessibleSetter()); foreach (var property in properties) ForMember(property.Name, opt => opt.Ignore()); return this; } public IMappingExpression<TSource, TDestination> IgnoreAllSourcePropertiesWithAnInaccessibleSetter() { var properties = SourceType.GetDeclaredProperties().Where(pm => pm.HasAnInaccessibleSetter()); foreach (var property in properties) ForSourceMember(property.Name, opt => opt.Ignore()); return this; } public IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>() where TOtherSource : TSource where TOtherDestination : TDestination { return Include(typeof(TOtherSource), typeof(TOtherDestination)); } public IMappingExpression<TSource, TDestination> Include(Type otherSourceType, Type otherDestinationType) { TypeMapActions.Add(tm => tm.IncludeDerivedTypes(otherSourceType, otherDestinationType)); return this; } public IMappingExpression<TSource, TDestination> IncludeBase<TSourceBase, TDestinationBase>() { return IncludeBase(typeof(TSourceBase), typeof(TDestinationBase)); } public IMappingExpression<TSource, TDestination> IncludeBase(Type sourceBase, Type destinationBase) { TypeMapActions.Add(tm => tm.IncludeBaseTypes(sourceBase, destinationBase)); return this; } public void ProjectUsing(Expression<Func<TSource, TDestination>> projectionExpression) { TypeMapActions.Add(tm => tm.UseCustomProjection(projectionExpression)); ConvertUsing(projectionExpression.Compile()); } public IMappingExpression<TSource, TDestination> MaxDepth(int depth) { TypeMapActions.Add(tm => tm.MaxDepth = depth); return PreserveReferences(); } public IMappingExpression<TSource, TDestination> ConstructUsingServiceLocator() { TypeMapActions.Add(tm => tm.ConstructDestinationUsingServiceLocator = true); return this; } public IMappingExpression<TDestination, TSource> ReverseMap() { var mappingExpression = CreateReverseMapExpression(); _reverseMap = mappingExpression; return mappingExpression; } public IMappingExpression<TSource, TDestination> ForSourceMember(Expression<Func<TSource, object>> sourceMember, Action<ISourceMemberConfigurationExpression> memberOptions) { var memberInfo = ReflectionHelper.FindProperty(sourceMember); var srcConfig = new SourceMappingExpression(memberInfo); memberOptions(srcConfig); _sourceMemberConfigurations.Add(srcConfig); return this; } public IMappingExpression<TSource, TDestination> ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions) { var memberInfo = SourceType.GetMember(sourceMemberName).First(); var srcConfig = new SourceMappingExpression(memberInfo); memberOptions(srcConfig); _sourceMemberConfigurations.Add(srcConfig); return this; } public IMappingExpression<TSource, TDestination> Substitute(Func<TSource, object> substituteFunc) { TypeMapActions.Add(tm => tm.Substitution = src => substituteFunc((TSource) src)); return this; } public void ConvertUsing(Func<TSource, TDestination> mappingFunction) { TypeMapActions.Add(tm => tm.UseCustomMapper((source, ctxt) => mappingFunction((TSource) source))); } public void ConvertUsing(Func<TSource, ResolutionContext, TDestination> mappingFunction) { TypeMapActions.Add(tm => tm.UseCustomMapper((source, ctxt) => mappingFunction((TSource) source, ctxt))); } public void ConvertUsing(ITypeConverter<TSource, TDestination> converter) { ConvertUsing(converter.Convert); } public void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination> { var converter = new DeferredInstantiatedConverter<TSource, TDestination>(typeof(TTypeConverter).BuildCtor<ITypeConverter<TSource, TDestination>>( context => typeof(ITypeConverter<,>).MakeGenericType(context.SourceType, context.DestinationType))); ConvertUsing(converter.Convert); } public IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination> beforeFunction) { TypeMapActions.Add(tm => tm.AddBeforeMapAction((src, dest, ctxt) => beforeFunction((TSource)src, (TDestination)dest))); return this; } public IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination, ResolutionContext> beforeFunction) { TypeMapActions.Add(tm => tm.AddBeforeMapAction((src, dest, ctxt) => beforeFunction((TSource)src, (TDestination)dest, ctxt))); return this; } public IMappingExpression<TSource, TDestination> BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination> { Action<TSource, TDestination, ResolutionContext> beforeFunction = (src, dest, ctxt) => ((TMappingAction)ctxt.Options.ServiceCtor(typeof(TMappingAction))).Process(src, dest); return BeforeMap(beforeFunction); } public IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination> afterFunction) { TypeMapActions.Add(tm => tm.AddAfterMapAction((src, dest, ctxt) => afterFunction((TSource)src, (TDestination)dest))); return this; } public IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination, ResolutionContext> afterFunction) { TypeMapActions.Add(tm => tm.AddAfterMapAction((src, dest, ctxt) => afterFunction((TSource)src, (TDestination)dest, ctxt))); return this; } public IMappingExpression<TSource, TDestination> AfterMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination> { Action<TSource, TDestination, ResolutionContext> afterFunction = (src, dest, ctxt) => ((TMappingAction)ctxt.Options.ServiceCtor(typeof(TMappingAction))).Process(src, dest); return AfterMap(afterFunction); } public IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor) { return ConstructUsing(ctxt => { var destination = ctor((TSource) ctxt.SourceValue); if (destination == null) throw new InvalidOperationException($"Cannot create destination object of type {typeof(TDestination)}"); return destination; }); } public IMappingExpression<TSource, TDestination> ConstructUsing(Func<ResolutionContext, TDestination> ctor) { TypeMapActions.Add(tm => tm.DestinationCtor = ctxt => ctor(ctxt)); return this; } public IMappingExpression<TSource, TDestination> ConstructProjectionUsing(Expression<Func<TSource, TDestination>> ctor) { var func = ctor.Compile(); TypeMapActions.Add(tm => tm.ConstructExpression = ctor); return ConstructUsing(ctxt => func((TSource)ctxt.SourceValue)); } private void ForDestinationMember<TMember>(IMemberAccessor destinationProperty, Action<IMemberConfigurationExpression<TSource, TMember>> memberOptions) { var expression = (MemberConfigurationExpression<TSource, TMember>) CreateMemberConfigurationExpression<TMember>(destinationProperty, SourceType); _memberConfigurations.Add(expression); memberOptions(expression); } public void As<T>() { TypeMapActions.Add(tm => tm.DestinationTypeOverride = typeof(T)); } public IMappingExpression<TSource, TDestination> ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<TSource>> paramOptions) { var ctorParamExpression = new CtorParamConfigurationExpression<TSource>(ctorParamName); paramOptions(ctorParamExpression); _ctorParamConfigurations.Add(ctorParamExpression); return this; } public void Configure(IProfileConfiguration profile, TypeMap typeMap) { foreach (var destProperty in typeMap.DestinationTypeDetails.PublicWriteAccessors) { var attrs = destProperty.GetCustomAttributes(true); if (attrs.Any(x => x is IgnoreMapAttribute)) { ForMember(destProperty.Name, y => y.Ignore()); _reverseMap?.ForMember(destProperty.Name, opt => opt.Ignore()); } if (profile.GlobalIgnores.Contains(destProperty.Name)) { ForMember(destProperty.Name, y => y.Ignore()); } } if (_allMemberOptions != null) { foreach (var accessor in typeMap.DestinationTypeDetails.PublicReadAccessors.Select(m=>m.ToMemberAccessor()).Where(_memberFilter)) { ForDestinationMember(accessor, _allMemberOptions); } } foreach (var action in TypeMapActions) { action(typeMap); } foreach (var memberConfig in _memberConfigurations) { memberConfig.Configure(typeMap); } foreach (var memberConfig in _sourceMemberConfigurations) { memberConfig.Configure(typeMap); } foreach (var paramConfig in _ctorParamConfigurations) { paramConfig.Configure(typeMap); } if (_reverseMap != null) { foreach (var destProperty in typeMap.GetPropertyMaps().Where(pm => pm.IsIgnored())) { _reverseMap.ForSourceMember(destProperty.DestinationProperty.Name, opt => opt.Ignore()); } foreach (var includedDerivedType in typeMap.IncludedDerivedTypes) { _reverseMap.Include(includedDerivedType.DestinationType, includedDerivedType.SourceType); } } } } }
using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.Service; using Microsoft.AspNetCore.Identity.Service.Extensions; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.Extensions.Logging; using SpentBook.Web.Identity.Models; using SpentBook.Web.Identity.Models.AccountViewModels; using SpentBook.Web.Identity.Services; namespace SpentBook.Web.Identity.Controllers { [Area("IdentityService")] [IdentityServiceRoute("[controller]/[action]")] [Authorize(IdentityServiceOptions.LoginPolicyName)] [AllowAnonymous] public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public AccountController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<AccountController>(); } [HttpGet] public async Task<IActionResult> Login(string returnUrl = null) { // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityCookieOptions.ExternalScheme); ViewData["ReturnUrl"] = returnUrl; return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { _logger.LogInformation(1, "User logged in."); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); } if (result.IsLockedOut) { _logger.LogWarning(2, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } } // If we got this far, something failed, redisplay form return View(model); } [HttpGet] public IActionResult Register(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", // $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>"); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User created a new account with password."); return RedirectToLocal(returnUrl); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Logout() { await _signInManager.SignOutAsync(); _logger.LogInformation(4, "User logged out."); return Redirect("/"); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult ExternalLogin(string provider, string returnUrl = null) { // Request a redirect to the external login provider. var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { ReturnUrl = returnUrl }); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return Challenge(properties, provider); } [HttpGet] public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}"); return View(nameof(Login)); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return RedirectToAction(nameof(Login)); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false); if (result.Succeeded) { _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl }); } if (result.IsLockedOut) { return View("Lockout"); } else { // If the user does not have an account, then ask the user to create an account. ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; var email = info.Principal.FindFirstValue(ClaimTypes.Email); return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email }); } } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewData["ReturnUrl"] = returnUrl; return View(model); } [HttpGet] public async Task<IActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return View("Error"); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return View("Error"); } var result = await _userManager.ConfirmEmailAsync(user, code); return View(result.Succeeded ? "ConfirmEmail" : "Error"); } [HttpGet] public IActionResult ForgotPassword() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByEmailAsync(model.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GeneratePasswordResetTokenAsync(user); //var callbackUrl = Url.Action(nameof(ResetPassword), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Reset Password", // $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>"); //return View("ForgotPasswordConfirmation"); } // If we got this far, something failed, redisplay form return View(model); } [HttpGet] public IActionResult ForgotPasswordConfirmation() { return View(); } [HttpGet] public IActionResult ResetPassword(string code = null) { return code == null ? View("Error") : View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.FindByEmailAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } AddErrors(result); return View(); } [HttpGet] public IActionResult ResetPasswordConfirmation() { return View(); } [HttpGet] public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false) { var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return View(); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } // Generate the token and send it var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider); if (string.IsNullOrWhiteSpace(code)) { return View("Error"); } var message = "Your security code is: " + code; if (model.SelectedProvider == "Email") { await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message); } else if (model.SelectedProvider == "Phone") { await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message); } return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); } [HttpGet] public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null) { // Require that the user has already logged in via username/password or external login var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model) { if (!ModelState.IsValid) { return View(model); } // The following code protects for brute force attacks against the two factor codes. // If a user enters incorrect codes for a specified amount of time then the user account // will be locked out for a specified amount of time. var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser); if (result.Succeeded) { return RedirectToLocal(model.ReturnUrl); } if (result.IsLockedOut) { _logger.LogWarning(7, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid code."); return View(model); } } [HttpGet] public IActionResult AccessDenied() { return View(); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } private IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return Redirect("/"); } } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; namespace Microsoft.Azure.Management.Sql { /// <summary> /// The Windows Azure SQL Database management API provides a RESTful set of /// web services that interact with Windows Azure SQL Database services to /// manage your databases. The API enables users to create, retrieve, /// update, and delete databases and servers. /// </summary> public static partial class ServerAdvisorOperationsExtensions { /// <summary> /// Returns details of a Server Advisor. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerAdvisorOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='advisorName'> /// Required. The name of the Azure SQL server advisor. /// </param> /// <param name='expand'> /// Optional. The comma separated list of child objects that we want to /// expand on in response. NULL if expand is not required. /// </param> /// <returns> /// Represents the response to a get advisor request. /// </returns> public static AdvisorGetResponse Get(this IServerAdvisorOperations operations, string resourceGroupName, string serverName, string advisorName, string expand) { return Task.Factory.StartNew((object s) => { return ((IServerAdvisorOperations)s).GetAsync(resourceGroupName, serverName, advisorName, expand); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns details of a Server Advisor. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerAdvisorOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='advisorName'> /// Required. The name of the Azure SQL server advisor. /// </param> /// <param name='expand'> /// Optional. The comma separated list of child objects that we want to /// expand on in response. NULL if expand is not required. /// </param> /// <returns> /// Represents the response to a get advisor request. /// </returns> public static Task<AdvisorGetResponse> GetAsync(this IServerAdvisorOperations operations, string resourceGroupName, string serverName, string advisorName, string expand) { return operations.GetAsync(resourceGroupName, serverName, advisorName, expand, CancellationToken.None); } /// <summary> /// Returns list of Advisors for the Azure SQL Server. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerAdvisorOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='expand'> /// Optional. The comma separated list of child objects that we want to /// expand on in response. NULL if expand is not required. /// </param> /// <returns> /// Represents the response to a list sql azure database advisors /// request. /// </returns> public static AdvisorListResponse List(this IServerAdvisorOperations operations, string resourceGroupName, string serverName, string expand) { return Task.Factory.StartNew((object s) => { return ((IServerAdvisorOperations)s).ListAsync(resourceGroupName, serverName, expand); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns list of Advisors for the Azure SQL Server. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerAdvisorOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL server. /// </param> /// <param name='expand'> /// Optional. The comma separated list of child objects that we want to /// expand on in response. NULL if expand is not required. /// </param> /// <returns> /// Represents the response to a list sql azure database advisors /// request. /// </returns> public static Task<AdvisorListResponse> ListAsync(this IServerAdvisorOperations operations, string resourceGroupName, string serverName, string expand) { return operations.ListAsync(resourceGroupName, serverName, expand, CancellationToken.None); } /// <summary> /// Updates the auto-execute status for this Advisor. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerAdvisorOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server on which the database is /// hosted. /// </param> /// <param name='advisorName'> /// Required. The name of the Azure SQL Server advisor. /// </param> /// <param name='parameters'> /// Required. The required parameters for updating auto-execute status /// of an Advisor /// </param> /// <returns> /// Represents the response to a update advisor request. /// </returns> public static AdvisorUpdateResponse Update(this IServerAdvisorOperations operations, string resourceGroupName, string serverName, string advisorName, AdvisorUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IServerAdvisorOperations)s).UpdateAsync(resourceGroupName, serverName, advisorName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Updates the auto-execute status for this Advisor. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.IServerAdvisorOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server on which the database is /// hosted. /// </param> /// <param name='advisorName'> /// Required. The name of the Azure SQL Server advisor. /// </param> /// <param name='parameters'> /// Required. The required parameters for updating auto-execute status /// of an Advisor /// </param> /// <returns> /// Represents the response to a update advisor request. /// </returns> public static Task<AdvisorUpdateResponse> UpdateAsync(this IServerAdvisorOperations operations, string resourceGroupName, string serverName, string advisorName, AdvisorUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, serverName, advisorName, parameters, CancellationToken.None); } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Reflection; using System.Collections.Generic; using Sensus.Anonymization; using Sensus.Anonymization.Anonymizers; namespace Sensus.Probes.Apps { public class FacebookDatum : Datum { private static Dictionary<string, PropertyInfo> JSON_FIELD_DATUM_PROPERTY; static FacebookDatum() { JSON_FIELD_DATUM_PROPERTY = new Dictionary<string, PropertyInfo>(); foreach (PropertyInfo property in typeof(FacebookDatum).GetProperties()) { FacebookPermission permission = property.GetCustomAttribute<FacebookPermission>(); if (permission != null) { JSON_FIELD_DATUM_PROPERTY.Add(permission.Edge ?? permission.Field, property); } } } public static bool TryGetProperty(string jsonField, out PropertyInfo property) { return JSON_FIELD_DATUM_PROPERTY.TryGetValue(jsonField, out property); } // below are the various permissions, the fields/edges that they provide access to, and the anonymization // options that sensus will provide. the list is taken from the following URL: // // https://developers.facebook.com/docs/facebook-login/permissions/v2.3#reference // user object fields [Anonymizable("Age Range:", typeof(StringHashAnonymizer), false)] [FacebookPermission("public_profile", null, "age_range")] public string AgeRange { get; set; } [Anonymizable("First Name:", typeof(StringHashAnonymizer), false)] [FacebookPermission("public_profile", null, "first_name")] public string FirstName { get; set; } [Anonymizable(null, typeof(StringHashAnonymizer), false)] [FacebookPermission("public_profile", null, "gender")] public string Gender { get; set; } [Anonymizable("User ID:", typeof(StringHashAnonymizer), false)] [FacebookPermission("public_profile", null, "id")] public string UserId { get; set; } [Anonymizable("Last Name:", typeof(StringHashAnonymizer), false)] [FacebookPermission("public_profile", null, "last_name")] public string LastName { get; set; } [Anonymizable("Link to Timeline:", typeof(StringHashAnonymizer), false)] [FacebookPermission("public_profile", null, "link")] public string TimelineLink { get; set; } [Anonymizable(null, typeof(StringHashAnonymizer), false)] [FacebookPermission("public_profile", null, "locale")] public string Locale { get; set; } [Anonymizable("Full Name:", typeof(StringHashAnonymizer), false)] [FacebookPermission("public_profile", null, "name")] public string FullName { get; set; } [Anonymizable(null, typeof(StringHashAnonymizer), false)] [FacebookPermission("public_profile", null, "timezone")] public string Timezone { get; set; } [Anonymizable("Time of Last Update:", typeof(DateTimeOffsetTimelineAnonymizer), false)] [FacebookPermission("public_profile", null, "updated_time")] public DateTimeOffset? UpdatedTime { get; set; } [Anonymizable("Whether User is Verified:", null, false)] [FacebookPermission("public_profile", null, "verified")] public bool? Verified { get; set; } [Anonymizable("Email Address:", typeof(StringHashAnonymizer), false)] [FacebookPermission("email", null, "email")] public string Email { get; set; } [Anonymizable("About:", typeof(StringHashAnonymizer), false)] [FacebookPermission("user_about_me", null, "about")] public string About { get; set; } [Anonymizable(null, typeof(StringHashAnonymizer), false)] [FacebookPermission("user_education_history", null, "education")] public List<string> Education { get; set; } [Anonymizable(null, typeof(StringHashAnonymizer), false)] [FacebookPermission("user_hometown", null, "hometown")] public string Hometown { get; set; } [Anonymizable(null, typeof(StringHashAnonymizer), false)] [FacebookPermission("user_location", null, "location")] public string Location { get; set; } [Anonymizable("Relationship Status:", typeof(StringHashAnonymizer), false)] [FacebookPermission("user_relationships", null, "relationship_status")] public string RelationshipStatus { get; set; } [Anonymizable("Significant Other:", typeof(StringHashAnonymizer), false)] [FacebookPermission("user_relationships", null, "significant_other")] public string SignificantOther { get; set; } [Anonymizable(null, typeof(StringHashAnonymizer), false)] [FacebookPermission("user_religion_politics", null, "religion")] public string Religion { get; set; } [Anonymizable(null, typeof(StringHashAnonymizer), false)] [FacebookPermission("user_religion_politics", null, "political")] public string Politics { get; set; } [Anonymizable(null, typeof(StringHashAnonymizer), false)] [FacebookPermission("user_website", null, "website")] public string Website { get; set; } [Anonymizable("Employment History:", typeof(StringHashAnonymizer), false)] [FacebookPermission("user_work_history", null, "work")] public List<string> Employment { get; set; } // user edges [Anonymizable(null, typeof(StringHashAnonymizer), false)] [FacebookPermission("user_friends", "friends", "summary=total_count")] public List<string> Friends { get; set; } [Anonymizable("Books Read:", typeof(StringHashAnonymizer), false)] [FacebookPermission("user_actions.books", "book.reads", "book")] public List<string> Books { get; set; } [Anonymizable(null, typeof(StringHashAnonymizer), false)] [FacebookPermission("user_actions.fitness", "fitness.runs", "course")] public List<string> Runs { get; set; } [Anonymizable(null, typeof(StringHashAnonymizer), false)] [FacebookPermission("user_actions.fitness", "fitness.walks", "course")] public List<string> Walks { get; set; } [Anonymizable("Bike Rides:", typeof(StringHashAnonymizer), false)] [FacebookPermission("user_actions.fitness", "fitness.bikes", "course")] public List<string> Bikes { get; set; } [Anonymizable("Songs Listened To:", typeof(StringHashAnonymizer), false)] [FacebookPermission("user_actions.music", "music.listens", "song")] public List<string> Songs { get; set; } [Anonymizable(null, typeof(StringHashAnonymizer), false)] [FacebookPermission("user_actions.music", "music.playlists", "playlist")] public List<string> Playlists { get; set; } [Anonymizable("News Read:", typeof(StringHashAnonymizer), false)] [FacebookPermission("user_actions.news", "news.reads", "article")] public List<string> NewsReads { get; set; } [Anonymizable("News Published:", typeof(StringHashAnonymizer), false)] [FacebookPermission("user_actions.news", "news.publishes", "article")] public List<string> NewsPublishes { get; set; } [Anonymizable("Videos Watched:", typeof(StringHashAnonymizer), false)] [FacebookPermission("user_actions.video", "video.watches", "video")] public List<string> VideosWatched { get; set; } [Anonymizable("Video Ratings:", typeof(StringHashAnonymizer), false)] [FacebookPermission("user_actions.video", "video.rates", "movie")] public List<string> VideoRatings { get; set; } [Anonymizable("Video Wish List:", typeof(StringHashAnonymizer), false)] [FacebookPermission("user_actions.video", "video.wants_to_watch", "movie")] public List<string> VideoWishList { get; set; } [Anonymizable(null, typeof(StringHashAnonymizer), false)] [FacebookPermission("user_events", "events", "id")] public List<string> Events { get; set; } [Anonymizable(null, typeof(StringHashAnonymizer), false)] [FacebookPermission("user_likes", "likes", "created_time")] public List<string> Likes { get; set; } [Anonymizable("Captions of Posted Photos:", typeof(StringHashAnonymizer), false)] [FacebookPermission("user_photos", "photos", "id")] public List<string> PhotoCaptions { get; set; } [Anonymizable(null, typeof(StringHashAnonymizer), false)] [FacebookPermission("user_posts", "posts", "id")] public List<string> Posts { get; set; } [Anonymizable("Tagged Places:", typeof(StringHashAnonymizer), false)] [FacebookPermission("user_tagged_places", "tagged_places", "id")] public List<string> TaggedPlaces { get; set; } [Anonymizable("Titles of Posted Videos:", typeof(StringHashAnonymizer), false)] [FacebookPermission("user_videos", "videos", "id")] public List<string> VideoTitles { get; set; } /// <summary> /// Gets the string placeholder value, which is always empty. /// </summary> /// <value>The string placeholder value.</value> public override object StringPlaceholderValue { get { return ""; } } public override string DisplayDetail { get { return "(Facebook Data)"; } } public FacebookDatum(DateTimeOffset timestamp) : base(timestamp) { } } }
using org.javarosa.core.data; using org.javarosa.core.model; using org.javarosa.core.model.instance; using org.javarosa.core.model.utils; using org.javarosa.core.services.transport.payload; using org.javarosa.xform.util; using System; using System.Collections; using System.Text; using System.Xml; namespace org.javarosa.model.xform { /* * Copyright (C) 2009 JavaRosa ,Copyright (C) 2014 Simbacode * * 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. */ /** * A modified version of Clayton's XFormSerializingVisitor that constructs * SMS's. * * @author Acellam Guy , Munaf Sheikh, Cell-Life * */ public class SMSSerializingVisitor : IInstanceSerializingVisitor { private String theSmsStr = null; // sms string to be returned private String nodeSet = null; // which nodeset the sms contents are in private String xmlns = null; private String delimeter = null; private String prefix = null; private String method = null; private TreeReference rootRef; /** The serializer to be used in constructing XML for AnswerData elements */ IAnswerDataSerializer serializer; /** The schema to be used to serialize answer data */ FormDef schema; // not used ArrayList dataPointers; private void init() { theSmsStr = null; schema = null; dataPointers = new ArrayList(); theSmsStr = ""; } public byte[] serializeInstance(FormInstance model, FormDef formDef) { init(); this.schema = formDef; return serializeInstance(model); } /* * (non-Javadoc) * @see org.javarosa.core.model.utils.IInstanceSerializingVisitor#serializeInstance(org.javarosa.core.model.instance.FormInstance) */ public byte[] serializeInstance(FormInstance model) { return this.serializeInstance(model, new XPathReference("/")); } /* * (non-Javadoc) * @see org.javarosa.core.model.utils.IInstanceSerializingVisitor#serializeInstance(org.javarosa.core.model.instance.FormInstance, org.javarosa.core.model.IDataReference) */ public byte[] serializeInstance(FormInstance model, IDataReference ref_) { init(); rootRef = model.unpackReference2(ref_); if (this.serializer == null) { this.setAnswerDataSerializer(new XFormAnswerDataSerializer()); } model.accept(this); if (theSmsStr != null) { //Encode in UTF-16 by default, since it's the default for complex messages return Encoding.UTF8.GetBytes(theSmsStr); } else { return null; } } /* * (non-Javadoc) * @see org.javarosa.core.model.utils.IInstanceSerializingVisitor#createSerializedPayload(org.javarosa.core.model.instance.FormInstance) */ public IDataPayload createSerializedPayload(FormInstance model) { return createSerializedPayload(model, new XPathReference("/")); } public IDataPayload createSerializedPayload(FormInstance model, IDataReference ref_) { init(); rootRef = model.unpackReference2(ref_); if (this.serializer == null) { this.setAnswerDataSerializer(new XFormAnswerDataSerializer()); } model.accept(this); if (theSmsStr != null) { byte[] form = Encoding.UTF8.GetBytes(theSmsStr); return new ByteArrayPayload(form, null, IDataPayload_Fields.PAYLOAD_TYPE_SMS); } else { return null; } } /* * (non-Javadoc) * * @see * org.javarosa.core.model.utils.ITreeVisitor#visit(org.javarosa.core.model * .DataModelTree) */ public void visit(FormInstance tree) { nodeSet = ""; //TreeElement root = tree.getRoot(); TreeElement root = tree.resolveReference(rootRef); xmlns = root.getAttributeValue("", "xmlns"); delimeter = root.getAttributeValue("", "delimeter"); prefix = root.getAttributeValue("", "prefix"); xmlns = (xmlns != null) ? xmlns : " "; delimeter = (delimeter != null) ? delimeter : " "; prefix = (prefix != null) ? prefix : " "; //Don't bother adding any delimiters, yet. Delimiters are //added before tags/data theSmsStr = prefix; // serialize each node to get it's answers for (int j = 0; j < root.getNumChildren(); j++) { TreeElement tee = root.getChildAt(j); String e = serializeNode(tee); if (e != null) { theSmsStr += e; } } theSmsStr = theSmsStr.Trim(); } public String serializeNode(TreeElement instanceNode) { String ae = ""; // don't serialize template nodes or non-relevant nodes if (!instanceNode.isRelevant() || instanceNode.getMult() == TreeReference.INDEX_TEMPLATE) return null; if (instanceNode.getValue() != null) { Object serializedAnswer = serializer.serializeAnswerData( instanceNode.getValue(), instanceNode.dataType); if (serializedAnswer is XmlElement) { // DON"T handle this. throw new SystemException("Can't handle serialized output for" + instanceNode.getValue().ToString() + ", " + serializedAnswer); } else if (serializedAnswer is String) { XmlDocument theXmlDoc = new XmlDocument(); XmlElement e = theXmlDoc.CreateElement("TreeElement");//TODO XmlText xmlText = theXmlDoc.CreateTextNode((String)serializedAnswer); e.AppendChild(xmlText); String tag = instanceNode.getAttributeValue("", "tag"); ae += ((tag != null) ? tag + delimeter : delimeter); // tag // might // be // null for (int k = 0; k < e.ChildNodes.Count; k++) { ae += e.ChildNodes[k].InnerText.ToString() + delimeter; } } else { throw new SystemException("Can't handle serialized output for" + instanceNode.getValue().ToString() + ", " + serializedAnswer); } if (serializer.containsExternalData(instanceNode.getValue())) { IDataPointer[] pointer = serializer .retrieveExternalDataPointer(instanceNode.getValue()); for (int i = 0; i < pointer.Length; ++i) { dataPointers.Add(pointer[i]); } } } return ae; } /* * (non-Javadoc) * * @seeorg.javarosa.core.model.utils.IInstanceSerializingVisitor# * setAnswerDataSerializer(org.javarosa.core.model.IAnswerDataSerializer) */ public IInstanceSerializingVisitor newInstance() { XFormSerializingVisitor modelSerializer = new XFormSerializingVisitor(); modelSerializer.setAnswerDataSerializer(this.serializer); return modelSerializer; } public void setAnswerDataSerializer(IAnswerDataSerializer ads) { this.serializer = ads; } } }
namespace InControl { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using UnityEngine; [ExecuteInEditMode] public class TouchManager : SingletonMonoBehavior<TouchManager, InControlManager> { public enum GizmoShowOption { Never, WhenSelected, UnlessPlaying, Always } [Space( 10 )] public Camera touchCamera; public GizmoShowOption controlsShowGizmos = GizmoShowOption.Always; [HideInInspector] public bool enableControlsOnTouch = false; [SerializeField, HideInInspector] bool _controlsEnabled = true; // Defaults to UI layer. [HideInInspector] public int controlsLayer = 5; public static event Action OnSetup; InputDevice device; Vector3 viewSize; Vector2 screenSize; Vector2 halfScreenSize; float percentToWorld; float halfPercentToWorld; float pixelToWorld; float halfPixelToWorld; TouchControl[] touchControls; TouchPool cachedTouches; List<Touch> activeTouches; ReadOnlyCollection<Touch> readOnlyActiveTouches; Vector2 lastMousePosition; bool isReady; #pragma warning disable 414 Touch mouseTouch; #pragma warning restore 414 protected TouchManager() { } void OnEnable() { var manager = GetComponent<InControlManager>(); if (manager == null) { Debug.LogError( "Touch Manager component can only be added to the InControl Manager object." ); DestroyImmediate( this ); return; } if (EnforceSingletonComponent() == false) { Debug.LogWarning( "There is already a Touch Manager component on this game object." ); return; } #if UNITY_EDITOR if (touchCamera == null) { foreach (var component in manager.gameObject.GetComponentsInChildren<Camera>()) { DestroyImmediate( component.gameObject ); } var cameraGameObject = new GameObject( "Touch Camera" ); cameraGameObject.transform.parent = manager.gameObject.transform; cameraGameObject.transform.SetAsFirstSibling(); touchCamera = cameraGameObject.AddComponent<Camera>(); touchCamera.transform.position = new Vector3( 0.0f, 0.0f, -10.0f ); touchCamera.clearFlags = CameraClearFlags.Nothing; touchCamera.cullingMask = 1 << LayerMask.NameToLayer( "UI" ); touchCamera.orthographic = true; touchCamera.orthographicSize = 5.0f; touchCamera.nearClipPlane = 0.3f; touchCamera.farClipPlane = 1000.0f; touchCamera.rect = new Rect( 0.0f, 0.0f, 1.0f, 1.0f ); touchCamera.depth = 100; } #endif touchControls = GetComponentsInChildren<TouchControl>( true ); if (Application.isPlaying) { InputManager.OnSetup += Setup; InputManager.OnUpdateDevices += UpdateDevice; InputManager.OnCommitDevices += CommitDevice; } } void OnDisable() { if (Application.isPlaying) { InputManager.OnSetup -= Setup; InputManager.OnUpdateDevices -= UpdateDevice; InputManager.OnCommitDevices -= CommitDevice; } Reset(); } void Setup() { UpdateScreenSize( new Vector2( Screen.width, Screen.height ) ); CreateDevice(); CreateTouches(); if (OnSetup != null) { OnSetup.Invoke(); OnSetup = null; } } void Reset() { device = null; mouseTouch = null; cachedTouches = null; activeTouches = null; readOnlyActiveTouches = null; touchControls = null; OnSetup = null; } IEnumerator UpdateScreenSizeAtEndOfFrame() { yield return new WaitForEndOfFrame(); UpdateScreenSize( new Vector2( Screen.width, Screen.height ) ); yield return null; } void Update() { var currentScreenSize = new Vector2( Screen.width, Screen.height ); if (!isReady) { // This little hack is necessary because right after Unity starts up, // cameras don't seem to have a correct projection matrix until after // their first update or around that time. So we basically need to // wait until the end of the first frame before everything is quite ready. StartCoroutine( UpdateScreenSizeAtEndOfFrame() ); UpdateScreenSize( currentScreenSize ); isReady = true; return; } if (screenSize != currentScreenSize) { UpdateScreenSize( currentScreenSize ); } if (OnSetup != null) { OnSetup.Invoke(); OnSetup = null; } } void CreateDevice() { device = new TouchInputDevice(); device.AddControl( InputControlType.LeftStickLeft, "LeftStickLeft" ); device.AddControl( InputControlType.LeftStickRight, "LeftStickRight" ); device.AddControl( InputControlType.LeftStickUp, "LeftStickUp" ); device.AddControl( InputControlType.LeftStickDown, "LeftStickDown" ); device.AddControl( InputControlType.RightStickLeft, "RightStickLeft" ); device.AddControl( InputControlType.RightStickRight, "RightStickRight" ); device.AddControl( InputControlType.RightStickUp, "RightStickUp" ); device.AddControl( InputControlType.RightStickDown, "RightStickDown" ); device.AddControl( InputControlType.DPadUp, "DPadUp" ); device.AddControl( InputControlType.DPadDown, "DPadDown" ); device.AddControl( InputControlType.DPadLeft, "DPadLeft" ); device.AddControl( InputControlType.DPadRight, "DPadRight" ); device.AddControl( InputControlType.LeftTrigger, "LeftTrigger" ); device.AddControl( InputControlType.RightTrigger, "RightTrigger" ); device.AddControl( InputControlType.LeftBumper, "LeftBumper" ); device.AddControl( InputControlType.RightBumper, "RightBumper" ); for (var control = InputControlType.Action1; control <= InputControlType.Action4; control++) { device.AddControl( control, control.ToString() ); } device.AddControl( InputControlType.Menu, "Menu" ); for (var control = InputControlType.Button0; control <= InputControlType.Button19; control++) { device.AddControl( control, control.ToString() ); } InputManager.AttachDevice( device ); } void UpdateDevice( ulong updateTick, float deltaTime ) { UpdateTouches( updateTick, deltaTime ); SubmitControlStates( updateTick, deltaTime ); } void CommitDevice( ulong updateTick, float deltaTime ) { CommitControlStates( updateTick, deltaTime ); } void SubmitControlStates( ulong updateTick, float deltaTime ) { var touchControlCount = touchControls.Length; for (var i = 0; i < touchControlCount; i++) { var touchControl = touchControls[i]; if (touchControl.enabled && touchControl.gameObject.activeInHierarchy) { touchControl.SubmitControlState( updateTick, deltaTime ); } } } void CommitControlStates( ulong updateTick, float deltaTime ) { var touchControlCount = touchControls.Length; for (var i = 0; i < touchControlCount; i++) { var touchControl = touchControls[i]; if (touchControl.enabled && touchControl.gameObject.activeInHierarchy) { touchControl.CommitControlState( updateTick, deltaTime ); } } } void UpdateScreenSize( Vector2 currentScreenSize ) { screenSize = currentScreenSize; halfScreenSize = screenSize / 2.0f; viewSize = ConvertViewToWorldPoint( Vector2.one ) * 0.02f; percentToWorld = Mathf.Min( viewSize.x, viewSize.y ); halfPercentToWorld = percentToWorld / 2.0f; if (touchCamera != null) { halfPixelToWorld = touchCamera.orthographicSize / screenSize.y; pixelToWorld = halfPixelToWorld * 2.0f; } if (touchControls != null) { var touchControlCount = touchControls.Length; for (var i = 0; i < touchControlCount; i++) { touchControls[i].ConfigureControl(); } } } void CreateTouches() { cachedTouches = new TouchPool(); mouseTouch = new Touch(); mouseTouch.fingerId = Touch.FingerID_Mouse; activeTouches = new List<Touch>( 32 ); readOnlyActiveTouches = new ReadOnlyCollection<Touch>( activeTouches ); } void UpdateTouches( ulong updateTick, float deltaTime ) { activeTouches.Clear(); cachedTouches.FreeEndedTouches(); #if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WEBGL || UNITY_WSA if (mouseTouch.SetWithMouseData( updateTick, deltaTime )) { activeTouches.Add( mouseTouch ); } #endif for (var i = 0; i < Input.touchCount; i++) { var unityTouch = Input.GetTouch( i ); var cacheTouch = cachedTouches.FindOrCreateTouch( unityTouch.fingerId ); cacheTouch.SetWithTouchData( unityTouch, updateTick, deltaTime ); activeTouches.Add( cacheTouch ); } // Find any touches that Unity may have "forgotten" to end properly. var touchCount = cachedTouches.Touches.Count; for (var i = 0; i < touchCount; i++) { var touch = cachedTouches.Touches[i]; if (touch.phase != TouchPhase.Ended && touch.updateTick != updateTick) { touch.phase = TouchPhase.Ended; activeTouches.Add( touch ); } } InvokeTouchEvents(); } void SendTouchBegan( Touch touch ) { var touchControlCount = touchControls.Length; for (var i = 0; i < touchControlCount; i++) { var touchControl = touchControls[i]; if (touchControl.enabled && touchControl.gameObject.activeInHierarchy) { touchControl.TouchBegan( touch ); } } } void SendTouchMoved( Touch touch ) { var touchControlCount = touchControls.Length; for (var i = 0; i < touchControlCount; i++) { var touchControl = touchControls[i]; if (touchControl.enabled && touchControl.gameObject.activeInHierarchy) { touchControl.TouchMoved( touch ); } } } void SendTouchEnded( Touch touch ) { var touchControlCount = touchControls.Length; for (var i = 0; i < touchControlCount; i++) { var touchControl = touchControls[i]; if (touchControl.enabled && touchControl.gameObject.activeInHierarchy) { touchControl.TouchEnded( touch ); } } } void InvokeTouchEvents() { var touchCount = activeTouches.Count; if (enableControlsOnTouch) { if (touchCount > 0 && !controlsEnabled) { Device.RequestActivation(); controlsEnabled = true; } } for (var i = 0; i < touchCount; i++) { var touch = activeTouches[i]; switch (touch.phase) { case TouchPhase.Began: SendTouchBegan( touch ); break; case TouchPhase.Moved: SendTouchMoved( touch ); break; case TouchPhase.Ended: SendTouchEnded( touch ); break; case TouchPhase.Canceled: SendTouchEnded( touch ); break; } } } bool TouchCameraIsValid() { if (touchCamera == null) { return false; } if (Utility.IsZero( touchCamera.orthographicSize )) { return false; } if (Utility.IsZero( touchCamera.rect.width ) && Utility.IsZero( touchCamera.rect.height )) { return false; } if (Utility.IsZero( touchCamera.pixelRect.width ) && Utility.IsZero( touchCamera.pixelRect.height )) { return false; } return true; } Vector3 ConvertScreenToWorldPoint( Vector2 point ) { if (TouchCameraIsValid()) { return touchCamera.ScreenToWorldPoint( new Vector3( point.x, point.y, -touchCamera.transform.position.z ) ); } else { return Vector3.zero; } } Vector3 ConvertViewToWorldPoint( Vector2 point ) { if (TouchCameraIsValid()) { return touchCamera.ViewportToWorldPoint( new Vector3( point.x, point.y, -touchCamera.transform.position.z ) ); } else { return Vector3.zero; } } Vector3 ConvertScreenToViewPoint( Vector2 point ) { if (TouchCameraIsValid()) { return touchCamera.ScreenToViewportPoint( new Vector3( point.x, point.y, -touchCamera.transform.position.z ) ); } else { return Vector3.zero; } } public bool controlsEnabled { get { return _controlsEnabled; } set { if (_controlsEnabled != value) { var touchControlCount = touchControls.Length; for (var i = 0; i < touchControlCount; i++) { touchControls[i].enabled = value; } _controlsEnabled = value; } } } #region Static interface. public static ReadOnlyCollection<Touch> Touches { get { return Instance.readOnlyActiveTouches; } } public static int TouchCount { get { return Instance.activeTouches.Count; } } public static Touch GetTouch( int touchIndex ) { return Instance.activeTouches[touchIndex]; } public static Touch GetTouchByFingerId( int fingerId ) { return Instance.cachedTouches.FindTouch( fingerId ); } public static Vector3 ScreenToWorldPoint( Vector2 point ) { return Instance.ConvertScreenToWorldPoint( point ); } public static Vector3 ViewToWorldPoint( Vector2 point ) { return Instance.ConvertViewToWorldPoint( point ); } public static Vector3 ScreenToViewPoint( Vector2 point ) { return Instance.ConvertScreenToViewPoint( point ); } public static float ConvertToWorld( float value, TouchUnitType unitType ) { return value * (unitType == TouchUnitType.Pixels ? PixelToWorld : PercentToWorld); } public static Rect PercentToWorldRect( Rect rect ) { return new Rect( (rect.xMin - 50.0f) * ViewSize.x, (rect.yMin - 50.0f) * ViewSize.y, rect.width * ViewSize.x, rect.height * ViewSize.y ); } public static Rect PixelToWorldRect( Rect rect ) { return new Rect( Mathf.Round( rect.xMin - HalfScreenSize.x ) * PixelToWorld, Mathf.Round( rect.yMin - HalfScreenSize.y ) * PixelToWorld, Mathf.Round( rect.width ) * PixelToWorld, Mathf.Round( rect.height ) * PixelToWorld ); } public static Rect ConvertToWorld( Rect rect, TouchUnitType unitType ) { return unitType == TouchUnitType.Pixels ? PixelToWorldRect( rect ) : PercentToWorldRect( rect ); } public static Camera Camera { get { return Instance.touchCamera; } } public static InputDevice Device { get { return Instance.device; } } public static Vector3 ViewSize { get { return Instance.viewSize; } } public static float PercentToWorld { get { return Instance.percentToWorld; } } public static float HalfPercentToWorld { get { return Instance.halfPercentToWorld; } } public static float PixelToWorld { get { return Instance.pixelToWorld; } } public static float HalfPixelToWorld { get { return Instance.halfPixelToWorld; } } public static Vector2 ScreenSize { get { return Instance.screenSize; } } public static Vector2 HalfScreenSize { get { return Instance.halfScreenSize; } } public static GizmoShowOption ControlsShowGizmos { get { return Instance.controlsShowGizmos; } } public static bool ControlsEnabled { get { return Instance.controlsEnabled; } set { Instance.controlsEnabled = value; } } #endregion public static implicit operator bool( TouchManager instance ) { return instance != null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using XmlCoreTest.Common; using Xunit; namespace CoreXml.Test.XLinq { public class LoadSaveAsyncTests : BridgeHelpers { [Fact] public static void ArgumentValidation() { // Verify that ArgumentNullExceptions are thrown when passing null to LoadAsync and SaveAsync Assert.Throws<ArgumentNullException>(() => { XDocument.LoadAsync((XmlReader)null, LoadOptions.None, CancellationToken.None); }); Assert.Throws<ArgumentNullException>(() => { new XDocument().SaveAsync((XmlWriter)null, CancellationToken.None); }); Assert.Throws<ArgumentNullException>(() => { XElement.LoadAsync((XmlReader)null, LoadOptions.None, CancellationToken.None); }); Assert.Throws<ArgumentNullException>(() => { new XElement("Name").SaveAsync((XmlWriter)null, CancellationToken.None); }); } [Fact] public static async Task AlreadyCanceled() { // Verify that providing an already canceled cancellation token will result in a canceled task await Assert.ThrowsAnyAsync<OperationCanceledException>(() => XDocument.LoadAsync(Stream.Null, LoadOptions.None, new CancellationToken(true))); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => XDocument.LoadAsync(StreamReader.Null, LoadOptions.None, new CancellationToken(true))); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => XDocument.LoadAsync(XmlReader.Create(Stream.Null), LoadOptions.None, new CancellationToken(true))); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => new XDocument().SaveAsync(Stream.Null, SaveOptions.None, new CancellationToken(true))); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => new XDocument().SaveAsync(StreamWriter.Null, SaveOptions.None, new CancellationToken(true))); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => new XDocument().SaveAsync(XmlWriter.Create(Stream.Null), new CancellationToken(true))); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => XElement.LoadAsync(Stream.Null, LoadOptions.None, new CancellationToken(true))); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => XElement.LoadAsync(StreamReader.Null, LoadOptions.None, new CancellationToken(true))); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => XElement.LoadAsync(XmlReader.Create(Stream.Null), LoadOptions.None, new CancellationToken(true))); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => new XElement("Name").SaveAsync(Stream.Null, SaveOptions.None, new CancellationToken(true))); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => new XElement("Name").SaveAsync(StreamWriter.Null, SaveOptions.None, new CancellationToken(true))); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => new XElement("Name").SaveAsync(XmlWriter.Create(Stream.Null), new CancellationToken(true))); } [Theory] [MemberData(nameof(RoundtripOptions_MemberData))] public static async Task RoundtripSyncAsyncMatches_XmlReader(bool document, LoadOptions loadOptions, SaveOptions saveOptions) { // Create reader and writer settings var readerSettings = new XmlReaderSettings(); var writerSettings = new XmlWriterSettings(); if ((saveOptions & SaveOptions.OmitDuplicateNamespaces) != 0) { writerSettings.NamespaceHandling = NamespaceHandling.OmitDuplicates; } if ((saveOptions & SaveOptions.DisableFormatting) != 0) { writerSettings.Indent = false; writerSettings.NewLineHandling = NewLineHandling.None; } // Roundtrip XML using synchronous and XmlReader/Writer MemoryStream syncOutput = new MemoryStream(); using (XmlReader syncReader = XmlReader.Create(FilePathUtil.getStream(GetTestFileName()), readerSettings)) using (XmlWriter syncWriter = XmlWriter.Create(syncOutput, writerSettings)) { if (document) { XDocument syncDoc = XDocument.Load(syncReader, loadOptions); syncDoc.Save(syncWriter); } else { XElement syncElement = XElement.Load(syncReader, loadOptions); syncElement.Save(syncWriter); } } // Roundtrip XML using asynchronous and XmlReader/Writer readerSettings.Async = true; writerSettings.Async = true; MemoryStream asyncOutput = new MemoryStream(); using (XmlReader asyncReader = XmlReader.Create(FilePathUtil.getStream(GetTestFileName()), readerSettings)) using (XmlWriter asyncWriter = XmlWriter.Create(asyncOutput, writerSettings)) { if (document) { XDocument asyncDoc = await XDocument.LoadAsync(asyncReader, loadOptions, CancellationToken.None); await asyncDoc.SaveAsync(asyncWriter, CancellationToken.None); } else { XElement asyncElement = await XElement.LoadAsync(asyncReader, loadOptions, CancellationToken.None); await asyncElement.SaveAsync(asyncWriter, CancellationToken.None); } } // Compare to make sure the synchronous and asynchronous results are the same Assert.Equal(syncOutput.ToArray(), asyncOutput.ToArray()); } [Theory] [MemberData(nameof(RoundtripOptions_MemberData))] public static async Task RoundtripSyncAsyncMatches_StreamReader(bool document, LoadOptions loadOptions, SaveOptions saveOptions) { // Roundtrip XML using synchronous and StreamReader/Writer MemoryStream syncOutput = new MemoryStream(); using (StreamReader syncReader = new StreamReader(FilePathUtil.getStream(GetTestFileName()))) using (StreamWriter syncWriter = new StreamWriter(syncOutput)) { if (document) { XDocument syncDoc = XDocument.Load(syncReader, loadOptions); syncDoc.Save(syncWriter, saveOptions); } else { XElement syncElement = XElement.Load(syncReader, loadOptions); syncElement.Save(syncWriter, saveOptions); } } // Roundtrip XML using asynchronous and StreamReader/Writer MemoryStream asyncOutput = new MemoryStream(); using (StreamReader asyncReader = new StreamReader(FilePathUtil.getStream(GetTestFileName()))) using (StreamWriter asyncWriter = new StreamWriter(asyncOutput)) { if (document) { XDocument asyncDoc = await XDocument.LoadAsync(asyncReader, loadOptions, CancellationToken.None); await asyncDoc.SaveAsync(asyncWriter, saveOptions, CancellationToken.None); } else { XElement asyncElement = await XElement.LoadAsync(asyncReader, loadOptions, CancellationToken.None); await asyncElement.SaveAsync(asyncWriter, saveOptions, CancellationToken.None); } } // Compare to make sure the synchronous and asynchronous results are the same Assert.Equal(syncOutput.ToArray(), asyncOutput.ToArray()); } [Theory] [MemberData(nameof(RoundtripOptions_MemberData))] public static async Task RoundtripSyncAsyncMatches_Stream(bool document, LoadOptions loadOptions, SaveOptions saveOptions) { // Roundtrip XML using synchronous and Stream MemoryStream syncOutput = new MemoryStream(); using (Stream syncStream = FilePathUtil.getStream(GetTestFileName())) { if (document) { XDocument syncDoc = XDocument.Load(syncStream, loadOptions); syncDoc.Save(syncOutput, saveOptions); } else { XElement syncElement = XElement.Load(syncStream, loadOptions); syncElement.Save(syncOutput, saveOptions); } } // Roundtrip XML using asynchronous and Stream MemoryStream asyncOutput = new MemoryStream(); using (Stream asyncStream = FilePathUtil.getStream(GetTestFileName())) { if (document) { XDocument asyncDoc = await XDocument.LoadAsync(asyncStream, loadOptions, CancellationToken.None); await asyncDoc.SaveAsync(asyncOutput, saveOptions, CancellationToken.None); } else { XElement asyncElement = await XElement.LoadAsync(asyncStream, loadOptions, CancellationToken.None); await asyncElement.SaveAsync(asyncOutput, saveOptions, CancellationToken.None); } } // Compare to make sure the synchronous and asynchronous results are the same Assert.Equal(syncOutput.ToArray(), asyncOutput.ToArray()); } // Inputs to the Roundtrip* tests: // - Boolean for whether to test XDocument (true) or XElement (false) // - LoadOptions value // - SaveOptions value public static IEnumerable<object[]> RoundtripOptions_MemberData { get { foreach (bool doc in new[] { true, false }) foreach (LoadOptions loadOptions in Enum.GetValues(typeof(LoadOptions))) foreach (SaveOptions saveOptions in Enum.GetValues(typeof(SaveOptions))) yield return new object[] { doc, loadOptions, saveOptions }; } } } }
using System; using System.Reflection; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace IO.Swagger.Client { /// <summary> /// Represents a set of configuration settings /// </summary> public class Configuration { /// <summary> /// Initializes a new instance of the Configuration class with different settings /// </summary> /// <param name="apiClient">Api client</param> /// <param name="defaultHeader">Dictionary of default HTTP header</param> /// <param name="username">Username</param> /// <param name="password">Password</param> /// <param name="accessToken">accessToken</param> /// <param name="apiKey">Dictionary of API key</param> /// <param name="apiKeyPrefix">Dictionary of API key prefix</param> /// <param name="tempFolderPath">Temp folder path</param> /// <param name="dateTimeFormat">DateTime format string</param> /// <param name="timeout">HTTP connection timeout (in milliseconds)</param> public Configuration(ApiClient apiClient = null, Dictionary<String, String> defaultHeader = null, string username = null, string password = null, string accessToken = null, Dictionary<String, String> apiKey = null, Dictionary<String, String> apiKeyPrefix = null, string tempFolderPath = null, string dateTimeFormat = null, int timeout = 100000, string httpUserAgent = "Swagger-Codegen/1.0.0/csharp" ) { setApiClientUsingDefault(apiClient); Username = username; Password = password; AccessToken = accessToken; HttpUserAgent = httpUserAgent; if (defaultHeader != null) DefaultHeader = defaultHeader; if (apiKey != null) ApiKey = apiKey; if (apiKeyPrefix != null) ApiKeyPrefix = apiKeyPrefix; TempFolderPath = tempFolderPath; DateTimeFormat = dateTimeFormat; Timeout = timeout; } /// <summary> /// Initializes a new instance of the Configuration class. /// </summary> /// <param name="apiClient">Api client.</param> public Configuration(ApiClient apiClient) { setApiClientUsingDefault(apiClient); } /// <summary> /// Version of the package. /// </summary> /// <value>Version of the package.</value> public const string Version = "1.0.0"; /// <summary> /// Gets or sets the default Configuration. /// </summary> /// <value>Configuration.</value> public static Configuration Default = new Configuration(); /// <summary> /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. /// </summary> /// <value>Timeout.</value> public int Timeout { get { return ApiClient.RestClient.Timeout; } set { if (ApiClient != null) ApiClient.RestClient.Timeout = value; } } /// <summary> /// Gets or sets the default API client for making HTTP calls. /// </summary> /// <value>The API client.</value> public ApiClient ApiClient; /// <summary> /// Set the ApiClient using Default or ApiClient instance. /// </summary> /// <param name="apiClient">An instance of ApiClient.</param> /// <returns></returns> public void setApiClientUsingDefault (ApiClient apiClient = null) { if (apiClient == null) { if (Default != null && Default.ApiClient == null) Default.ApiClient = new ApiClient(); ApiClient = Default != null ? Default.ApiClient : new ApiClient(); } else { if (Default != null && Default.ApiClient == null) Default.ApiClient = apiClient; ApiClient = apiClient; } } private Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>(); /// <summary> /// Gets or sets the default header. /// </summary> public Dictionary<String, String> DefaultHeader { get { return _defaultHeaderMap; } set { _defaultHeaderMap = value; } } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> public void AddDefaultHeader(string key, string value) { _defaultHeaderMap.Add(key, value); } /// <summary> /// Gets or sets the HTTP user agent. /// </summary> /// <value>Http user agent.</value> public String HttpUserAgent { get; set; } /// <summary> /// Gets or sets the username (HTTP basic authentication). /// </summary> /// <value>The username.</value> public String Username { get; set; } /// <summary> /// Gets or sets the password (HTTP basic authentication). /// </summary> /// <value>The password.</value> public String Password { get; set; } /// <summary> /// Gets or sets the access token for OAuth2 authentication. /// </summary> /// <value>The access token.</value> public String AccessToken { get; set; } /// <summary> /// Gets or sets the API key based on the authentication name. /// </summary> /// <value>The API key.</value> public Dictionary<String, String> ApiKey = new Dictionary<String, String>(); /// <summary> /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. /// </summary> /// <value>The prefix of the API key.</value> public Dictionary<String, String> ApiKeyPrefix = new Dictionary<String, String>(); /// <summary> /// Get the API key with prefix. /// </summary> /// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param> /// <returns>API key with prefix.</returns> public string GetApiKeyWithPrefix (string apiKeyIdentifier) { var apiKeyValue = ""; ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue); var apiKeyPrefix = ""; if (ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) return apiKeyPrefix + " " + apiKeyValue; else return apiKeyValue; } private string _tempFolderPath = Path.GetTempPath(); /// <summary> /// Gets or sets the temporary folder path to store the files downloaded from the server. /// </summary> /// <value>Folder path.</value> public String TempFolderPath { get { return _tempFolderPath; } set { if (String.IsNullOrEmpty(value)) { _tempFolderPath = value; return; } // create the directory if it does not exist if (!Directory.Exists(value)) Directory.CreateDirectory(value); // check if the path contains directory separator at the end if (value[value.Length - 1] == Path.DirectorySeparatorChar) _tempFolderPath = value; else _tempFolderPath = value + Path.DirectorySeparatorChar; } } private const string ISO8601_DATETIME_FORMAT = "o"; private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; /// <summary> /// Gets or sets the the date time format used when serializing in the ApiClient /// By default, it's set to ISO 8601 - "o", for others see: /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx /// No validation is done to ensure that the string you're providing is valid /// </summary> /// <value>The DateTimeFormat string</value> public String DateTimeFormat { get { return _dateTimeFormat; } set { if (string.IsNullOrEmpty(value)) { // Never allow a blank or null string, go back to the default _dateTimeFormat = ISO8601_DATETIME_FORMAT; return; } // Caution, no validation when you choose date time format other than ISO 8601 // Take a look at the above links _dateTimeFormat = value; } } /// <summary> /// Returns a string with essential information for debugging. /// </summary> public static String ToDebugReport() { String report = "C# SDK (IO.Swagger) Debug Report:\n"; report += " OS: " + Environment.OSVersion + "\n"; report += " .NET Framework Version: " + Assembly .GetExecutingAssembly() .GetReferencedAssemblies() .Where(x => x.Name == "System.Core").First().Version.ToString() + "\n"; report += " Version of the API: 1.0.0\n"; report += " SDK Package Version: 1.0.0\n"; return report; } } }
// // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. //using System; using System.IO; using Apache.Http; using Apache.Http.Client; using Apache.Http.Client.Methods; using Apache.Http.Entity; using Apache.Http.Impl.Client; using Apache.Http.Message; using Couchbase.Lite; using Couchbase.Lite.Performance; using Couchbase.Lite.Replicator; using Couchbase.Lite.Support; using Couchbase.Lite.Threading; using Couchbase.Lite.Util; using NUnit.Framework; using Org.Apache.Commons.IO; using Org.Apache.Commons.IO.Output; using Sharpen; namespace Couchbase.Lite.Performance { public class Test7_PullReplication : LiteTestCase { public const string Tag = "PullReplicationPerformance"; private const string _propertyValue = "1234567"; /// <exception cref="System.Exception"></exception> protected override void SetUp() { Log.V(Tag, "DeleteDBPerformance setUp"); base.SetUp(); string docIdTimestamp = System.Convert.ToString(Runtime.CurrentTimeMillis()); for (int i = 0; i < GetNumberOfDocuments(); i++) { string docId = string.Format("doc%d-%s", i, docIdTimestamp); Log.D(Tag, "Adding " + docId + " directly to sync gateway"); try { AddDocWithId(docId, "attachment.png", false); } catch (IOException ioex) { Log.E(Tag, "Add document directly to sync gateway failed", ioex); Fail(); } } } /// <exception cref="Couchbase.Lite.CouchbaseLiteException"></exception> public virtual void TestPullReplicationPerformance() { long startMillis = Runtime.CurrentTimeMillis(); Log.D(Tag, "testPullReplicationPerformance() started"); DoPullReplication(); NUnit.Framework.Assert.IsNotNull(database); Log.D(Tag, "testPullReplicationPerformance() finished"); Log.V("PerformanceStats", Tag + "," + Sharpen.Extensions.ValueOf(Runtime.CurrentTimeMillis () - startMillis).ToString() + "," + GetNumberOfDocuments()); } private void DoPullReplication() { Uri remote = GetReplicationURL(); Replication repl = (Replication)database.CreatePullReplication(remote); repl.SetContinuous(false); Log.D(Tag, "Doing pull replication with: " + repl); RunReplication(repl); Log.D(Tag, "Finished pull replication with: " + repl); } /// <exception cref="System.IO.IOException"></exception> private void AddDocWithId(string docId, string attachmentName, bool gzipped) { string docJson; if (attachmentName != null) { // add attachment to document InputStream attachmentStream = GetAsset(attachmentName); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.Copy(attachmentStream, baos); if (gzipped == false) { string attachmentBase64 = Base64.EncodeBytes(baos.ToByteArray()); docJson = string.Format("{\"foo\":1,\"bar\":false, \"_attachments\": { \"%s\": { \"content_type\": \"image/png\", \"data\": \"%s\" } } }" , attachmentName, attachmentBase64); } else { byte[] bytes = baos.ToByteArray(); string attachmentBase64 = Base64.EncodeBytes(bytes, Base64.Gzip); docJson = string.Format("{\"foo\":1,\"bar\":false, \"_attachments\": { \"%s\": { \"content_type\": \"image/png\", \"data\": \"%s\", \"encoding\": \"gzip\", \"length\":%d } } }" , attachmentName, attachmentBase64, bytes.Length); } } else { docJson = "{\"foo\":1,\"bar\":false}"; } PushDocumentToSyncGateway(docId, docJson); WorkaroundSyncGatewayRaceCondition(); } /// <exception cref="System.UriFormatException"></exception> private void PushDocumentToSyncGateway(string docId, string docJson) { // push a document to server Uri replicationUrlTrailingDoc1 = new Uri(string.Format("%s/%s", GetReplicationURL ().ToExternalForm(), docId)); Uri pathToDoc1 = new Uri(replicationUrlTrailingDoc1, docId); Log.D(Tag, "Send http request to " + pathToDoc1); CountDownLatch httpRequestDoneSignal = new CountDownLatch(1); BackgroundTask getDocTask = new _BackgroundTask_139(pathToDoc1, docJson, httpRequestDoneSignal ); getDocTask.Execute(); Log.D(Tag, "Waiting for http request to finish"); try { httpRequestDoneSignal.Await(300, TimeUnit.Seconds); Log.D(Tag, "http request finished"); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } private sealed class _BackgroundTask_139 : BackgroundTask { public _BackgroundTask_139(Uri pathToDoc1, string docJson, CountDownLatch httpRequestDoneSignal ) { this.pathToDoc1 = pathToDoc1; this.docJson = docJson; this.httpRequestDoneSignal = httpRequestDoneSignal; } public override void Run() { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response; string responseString = null; try { HttpPut post = new HttpPut(pathToDoc1.ToExternalForm()); StringEntity se = new StringEntity(docJson.ToString()); se.SetContentType(new BasicHeader("content_type", "application/json")); post.SetEntity(se); response = httpclient.Execute(post); StatusLine statusLine = response.GetStatusLine(); Log.D(Test7_PullReplication.Tag, "Got response: " + statusLine); NUnit.Framework.Assert.IsTrue(statusLine.GetStatusCode() == HttpStatus.ScCreated); } catch (ClientProtocolException e) { NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage (), e); } catch (IOException e) { NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e); } httpRequestDoneSignal.CountDown(); } private readonly Uri pathToDoc1; private readonly string docJson; private readonly CountDownLatch httpRequestDoneSignal; } /// <summary> /// Whenever posting information directly to sync gateway via HTTP, the client /// must pause briefly to give it a chance to achieve internal consistency. /// </summary> /// <remarks> /// Whenever posting information directly to sync gateway via HTTP, the client /// must pause briefly to give it a chance to achieve internal consistency. /// <p/> /// This is documented in https://github.com/couchbase/sync_gateway/issues/228 /// </remarks> private void WorkaroundSyncGatewayRaceCondition() { try { Sharpen.Thread.Sleep(5 * 1000); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } private int GetNumberOfDocuments() { return System.Convert.ToInt32(Runtime.GetProperty("Test7_numberOfDocuments")); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace Scriban.Helpers { [DebuggerTypeProxy(typeof(InlineList<>.DebugListView)), DebuggerDisplay("Count = {Count}")] internal struct InlineList<T> : IEnumerable<T> { private const int DefaultCapacity = 4; public int Count; public T[] Items; public InlineList(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity)); Count = 0; Items = capacity == 0 ? Array.Empty<T>() : new T[capacity]; } public int Capacity { get => Items?.Length ?? 0; set { Ensure(); if (value <= Items.Length) return; EnsureCapacity(value); } } public static InlineList<T> Create() { return new InlineList<T>(0); } public static InlineList<T> Create(int capacity) { return new InlineList<T>(capacity); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Ensure() { if (Items == null) Items = Array.Empty<T>(); } public bool IsReadOnly => false; [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { if (Count > 0) { Array.Clear(Items, 0, Count); Count = 0; } } public InlineList<T> Clone() { var items = (T[])Items?.Clone(); return new InlineList<T>() { Count = Count, Items = items }; } public bool Contains(T item) { return Count > 0 && IndexOf(item) >= 0; } public void CopyTo(T[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException(nameof(array)); if (Count > 0) { System.Array.Copy(Items, 0, array, arrayIndex, Count); } } public T[] ToArray() { var array = new T[Count]; CopyTo(array, 0); return array; } public void Reset() { Clear(); Count = 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(T child) { if (Count == Items.Length) { EnsureCapacity(Count + 1); } Items[Count++] = child; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AddByRef(in T child) { if (Count == Items.Length) { EnsureCapacity(Count + 1); } Items[Count++] = child; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Insert(int index, T item) { if (Count == Items.Length) { EnsureCapacity(Count + 1); } if (index < Count) { Array.Copy(Items, index, Items, index + 1, Count - index); } Items[index] = item; Count++; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref T InsertReturnRef(int index, T item) { if (Count == Items.Length) { EnsureCapacity(Count + 1); } if (index < Count) { Array.Copy(Items, index, Items, index + 1, Count - index); } ref var refItem = ref Items[index]; refItem = item; Count++; return ref refItem; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void InsertByRef(int index, in T item) { if (Count == Items.Length) { EnsureCapacity(Count + 1); } if (index < Count) { Array.Copy(Items, index, Items, index + 1, Count - index); } Items[index] = item; Count++; } public bool Remove(T element) { var index = IndexOf(element); if (index >= 0) { RemoveAt(index); return true; } return false; } public int IndexOf(T element) { return Array.IndexOf(Items, element, 0, Count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T RemoveAt(int index) { if (index < 0 || index >= Count) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); Count--; // previous children var item = Items[index]; if (index < Count) { Array.Copy(Items, index + 1, Items, index, Count - index); } Items[Count] = default(T); return item; } public T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((uint)index >= (uint)Count) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); return Items[index]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { if ((uint)index >= (uint)Count) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); Items[index] = value; } } private void EnsureCapacity(int min) { if (Items.Length < min) { int num = (Items.Length == 0) ? DefaultCapacity : (Items.Length * 2); if (num < min) { num = min; } Array.Resize(ref Items, num); } } public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public struct Enumerator : IEnumerator<T> { private readonly InlineList<T> list; private int index; private T current; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(InlineList<T> list) { this.list = list; index = 0; current = default(T); } public T Current => current; object IEnumerator.Current => Current; public void Dispose() { } public bool MoveNext() { if (index < list.Count) { current = list[index]; index++; return true; } return MoveNextRare(); } private bool MoveNextRare() { index = list.Count + 1; current = default(T); return false; } void IEnumerator.Reset() { index = 0; current = default(T); } } internal class DebugListView { private InlineList<T> _collection; public DebugListView(InlineList<T> collection) { this._collection = collection; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items { get { var array = new T[this._collection.Count]; for (int i = 0; i < array.Length; i++) { array[i] = _collection[i]; } return array; } } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace UoKRUnpacker { public interface StupidInterface { void SetLoadIcon(bool bStatus); void DisableOtherIcon(bool bEnable); void SetTextArea(string sText); void SetNodes(); void SetCursor(System.Windows.Forms.Cursor cCursore); void SetWaitStatus(bool bEnable); } public class ThreadArgs { private object[] m_Args; public delegate void MyThreadDelegate(object args); public ThreadArgs() { m_Args = null; } public ThreadArgs(object[] args) { m_Args = args; } public object[] Args { get { return m_Args; } set { m_Args = value; } } } public class DoingSomeJob { private static bool sm_Working = false; private static StupidInterface sm_Interface = null; public static bool Working { get { return sm_Working; } set { sm_Working = value; if (sm_Interface != null) { sm_Interface.SetWaitStatus(sm_Working); } } } public static StupidInterface TheForm { set { sm_Interface = value; } } } class StaticData { public const string UNPACK_DIR = @"\Unpacked"; public const string DUMPINFO_DIR = @"\Dumpinfo"; public const string UNPACK_NAMEPATTERN = "{0}-{1:00}_{2:00}.{3}"; public const string UNPACK_EXT_COMP = "dat"; public const string UNPACK_EXT_UCOMP = "raw"; public const string HELP_STRING = "This program can view, parse, dump and patch an uop file through a stupid interface." + "\n" + "This program is not optimized and/or written using a decent method." + "\n" + "This program is absolutely not for newbies." + "\n" + "\n" + "\n" + "It contains also a console mode to patch (multiple) file without the interface (--help for more info)," + "\n" + "it can be useful for batch process."; } class Utility { public static string GetPathForSave(string sInput) { return System.Windows.Forms.Application.StartupPath + @"\" + "NEW-" + Utility.GetFileName(sInput); } public static string GetFileName(string sInput) { return System.IO.Path.GetFileName(sInput); } public enum HashStringStyle : int { BigHex = 0, SingleHex, HexWithSeparator } public static string ByteArrayToString(byte[] thearray, HashStringStyle style) { StringBuilder sbBuffer = new StringBuilder(); if (style == HashStringStyle.BigHex) { sbBuffer.Append("0x"); } foreach (byte bSingle in thearray) { if (style == HashStringStyle.BigHex) sbBuffer.AppendFormat("{0:X}", bSingle); else if (style == HashStringStyle.SingleHex) sbBuffer.AppendFormat("0x{0:X} ", bSingle); else if (style == HashStringStyle.HexWithSeparator) sbBuffer.AppendFormat("{0:X} ", bSingle); } string toReturn = sbBuffer.ToString().Trim(); if (style == HashStringStyle.HexWithSeparator) { toReturn = toReturn.Replace(' ', '-'); } return toReturn; } public static byte[] StringToByteArray(string thearray, HashStringStyle style, int expectedLength) { byte[] toReturn = null; if (expectedLength > 0) toReturn = new byte[expectedLength]; if (style == HashStringStyle.BigHex) { // sbBuffer.AppendFormat("{0:X}", bSingle); } else if (style == HashStringStyle.SingleHex) { // sbBuffer.AppendFormat("0x{0:X} ", bSingle); } else if (style == HashStringStyle.HexWithSeparator) { string[] separated = thearray.Split(new char[] { '-' }); if (expectedLength > 0) { if (expectedLength == separated.Length) { for(int i = 0; i < separated.Length; i++) { if (!Byte.TryParse(separated[i], NumberStyles.AllowHexSpecifier, null, out toReturn[i])) return null; // error } } } else { toReturn = new byte[separated.Length]; for (int i = 0; i < separated.Length; i++) { if (!Byte.TryParse(separated[i], NumberStyles.AllowHexSpecifier, null, out toReturn[i])) return null; // error } } } return toReturn; } public static string StringFileSize(uint uSize) { if (uSize > 1000000) return (uSize / 1000000).ToString() + " Mb"; else if (uSize > 1000) return (uSize / 1000).ToString() + " Kb"; else return uSize.ToString() + " bytes"; } } } /* // QWORD 1 Hashcode (HashMeGently(filename)) public const uint SEED = 0xDEADBEEF; public static ulong HashMeGently( string s ) { uint eax, ecx, edx, ebx, esi, edi; eax = ecx = edx = ebx = esi = edi = 0; ebx = edi = esi = (uint) s.Length + SEED; int i = 0; for ( i = 0; i + 12 < s.Length; i += 12 ) { edi = (uint) ( ( s[ i + 7 ] << 24 ) | ( s[ i + 6 ] << 16 ) | ( s[ i + 5 ] << 8 ) | s[ i + 4 ] ) + edi; esi = (uint) ( ( s[ i + 11 ] << 24 ) | ( s[ i + 10 ] << 16 ) | ( s[ i + 9 ] << 8 ) | s[ i + 8 ] ) + esi; edx = (uint) ( ( s[ i + 3 ] << 24 ) | ( s[ i + 2 ] << 16 ) | ( s[ i + 1 ] << 8 ) | s[ i ] ) - esi; edx = ( edx + ebx ) ^ ( esi >> 28 ) ^ ( esi << 4 ); esi += edi; edi = ( edi - edx ) ^ ( edx >> 26 ) ^ ( edx << 6 ); edx += esi; esi = ( esi - edi ) ^ ( edi >> 24 ) ^ ( edi << 8 ); edi += edx; ebx = ( edx - esi ) ^ ( esi >> 16 ) ^ ( esi << 16 ); esi += edi; edi = ( edi - ebx ) ^ ( ebx >> 13 ) ^ ( ebx << 19 ); ebx += esi; esi = ( esi - edi ) ^ ( edi >> 28 ) ^ ( edi << 4 ); edi += ebx; } if ( s.Length - i > 0 ) { switch ( s.Length - i ) { case 12: esi += (uint) s[ i + 11 ] << 24; goto case 11; case 11: esi += (uint) s[ i + 10 ] << 16; goto case 10; case 10: esi += (uint) s[ i + 9 ] << 8; goto case 9; case 9: esi += (uint) s[ i + 8 ]; goto case 8; case 8: edi += (uint) s[ i + 7 ] << 24; goto case 7; case 7: edi += (uint) s[ i + 6 ] << 16; goto case 6; case 6: edi += (uint) s[ i + 5 ] << 8; goto case 5; case 5: edi += (uint) s[ i + 4 ]; goto case 4; case 4: ebx += (uint) s[ i + 3 ] << 24; goto case 3; case 3: ebx += (uint) s[ i + 2 ] << 16; goto case 2; case 2: ebx += (uint) s[ i + 1 ] << 8; goto case 1; case 1: ebx += (uint) s[ i ]; break; } esi = ( esi ^ edi ) - ( ( edi >> 18 ) ^ ( edi << 14 ) ); ecx = ( esi ^ ebx ) - ( ( esi >> 21 ) ^ ( esi << 11 ) ); edi = ( edi ^ ecx ) - ( ( ecx >> 7 ) ^ ( ecx << 25 ) ); esi = ( esi ^ edi ) - ( ( edi >> 16 ) ^ ( edi << 16 ) ); edx = ( esi ^ ecx ) - ( ( esi >> 28 ) ^ ( esi << 4 ) ); edi = ( edi ^ edx ) - ( ( edx >> 18 ) ^ ( edx << 14 ) ); eax = ( esi ^ edi ) - ( ( edi >> 8 ) ^ ( edi << 24 ) ); return ( (ulong) edi << 32 ) | eax; } return ( (ulong) esi << 32 ) | eax; } */
using System; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; using StackingEntities.Model.Annotations; using StackingEntities.Model.Enums; using StackingEntities.Model.Helpers; using StackingEntities.Model.Interface; using StackingEntities.Model.Items; using SimpleStringList = System.Collections.ObjectModel.ObservableCollection<StackingEntities.Model.Objects.SimpleTypes.SimpleString>; using JsonTextElementList = System.Collections.ObjectModel.ObservableCollection<StackingEntities.Model.Objects.JsonTextElement>; namespace StackingEntities.Model.Objects { [Serializable] public class JsonTextElement : IJsonAble, INotifyPropertyChanged { private JsonTextHoverEvent _hoverEvent = JsonTextHoverEvent.None; public string Text { get; set; } public string Translate { get; set; } public SimpleStringList TranslateWith { get; } = new SimpleStringList(); public string ScoreName { get; set; } public string ScoreObjective { get; set; } public string ScoreValue { get; set; } public string Selector { get; set; } private JsonTextType _textType = JsonTextType.Text; public JsonTextType TextType { get { return _textType; } set { _textType = value; PropChanged("TextType"); } } public JsonTextColor Color { get; set; } = JsonTextColor.Inherit; public bool? Bold { get; set; } public bool? Underlined { get; set; } public bool? Italic { get; set; } public bool? Strikethrough { get; set; } public bool? Obfuscated { get; set; } private JsonTextClickEvent _clickEvent = JsonTextClickEvent.None; public JsonTextClickEvent ClickEvent { get { return _clickEvent; } set { _clickEvent = value; PropChanged("ClickEvent"); } } public string ClickEventValue { get; set; } public JsonTextHoverEvent HoverEvent { get { return _hoverEvent; } set { _hoverEvent = value; if (value == JsonTextHoverEvent.show_text) { if (HoverEventText == null) { HoverEventText = _hoverEventTextBackup ?? new JsonTextElement { Title = "Hover Text" }; PropChanged("HoverEventText"); } } else if (HoverEventText != null) { _hoverEventTextBackup = HoverEventText; HoverEventText = null; PropChanged("HoverEventText"); } PropChanged("HoverEvent"); } } private JsonTextElement _hoverEventTextBackup; public JsonTextElement HoverEventText { get; private set; } public string HoverEventEntityName { get; set; } public AchievementName HoverEventAchievementName { get; set; } public Item HoverEventItem { get; } = new Item { Count = null, Slot = null }; public EntityType HoverEntityType { get; set; } public string HoverEntityId { get; set; } public JsonTextElementList Extra { get; } = new JsonTextElementList(); public string InsertionText { get; set; } public string Title { get; set; } public string GenerateJson(bool topLevel) { return ComputeJson(this); } // Currently do not need. //public bool HasValue() //{ // var ret = false; // switch (TextType) // { // case JsonTextType.Text: // ret |= !string.IsNullOrWhiteSpace(Text); // break; // case JsonTextType.Selector: // ret |= !string.IsNullOrWhiteSpace(Selector); // break; // case JsonTextType.Score: // ret |= !string.IsNullOrWhiteSpace(ScoreName); // break; // case JsonTextType.Translate: // ret |= !string.IsNullOrWhiteSpace(Translate); // break; // } // ret |= Color != JsonTextColor.Inherit; // ret |= Bold.HasValue; // ret |= Underlined.HasValue; // ret |= Italic.HasValue; // ret |= Strikethrough.HasValue; // ret |= Obfuscated.HasValue; // ret |= !string.IsNullOrWhiteSpace(InsertionText); // ret |= ClickEvent != JsonTextClickEvent.None; // switch (HoverEvent) // { // case JsonTextHoverEvent.show_text: // ret |= HoverEventText?.HasValue() ?? false; // break; // case JsonTextHoverEvent.show_item: // case JsonTextHoverEvent.show_achievement: // case JsonTextHoverEvent.show_entity: // ret = true; // break; // } // ret |= Extra.Count > 0; // return ret; //} private static string ComputeJson(JsonTextElement j) { var b = new StringBuilder("{"); switch (j.TextType) { case JsonTextType.Text: b.AppendFormat("text:\"{0}\",", j.Text.EscapeJsonString()); break; case JsonTextType.Selector: b.AppendFormat("selector:\"{0}\",", j.Selector.EscapeJsonString()); break; case JsonTextType.Score: b.AppendFormat("score:{{name:\"{0}\",objective:\"{1}\"", j.ScoreName.EscapeJsonString(), j.ScoreObjective.EscapeJsonString()); if (!string.IsNullOrWhiteSpace(j.ScoreValue)) b.AppendFormat(",value:\"{0}\"", j.ScoreValue.EscapeJsonString()); b.Append("}},"); break; case JsonTextType.Translate: b.AppendFormat("translate:\"{0}\",", j.Translate.EscapeJsonString()); if (j.TranslateWith.Count == 0) break; b.Append("with:["); foreach (var simpleString in j.TranslateWith) { b.AppendFormat("\"{0}\",", simpleString.Value.EscapeJsonString()); } if (b[b.Length - 1] == ',') b.Remove(b.Length - 1, 1); b.Append("],"); break; } if (j.Color != JsonTextColor.Inherit) b.AppendFormat("color:\"{0}\",", j.Color); AppendBoolQ(b, "bold", j.Bold); AppendBoolQ(b, "underlined", j.Underlined); AppendBoolQ(b, "italic", j.Italic); AppendBoolQ(b, "strikethrough", j.Strikethrough); AppendBoolQ(b, "obfuscated", j.Obfuscated); if (!string.IsNullOrWhiteSpace(j.InsertionText)) b.AppendFormat("insertion:\"{0}\",", j.InsertionText.EscapeJsonString()); if (j.ClickEvent != JsonTextClickEvent.None) { b.AppendFormat("clickEvent:{{action:\"{0}\",value:\"{1}\"}},", j.ClickEvent, j.ClickEventValue.EscapeJsonString()); } switch (j.HoverEvent) { case JsonTextHoverEvent.show_text: b.AppendFormat("hoverEvent:{{action:\"{0}\",value:{1}}},", j.HoverEvent, ComputeJson(j.HoverEventText)); break; case JsonTextHoverEvent.show_item: b.AppendFormat("hoverEvent:{{action:\"{0}\",value:\"{1}\"}},", j.HoverEvent, j.HoverEventItem.GenerateJson(false).EscapeJsonString()); break; case JsonTextHoverEvent.show_achievement: b.AppendFormat("hoverEvent:{{action:\"{0}\",value:\"achievement.{1}\"}},", j.HoverEvent, j.HoverEventAchievementName); break; case JsonTextHoverEvent.show_entity: b.AppendFormat("hoverEvent:{{action:\"{0}\",value:\"{{type:\\\"{1}\\\",name:\\\"{2}\\\",id:\\\"{3}\\\"}}\"}},", j.HoverEvent, j.HoverEntityType, j.HoverEventEntityName.EscapeJsonString(), j.HoverEntityId.EscapeJsonString()); break; } if (j.Extra.Count == 0) { if (b[b.Length - 1] == ',') b.Remove(b.Length - 1, 1); b.Append("}"); return b.ToString() == string.Format("{{text:\"{0}\"}}", j.Text.EscapeJsonString()) ? string.Format("\"{0}\"", j.Text.EscapeJsonString()) : b.ToString(); } b.Append("extra:["); foreach (var jsonTextElement in j.Extra) { b.AppendFormat("{0},", ComputeJson(jsonTextElement)); } b.Remove(b.Length - 1, 1); b.Append("]}"); return b.ToString(); } private static void AppendBoolQ(StringBuilder b, string bold, bool? boo) { if (boo.HasValue) b.AppendFormat("{0}:\"{1}\",", bold, boo.Value ? "true" : "false"); } [field: NonSerialized] public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void PropChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
// Copyright (c) .NET Foundation. 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; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Hosting.Internal { internal static class HostingLoggerExtensions { private static readonly double TimestampToTicks = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency; public static IDisposable RequestScope(this ILogger logger, HttpContext httpContext) { return logger.BeginScope(new HostingLogScope(httpContext)); } public static void RequestStarting(this ILogger logger, HttpContext httpContext) { if (logger.IsEnabled(LogLevel.Information)) { logger.Log( logLevel: LogLevel.Information, eventId: LoggerEventIds.RequestStarting, state: new HostingRequestStarting(httpContext), exception: null, formatter: HostingRequestStarting.Callback); } } public static void RequestFinished(this ILogger logger, HttpContext httpContext, long startTimestamp, long currentTimestamp) { // Don't log if Information logging wasn't enabled at start or end of request as time will be wildly wrong. if (startTimestamp != 0) { var elapsed = new TimeSpan((long)(TimestampToTicks * (currentTimestamp - startTimestamp))); logger.Log( logLevel: LogLevel.Information, eventId: LoggerEventIds.RequestFinished, state: new HostingRequestFinished(httpContext, elapsed), exception: null, formatter: HostingRequestFinished.Callback); } } public static void ApplicationError(this ILogger logger, Exception exception) { logger.LogCritical( eventId: LoggerEventIds.ApplicationStartupException, message: "Application startup exception", exception: exception); } public static void Starting(this ILogger logger) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug( eventId: LoggerEventIds.Starting, message: "Hosting starting"); } } public static void Started(this ILogger logger) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug( eventId: LoggerEventIds.Started, message: "Hosting started"); } } public static void Shutdown(this ILogger logger) { if (logger.IsEnabled(LogLevel.Debug)) { logger.LogDebug( eventId: LoggerEventIds.Shutdown, message: "Hosting shutdown"); } } private class HostingLogScope : IReadOnlyList<KeyValuePair<string, object>> { private readonly HttpContext _httpContext; private string _cachedToString; public int Count { get { return 2; } } public KeyValuePair<string, object> this[int index] { get { if (index == 0) { return new KeyValuePair<string, object>("RequestId", _httpContext.TraceIdentifier); } else if (index == 1) { return new KeyValuePair<string, object>("RequestPath", _httpContext.Request.Path.ToString()); } throw new IndexOutOfRangeException(nameof(index)); } } public HostingLogScope(HttpContext httpContext) { _httpContext = httpContext; } public override string ToString() { if (_cachedToString == null) { _cachedToString = string.Format( CultureInfo.InvariantCulture, "RequestId:{0} RequestPath:{1}", _httpContext.TraceIdentifier, _httpContext.Request.Path); } return _cachedToString; } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { for (int i = 0; i < Count; ++i) { yield return this[i]; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private class HostingRequestStarting : IReadOnlyList<KeyValuePair<string, object>> { internal static readonly Func<object, Exception, string> Callback = (state, exception) => ((HostingRequestStarting)state).ToString(); private readonly HttpRequest _request; private string _cachedToString; public int Count { get { return 9; } } public KeyValuePair<string, object> this[int index] { get { switch (index) { case 0: return new KeyValuePair<string, object>("Protocol", _request.Protocol); case 1: return new KeyValuePair<string, object>("Method", _request.Method); case 2: return new KeyValuePair<string, object>("ContentType", _request.ContentType); case 3: return new KeyValuePair<string, object>("ContentLength", _request.ContentLength); case 4: return new KeyValuePair<string, object>("Scheme", _request.Scheme.ToString()); case 5: return new KeyValuePair<string, object>("Host", _request.Host.ToString()); case 6: return new KeyValuePair<string, object>("PathBase", _request.PathBase.ToString()); case 7: return new KeyValuePair<string, object>("Path", _request.Path.ToString()); case 8: return new KeyValuePair<string, object>("QueryString", _request.QueryString.ToString()); default: throw new IndexOutOfRangeException(nameof(index)); } } } public HostingRequestStarting(HttpContext httpContext) { _request = httpContext.Request; } public override string ToString() { if (_cachedToString == null) { _cachedToString = string.Format( CultureInfo.InvariantCulture, "Request starting {0} {1} {2}://{3}{4}{5}{6} {7} {8}", _request.Protocol, _request.Method, _request.Scheme, _request.Host, _request.PathBase, _request.Path, _request.QueryString, _request.ContentType, _request.ContentLength); } return _cachedToString; } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { for (int i = 0; i < Count; ++i) { yield return this[i]; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private class HostingRequestFinished : IReadOnlyList<KeyValuePair<string, object>> { internal static readonly Func<object, Exception, string> Callback = (state, exception) => ((HostingRequestFinished)state).ToString(); private readonly HttpContext _httpContext; private readonly TimeSpan _elapsed; private string _cachedToString; public int Count { get { return 3; } } public KeyValuePair<string, object> this[int index] { get { switch (index) { case 0: return new KeyValuePair<string, object>("ElapsedMilliseconds", _elapsed.TotalMilliseconds); case 1: return new KeyValuePair<string, object>("StatusCode", _httpContext.Response.StatusCode); case 2: return new KeyValuePair<string, object>("ContentType", _httpContext.Response.ContentType); default: throw new IndexOutOfRangeException(nameof(index)); } } } public HostingRequestFinished(HttpContext httpContext, TimeSpan elapsed) { _httpContext = httpContext; _elapsed = elapsed; } public override string ToString() { if (_cachedToString == null) { _cachedToString = string.Format( CultureInfo.InvariantCulture, "Request finished in {0}ms {1} {2}", _elapsed.TotalMilliseconds, _httpContext.Response.StatusCode, _httpContext.Response.ContentType); } return _cachedToString; } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { for (int i = 0; i < Count; ++i) { yield return this[i]; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } }
/* * 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 log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Messages.Linden; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections.Generic; using System.Reflection; using Caps = OpenSim.Framework.Capabilities.Caps; using OSDMap = OpenMetaverse.StructuredData.OSDMap; namespace OpenSim.Region.CoreModules.World.Media.Moap { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MoapModule")] public class MoapModule : INonSharedRegionModule, IMoapModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string Name { get { return "MoapModule"; } } public Type ReplaceableInterface { get { return null; } } /// <summary> /// Is this module enabled? /// </summary> protected bool m_isEnabled = true; /// <summary> /// The scene to which this module is attached /// </summary> protected Scene m_scene; /// <summary> /// Track the ObjectMedia capabilities given to users keyed by path /// </summary> protected ThreadedClasses.RwLockedBiDiMappingDictionary<string, UUID> m_omCap = new ThreadedClasses.RwLockedBiDiMappingDictionary<string, UUID>(); /// <summary> /// Track the ObjectMediaUpdate capabilities given to users keyed by path /// </summary> protected ThreadedClasses.RwLockedBiDiMappingDictionary<string, UUID> m_omuCap = new ThreadedClasses.RwLockedBiDiMappingDictionary<string, UUID>(); public void Initialise(IConfigSource configSource) { IConfig config = configSource.Configs["MediaOnAPrim"]; if (config != null && !config.GetBoolean("Enabled", false)) m_isEnabled = false; // else // m_log.Debug("[MOAP]: Initialised module.")l } public void AddRegion(Scene scene) { if (!m_isEnabled) return; m_scene = scene; m_scene.RegisterModuleInterface<IMoapModule>(this); } public void RemoveRegion(Scene scene) {} public void RegionLoaded(Scene scene) { if (!m_isEnabled) return; m_scene.EventManager.OnRegisterCaps += OnRegisterCaps; m_scene.EventManager.OnDeregisterCaps += OnDeregisterCaps; m_scene.EventManager.OnSceneObjectPartCopy += OnSceneObjectPartCopy; } public void Close() { if (!m_isEnabled) return; m_scene.EventManager.OnRegisterCaps -= OnRegisterCaps; m_scene.EventManager.OnDeregisterCaps -= OnDeregisterCaps; m_scene.EventManager.OnSceneObjectPartCopy -= OnSceneObjectPartCopy; } public void OnRegisterCaps(UUID agentID, Caps caps) { // m_log.DebugFormat( // "[MOAP]: Registering ObjectMedia and ObjectMediaNavigate capabilities for agent {0}", agentID); string omCapUrl = "/CAPS/" + UUID.Random(); m_omCap.Remove(agentID); m_omCap.Remove(omCapUrl); m_omCap.Add(omCapUrl, agentID); // Even though we're registering for POST we're going to get GETS and UPDATES too caps.RegisterHandler( "ObjectMedia", new RestStreamHandler( "POST", omCapUrl, HandleObjectMediaMessage, "ObjectMedia", agentID.ToString())); string omuCapUrl = "/CAPS/" + UUID.Random(); m_omuCap.Remove(agentID); m_omuCap.Remove(omuCapUrl); m_omuCap.Add(omuCapUrl, agentID); // Even though we're registering for POST we're going to get GETS and UPDATES too caps.RegisterHandler( "ObjectMediaNavigate", new RestStreamHandler( "POST", omuCapUrl, HandleObjectMediaNavigateMessage, "ObjectMediaNavigate", agentID.ToString())); } public void OnDeregisterCaps(UUID agentID, Caps caps) { m_omCap.Remove(agentID); m_omuCap.Remove(agentID); } protected void OnSceneObjectPartCopy(SceneObjectPart copy, SceneObjectPart original, bool userExposed) { if (original.Shape.Media != null) { PrimitiveBaseShape.MediaList dupeMedia = new PrimitiveBaseShape.MediaList(); lock (original.Shape.Media) { foreach (MediaEntry me in original.Shape.Media) { if (me != null) dupeMedia.Add(MediaEntry.FromOSD(me.GetOSD())); else dupeMedia.Add(null); } } copy.Shape.Media = dupeMedia; } } public MediaEntry GetMediaEntry(SceneObjectPart part, int face) { MediaEntry me = null; CheckFaceParam(part, face); List<MediaEntry> media = part.Shape.Media; if (null == media) { me = null; } else { lock (media) me = media[face]; // TODO: Really need a proper copy constructor down in libopenmetaverse if (me != null) me = MediaEntry.FromOSD(me.GetOSD()); } // m_log.DebugFormat("[MOAP]: GetMediaEntry for {0} face {1} found {2}", part.Name, face, me); return me; } /// <summary> /// Set the media entry on the face of the given part. /// </summary> /// <param name="part">/param> /// <param name="face"></param> /// <param name="me">If null, then the media entry is cleared.</param> public void SetMediaEntry(SceneObjectPart part, int face, MediaEntry me) { // m_log.DebugFormat("[MOAP]: SetMediaEntry for {0}, face {1}", part.Name, face); CheckFaceParam(part, face); if (null == part.Shape.Media) { if (me == null) return; else part.Shape.Media = new PrimitiveBaseShape.MediaList(new MediaEntry[part.GetNumberOfSides()]); } lock (part.Shape.Media) part.Shape.Media[face] = me; UpdateMediaUrl(part, UUID.Zero); SetPartMediaFlags(part, face, me != null); part.ScheduleFullUpdate(); part.TriggerScriptChangedEvent(Changed.MEDIA); } /// <summary> /// Clear the media entry from the face of the given part. /// </summary> /// <param name="part"></param> /// <param name="face"></param> public void ClearMediaEntry(SceneObjectPart part, int face) { SetMediaEntry(part, face, null); } /// <summary> /// Set the media flags on the texture face of the given part. /// </summary> /// <remarks> /// The fact that we need a separate function to do what should be a simple one line operation is BUTT UGLY. /// </remarks> /// <param name="part"></param> /// <param name="face"></param> /// <param name="flag"></param> protected void SetPartMediaFlags(SceneObjectPart part, int face, bool flag) { Primitive.TextureEntry te = part.Shape.Textures; Primitive.TextureEntryFace teFace = te.CreateFace((uint)face); teFace.MediaFlags = flag; part.Shape.Textures = te; } /// <summary> /// Sets or gets per face media textures. /// </summary> /// <param name="request"></param> /// <param name="path"></param> /// <param name="param"></param> /// <param name="httpRequest"></param> /// <param name="httpResponse"></param> /// <returns></returns> protected string HandleObjectMediaMessage( string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[MOAP]: Got ObjectMedia path [{0}], raw request [{1}]", path, request); OSDMap osd = (OSDMap)OSDParser.DeserializeLLSDXml(request); ObjectMediaMessage omm = new ObjectMediaMessage(); omm.Deserialize(osd); if (omm.Request is ObjectMediaRequest) return HandleObjectMediaRequest(omm.Request as ObjectMediaRequest); else if (omm.Request is ObjectMediaUpdate) return HandleObjectMediaUpdate(path, omm.Request as ObjectMediaUpdate); throw new Exception( string.Format( "[MOAP]: ObjectMediaMessage has unrecognized ObjectMediaBlock of {0}", omm.Request.GetType())); } /// <summary> /// Handle a fetch request for media textures /// </summary> /// <param name="omr"></param> /// <returns></returns> protected string HandleObjectMediaRequest(ObjectMediaRequest omr) { UUID primId = omr.PrimID; SceneObjectPart part = m_scene.GetSceneObjectPart(primId); if (null == part) { m_log.WarnFormat( "[MOAP]: Received a GET ObjectMediaRequest for prim {0} but this doesn't exist in region {1}", primId, m_scene.RegionInfo.RegionName); return string.Empty; } if (null == part.Shape.Media) return string.Empty; ObjectMediaResponse resp = new ObjectMediaResponse(); resp.PrimID = primId; lock (part.Shape.Media) resp.FaceMedia = part.Shape.Media.ToArray(); resp.Version = part.MediaUrl; string rawResp = OSDParser.SerializeLLSDXmlString(resp.Serialize()); // m_log.DebugFormat("[MOAP]: Got HandleObjectMediaRequestGet raw response is [{0}]", rawResp); return rawResp; } /// <summary> /// Handle an update of media textures. /// </summary> /// <param name="path">Path on which this request was made</param> /// <param name="omu">/param> /// <returns></returns> protected string HandleObjectMediaUpdate(string path, ObjectMediaUpdate omu) { UUID primId = omu.PrimID; SceneObjectPart part = m_scene.GetSceneObjectPart(primId); if (null == part) { m_log.WarnFormat( "[MOAP]: Received an UPDATE ObjectMediaRequest for prim {0} but this doesn't exist in region {1}", primId, m_scene.RegionInfo.RegionName); return string.Empty; } // m_log.DebugFormat("[MOAP]: Received {0} media entries for prim {1}", omu.FaceMedia.Length, primId); // // for (int i = 0; i < omu.FaceMedia.Length; i++) // { // MediaEntry me = omu.FaceMedia[i]; // string v = (null == me ? "null": OSDParser.SerializeLLSDXmlString(me.GetOSD())); // m_log.DebugFormat("[MOAP]: Face {0} [{1}]", i, v); // } if (omu.FaceMedia.Length > part.GetNumberOfSides()) { m_log.WarnFormat( "[MOAP]: Received {0} media entries from client for prim {1} {2} but this prim has only {3} faces. Dropping request.", omu.FaceMedia.Length, part.Name, part.UUID, part.GetNumberOfSides()); return string.Empty; } UUID agentId = default(UUID); agentId = m_omCap[path]; List<MediaEntry> media = part.Shape.Media; if (null == media) { // m_log.DebugFormat("[MOAP]: Setting all new media list for {0}", part.Name); part.Shape.Media = new PrimitiveBaseShape.MediaList(omu.FaceMedia); for (int i = 0; i < omu.FaceMedia.Length; i++) { if (omu.FaceMedia[i] != null) { // FIXME: Race condition here since some other texture entry manipulator may overwrite/get // overwritten. Unfortunately, PrimitiveBaseShape does not allow us to change texture entry // directly. SetPartMediaFlags(part, i, true); // m_log.DebugFormat( // "[MOAP]: Media flags for face {0} is {1}", // i, part.Shape.Textures.FaceTextures[i].MediaFlags); } } } else { // m_log.DebugFormat("[MOAP]: Setting existing media list for {0}", part.Name); // We need to go through the media textures one at a time to make sure that we have permission // to change them // FIXME: Race condition here since some other texture entry manipulator may overwrite/get // overwritten. Unfortunately, PrimitiveBaseShape does not allow us to change texture entry // directly. Primitive.TextureEntry te = part.Shape.Textures; lock (media) { for (int i = 0; i < media.Count; i++) { if (m_scene.Permissions.CanControlPrimMedia(agentId, part.UUID, i)) { media[i] = omu.FaceMedia[i]; // When a face is cleared this is done by setting the MediaFlags in the TextureEntry via a normal // texture update, so we don't need to worry about clearing MediaFlags here. if (null == media[i]) continue; SetPartMediaFlags(part, i, true); // m_log.DebugFormat( // "[MOAP]: Media flags for face {0} is {1}", // i, face.MediaFlags); // m_log.DebugFormat("[MOAP]: Set media entry for face {0} on {1}", i, part.Name); } } } part.Shape.Textures = te; // for (int i2 = 0; i2 < part.Shape.Textures.FaceTextures.Length; i2++) // m_log.DebugFormat("[MOAP]: FaceTexture[{0}] is {1}", i2, part.Shape.Textures.FaceTextures[i2]); } UpdateMediaUrl(part, agentId); // Arguably, we could avoid sending a full update to the avatar that just changed the texture. part.ScheduleFullUpdate(); part.TriggerScriptChangedEvent(Changed.MEDIA); return string.Empty; } /// <summary> /// Received from the viewer if a user has changed the url of a media texture. /// </summary> /// <param name="request"></param> /// <param name="path"></param> /// <param name="param"></param> /// <param name="httpRequest">/param> /// <param name="httpResponse">/param> /// <returns></returns> protected string HandleObjectMediaNavigateMessage( string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // m_log.DebugFormat("[MOAP]: Got ObjectMediaNavigate request [{0}]", request); OSDMap osd = (OSDMap)OSDParser.DeserializeLLSDXml(request); ObjectMediaNavigateMessage omn = new ObjectMediaNavigateMessage(); omn.Deserialize(osd); UUID primId = omn.PrimID; SceneObjectPart part = m_scene.GetSceneObjectPart(primId); if (null == part) { m_log.WarnFormat( "[MOAP]: Received an ObjectMediaNavigateMessage for prim {0} but this doesn't exist in region {1}", primId, m_scene.RegionInfo.RegionName); return string.Empty; } UUID agentId = default(UUID); agentId = m_omuCap[path]; if (!m_scene.Permissions.CanInteractWithPrimMedia(agentId, part.UUID, omn.Face)) return string.Empty; // m_log.DebugFormat( // "[MOAP]: Received request to update media entry for face {0} on prim {1} {2} to {3}", // omn.Face, part.Name, part.UUID, omn.URL); // If media has never been set for this prim, then just return. if (null == part.Shape.Media) return string.Empty; MediaEntry me = null; lock (part.Shape.Media) me = part.Shape.Media[omn.Face]; // Do the same if media has not been set up for a specific face if (null == me) return string.Empty; if (me.EnableWhiteList) { if (!CheckUrlAgainstWhitelist(omn.URL, me.WhiteList)) { // m_log.DebugFormat( // "[MOAP]: Blocking change of face {0} on prim {1} {2} to {3} since it's not on the enabled whitelist", // omn.Face, part.Name, part.UUID, omn.URL); return string.Empty; } } me.CurrentURL = omn.URL; UpdateMediaUrl(part, agentId); part.ScheduleFullUpdate(); part.TriggerScriptChangedEvent(Changed.MEDIA); return OSDParser.SerializeLLSDXmlString(new OSD()); } /// <summary> /// Check that the face number is valid for the given prim. /// </summary> /// <param name="part"></param> /// <param name="face"></param> protected void CheckFaceParam(SceneObjectPart part, int face) { if (face < 0) throw new ArgumentException("Face cannot be less than zero"); int maxFaces = part.GetNumberOfSides() - 1; if (face > maxFaces) throw new ArgumentException( string.Format("Face argument was {0} but max is {1}", face, maxFaces)); } /// <summary> /// Update the media url of the given part /// </summary> /// <param name="part"></param> /// <param name="updateId"> /// The id to attach to this update. Normally, this is the user that changed the /// texture /// </param> protected void UpdateMediaUrl(SceneObjectPart part, UUID updateId) { if (null == part.MediaUrl) { // TODO: We can't set the last changer until we start tracking which cap we give to which agent id part.MediaUrl = "x-mv:0000000000/" + updateId; } else { string rawVersion = part.MediaUrl.Substring(5, 10); int version = int.Parse(rawVersion); part.MediaUrl = string.Format("x-mv:{0:D10}/{1}", ++version, updateId); } // m_log.DebugFormat("[MOAP]: Storing media url [{0}] in prim {1} {2}", part.MediaUrl, part.Name, part.UUID); } /// <summary> /// Check the given url against the given whitelist. /// </summary> /// <param name="rawUrl"></param> /// <param name="whitelist"></param> /// <returns>true if the url matches an entry on the whitelist, false otherwise</returns> protected bool CheckUrlAgainstWhitelist(string rawUrl, string[] whitelist) { Uri url = new Uri(rawUrl); foreach (string origWlUrl in whitelist) { string wlUrl = origWlUrl; // Deal with a line-ending wildcard if (wlUrl.EndsWith("*")) wlUrl = wlUrl.Remove(wlUrl.Length - 1); // m_log.DebugFormat("[MOAP]: Checking whitelist URL pattern {0}", origWlUrl); // Handle a line starting wildcard slightly differently since this can only match the domain, not the path if (wlUrl.StartsWith("*")) { wlUrl = wlUrl.Substring(1); if (url.Host.Contains(wlUrl)) { // m_log.DebugFormat("[MOAP]: Whitelist URL {0} matches {1}", origWlUrl, rawUrl); return true; } } else { string urlToMatch = url.Authority + url.AbsolutePath; if (urlToMatch.StartsWith(wlUrl)) { // m_log.DebugFormat("[MOAP]: Whitelist URL {0} matches {1}", origWlUrl, rawUrl); return true; } } } return false; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking { internal sealed partial class RenameTrackingTaggerProvider { /// <summary> /// Keeps track of the rename tracking state for a given text buffer by tracking its /// changes over time. /// </summary> private class StateMachine : ForegroundThreadAffinitizedObject { private readonly IInlineRenameService _inlineRenameService; private readonly IAsynchronousOperationListener _asyncListener; private readonly ITextBuffer _buffer; private int _refCount; public TrackingSession TrackingSession { get; private set; } public ITextBuffer Buffer { get { return _buffer; } } public event Action TrackingSessionUpdated = delegate { }; public event Action<ITrackingSpan> TrackingSessionCleared = delegate { }; public StateMachine(ITextBuffer buffer, IInlineRenameService inlineRenameService, IAsynchronousOperationListener asyncListener) { _buffer = buffer; _buffer.Changed += Buffer_Changed; _inlineRenameService = inlineRenameService; _asyncListener = asyncListener; } private void Buffer_Changed(object sender, TextContentChangedEventArgs e) { AssertIsForeground(); if (!_buffer.GetOption(InternalFeatureOnOffOptions.RenameTracking)) { // When disabled, ignore all text buffer changes and do not trigger retagging return; } using (Logger.LogBlock(FunctionId.Rename_Tracking_BufferChanged, CancellationToken.None)) { // When the buffer changes, several things might be happening: // 1. If a non-identifer character has been added or deleted, we stop tracking // completely. // 2. Otherwise, if the changes are completely contained an existing session, then // continue that session. // 3. Otherwise, we're starting a new tracking session. Find and track the span of // the relevant word in the foreground, and use a task to figure out whether the // original word was a renamable identifier or not. if (e.Changes.Count != 1 || ShouldClearTrackingSession(e.Changes.Single())) { ClearTrackingSession(); return; } // The change is trackable. Figure out whether we should continue an existing // session var change = e.Changes.Single(); if (this.TrackingSession == null) { StartTrackingSession(e); return; } // There's an existing session. Continue that session if the current change is // contained inside the tracking span. SnapshotSpan trackingSpanInNewSnapshot = this.TrackingSession.TrackingSpan.GetSpan(e.After); if (trackingSpanInNewSnapshot.Contains(change.NewSpan)) { // Continuing an existing tracking session. If there may have been a tag // showing, then update the tags. if (this.TrackingSession.IsDefinitelyRenamableIdentifier()) { this.TrackingSession.CheckNewIdentifier(this, _buffer.CurrentSnapshot); TrackingSessionUpdated(); } } else { StartTrackingSession(e); } } } private bool ShouldClearTrackingSession(ITextChange change) { AssertIsForeground(); ISyntaxFactsService syntaxFactsService; if (!TryGetSyntaxFactsService(out syntaxFactsService)) { return true; } // The editor will replace virtual space with spaces and/or tabs when typing on a // previously blank line. Trim these characters from the start of change.NewText. If // the resulting change is empty (the user just typed a <space>), clear the session. var changedText = change.OldText + change.NewText.TrimStart(' ', '\t'); if (changedText.IsEmpty()) { return true; } return changedText.Any(c => !IsTrackableCharacter(syntaxFactsService, c)); } private void StartTrackingSession(TextContentChangedEventArgs eventArgs) { AssertIsForeground(); ClearTrackingSession(); if (_inlineRenameService.ActiveSession != null) { return; } // Synchronously find the tracking span in the old document. var change = eventArgs.Changes.Single(); var beforeText = eventArgs.Before.AsText(); ISyntaxFactsService syntaxFactsService; if (!TryGetSyntaxFactsService(out syntaxFactsService)) { return; } int leftSidePosition = change.OldPosition; int rightSidePosition = change.OldPosition + change.OldText.Length; while (leftSidePosition > 0 && IsTrackableCharacter(syntaxFactsService, beforeText[leftSidePosition - 1])) { leftSidePosition--; } while (rightSidePosition < beforeText.Length && IsTrackableCharacter(syntaxFactsService, beforeText[rightSidePosition])) { rightSidePosition++; } var originalSpan = new Span(leftSidePosition, rightSidePosition - leftSidePosition); this.TrackingSession = new TrackingSession(this, new SnapshotSpan(eventArgs.Before, originalSpan), _asyncListener); } private bool IsTrackableCharacter(ISyntaxFactsService syntaxFactsService, char c) { // Allow identifier part characters at the beginning of strings (even if they are // not identifier start characters). If an intermediate name is not valid, the smart // tag will not be shown due to later checks. Also allow escape chars anywhere as // they might be in the middle of a complex edit. return syntaxFactsService.IsIdentifierPartCharacter(c) || syntaxFactsService.IsIdentifierEscapeCharacter(c); } public bool ClearTrackingSession() { AssertIsForeground(); if (this.TrackingSession != null) { // Disallow the existing TrackingSession from triggering IdentifierFound. var previousTrackingSession = this.TrackingSession; this.TrackingSession = null; previousTrackingSession.Cancel(); // If there may have been a tag showing, then actually clear the tags. if (previousTrackingSession.IsDefinitelyRenamableIdentifier()) { TrackingSessionCleared(previousTrackingSession.TrackingSpan); } return true; } return false; } public bool ClearVisibleTrackingSession() { AssertIsForeground(); if (this.TrackingSession != null && this.TrackingSession.IsDefinitelyRenamableIdentifier()) { // Disallow the existing TrackingSession from triggering IdentifierFound. var previousTrackingSession = this.TrackingSession; this.TrackingSession = null; previousTrackingSession.Cancel(); TrackingSessionCleared(previousTrackingSession.TrackingSpan); return true; } return false; } public bool CanInvokeRename(out TrackingSession trackingSession, bool isSmartTagCheck = false, bool waitForResult = false, CancellationToken cancellationToken = default(CancellationToken)) { // This needs to be able to run on a background thread for the diagnostic. trackingSession = this.TrackingSession; if (trackingSession == null) { return false; } ISyntaxFactsService syntaxFactsService; return TryGetSyntaxFactsService(out syntaxFactsService) && trackingSession.CanInvokeRename(syntaxFactsService, isSmartTagCheck, waitForResult, cancellationToken); } internal async Task<IEnumerable<Diagnostic>> GetDiagnostic(SyntaxTree tree, DiagnosticDescriptor diagnosticDescriptor, CancellationToken cancellationToken) { try { // This can be called on a background thread. We are being asked whether a // lightbulb should be shown for the given document, but we only know about the // current state of the buffer. Compare the text to see if we should bail early. // Even if the text is the same, the buffer may change on the UI thread during this // method. If it does, we may give an incorrect response, but the diagnostics // engine will know that the document changed and not display the lightbulb anyway. if (Buffer.AsTextContainer().CurrentText != await tree.GetTextAsync(cancellationToken).ConfigureAwait(false)) { return SpecializedCollections.EmptyEnumerable<Diagnostic>(); } TrackingSession trackingSession; if (CanInvokeRename(out trackingSession, waitForResult: true, cancellationToken: cancellationToken)) { SnapshotSpan snapshotSpan = trackingSession.TrackingSpan.GetSpan(Buffer.CurrentSnapshot); var textSpan = snapshotSpan.Span.ToTextSpan(); var diagnostic = Diagnostic.Create(diagnosticDescriptor, tree.GetLocation(textSpan), trackingSession.OriginalName, snapshotSpan.GetText()); return SpecializedCollections.SingletonEnumerable(diagnostic); } return SpecializedCollections.EmptyEnumerable<Diagnostic>(); } catch (Exception e) when(FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } public void RestoreTrackingSession(TrackingSession trackingSession) { AssertIsForeground(); ClearTrackingSession(); this.TrackingSession = trackingSession; TrackingSessionUpdated(); } public void OnTrackingSessionUpdated(TrackingSession trackingSession) { AssertIsForeground(); if (this.TrackingSession == trackingSession) { TrackingSessionUpdated(); } } private bool TryGetSyntaxFactsService(out ISyntaxFactsService syntaxFactsService) { // Can be called on a background thread syntaxFactsService = null; var document = _buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { syntaxFactsService = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); } return syntaxFactsService != null; } public void Connect() { AssertIsForeground(); _refCount++; } public void Disconnect() { AssertIsForeground(); _refCount--; Contract.ThrowIfFalse(_refCount >= 0); if (_refCount == 0) { this.Buffer.Properties.RemoveProperty(typeof(StateMachine)); this.Buffer.Changed -= Buffer_Changed; } } } } }
// // OpCode.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2010 Jb Evain // // 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 ScriptSharp.Importer.IL.Cil { internal /* public */ enum FlowControl { Branch, Break, Call, Cond_Branch, Meta, Next, Phi, Return, Throw, } internal /* public */ enum OpCodeType { Annotation, Macro, Nternal, Objmodel, Prefix, Primitive, } internal /* public */ enum OperandType { InlineBrTarget, InlineField, InlineI, InlineI8, InlineMethod, InlineNone, InlinePhi, InlineR, InlineSig, InlineString, InlineSwitch, InlineTok, InlineType, InlineVar, InlineArg, ShortInlineBrTarget, ShortInlineI, ShortInlineR, ShortInlineVar, ShortInlineArg, } internal /* public */ enum StackBehaviour { Pop0, Pop1, Pop1_pop1, Popi, Popi_pop1, Popi_popi, Popi_popi8, Popi_popi_popi, Popi_popr4, Popi_popr8, Popref, Popref_pop1, Popref_popi, Popref_popi_popi, Popref_popi_popi8, Popref_popi_popr4, Popref_popi_popr8, Popref_popi_popref, PopAll, Push0, Push1, Push1_push1, Pushi, Pushi8, Pushr4, Pushr8, Pushref, Varpop, Varpush, } internal /* public */ struct OpCode { readonly byte op1; readonly byte op2; readonly byte code; readonly byte flow_control; readonly byte opcode_type; readonly byte operand_type; readonly byte stack_behavior_pop; readonly byte stack_behavior_push; public string Name { get { return OpCodeNames.names [op1 == 0xff ? op2 : op2 + 256]; } } public int Size { get { return op1 == 0xff ? 1 : 2; } } public byte Op1 { get { return op1; } } public byte Op2 { get { return op2; } } public short Value { get { return (short) ((op1 << 8) | op2); } } public Code Code { get { return (Code) code; } } public FlowControl FlowControl { get { return (FlowControl) flow_control; } } public OpCodeType OpCodeType { get { return (OpCodeType) opcode_type; } } public OperandType OperandType { get { return (OperandType) operand_type; } } public StackBehaviour StackBehaviourPop { get { return (StackBehaviour) stack_behavior_pop; } } public StackBehaviour StackBehaviourPush { get { return (StackBehaviour) stack_behavior_push; } } internal OpCode (int x, int y) { this.op1 = (byte) ((x >> 0) & 0xff); this.op2 = (byte) ((x >> 8) & 0xff); this.code = (byte) ((x >> 16) & 0xff); this.flow_control = (byte) ((x >> 24) & 0xff); this.opcode_type = (byte) ((y >> 0) & 0xff); this.operand_type = (byte) ((y >> 8) & 0xff); this.stack_behavior_pop = (byte) ((y >> 16) & 0xff); this.stack_behavior_push = (byte) ((y >> 24) & 0xff); if (op1 == 0xff) OpCodes.OneByteOpCode [op2] = this; else OpCodes.TwoBytesOpCode [op2] = this; } public override int GetHashCode () { return Value; } public override bool Equals (object obj) { if (!(obj is OpCode)) return false; var opcode = (OpCode) obj; return op1 == opcode.op1 && op2 == opcode.op2; } public bool Equals (OpCode opcode) { return op1 == opcode.op1 && op2 == opcode.op2; } public static bool operator == (OpCode one, OpCode other) { return one.op1 == other.op1 && one.op2 == other.op2; } public static bool operator != (OpCode one, OpCode other) { return one.op1 != other.op1 || one.op2 != other.op2; } public override string ToString () { return Name; } } static class OpCodeNames { internal static readonly string [] names = { "nop", "break", "ldarg.0", "ldarg.1", "ldarg.2", "ldarg.3", "ldloc.0", "ldloc.1", "ldloc.2", "ldloc.3", "stloc.0", "stloc.1", "stloc.2", "stloc.3", "ldarg.s", "ldarga.s", "starg.s", "ldloc.s", "ldloca.s", "stloc.s", "ldnull", "ldc.i4.m1", "ldc.i4.0", "ldc.i4.1", "ldc.i4.2", "ldc.i4.3", "ldc.i4.4", "ldc.i4.5", "ldc.i4.6", "ldc.i4.7", "ldc.i4.8", "ldc.i4.s", "ldc.i4", "ldc.i8", "ldc.r4", "ldc.r8", null, "dup", "pop", "jmp", "call", "calli", "ret", "br.s", "brfalse.s", "brtrue.s", "beq.s", "bge.s", "bgt.s", "ble.s", "blt.s", "bne.un.s", "bge.un.s", "bgt.un.s", "ble.un.s", "blt.un.s", "br", "brfalse", "brtrue", "beq", "bge", "bgt", "ble", "blt", "bne.un", "bge.un", "bgt.un", "ble.un", "blt.un", "switch", "ldind.i1", "ldind.u1", "ldind.i2", "ldind.u2", "ldind.i4", "ldind.u4", "ldind.i8", "ldind.i", "ldind.r4", "ldind.r8", "ldind.ref", "stind.ref", "stind.i1", "stind.i2", "stind.i4", "stind.i8", "stind.r4", "stind.r8", "add", "sub", "mul", "div", "div.un", "rem", "rem.un", "and", "or", "xor", "shl", "shr", "shr.un", "neg", "not", "conv.i1", "conv.i2", "conv.i4", "conv.i8", "conv.r4", "conv.r8", "conv.u4", "conv.u8", "callvirt", "cpobj", "ldobj", "ldstr", "newobj", "castclass", "isinst", "conv.r.un", null, null, "unbox", "throw", "ldfld", "ldflda", "stfld", "ldsfld", "ldsflda", "stsfld", "stobj", "conv.ovf.i1.un", "conv.ovf.i2.un", "conv.ovf.i4.un", "conv.ovf.i8.un", "conv.ovf.u1.un", "conv.ovf.u2.un", "conv.ovf.u4.un", "conv.ovf.u8.un", "conv.ovf.i.un", "conv.ovf.u.un", "box", "newarr", "ldlen", "ldelema", "ldelem.i1", "ldelem.u1", "ldelem.i2", "ldelem.u2", "ldelem.i4", "ldelem.u4", "ldelem.i8", "ldelem.i", "ldelem.r4", "ldelem.r8", "ldelem.ref", "stelem.i", "stelem.i1", "stelem.i2", "stelem.i4", "stelem.i8", "stelem.r4", "stelem.r8", "stelem.ref", "ldelem.any", "stelem.any", "unbox.any", null, null, null, null, null, null, null, null, null, null, null, null, null, "conv.ovf.i1", "conv.ovf.u1", "conv.ovf.i2", "conv.ovf.u2", "conv.ovf.i4", "conv.ovf.u4", "conv.ovf.i8", "conv.ovf.u8", null, null, null, null, null, null, null, "refanyval", "ckfinite", null, null, "mkrefany", null, null, null, null, null, null, null, null, null, "ldtoken", "conv.u2", "conv.u1", "conv.i", "conv.ovf.i", "conv.ovf.u", "add.ovf", "add.ovf.un", "mul.ovf", "mul.ovf.un", "sub.ovf", "sub.ovf.un", "endfinally", "leave", "leave.s", "stind.i", "conv.u", null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, "prefix7", "prefix6", "prefix5", "prefix4", "prefix3", "prefix2", "prefix1", "prefixref", "arglist", "ceq", "cgt", "cgt.un", "clt", "clt.un", "ldftn", "ldvirtftn", null, "ldarg", "ldarga", "starg", "ldloc", "ldloca", "stloc", "localloc", null, "endfilter", "unaligned.", "volatile.", "tail.", "initobj", "constrained.", "cpblk", "initblk", "no.", // added by spouliot to match Cecil existing definitions "rethrow", null, "sizeof", "refanytype", "readonly.", // added by spouliot to match Cecil existing definitions null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, }; } }
using System; using System.Collections; using NUnit.Framework; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.CryptoPro; using Org.BouncyCastle.Asn1.Nist; using Org.BouncyCastle.Asn1.Sec; using Org.BouncyCastle.Asn1.TeleTrust; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Pkcs; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities.Test; using Org.BouncyCastle.X509; namespace Org.BouncyCastle.Tests { [TestFixture] public class NamedCurveTest : SimpleTest { // private static readonly Hashtable CurveNames = new Hashtable(); // private static readonly Hashtable CurveAliases = new Hashtable(); // // static NamedCurveTest() // { // CurveNames.Add("prime192v1", "prime192v1"); // X9.62 // CurveNames.Add("sect571r1", "sect571r1"); // sec // CurveNames.Add("secp224r1", "secp224r1"); // CurveNames.Add("B-409", SecNamedCurves.GetName(NistNamedCurves.GetOid("B-409"))); // nist // CurveNames.Add("P-521", SecNamedCurves.GetName(NistNamedCurves.GetOid("P-521"))); // CurveNames.Add("brainpoolp160r1", "brainpoolp160r1"); // TeleTrusT // // CurveAliases.Add("secp192r1", "prime192v1"); // CurveAliases.Add("secp256r1", "prime256v1"); // } private static ECDomainParameters GetCurveParameters( string name) { ECDomainParameters ecdp = ECGost3410NamedCurves.GetByName(name); if (ecdp != null) return ecdp; X9ECParameters ecP = X962NamedCurves.GetByName(name); if (ecP == null) { ecP = SecNamedCurves.GetByName(name); if (ecP == null) { ecP = NistNamedCurves.GetByName(name); if (ecP == null) { ecP = TeleTrusTNamedCurves.GetByName(name); if (ecP == null) throw new Exception("unknown curve name: " + name); } } } return new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed()); } public void doTestCurve( string name) { // ECGenParameterSpec ecSpec = new ECGenParameterSpec(name); ECDomainParameters ecSpec = GetCurveParameters(name); IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDH"); // g.initialize(ecSpec, new SecureRandom()); g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); // // a side // IAsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair(); // KeyAgreement aKeyAgree = KeyAgreement.getInstance("ECDHC"); IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement("ECDHC"); aKeyAgree.Init(aKeyPair.Private); // // b side // IAsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair(); // KeyAgreement bKeyAgree = KeyAgreement.getInstance("ECDHC"); IBasicAgreement bKeyAgree = AgreementUtilities.GetBasicAgreement("ECDHC"); bKeyAgree.Init(bKeyPair.Private); // // agreement // // aKeyAgree.doPhase(bKeyPair.Public, true); // bKeyAgree.doPhase(aKeyPair.Public, true); // // IBigInteger k1 = new BigInteger(aKeyAgree.generateSecret()); // IBigInteger k2 = new BigInteger(bKeyAgree.generateSecret()); IBigInteger k1 = aKeyAgree.CalculateAgreement(bKeyPair.Public); IBigInteger k2 = bKeyAgree.CalculateAgreement(aKeyPair.Public); if (!k1.Equals(k2)) { Fail("2-way test failed"); } // // public key encoding test // // byte[] pubEnc = aKeyPair.Public.getEncoded(); byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded(); // KeyFactory keyFac = KeyFactory.getInstance("ECDH"); // X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc); // ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509); ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.CreateKey(pubEnc); // if (!pubKey.getW().Equals(((ECPublicKey)aKeyPair.Public).getW())) if (!pubKey.Q.Equals(((ECPublicKeyParameters)aKeyPair.Public).Q)) { Fail("public key encoding (Q test) failed"); } // TODO Put back in? // if (!(pubKey.getParams() is ECNamedCurveSpec)) // { // Fail("public key encoding not named curve"); // } // // private key encoding test // // byte[] privEnc = aKeyPair.Private.getEncoded(); byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded(); // PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc); // ECPrivateKey privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8); ECPrivateKeyParameters privKey = (ECPrivateKeyParameters) PrivateKeyFactory.CreateKey(privEnc); // if (!privKey.getS().Equals(((ECPrivateKey)aKeyPair.Private).getS())) if (!privKey.D.Equals(((ECPrivateKeyParameters)aKeyPair.Private).D)) { Fail("private key encoding (S test) failed"); } // TODO Put back in? // if (!(privKey.getParams() is ECNamedCurveSpec)) // { // Fail("private key encoding not named curve"); // } // // ECNamedCurveSpec privSpec = (ECNamedCurveSpec)privKey.getParams(); // if (!(privSpec.GetName().Equals(name) || privSpec.GetName().Equals(CurveNames.get(name)))) // { // Fail("private key encoding wrong named curve. Expected: " // + CurveNames[name] + " got " + privSpec.GetName()); // } } public void doTestECDsa( string name) { // ECGenParameterSpec ecSpec = new ECGenParameterSpec(name); ECDomainParameters ecSpec = GetCurveParameters(name); IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECDSA"); // g.initialize(ecSpec, new SecureRandom()); g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); ISigner sgr = SignerUtilities.GetSigner("ECDSA"); IAsymmetricCipherKeyPair pair = g.GenerateKeyPair(); IAsymmetricKeyParameter sKey = pair.Private; IAsymmetricKeyParameter vKey = pair.Public; sgr.Init(true, sKey); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.BlockUpdate(message, 0, message.Length); byte[] sigBytes = sgr.GenerateSignature(); sgr.Init(false, vKey); sgr.BlockUpdate(message, 0, message.Length); if (!sgr.VerifySignature(sigBytes)) { Fail(name + " verification failed"); } // // public key encoding test // // byte[] pubEnc = vKey.getEncoded(); byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(vKey).GetDerEncoded(); // KeyFactory keyFac = KeyFactory.getInstance("ECDH"); // X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc); // ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509); ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.CreateKey(pubEnc); // if (!pubKey.getW().Equals(((ECPublicKey)vKey).getW())) if (!pubKey.Q.Equals(((ECPublicKeyParameters)vKey).Q)) { Fail("public key encoding (Q test) failed"); } // TODO Put back in? // if (!(pubKey.Parameters is ECNamedCurveSpec)) // { // Fail("public key encoding not named curve"); // } // // private key encoding test // // byte[] privEnc = sKey.getEncoded(); byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(sKey).GetDerEncoded(); // PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc); // ECPrivateKey privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8); ECPrivateKeyParameters privKey = (ECPrivateKeyParameters) PrivateKeyFactory.CreateKey(privEnc); // if (!privKey.getS().Equals(((ECPrivateKey)sKey).getS())) if (!privKey.D.Equals(((ECPrivateKeyParameters)sKey).D)) { Fail("private key encoding (D test) failed"); } // TODO Put back in? // if (!(privKey.Parameters is ECNamedCurveSpec)) // { // Fail("private key encoding not named curve"); // } // // ECNamedCurveSpec privSpec = (ECNamedCurveSpec)privKey.getParams(); // if (!privSpec.GetName().EqualsIgnoreCase(name) // && !privSpec.GetName().EqualsIgnoreCase((string) CurveAliases[name])) // { // Fail("private key encoding wrong named curve. Expected: " + name + " got " + privSpec.GetName()); // } } public void doTestECGost( string name) { // ECGenParameterSpec ecSpec = new ECGenParameterSpec(name); ECDomainParameters ecSpec = GetCurveParameters(name); IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410"); // g.initialize(ecSpec, new SecureRandom()); g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom())); ISigner sgr = SignerUtilities.GetSigner("ECGOST3410"); IAsymmetricCipherKeyPair pair = g.GenerateKeyPair(); IAsymmetricKeyParameter sKey = pair.Private; IAsymmetricKeyParameter vKey = pair.Public; sgr.Init(true, sKey); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.BlockUpdate(message, 0, message.Length); byte[] sigBytes = sgr.GenerateSignature(); sgr.Init(false, vKey); sgr.BlockUpdate(message, 0, message.Length); if (!sgr.VerifySignature(sigBytes)) { Fail(name + " verification failed"); } // TODO Get this working? // // // // public key encoding test // // //// byte[] pubEnc = vKey.getEncoded(); // byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(vKey).GetDerEncoded(); // //// KeyFactory keyFac = KeyFactory.getInstance("ECGOST3410"); //// X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc); //// ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509); // ECPublicKeyParameters pubKey = (ECPublicKeyParameters) PublicKeyFactory.CreateKey(pubEnc); // //// if (!pubKey.getW().equals(((ECPublicKey)vKey).getW())) // if (!pubKey.Q.Equals(((ECPublicKeyParameters)vKey).Q)) // { // Fail("public key encoding (Q test) failed"); // } // TODO Put back in? // if (!(pubKey.Parameters is ECNamedCurveSpec)) // { // Fail("public key encoding not named curve"); // } // TODO Get this working? // // // // private key encoding test // // //// byte[] privEnc = sKey.getEncoded(); // byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(sKey).GetDerEncoded(); // //// PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc); //// ECPrivateKey privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8); // ECPrivateKeyParameters privKey = (ECPrivateKeyParameters) PrivateKeyFactory.CreateKey(privEnc); // //// if (!privKey.getS().Equals(((ECPrivateKey)sKey).getS())) // if (!privKey.D.Equals(((ECPrivateKeyParameters)sKey).D)) // { // Fail("GOST private key encoding (D test) failed"); // } // TODO Put back in? // if (!(privKey.Parameters is ECNamedCurveSpec)) // { // Fail("GOST private key encoding not named curve"); // } // // ECNamedCurveSpec privSpec = (ECNamedCurveSpec)privKey.getParams(); // if (!privSpec.getName().equalsIgnoreCase(name) // && !privSpec.getName().equalsIgnoreCase((String)CURVE_ALIASES[name])) // { // Fail("GOST private key encoding wrong named curve. Expected: " + name + " got " + privSpec.getName()); // } } public override string Name { get { return "NamedCurve"; } } public override void PerformTest() { doTestCurve("prime192v1"); // X9.62 doTestCurve("sect571r1"); // sec doTestCurve("secp224r1"); doTestCurve("B-409"); // nist doTestCurve("P-521"); doTestCurve("brainpoolp160r1"); // TeleTrusT foreach (string name in X962NamedCurves.Names) { doTestECDsa(name); } foreach (string name in SecNamedCurves.Names) { doTestECDsa(name); } foreach (string name in TeleTrusTNamedCurves.Names) { doTestECDsa(name); } foreach (string name in ECGost3410NamedCurves.Names) { doTestECGost(name); } } public static void Main( string[] args) { RunTest(new NamedCurveTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Collections.Tests { public class Hashtable_GetEnumeratorTests { [Fact] public void TestGetEnumeratorBasic() { Hashtable hash1; IDictionaryEnumerator dicEnum1; int ii; string str1; string strRetKey; int iExpValue; Queue que1; Queue que2; //[] 1) Empty Hash table //Get enumerator for an empty table hash1 = new Hashtable(); dicEnum1 = hash1.GetEnumerator(); Assert.Equal(dicEnum1.MoveNext(), false); //[] 2) Full hash table hash1 = new Hashtable(); for (ii = 0; ii < 100; ii++) { str1 = string.Concat("key_", ii.ToString()); hash1.Add(str1, ii); } dicEnum1 = hash1.GetEnumerator(); ii = 0; //Enumerator (well, Hashtable really) does not hold values in the order we put them in!! //so we will use 2 ques to confirm that all the keys and values we put inside the hashtable was there que1 = new Queue(); que2 = new Queue(); while (dicEnum1.MoveNext() != false) { strRetKey = (string)dicEnum1.Key; iExpValue = Convert.ToInt32(dicEnum1.Value); //we make sure that the values are there Assert.True(hash1.ContainsKey(strRetKey)); Assert.True(hash1.ContainsValue(iExpValue)); //we will make sure that enumerator get all the objects que1.Enqueue(strRetKey); que2.Enqueue(iExpValue); } //making sure the que size is right Assert.Equal(100, que1.Count); Assert.Equal(100, que2.Count); // 3) Full hash table, allow remove true hash1 = new Hashtable(); for (ii = 0; ii < 100; ii++) { str1 = string.Concat("key_", ii.ToString()); hash1.Add(str1, ii); } dicEnum1 = hash1.GetEnumerator(); //Enumerator (well, Hashtable really) does not hold values in the order we put them in!! //so we will use 2 ques to confirm that all the keys and values we put inside the hashtable was there que1 = new Queue(); que2 = new Queue(); while (dicEnum1.MoveNext() != false) { strRetKey = (string)dicEnum1.Key; iExpValue = Convert.ToInt32(dicEnum1.Value); //we make sure that the values are there Assert.True(hash1.ContainsKey(strRetKey)); Assert.True(hash1.ContainsValue(iExpValue)); //we will make sure that enumerator get all the objects que1.Enqueue(strRetKey); que2.Enqueue(iExpValue); } //making sure the que size is right Assert.Equal(100, que1.Count); Assert.Equal(100, que2.Count); //[] 3) change hash table externally whilst in the middle of enumerating hash1 = new Hashtable(); for (ii = 0; ii < 100; ii++) { str1 = string.Concat("key_", ii.ToString()); hash1.Add(str1, ii); } dicEnum1 = hash1.GetEnumerator(); //this is the first object. we have a true Assert.True(dicEnum1.MoveNext()); strRetKey = (string)dicEnum1.Key; iExpValue = Convert.ToInt32(dicEnum1.Value); //we make sure that the values are there Assert.True(hash1.ContainsKey(strRetKey)); Assert.True(hash1.ContainsValue(iExpValue)); // we will change the underlying hashtable ii = 87; str1 = string.Concat("key_", ii.ToString()); hash1[str1] = ii; // MoveNext should throw Assert.Throws<InvalidOperationException>(() => { dicEnum1.MoveNext(); } ); // Value should NOT throw object foo = dicEnum1.Value; object foo1 = dicEnum1.Key; // Current should NOT throw object foo2 = dicEnum1.Current; Assert.Throws<InvalidOperationException>(() => { dicEnum1.Reset(); } ); //[] 5) try getting object // a) before moving // b) twice before moving to next // c) after next returns false hash1 = new Hashtable(); for (ii = 0; ii < 100; ii++) { str1 = string.Concat("key_", ii.ToString()); hash1.Add(str1, ii); } dicEnum1 = hash1.GetEnumerator(); // a) before moving Assert.Throws<InvalidOperationException>(() => { strRetKey = (string)dicEnum1.Key; } ); //Entry dicEnum1 = (IDictionaryEnumerator *)hash1.GetEnumerator(); dicEnum1 = hash1.GetEnumerator(); while (dicEnum1.MoveNext() != false) { ;//dicEntr1 = (dicEnum1.Entry); } Assert.Throws<InvalidOperationException>(() => { strRetKey = (string)dicEnum1.Key; } ); //[]We will get a valid enumerator, move to a valid position, then change the underlying HT. Current shouold not throw. //Only calling MoveNext should throw. //create the HT hash1 = new Hashtable(); for (ii = 0; ii < 100; ii++) { str1 = string.Concat("key_", ii.ToString()); hash1.Add(str1, ii); } //get the enumerator and move to a valid location dicEnum1 = hash1.GetEnumerator(); dicEnum1.MoveNext(); dicEnum1.MoveNext(); ii = 87; str1 = string.Concat("key_", ii.ToString()); //if we are currently pointer at the item that we are going to change then move to the next one if (0 == string.Compare((string)dicEnum1.Key, str1)) { dicEnum1.MoveNext(); } //change the underlying HT hash1[str1] = ii + 50; //calling current on the Enumerator should not throw strRetKey = (string)dicEnum1.Key; iExpValue = Convert.ToInt32(dicEnum1.Value); Assert.True(hash1.ContainsKey(strRetKey)); Assert.True(hash1.ContainsValue(iExpValue)); strRetKey = (string)dicEnum1.Entry.Key; iExpValue = Convert.ToInt32(dicEnum1.Entry.Value); Assert.True(hash1.ContainsKey(strRetKey)); Assert.True(hash1.ContainsValue(iExpValue)); strRetKey = (string)(((DictionaryEntry)(dicEnum1.Current)).Key); iExpValue = Convert.ToInt32(((DictionaryEntry)dicEnum1.Current).Value); Assert.True(hash1.ContainsKey(strRetKey)); Assert.True(hash1.ContainsValue(iExpValue)); // calling MoveNExt should throw Assert.Throws<InvalidOperationException>(() => { dicEnum1.MoveNext(); } ); //[] Try calling clone on the enumerator dicEnum1 = hash1.GetEnumerator(); var anotherEnumerator = hash1.GetEnumerator(); Assert.False(object.ReferenceEquals(dicEnum1, anotherEnumerator)); } } }
#region using System; using System.Collections.Generic; using OpenGL; #endregion namespace GameCore.Render.OpenGl4CSharp { public class ObjObject : IDisposable { internal VBO<Vector3> vertices; internal VBO<Vector3> normals; internal VBO<Vector2> uvs; internal VBO<int> triangles; public string Name { get; internal set; } public ObjMaterial Material { get; set; } public ObjObject(Vector3[] vertexData, int[] elementData) { vertices = new VBO<Vector3>(vertexData); triangles = new VBO<int>(elementData, BufferTarget.ElementArrayBuffer); Vector3[] normalData = CalculateNormals(vertexData, elementData); vertices = new VBO<Vector3>(vertexData); normals = new VBO<Vector3>(normalData); triangles = new VBO<int>(elementData, BufferTarget.ElementArrayBuffer); } public ObjObject(List<string> lines, Dictionary<string, ObjMaterial> materials, int vertexOffset, int uvOffset) { // we need at least 1 line to be a valid file if (lines.Count == 0) return; // the first line should contain 'o' if (lines[0][0] != 'o' && lines[0][0] != 'g') return; Name = lines[0].Substring(2); List<Vector3> vertexList = new List<Vector3>(); List<Vector2> uvList = new List<Vector2>(); List<int> triangleList = new List<int>(); List<Vector2> unpackedUvs = new List<Vector2>(); List<int> normalsList = new List<int>(); // now we read the lines for (int i = 1; i < lines.Count; i++) { string[] split = lines[i].Split(' '); switch (split[0]) { case "v": vertexList.Add( new Vector3(double.Parse(split[1]), double.Parse(split[2]), double.Parse(split[3]))*0.025f); break; case "vt": uvList.Add(new Vector2(double.Parse(split[1]), double.Parse(split[2]))); break; case "f": string[] indices = new string[] {split[1], split[2], split[3]}; if (split[1].Contains("/")) { indices[0] = split[1].Substring(0, split[1].IndexOf("/")); indices[1] = split[2].Substring(0, split[2].IndexOf("/")); indices[2] = split[3].Substring(0, split[3].IndexOf("/")); // TODO there was something wrong here. // string[] uvs = new string[3]; string[] tempUvs = new string[3]; tempUvs[0] = split[1].Substring(split[1].IndexOf("/") + 1); tempUvs[1] = split[2].Substring(split[2].IndexOf("/") + 1); tempUvs[2] = split[3].Substring(split[3].IndexOf("/") + 1); int[] triangle = new int[] { int.Parse(indices[0]) - vertexOffset, int.Parse(indices[1]) - vertexOffset, int.Parse(indices[2]) - vertexOffset }; if (unpackedUvs.Count == 0) for (int j = 0; j < vertexList.Count; j++) unpackedUvs.Add(Vector2.Zero); normalsList.Add(triangle[0]); normalsList.Add(triangle[1]); normalsList.Add(triangle[2]); if (unpackedUvs[triangle[0]] == Vector2.Zero) unpackedUvs[triangle[0]] = uvList[int.Parse(tempUvs[0]) - uvOffset]; else { unpackedUvs.Add(uvList[int.Parse(tempUvs[0]) - uvOffset]); vertexList.Add(vertexList[triangle[0]]); triangle[0] = unpackedUvs.Count - 1; } if (unpackedUvs[triangle[1]] == Vector2.Zero) unpackedUvs[triangle[1]] = uvList[int.Parse(tempUvs[1]) - uvOffset]; else { unpackedUvs.Add(uvList[int.Parse(tempUvs[1]) - uvOffset]); vertexList.Add(vertexList[triangle[1]]); triangle[1] = unpackedUvs.Count - 1; } if (unpackedUvs[triangle[2]] == Vector2.Zero) unpackedUvs[triangle[2]] = uvList[int.Parse(tempUvs[2]) - uvOffset]; else { unpackedUvs.Add(uvList[int.Parse(tempUvs[2]) - uvOffset]); vertexList.Add(vertexList[triangle[2]]); triangle[2] = unpackedUvs.Count - 1; } triangleList.Add(triangle[0]); triangleList.Add(triangle[1]); triangleList.Add(triangle[2]); } else { triangleList.Add(int.Parse(indices[0]) - vertexOffset); triangleList.Add(int.Parse(indices[1]) - vertexOffset); triangleList.Add(int.Parse(indices[2]) - vertexOffset); } break; case "usemtl": if (materials.ContainsKey(split[1])) Material = materials[split[1]]; break; } } // calculate the normals (if they didn't exist) Vector3[] vertexData = vertexList.ToArray(); int[] elementData = triangleList.ToArray(); Vector3[] normalData = CalculateNormals(vertexData, elementData); // now convert the lists over to vertex buffer objects to be rendered by OpenGL vertices = new VBO<Vector3>(vertexData); normals = new VBO<Vector3>(normalData); if (unpackedUvs.Count != 0) uvs = new VBO<Vector2>(unpackedUvs.ToArray()); triangles = new VBO<int>(elementData, BufferTarget.ElementArrayBuffer); } public static Vector3[] CalculateNormals(Vector3[] vertexData, int[] elementData) { Vector3 b1, b2, normal; Vector3[] normalData = new Vector3[vertexData.Length]; for (int i = 0; i < elementData.Length/3; i++) { int cornerA = elementData[i*3]; int cornerB = elementData[i*3 + 1]; int cornerC = elementData[i*3 + 2]; b1 = vertexData[cornerB] - vertexData[cornerA]; b2 = vertexData[cornerC] - vertexData[cornerA]; normal = Vector3.Cross(b1, b2).Normalize(); normalData[cornerA] += normal; normalData[cornerB] += normal; normalData[cornerC] += normal; } for (int i = 0; i < normalData.Length; i++) normalData[i] = normalData[i].Normalize(); return normalData; } public void Draw() { if (vertices == null || triangles == null) return; Gl.Disable(EnableCap.CullFace); if (Material != null) Material.Use(); Gl.BindBufferToShaderAttribute(vertices, Material.Program, "vertexPosition"); Gl.BindBufferToShaderAttribute(normals, Material.Program, "vertexNormal"); if (uvs != null) Gl.BindBufferToShaderAttribute(uvs, Material.Program, "vertexUV"); Gl.BindBuffer(triangles); Gl.DrawElements(BeginMode.Triangles, triangles.Count, DrawElementsType.UnsignedInt, IntPtr.Zero); } public void Dispose() { if (vertices != null) vertices.Dispose(); if (normals != null) normals.Dispose(); if (triangles != null) triangles.Dispose(); if (uvs != null) uvs.Dispose(); if (Material != null) Material.Dispose(); } public override string ToString() { string outStr = ""; outStr += Name; return outStr; } } }
using System; using Encoding = System.Text.Encoding; #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: Contains the information needed to generate tracelogging /// metadata for an event field. /// </summary> internal class FieldMetadata { /// <summary> /// Name of the field /// </summary> private readonly string name; /// <summary> /// The number of bytes in the UTF8 Encoding of 'name' INCLUDING a null terminator. /// </summary> private readonly int nameSize; private readonly EventFieldTags tags; private readonly byte[] custom; /// <summary> /// ETW supports fixed sized arrays. If inType has the InTypeFixedCountFlag then this is the /// statically known count for the array. It is also used to encode the number of bytes of /// custom meta-data if InTypeCustomCountFlag set. /// </summary> private readonly ushort fixedCount; private byte inType; private byte outType; /// <summary> /// Scalar or variable-length array. /// </summary> public FieldMetadata( string name, TraceLoggingDataType type, EventFieldTags tags, bool variableCount) : this( name, type, tags, variableCount ? Statics.InTypeVariableCountFlag : (byte)0, 0, null) { return; } /// <summary> /// Fixed-length array. /// </summary> public FieldMetadata( string name, TraceLoggingDataType type, EventFieldTags tags, ushort fixedCount) : this( name, type, tags, Statics.InTypeFixedCountFlag, fixedCount, null) { return; } /// <summary> /// Custom serializer /// </summary> public FieldMetadata( string name, TraceLoggingDataType type, EventFieldTags tags, byte[] custom) : this( name, type, tags, Statics.InTypeCustomCountFlag, checked((ushort)(custom == null ? 0 : custom.Length)), custom) { return; } private FieldMetadata( string name, TraceLoggingDataType dataType, EventFieldTags tags, byte countFlags, ushort fixedCount = 0, byte[] custom = null) { if (name == null) { throw new ArgumentNullException( "name", "This usually means that the object passed to Write is of a type that" + " does not support being used as the top-level object in an event," + " e.g. a primitive or built-in type."); } Statics.CheckName(name); var coreType = (int)dataType & Statics.InTypeMask; this.name = name; this.nameSize = Encoding.UTF8.GetByteCount(this.name) + 1; this.inType = (byte)(coreType | countFlags); this.outType = (byte)(((int)dataType >> 8) & Statics.OutTypeMask); this.tags = tags; this.fixedCount = fixedCount; this.custom = custom; if (countFlags != 0) { if (coreType == (int)TraceLoggingDataType.Nil) { #if PROJECTN throw new NotSupportedException(SR.GetResourceString("EventSource_NotSupportedArrayOfNil", null)); #else throw new NotSupportedException(Environment.GetResourceString("EventSource_NotSupportedArrayOfNil")); #endif } if (coreType == (int)TraceLoggingDataType.Binary) { #if PROJECTN throw new NotSupportedException(SR.GetResourceString("EventSource_NotSupportedArrayOfBinary", null)); #else throw new NotSupportedException(Environment.GetResourceString("EventSource_NotSupportedArrayOfBinary")); #endif } #if !BROKEN_UNTIL_M3 if (coreType == (int)TraceLoggingDataType.Utf16String || coreType == (int)TraceLoggingDataType.MbcsString) { #if PROJECTN throw new NotSupportedException(SR.GetResourceString("EventSource_NotSupportedArrayOfNullTerminatedString", null)); #else throw new NotSupportedException(Environment.GetResourceString("EventSource_NotSupportedArrayOfNullTerminatedString")); #endif } #endif } if (((int)this.tags & 0xfffffff) != 0) { this.outType |= Statics.OutTypeChainFlag; } if (this.outType != 0) { this.inType |= Statics.InTypeChainFlag; } } public void IncrementStructFieldCount() { this.inType |= Statics.InTypeChainFlag; this.outType++; if ((this.outType & Statics.OutTypeMask) == 0) { #if PROJECTN throw new NotSupportedException(SR.GetResourceString("EventSource_TooManyFields", null)); #else throw new NotSupportedException(Environment.GetResourceString("EventSource_TooManyFields")); #endif } } /// <summary> /// This is the main routine for FieldMetaData. Basically it will serialize the data in /// this structure as TraceLogging style meta-data into the array 'metaArray' starting at /// 'pos' (pos is updated to reflect the bytes written). /// /// Note that 'metaData' can be null, in which case it only updates 'pos'. This is useful /// for a 'two pass' approach where you figure out how big to make the array, and then you /// fill it in. /// </summary> public void Encode(ref int pos, byte[] metadata) { // Write out the null terminated UTF8 encoded name if (metadata != null) { Encoding.UTF8.GetBytes(this.name, 0, this.name.Length, metadata, pos); } pos += this.nameSize; // Write 1 byte for inType if (metadata != null) { metadata[pos] = this.inType; } pos += 1; // If InTypeChainFlag set, then write out the outType if (0 != (this.inType & Statics.InTypeChainFlag)) { if (metadata != null) { metadata[pos] = this.outType; } pos += 1; // If OutTypeChainFlag set, then write out tags if (0 != (this.outType & Statics.OutTypeChainFlag)) { Statics.EncodeTags((int)this.tags, ref pos, metadata); } } // If InTypeFixedCountFlag set, write out the fixedCount (2 bytes little endian) if (0 != (this.inType & Statics.InTypeFixedCountFlag)) { if (metadata != null) { metadata[pos + 0] = unchecked((byte)this.fixedCount); metadata[pos + 1] = (byte)(this.fixedCount >> 8); } pos += 2; // If InTypeCustomCountFlag set, write out the blob of custom meta-data. if (Statics.InTypeCustomCountFlag == (this.inType & Statics.InTypeCountMask) && this.fixedCount != 0) { if (metadata != null) { Buffer.BlockCopy(this.custom, 0, metadata, pos, this.fixedCount); } pos += this.fixedCount; } } } } }
/* * MindTouch Deki Wiki - a commercial grade open source wiki * Copyright (C) 2006, 2007 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography.X509Certificates; using Novell.Directory.Ldap; using MindTouch; using MindTouch.Dream; using log4net; using System.Text.RegularExpressions; namespace MindTouch.Deki.Services { public class LdapClient { //--- Fields --- private string _username; private string _password; private ILog _log; private int _timeLimit = 5000; private const int LDAP_PORT = 389; private const int LDAPS_PORT = 636; private LdapAuthenticationService.LdapConfig _config; //--- Constructors --- public LdapClient(LdapAuthenticationService.LdapConfig config, string username, string password, ILog logger) { _config = config; _log = logger; _username = username; _password = password; } //--- Methods --- private LdapConnection GetLdapConnectionFromBindingDN(string server, string bindingdn, string password) { LdapConnection conn = null; try { conn = new LdapConnection(); conn.SecureSocketLayer = _config.SSL; int port = _config.SSL ? LDAPS_PORT : LDAP_PORT; conn.UserDefinedServerCertValidationDelegate += new CertificateValidationCallback(ValidateCert); //if server has a port number specified, it's used instead. conn.Connect(server, port); if (!string.IsNullOrEmpty(bindingdn)) { conn.Bind(bindingdn, password); } } catch (Exception x) { UnBind(conn); LogUtils.LogWarning(_log, x, "GetLdapConnection", string.Format("Failed to bind to LDAP server: '{0}' with bindingdn: '{1}'. Password provided? {2}. Exception: {3}", server, bindingdn, string.IsNullOrEmpty(password).ToString(), x.ToString())); throw; } return conn; } /// <summary> /// Authenticates by creating a bind. /// Connection exceptions will be thrown but invalid credential will return false /// </summary> /// <returns></returns> public bool Authenticate() { bool ret = false; LdapConnection conn = null; LdapConnection queryConn = null; try { //When using the proxy bind, authentications requires a user lookup and another bind. if (!string.IsNullOrEmpty(_config.BindingPw)) { LdapSearchResults authUser = LookupLdapUser(false, _username, out queryConn); if (authUser.hasMore()) { LdapEntry entry = authUser.next(); conn = Bind(_config.LdapHostname, entry.DN, _password); } else { _log.WarnFormat("No users matched search creteria for username '{0}'", _username); ret = false; } } else { conn = Bind(); } if (conn != null) { ret = conn.Bound; } } catch (LdapException x) { ret = false; if (x.ResultCode != LdapException.INVALID_CREDENTIALS) { throw; } } finally { UnBind(queryConn); UnBind(conn); } return ret; } private LdapConnection Bind() { string hostname = _config.LdapHostname; string bindDN = string.Empty; string bindPW = string.Empty; //Determine if a query account is configured or not with BindingDN and BindingPW if (!string.IsNullOrEmpty(_config.BindingPw)) { bindDN = _config.BindingDn; bindPW = _config.BindingPw; } else { //No preconfigured account exists: need to establish a bind with provided credentials. bindDN = BuildBindDn(_username); bindPW = _password; } return Bind(hostname, bindDN, bindPW); } private LdapConnection Bind(string hostname, string bindDN, string bindPW) { LdapConnection conn = null; try { //Establish ldap bind conn = GetLdapConnectionFromBindingDN(hostname, bindDN, bindPW); if (!conn.Bound) { UnBind(conn); conn = null; //Sometimes it doesn't throw an exception but ramains unbound. throw new DreamAbortException(DreamMessage.AccessDenied("Deki LDAP Service", string.Format("An LDAP bind was not established. Server: '{0}'. BindingDN: '{1}'. Password provided? '{2}'", hostname, bindDN, string.IsNullOrEmpty(bindPW) ? "No." : "Yes."))); } } catch (LdapException x) { UnBind(conn); if (x.ResultCode == LdapException.INVALID_CREDENTIALS) { throw new DreamAbortException(DreamMessage.AccessDenied("Deki LDAP Service", string.Format("Invalid LDAP credentials. Server: '{0}'. BindingDN: '{1}'. Password provided? '{2}'", hostname, bindDN, string.IsNullOrEmpty(bindPW) ? "No." : "Yes."))); } else { throw; } } return conn; } private void UnBind(LdapConnection conn) { if (conn != null && conn.Connected) { try { conn.Disconnect(); } catch { } } } private LdapSearchResults LookupLdapUser(bool retrieveGroupMembership, string username, out LdapConnection conn) { conn = Bind(); username = EscapeLdapString(username); //search filter is built based on passed userQuery with username substitution string searchFilter = this.BuildUserSearchQuery(username); //Build interesting attribute list List<string> attrs = new List<string>(); attrs.AddRange(new string[] { "sAMAccountName", "uid", "cn", "userAccountControl", "whenCreated", "name", "givenname", "sn", "telephonenumber", "mail", "description" }); if (retrieveGroupMembership) { attrs.Add(_config.GroupMembersAttribute); } if (!string.IsNullOrEmpty(_config.UserNameAttribute) && !attrs.Contains(_config.UserNameAttribute)) { attrs.Add(_config.UserNameAttribute); } //add more attributes to lookup if using a displayname-pattern string[] patternAttributes = RetrieveAttributesFromPattern(_config.DisplayNamePattern); if (patternAttributes != null) { foreach (string patternAttribute in patternAttributes) { if (!attrs.Contains(patternAttribute)) attrs.Add(patternAttribute); } } LdapSearchConstraints cons = new LdapSearchConstraints(new LdapConstraints(_timeLimit, true, null, 0)); cons.BatchSize = 0; LdapSearchResults results = conn.Search(_config.LdapSearchBase, LdapConnection.SCOPE_SUB, searchFilter, attrs.ToArray(), false, cons); return results; } /// <summary> /// Authenticates by creating a bind and returning info about the user. /// This either returns a /users/user xml block or an exception xml if unable to connect or authenticate. /// In case of exception, invalid credentials is noted as /exception/message = "invalid credentials" /// </summary> /// <returns></returns> public XDoc AuthenticateXml() { return GetUserInfo(false, _username); } #region overloads for retrial handling public XDoc GetUserInfo(bool retrieveGroupMembership, uint retries, string username) { do { try { return GetUserInfo(retrieveGroupMembership, username); } catch (TimeoutException) { } } while (retries-- > 0); throw new TimeoutException(); } public XDoc GetGroupInfo(bool retrieveGroupMembers, uint retries, string optionalGroupName) { do { try { return GetGroupInfo(retrieveGroupMembers, optionalGroupName); } catch (TimeoutException) { } } while (retries-- > 0); throw new TimeoutException(); } #endregion /// <summary> /// Retrieve information about one or more users /// </summary> /// <param name="retrieveGroupMembership">retrieving list of groups for each user will take longer</param> /// <param name="username">Username to lookup</param> /// <returns></returns> public XDoc GetUserInfo(bool retrieveGroupMembership, string username) { XDoc resultXml = null; LdapConnection conn = null; try { LdapSearchResults results = LookupLdapUser(retrieveGroupMembership, username, out conn); if (results.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = results.next(); } catch (LdapException x) { HandleLdapException(x); } if (nextEntry == null) throw new ArgumentNullException("nextEntry"); //Create xml from search entry resultXml = new XDoc("user"); string name = string.Empty; //If a usernameattribute is configured, use that. Otherwise try the common ones. if (!string.IsNullOrEmpty(_config.UserNameAttribute)) { name = GetAttributeSafe(nextEntry, _config.UserNameAttribute); } else { name = GetAttributeSafe(nextEntry, "sAMAccountName"); //MS Active Directory if (string.IsNullOrEmpty(name)) name = GetAttributeSafe(nextEntry, "uid"); //OpenLDAP if (string.IsNullOrEmpty(name)) name = GetAttributeSafe(nextEntry, "name"); //OpenLDAP if (string.IsNullOrEmpty(name)) name = GetAttributeSafe(nextEntry, "cn"); //Novell eDirectory } string displayName = BuildDisplayNameFromPattern(_config.DisplayNamePattern, nextEntry); resultXml.Attr("name", name); if (!string.IsNullOrEmpty(displayName)) resultXml.Attr("displayname", displayName); resultXml.Start("ldap-dn").Value(nextEntry.DN).End(); resultXml.Start("date.created").Value(ldapStringToDate(GetAttributeSafe(nextEntry, "whenCreated"))).End(); resultXml.Start("firstname").Value(GetAttributeSafe(nextEntry, "givenname")).End(); resultXml.Start("lastname").Value(GetAttributeSafe(nextEntry, "sn")).End(); resultXml.Start("phonenumber").Value(GetAttributeSafe(nextEntry, "telephonenumber")).End(); resultXml.Start("email").Value(GetAttributeSafe(nextEntry, "mail")).End(); resultXml.Start("description").Value(GetAttributeSafe(nextEntry, "description")).End(); //Retrieve group memberships if (string.IsNullOrEmpty(_config.GroupMembershipQuery)) { LdapAttributeSet memberAttrSet = nextEntry.getAttributeSet(); LdapAttribute memberAttr = null; if (memberAttrSet != null) memberAttr = memberAttrSet.getAttribute(_config.GroupMembersAttribute); if (memberAttr != null) { resultXml.Start("groups"); foreach (string member in memberAttr.StringValueArray) { resultXml.Start("group"); resultXml.Attr("name", GetNameFromDn(member)); resultXml.Start("ldap-dn").Value(member).End(); resultXml.End(); } resultXml.End(); } } else { //Perform custom query to determine groups of a user PopulateGroupsForUserWithQuery(resultXml, username, conn); } } } finally { UnBind(conn); } return resultXml; } private void PopulateGroupsForUserWithQuery(XDoc doc, string username, LdapConnection conn) { doc.Start("groups"); string searchFilter = string.Format(Dream.PhpUtil.ConvertToFormatString(_config.GroupMembershipQuery), username); //Build interesting attribute list List<string> attrs = new List<string>(); attrs.AddRange(new string[] { "whenCreated", "name", "sAMAccountName", "cn" }); LdapSearchConstraints cons = new LdapSearchConstraints(new LdapConstraints(_timeLimit, true, null, 0)); cons.BatchSize = 0; LdapSearchResults results = conn.Search(_config.LdapSearchBase, LdapConnection.SCOPE_SUB, searchFilter, attrs.ToArray(), false, cons); while (results.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = results.next(); } catch (LdapException x) { HandleLdapException(x); } if (nextEntry == null) throw new ArgumentNullException("nextEntry"); //Create xml from search entry doc.Start("group").Attr("name", GetNameFromDn(nextEntry.DN)).Start("ldap-dn").Value(nextEntry.DN).End().End(); } doc.End(); //groups } /// <summary> /// Retrieves group information from ldap /// </summary> /// <param name="retrieveGroupMembers">true to return users in each group. This may hurt performance</param> /// <param name="optionalGroupName">Group to lookup by name. Null for all groups</param> /// <returns></returns> public XDoc GetGroupInfo(bool retrieveGroupMembers, string optionalGroupName) { LdapConnection conn = null; XDoc resultXml = null; try { //Confirm a query bind has been established conn = Bind(); string searchFilter; //Build the searchfilter based on if a group name is given. if (!string.IsNullOrEmpty(optionalGroupName)) { optionalGroupName = EscapeLdapString(optionalGroupName); //Looking up group by name searchFilter = string.Format(PhpUtil.ConvertToFormatString(_config.GroupQuery), optionalGroupName); } else { //Looking up all groups searchFilter = _config.GroupQueryAll; } //Build interesting attribute list List<string> attrs = new List<string>(); attrs.AddRange(new string[] { "whenCreated", "name", "sAMAccountName", "cn" }); if (retrieveGroupMembers) { attrs.Add("member"); } if (!string.IsNullOrEmpty(_config.GroupNameAttribute) && !attrs.Contains(_config.GroupNameAttribute)) { attrs.Add(_config.GroupNameAttribute); } LdapSearchConstraints cons = new LdapSearchConstraints(new LdapConstraints(_timeLimit, true, null, 0)); cons.BatchSize = 0; LdapSearchResults results = conn.Search(_config.LdapSearchBase, LdapConnection.SCOPE_SUB, searchFilter, attrs.ToArray(), false, cons); //Create outer groups collection if multiple groups are being looked up or none provided if (string.IsNullOrEmpty(optionalGroupName)) resultXml = new XDoc("groups"); while (results.hasMore()) { LdapEntry nextEntry = null; try { nextEntry = results.next(); } catch (LdapException x) { HandleLdapException(x); continue; } //Create xml from search entry if (resultXml == null) resultXml = new XDoc("group"); else resultXml.Start("group"); string name = string.Empty; //If a groupnameattribute is configured, use that. Otherwise try the common ones. if (!string.IsNullOrEmpty(_config.GroupNameAttribute)) { name = GetAttributeSafe(nextEntry, _config.GroupNameAttribute); } else { name = GetAttributeSafe(nextEntry, "sAMAccountName"); //MS Active Directory if (string.IsNullOrEmpty(name)) name = GetAttributeSafe(nextEntry, "uid"); //OpenLDAP if (string.IsNullOrEmpty(name)) name = GetAttributeSafe(nextEntry, "name"); //OpenLDAP if (string.IsNullOrEmpty(name)) name = GetAttributeSafe(nextEntry, "cn"); //Novell eDirectory } resultXml.Attr("name", name); resultXml.Start("ldap-dn").Value(nextEntry.DN).End(); resultXml.Start("date.created").Value(ldapStringToDate(GetAttributeSafe(nextEntry, "whenCreated"))).End(); //Retrieve and write group membership to xml LdapAttributeSet memberAttrSet = nextEntry.getAttributeSet(); LdapAttribute memberAttr = memberAttrSet.getAttribute("member"); // TODO MaxM: This currently does not differentiate between user and group // members. if (memberAttr != null) { foreach (string member in memberAttr.StringValueArray) { resultXml.Start("member"); resultXml.Attr("name", GetNameFromDn(member)); resultXml.Start("ldap-dn").Value(member).End(); resultXml.End(); } } if (string.IsNullOrEmpty(optionalGroupName)) resultXml.End(); } } finally { UnBind(conn); } return resultXml; } #region Properties /// <summary> /// In milliseconds. Default = 5000 /// </summary> public int TimeLimit { get { return _timeLimit; } set { _timeLimit = value; } } public string UserName { get { return _username; } } #endregion public string BuildUserSearchQuery(string username) { return string.Format(Dream.PhpUtil.ConvertToFormatString(_config.UserQuery), username); } public string BuildBindDn(string username) { if (string.IsNullOrEmpty(username)) return null; return string.Format(PhpUtil.ConvertToFormatString(_config.BindingDn), username); } #region Helper methods private string GetNameFromDn(string dn) { string name; name = dn.Split(',')[0].Split('=')[1]; name = UnEscapeLdapString(name); return name; } private DateTime ldapStringToDate(string ldapDate) { if (string.IsNullOrEmpty(ldapDate)) return DateTime.MinValue; else { DateTime result; return DateTime.TryParseExact(ldapDate, "yyyyMMddHHmmss.0Z", System.Globalization.DateTimeFormatInfo.CurrentInfo, System.Globalization.DateTimeStyles.AssumeUniversal, out result) ? result : DateTime.MinValue; } } private string GetAttributeSafe(LdapEntry entry, string attributeName) { string ret = string.Empty; if (entry != null && !String.IsNullOrEmpty(attributeName)) { LdapAttribute attr = entry.getAttribute(attributeName); if (attr != null) ret = attr.StringValue; } return ret; } private static readonly Regex _displayNamePatternRegex = new Regex("{(?<attribute>[^}]*)}", RegexOptions.Compiled | RegexOptions.CultureInvariant); private string BuildDisplayNameFromPattern(string displayNamePattern, LdapEntry entry) { if (string.IsNullOrEmpty(displayNamePattern)) return string.Empty; string displayName = displayNamePattern; string[] attributes = RetrieveAttributesFromPattern(displayNamePattern); if (attributes != null) { foreach (string attribute in attributes) { displayName = displayName.Replace("{" + attribute + "}", GetAttributeSafe(entry, attribute)); } } return displayName; } private string[] RetrieveAttributesFromPattern(string displayNamePattern) { if (string.IsNullOrEmpty(displayNamePattern)) return null; List<string> attributes = null; try { MatchCollection mc = _displayNamePatternRegex.Matches(displayNamePattern); attributes = new List<string>(); foreach (Match m in mc) { attributes.Add(m.Groups["attribute"].Value); } } catch (Exception x) { _log.Warn(string.Format("Could not parse the displayname-pattern '{0}'", displayNamePattern), x); attributes = null; } if (attributes == null) return null; else return attributes.ToArray(); } private void HandleLdapException(LdapException x) { switch (x.ResultCode) { case LdapException.Ldap_TIMEOUT: throw new TimeoutException("Ldap lookup timed out", x); case LdapException.OPERATIONS_ERROR: case LdapException.INVALID_DN_SYNTAX: if (x.ResultCode == 1 && x.LdapErrorMessage.Contains("DSID-0C090627")) throw new DreamAbortException(DreamMessage.Forbidden(string.Format("Account '{0}' is disabled", this._username))); throw new ArgumentException(string.Format("The search base '{0}' may have invalid format (Example: 'DC=sales,DC=acme,DC=com') or the account used for binding may be disabled. Error returned from LDAP: {1}", _config.LdapSearchBase, x.LdapErrorMessage), x); default: throw x; } } private string UnEscapeLdapString(string original) { if (string.IsNullOrEmpty(original)) return original; return original.Replace("\\", ""); } private string EscapeLdapString(string original) { //Per http://www.ietf.org/rfc/rfc2253.txt section 2.4 if (string.IsNullOrEmpty(original)) return original; StringBuilder sb = new StringBuilder(); foreach (char c in original) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == ' ')) { sb.Append(c); } else { sb.Append(@"\" + Convert.ToString((int) c, 16)); } } return sb.ToString(); } #endregion private bool ValidateCert(X509Certificate certificate, int[] certificateErrors) { if (certificateErrors.Length == 0) { return true; } string errors = string.Join(",", Array.ConvertAll<int, string>(certificateErrors, new Converter<int, string>(delegate(int value) { return value.ToString(); }))); _log.WarnFormat("Got error# {0} from LDAPS certificate: {1}", errors, certificate.ToString(true)); return _config.SSLIgnoreCertErrors; } } public class AccountDisabledException : Exception { public AccountDisabledException() { } } }
/* 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.Concurrent; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using NetFreeSwitch.Framework.Common; using NetFreeSwitch.Framework.FreeSwitch.Codecs; using NetFreeSwitch.Framework.FreeSwitch.Commands; using NetFreeSwitch.Framework.FreeSwitch.Events; using NetFreeSwitch.Framework.FreeSwitch.Messages; using NetFreeSwitch.Framework.Net; using NetFreeSwitch.Framework.Net.Buffers; using NetFreeSwitch.Framework.Net.Channels; using NLog; namespace NetFreeSwitch.Framework.FreeSwitch.Outbound { /// <summary> /// Connects to FreeSwitch and execute commands. /// </summary> public class OutboundChannelSession : IDisposable { private static bool _authenticated; private readonly SocketAsyncEventArgs _args = new SocketAsyncEventArgs(); private readonly SemaphoreSlim _connectSemaphore = new SemaphoreSlim(0, 1); private readonly Logger _log = LogManager.GetCurrentClassLogger(); private readonly ConcurrentQueue<CommandAsyncEvent> _requestsQueue; private readonly SemaphoreSlim _sendCompletedSemaphore = new SemaphoreSlim(0, 1); private readonly SemaphoreSlim _sendQueueSemaphore = new SemaphoreSlim(1, 1); private TcpChannel _channel; private Exception _connectException; private Exception _sendException; private Socket _socket; /// <summary> /// This constructor sets user defined values to connect to FreeSwitch. /// </summary> /// <param name="address">FreeSwitch mod_event_socket IP address or hostname</param> /// <param name="port">FreeSwitch mod_event_socket Port number</param> /// <param name="messageEncoder">FreeSwitch message encoder</param> /// <param name="messageDecoder">FreeSwitch message decoder</param> /// <param name="freeSwitchEventFilter">FreeSwitch event filters</param> /// <param name="connectionTimeout">Connection Timeout</param> /// <param name="password">FreeSwitch mod_event_socket Password</param> public OutboundChannelSession(string address, int port, IMessageEncoder messageEncoder, IMessageDecoder messageDecoder, string freeSwitchEventFilter, TimeSpan connectionTimeout, string password) { Address = address; Port = port; MessageEncoder = messageEncoder; MessageDecoder = messageDecoder; FreeSwitchEventFilter = freeSwitchEventFilter; ConnectionTimeout = connectionTimeout; Password = password; _authenticated = false; _requestsQueue = new ConcurrentQueue<CommandAsyncEvent>(); _channel = new TcpChannel(new BufferSlice(new byte[65535], 0, 65535), MessageEncoder, MessageDecoder); _channel.MessageReceived += OnMessageReceived; _channel.Disconnected += OnDisconnect; _channel.MessageSent += OnSendCompleted; _args.Completed += OnConnect; OnAuthentication += SendAuthentication; } /// <summary> /// This constructor sets user defined values to connect to FreeSwitch using in-built message encoder/decoders /// </summary> /// <param name="address">FreeSwitch mod_event_socket IP address or hostname</param> /// <param name="port">FreeSwitch mod_event_socket Port number</param> /// <param name="connectionTimeout">Connection Timeout</param> /// <param name="password">FreeSwitch mod_event_socket Password</param> public OutboundChannelSession(string address, int port, TimeSpan connectionTimeout, string password) { Address = address; Port = port; ConnectionTimeout = connectionTimeout; Password = password; MessageEncoder = new FreeSwitchEncoder(); MessageDecoder = new FreeSwitchDecoder(); FreeSwitchEventFilter = "plain ALL"; _authenticated = false; _requestsQueue = new ConcurrentQueue<CommandAsyncEvent>(); _channel = new TcpChannel(new BufferSlice(new byte[65535], 0, 65535), MessageEncoder, MessageDecoder); _channel.MessageReceived += OnMessageReceived; _channel.Disconnected += OnDisconnect; _channel.MessageSent += OnSendCompleted; _args.Completed += OnConnect; OnAuthentication += SendAuthentication; } /// <summary> /// This constructor sets user defined values to connect to FreeSwitch using in-built message encoder/decoders. /// The connection timeout is set to zero /// </summary> /// <param name="address">FreeSwitch mod_event_socket IP address or hostname</param> /// <param name="port">FreeSwitch mod_event_socket Port number</param> /// <param name="password">FreeSwitch mod_event_socket Password</param> public OutboundChannelSession(string address, int port, string password) { Address = address; Port = port; ConnectionTimeout = TimeSpan.Zero; Password = password; MessageEncoder = new FreeSwitchEncoder(); MessageDecoder = new FreeSwitchDecoder(); FreeSwitchEventFilter = "plain ALL"; _authenticated = false; _requestsQueue = new ConcurrentQueue<CommandAsyncEvent>(); _channel = new TcpChannel(new BufferSlice(new byte[65535], 0, 65535), MessageEncoder, MessageDecoder); _channel.MessageReceived += OnMessageReceived; _channel.Disconnected += OnDisconnect; _channel.MessageSent += OnSendCompleted; _args.Completed += OnConnect; OnAuthentication += SendAuthentication; } /// <summary> /// This constructor sets user defined values to connect to FreeSwitch using in-built message encoder/decoders. /// The connection timeout is set to zero /// </summary> /// <param name="address">FreeSwitch mod_event_socket IP address or hostname</param> /// <param name="port">FreeSwitch mod_event_socket Port number</param> /// <param name="password">FreeSwitch mod_event_socket Password</param> /// <param name="eventfilters">FreeSwitch event list</param> public OutboundChannelSession(string address, int port, string password, string eventfilters) { Address = address; Port = port; ConnectionTimeout = TimeSpan.Zero; Password = password; MessageEncoder = new FreeSwitchEncoder(); MessageDecoder = new FreeSwitchDecoder(); FreeSwitchEventFilter = "plain " + eventfilters; _authenticated = false; _requestsQueue = new ConcurrentQueue<CommandAsyncEvent>(); _channel = new TcpChannel(new BufferSlice(new byte[65535], 0, 65535), MessageEncoder, MessageDecoder); _channel.MessageReceived += OnMessageReceived; _channel.Disconnected += OnDisconnect; _channel.MessageSent += OnSendCompleted; _args.Completed += OnConnect; OnAuthentication += SendAuthentication; } /// <summary> /// Default constructor. It uses the default FreeSwitch mod_event_socket settings for connectivity /// </summary> public OutboundChannelSession() { Address = "127.0.0.1"; Port = 8021; ConnectionTimeout = TimeSpan.Zero; Password = "ClueCon"; MessageEncoder = new FreeSwitchEncoder(); MessageDecoder = new FreeSwitchDecoder(); FreeSwitchEventFilter = "plain ALL"; _authenticated = false; _requestsQueue = new ConcurrentQueue<CommandAsyncEvent>(); _channel = new TcpChannel(new BufferSlice(new byte[65535], 0, 65535), MessageEncoder, MessageDecoder); _channel.MessageReceived += OnMessageReceived; _channel.Disconnected += OnDisconnect; _channel.MessageSent += OnSendCompleted; _args.Completed += OnConnect; OnAuthentication += SendAuthentication; } /// <summary> /// Event Socket Address /// </summary> public string Address { get; } /// <summary> /// Authentication State /// </summary> public bool Authenticated { get { return _authenticated; } set { _authenticated = value; } } /// <summary> /// Connection State /// </summary> public bool Connected => _channel != null && _channel.IsConnected; /// <summary> /// Connection Timeout /// </summary> public TimeSpan ConnectionTimeout { get; } /// <summary> /// FreeSwitch Events Filter /// </summary> public string FreeSwitchEventFilter { get; } /// <summary> /// FreeSwitch Message Decoder /// </summary> public IMessageDecoder MessageDecoder { get; } /// <summary> /// FreeSwich Message Encoder /// </summary> public IMessageEncoder MessageEncoder { get; } /// <summary> /// Event Socket Password /// </summary> public string Password { get; } /// <summary> /// Event Socket Port /// </summary> public int Port { get; } /// <summary> /// Dispose() /// </summary> public void Dispose() { if (_channel == null) return; _channel.Close(); _channel = null; } public event AsyncEventHandler<EslEventArgs> OnBackgroundJob; public event AsyncEventHandler<EslEventArgs> OnCallUpdate; public event AsyncEventHandler<EslEventArgs> OnChannelAnswer; public event AsyncEventHandler<EslEventArgs> OnChannelBridge; public event AsyncEventHandler<EslEventArgs> OnChannelExecute; public event AsyncEventHandler<EslEventArgs> OnChannelExecuteComplete; public event AsyncEventHandler<EslEventArgs> OnChannelHangup; public event AsyncEventHandler<EslEventArgs> OnChannelHangupComplete; public event AsyncEventHandler<EslEventArgs> OnChannelOriginate; public event AsyncEventHandler<EslEventArgs> OnChannelPark; public event AsyncEventHandler<EslEventArgs> OnChannelProgress; public event AsyncEventHandler<EslEventArgs> OnChannelProgressMedia; public event AsyncEventHandler<EslEventArgs> OnChannelState; public event AsyncEventHandler<EslEventArgs> OnChannelUnbridge; public event AsyncEventHandler<EslEventArgs> OnChannelUnPark; public event AsyncEventHandler<EslEventArgs> OnCustom; public event AsyncEventHandler<EslDisconnectNoticeEventArgs> OnDisconnectNotice; public event AsyncEventHandler<EslEventArgs> OnDtmf; public event AsyncEventHandler<EslEventArgs> OnReceivedUnHandledEvent; public event AsyncEventHandler<EslEventArgs> OnRecordStop; public event AsyncEventHandler<EslRudeRejectionEventArgs> OnRudeRejection; public event AsyncEventHandler<EslEventArgs> OnSessionHeartbeat; public event AsyncEventHandler<EslUnhandledMessageEventArgs> OnUnhandledMessage; protected event AsyncEventHandler<EventArgs> OnAuthentication; /// <summary> /// Disconnect from FreeSwitch mod_event_socket /// </summary> /// <returns></returns> /// <summary> /// Wait for all messages to be sent and close the connection /// </summary> /// <returns>Async task</returns> public async Task CloseAsync() { await ShutdownGracefully(); await _channel.CloseAsync(); _authenticated = false; _channel = null; } /// <summary> /// ConnectAsync(). /// It used to connect to FreeSwitch mod_event_socket as a client. /// </summary> /// <returns>Async task</returns> public async Task ConnectAsync() { if (_socket != null) throw new InvalidOperationException("Socket is already connected"); _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, 600)); // configured address var address = Address.IsValidIPv4() ? IPAddress.Parse(Address) : Address.ToIPAddress(); _args.RemoteEndPoint = new IPEndPoint(address, Port); var isPending = _socket.ConnectAsync(_args); if (!isPending) return; await _connectSemaphore.WaitAsync(ConnectionTimeout); if (_connectException != null) throw _connectException; } /// <summary> /// Send(). /// It sends a command to FreeSwitch and awaist for a CommandReply response /// </summary> /// <param name="command">The command to send</param> /// <returns>CommandReply response</returns> public async Task<CommandReply> Send(BaseCommand command) { if (!Connected || !Authenticated) return null; // Send command var event2 = EnqueueCommand(command); if (_log.IsDebugEnabled) _log.Debug("command to be sent <<{0}>>", command.ToString()); await SendAsync(command); return await event2.Task as CommandReply; } /// <summary> /// SendApi(). /// It is used to send an api command to FreeSwitch. /// </summary> /// <param name="command"></param> /// <returns>ApiResponse response</returns> public async Task<ApiResponse> SendApi(ApiCommand command) { if (!Connected || !Authenticated) return null; // Send the command var event2 = EnqueueCommand(command); await SendAsync(command); return await event2.Task as ApiResponse; } /// <summary> /// SendBgApi(). /// It is used to send commands to FreeSwitch that will be executed in the background. It will return a UUID. /// </summary> /// <param name="command">The command to send</param> /// <returns>Job ID</returns> public async Task<Guid> SendBgApi(BgApiCommand command) { if (!Connected || !Authenticated) return Guid.Empty; // Send command var reply = await Send(command); if (reply == null) return Guid.Empty; if (!reply.IsSuccessful) return Guid.Empty; var jobId = reply["Job-UUID"]; Guid jobUuid; return Guid.TryParse(jobId, out jobUuid) ? jobUuid : Guid.Empty; } /// <summary> /// SendLog(). It is used to request for FreeSwitch log. /// </summary> /// <param name="level">The log level to specify</param> /// <returns></returns> public async Task SetLogLevel(EslLogLevels level) { var command = new LogCommand(level); await SendAsync(command); } /// <summary> /// ShutdownGracefully(). /// Send an exit command to FreeSwitch /// </summary> /// <returns>Async task</returns> public async Task ShutdownGracefully() { // Let us send exit command to FreeSwitch var exit = new ExitCommand(); await SendAsync(exit); } /// <summary> /// SubscribeToEvents() /// It is used to subscribe to FreeSwitch events. Returns true when successful. /// </summary> /// <returns>boolean</returns> public async Task<bool> SubscribeToEvents() { if (!Connected || !Authenticated) return false; var command = new EventCommand(FreeSwitchEventFilter); var reply = await Send(command); return reply != null && reply.IsSuccessful; } /// <summary> /// Authenticate(). /// It helps to send auth command to FreeSwitch using the provided password. /// </summary> /// <returns>Async task</returns> protected async Task Authenticate() { var command = new AuthCommand(Password); // Send the command var event2 = EnqueueCommand(command); await SendAsync(command); var response = await event2.Task as CommandReply; if (response == null) { await CloseAsync(); return; } if (!response.IsSuccessful) { await CloseAsync(); return; } _authenticated = true; if (!string.IsNullOrEmpty(FreeSwitchEventFilter)) await SubscribeToEvents(); } /// <summary> /// Used to dispatch .NET events /// </summary> protected void DispatchEvents(EslEventType eventType, EslEventArgs ea) { AsyncEventHandler<EslEventArgs> handler = null; switch (eventType) { case EslEventType.BACKGROUND_JOB: handler = OnBackgroundJob; break; case EslEventType.CALL_UPDATE: handler = OnCallUpdate; break; case EslEventType.CHANNEL_BRIDGE: handler = OnChannelBridge; break; case EslEventType.CHANNEL_HANGUP: handler = OnChannelHangup; break; case EslEventType.CHANNEL_HANGUP_COMPLETE: handler = OnChannelHangupComplete; break; case EslEventType.CHANNEL_PROGRESS: handler = OnChannelProgress; break; case EslEventType.CHANNEL_PROGRESS_MEDIA: handler = OnChannelProgressMedia; break; case EslEventType.CHANNEL_EXECUTE: handler = OnChannelExecute; break; case EslEventType.CHANNEL_EXECUTE_COMPLETE: handler = OnChannelExecuteComplete; break; case EslEventType.CHANNEL_UNBRIDGE: handler = OnChannelUnbridge; break; case EslEventType.SESSION_HEARTBEAT: handler = OnSessionHeartbeat; break; case EslEventType.DTMF: handler = OnDtmf; break; case EslEventType.RECORD_STOP: handler = OnRecordStop; break; case EslEventType.CUSTOM: handler = OnCustom; break; case EslEventType.CHANNEL_STATE: handler = OnChannelState; break; case EslEventType.CHANNEL_ANSWER: handler = OnChannelAnswer; break; case EslEventType.CHANNEL_ORIGINATE: handler = OnChannelOriginate; break; case EslEventType.CHANNEL_PARK: handler = OnChannelPark; break; case EslEventType.CHANNEL_UNPARK: handler = OnChannelUnPark; break; case EslEventType.UN_HANDLED_EVENT: handler = OnReceivedUnHandledEvent; break; } if (handler == null) return; try { handler(this, ea); } catch (Exception) { // ignored } } /// <summary> /// Add the command request to the waiting list. /// </summary> /// <param name="command">The command to send</param> /// <returns></returns> protected CommandAsyncEvent EnqueueCommand(BaseCommand command) { var event2 = new CommandAsyncEvent(command); _requestsQueue.Enqueue(event2); return event2; } protected async Task HandleResponse(object item) { if (item == null) return; var @event = item as EslEvent; if (@event != null) { PopEvent(@event); return; } var reply = item as CommandReply; if (reply != null) { if (_requestsQueue.Count <= 0) return; CommandAsyncEvent event2; if (!_requestsQueue.TryDequeue(out event2)) return; event2?.Complete(reply); return; } var response = item as ApiResponse; if (response != null) { if (_requestsQueue.Count <= 0) return; CommandAsyncEvent event2; if (!_requestsQueue.TryDequeue(out event2)) return; event2?.Complete(response); return; } var notice = item as DisconnectNotice; if (notice != null) { if (OnDisconnectNotice != null) await OnDisconnectNotice(this, new EslDisconnectNoticeEventArgs(notice)).ConfigureAwait(false); await _channel.CloseAsync(); return; } var rejection = item as RudeRejection; if (rejection != null) { if (OnRudeRejection != null) await OnRudeRejection(this, new EslRudeRejectionEventArgs(rejection)).ConfigureAwait(false); return; } var logdata = item as LogData; if (logdata != null) { //todo handle log/data return; } var msg = item as EslMessage; if (OnUnhandledMessage != null) await OnUnhandledMessage(this, new EslUnhandledMessageEventArgs(msg)).ConfigureAwait(false); } /// <summary> /// FreeSwitch Events listener hook /// </summary> protected void PopEvent(EslEvent @event) { if (string.IsNullOrEmpty(@event.EventName)) return; switch (@event.EventName.ToUpper()) { case "CHANNEL_HANGUP": DispatchEvents(EslEventType.CHANNEL_HANGUP, new EslEventArgs(new ChannelHangup(@event.Items))); break; case "CHANNEL_HANGUP_COMPLETE": DispatchEvents(EslEventType.CHANNEL_HANGUP_COMPLETE, new EslEventArgs(new ChannelHangup(@event.Items))); break; case "CHANNEL_PROGRESS": DispatchEvents(EslEventType.CHANNEL_PROGRESS, new EslEventArgs(new ChannelProgress(@event.Items))); break; case "CHANNEL_PROGRESS_MEDIA": DispatchEvents(EslEventType.CHANNEL_PROGRESS_MEDIA, new EslEventArgs(new ChannelProgressMedia(@event.Items))); break; case "CHANNEL_EXECUTE": DispatchEvents(EslEventType.CHANNEL_EXECUTE, new EslEventArgs(new ChannelExecute(@event.Items))); break; case "CHANNEL_EXECUTE_COMPLETE": DispatchEvents(EslEventType.CHANNEL_EXECUTE_COMPLETE, new EslEventArgs(new ChannelExecuteComplete(@event.Items))); break; case "CHANNEL_BRIDGE": DispatchEvents(EslEventType.CHANNEL_BRIDGE, new EslEventArgs(new ChannelBridge(@event.Items))); break; case "CHANNEL_UNBRIDGE": DispatchEvents(EslEventType.CHANNEL_UNBRIDGE, new EslEventArgs(new ChannelUnbridge(@event.Items))); break; case "BACKGROUND_JOB": DispatchEvents(EslEventType.BACKGROUND_JOB, new EslEventArgs(new BackgroundJob(@event.Items))); break; case "SESSION_HEARTBEAT": DispatchEvents(EslEventType.SESSION_HEARTBEAT, new EslEventArgs(new SessionHeartbeat(@event.Items))); break; case "CHANNEL_STATE": DispatchEvents(EslEventType.CHANNEL_STATE, new EslEventArgs(new ChannelStateEvent(@event.Items))); break; case "DTMF": DispatchEvents(EslEventType.DTMF, new EslEventArgs(new Dtmf(@event.Items))); break; case "RECORD_STOP": DispatchEvents(EslEventType.RECORD_STOP, new EslEventArgs(new RecordStop(@event.Items))); break; case "CALL_UPDATE": DispatchEvents(EslEventType.CALL_UPDATE, new EslEventArgs(new CallUpdate(@event.Items))); break; case "CUSTOM": DispatchEvents(EslEventType.CUSTOM, new EslEventArgs(new Custom(@event.Items))); break; case "CHANNEL_ANSWER": DispatchEvents(EslEventType.CHANNEL_ANSWER, new EslEventArgs(@event)); break; case "CHANNEL_ORIGINATE": DispatchEvents(EslEventType.CHANNEL_ORIGINATE, new EslEventArgs(@event)); break; case "CHANNEL_PARK": DispatchEvents(EslEventType.CHANNEL_PARK, new EslEventArgs(new ChannelPark(@event.Items))); break; case "CHANNEL_UNPARK": DispatchEvents(EslEventType.CHANNEL_UNPARK, new EslEventArgs(@event)); break; default: DispatchEvents(EslEventType.UN_HANDLED_EVENT, new EslEventArgs(@event)); break; } } /// <summary> /// SendAsync(). It is used internally to send command to FreeSwitch /// </summary> /// <param name="message">the command to send</param> /// <returns>Async task</returns> protected async Task SendAsync(object message) { if (message == null) throw new ArgumentNullException(nameof(message)); if (_sendException != null) { var ex = _sendException; _sendException = null; throw new AggregateException(ex); } await _sendQueueSemaphore.WaitAsync(); _channel.Send(message); await _sendCompletedSemaphore.WaitAsync(); _sendQueueSemaphore.Release(); } /// <summary> /// Valiates every response received seeing that we can send commands to FreeSwitch asynchronously and wait for /// responses. /// However some responses may be for another command previously sent. In that regard, every command has a sequence /// number /// attached to it that helps differentiate between them and easily map their responses. /// </summary> /// <param name="command">The original command send</param> /// <param name="response">The actual response received</param> /// <returns>EslMessage</returns> protected async Task<EslMessage> ValidateResponse(BaseCommand command, EslMessage response) { if (response == null) return null; if (_requestsQueue.Count <= 0) return null; CommandAsyncEvent event2; if (!_requestsQueue.TryDequeue(out event2)) return null; if (event2 == null) return null; if (!event2.Command.Equals(command)) return null; event2.Complete(response); return await event2.Task; } /// <summary> /// Connection event handler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnConnect(object sender, SocketAsyncEventArgs e) { if (e.SocketError != SocketError.Success) { _connectException = new SocketException((int) e.SocketError); _socket = null; } else _channel.Assign(_socket); _connectSemaphore.Release(); } /// <summary> /// Disconnection event handler /// </summary> /// <param name="arg1"></param> /// <param name="arg2"></param> private void OnDisconnect(ITcpChannel arg1, Exception arg2) { _socket = null; if (_sendCompletedSemaphore.CurrentCount == 0) { _sendException = arg2; _sendCompletedSemaphore.Release(); } } /// <summary> /// Fired when a decoded message is received by the channel. /// </summary> /// <param name="channel">Receiving channel</param> /// <param name="message">Decoded message received</param> private async void OnMessageReceived(ITcpChannel channel, object message) { var decodedMessage = message as EslDecodedMessage; // Handle decoded message. if (decodedMessage?.Headers == null || !decodedMessage.Headers.HasKeys()) return; var headers = decodedMessage.Headers; object response = null; var contentType = headers["Content-Type"]; if (string.IsNullOrEmpty(contentType)) return; contentType = contentType.ToLowerInvariant(); switch (contentType) { case "auth/request": if (OnAuthentication != null) await OnAuthentication(this, EventArgs.Empty).ConfigureAwait(false); break; case "command/reply": var reply = new CommandReply(headers, decodedMessage.OriginalMessage); response = reply; break; case "api/response": var apiResponse = new ApiResponse(decodedMessage.BodyText); response = apiResponse; break; case "text/event-plain": var parameters = decodedMessage.BodyLines.AllKeys.ToDictionary(key => key, key => decodedMessage.BodyLines[key]); var @event = new EslEvent(parameters); response = @event; break; case "log/data": var logdata = new LogData(headers, decodedMessage.BodyText); response = logdata; break; case "text/rude-rejection": await _channel.CloseAsync(); var reject = new RudeRejection(decodedMessage.BodyText); response = reject; break; case "text/disconnect-notice": var notice = new DisconnectNotice(decodedMessage.BodyText); response = notice; break; default: // Here we are handling an unknown message var msg = new EslMessage(decodedMessage.Headers, decodedMessage.OriginalMessage); response = msg; break; } await HandleResponse(response).ConfigureAwait(false); } /// <summary> /// Completed Send request event handler. Good for logging. /// </summary> /// <param name="channel">the Tcp channel used to send the request</param> /// <param name="sentMessage">the message sent</param> private void OnSendCompleted(ITcpChannel channel, object sentMessage) { if (_log.IsDebugEnabled) { var cmd = sentMessage as BaseCommand; _log.Debug("command sent to freeSwitch <<{0}>>", cmd.ToString()); } _sendCompletedSemaphore.Release(); } private async Task SendAuthentication(object sender, EventArgs e) { await Authenticate(); } } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Data.Services.Common; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Text; using System.Threading.Tasks; using Orleans.AzureUtils; using Microsoft.WindowsAzure.Storage.Table; namespace Orleans.Runtime.ReminderService { internal class ReminderTableEntry : TableEntity { public string GrainReference { get; set; } // Part of RowKey public string ReminderName { get; set; } // Part of RowKey public string ServiceId { get; set; } // Part of PartitionKey public string DeploymentId { get; set; } public string StartAt { get; set; } public string Period { get; set; } public string GrainRefConsistentHash { get; set; } // Part of PartitionKey public static string ConstructRowKey(GrainReference grainRef, string reminderName) { var key = String.Format("{0}-{1}", grainRef.ToKeyString(), reminderName); //grainRef.ToString(), reminderName); return AzureStorageUtils.SanitizeTableProperty(key); } public static string ConstructPartitionKey(Guid serviceId, GrainReference grainRef) { return ConstructPartitionKey(serviceId, grainRef.GetUniformHashCode()); } public static string ConstructPartitionKey(Guid serviceId, uint number) { // IMPORTANT NOTE: Other code using this return data is very sensitive to format changes, // so take great care when making any changes here!!! // this format of partition key makes sure that the comparisons in FindReminderEntries(begin, end) work correctly // the idea is that when converting to string, negative numbers start with 0, and positive start with 1. Now, // when comparisons will be done on strings, this will ensure that positive numbers are always greater than negative // string grainHash = number < 0 ? string.Format("0{0}", number.ToString("X")) : string.Format("1{0:d16}", number); var grainHash = String.Format("{0:X8}", number); return String.Format("{0}_{1}", ConstructServiceIdStr(serviceId), grainHash); } public static string ConstructServiceIdStr(Guid serviceId) { return serviceId.ToString(); } public override string ToString() { var sb = new StringBuilder(); sb.Append("Reminder ["); sb.Append(" PartitionKey=").Append(PartitionKey); sb.Append(" RowKey=").Append(RowKey); sb.Append(" GrainReference=").Append(GrainReference); sb.Append(" ReminderName=").Append(ReminderName); sb.Append(" Deployment=").Append(DeploymentId); sb.Append(" ServiceId=").Append(ServiceId); sb.Append(" StartAt=").Append(StartAt); sb.Append(" Period=").Append(Period); sb.Append(" GrainRefConsistentHash=").Append(GrainRefConsistentHash); sb.Append("]"); return sb.ToString(); } } internal class RemindersTableManager : AzureTableDataManager<ReminderTableEntry> { private const string REMINDERS_TABLE_NAME = "OrleansReminders"; public Guid ServiceId { get; private set; } public string DeploymentId { get; private set; } private static readonly TimeSpan initTimeout = AzureTableDefaultPolicies.TableCreationTimeout; public static async Task<RemindersTableManager> GetManager(Guid serviceId, string deploymentId, string storageConnectionString) { var singleton = new RemindersTableManager(serviceId, deploymentId, storageConnectionString); try { singleton.Logger.Info("Creating RemindersTableManager for service id {0} and deploymentId {1}.", serviceId, deploymentId); await singleton.InitTableAsync() .WithTimeout(initTimeout); } catch (TimeoutException te) { string errorMsg = String.Format("Unable to create or connect to the Azure table in {0}", initTimeout); singleton.Logger.Error(ErrorCode.AzureTable_38, errorMsg, te); throw new OrleansException(errorMsg, te); } catch (Exception ex) { string errorMsg = String.Format("Exception trying to create or connect to the Azure table: {0}", ex.Message); singleton.Logger.Error(ErrorCode.AzureTable_39, errorMsg, ex); throw new OrleansException(errorMsg, ex); } return singleton; } private RemindersTableManager(Guid serviceId, string deploymentId, string storageConnectionString) : base(REMINDERS_TABLE_NAME, storageConnectionString) { DeploymentId = deploymentId; ServiceId = serviceId; } internal async Task<List<Tuple<ReminderTableEntry, string>>> FindReminderEntries(uint begin, uint end) { string sBegin = ReminderTableEntry.ConstructPartitionKey(ServiceId, begin); string sEnd = ReminderTableEntry.ConstructPartitionKey(ServiceId, end); string serviceIdStr = ReminderTableEntry.ConstructServiceIdStr(ServiceId); if (begin < end) { Expression<Func<ReminderTableEntry, bool>> query = e => String.Compare(e.PartitionKey, serviceIdStr + '_') > 0 && String.Compare(e.PartitionKey, serviceIdStr + (char)('_' + 1)) <= 0 && String.Compare(e.PartitionKey, sBegin) > 0 && String.Compare(e.PartitionKey, sEnd) <= 0; var queryResults = await ReadTableEntriesAndEtagsAsync(query); return queryResults.ToList(); } if (begin == end) { Expression<Func<ReminderTableEntry, bool>> query = e => String.Compare(e.PartitionKey, serviceIdStr + '_') > 0 && String.Compare(e.PartitionKey, serviceIdStr + (char)('_' + 1)) <= 0; var queryResults = await ReadTableEntriesAndEtagsAsync(query); return queryResults.ToList(); } // (begin > end) Expression<Func<ReminderTableEntry, bool>> p1Query = e => String.Compare(e.PartitionKey, serviceIdStr + '_') > 0 && String.Compare(e.PartitionKey, serviceIdStr + (char)('_' + 1)) <= 0 && String.Compare(e.PartitionKey, sBegin) > 0; Expression<Func<ReminderTableEntry, bool>> p2Query = e => String.Compare(e.PartitionKey, serviceIdStr + '_') > 0 && String.Compare(e.PartitionKey, serviceIdStr + (char)('_' + 1)) <= 0 && String.Compare(e.PartitionKey, sEnd) <= 0; var p1 = ReadTableEntriesAndEtagsAsync(p1Query); var p2 = ReadTableEntriesAndEtagsAsync(p2Query); IEnumerable<Tuple<ReminderTableEntry, string>>[] arr = await Task.WhenAll(p1, p2); return arr[0].Concat(arr[1]).ToList(); } internal async Task<List<Tuple<ReminderTableEntry, string>>> FindReminderEntries(GrainReference grainRef) { var partitionKey = ReminderTableEntry.ConstructPartitionKey(ServiceId, grainRef); Expression<Func<ReminderTableEntry, bool>> query = e => e.PartitionKey == partitionKey && String.Compare(e.RowKey, grainRef.ToKeyString() + '-') > 0 && String.Compare(e.RowKey, grainRef.ToKeyString() + (char)('-' + 1)) <= 0; var queryResults = await ReadTableEntriesAndEtagsAsync(query); return queryResults.ToList(); } internal async Task<Tuple<ReminderTableEntry, string>> FindReminderEntry(GrainReference grainRef, string reminderName) { string partitionKey = ReminderTableEntry.ConstructPartitionKey(ServiceId, grainRef); string rowKey = ReminderTableEntry.ConstructRowKey(grainRef, reminderName); return await ReadSingleTableEntryAsync(partitionKey, rowKey); } private async Task<List<Tuple<ReminderTableEntry, string>>> FindAllReminderEntries() { Expression<Func<ReminderTableEntry, bool>> query = instance => instance.ServiceId.Equals(ReminderTableEntry.ConstructServiceIdStr(ServiceId)); var queryResults = await ReadTableEntriesAndEtagsAsync(query); return queryResults.ToList(); } internal async Task<string> UpsertRow(ReminderTableEntry reminderEntry) { try { return await UpsertTableEntryAsync(reminderEntry); } catch(Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) { if (Logger.IsVerbose2) Logger.Verbose2("UpsertRow failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureStorageUtils.IsContentionError(httpStatusCode)) return null; // false; } throw; } } internal async Task<bool> DeleteReminderEntryConditionally(ReminderTableEntry reminderEntry, string eTag) { try { await DeleteTableEntryAsync(reminderEntry, eTag); return true; }catch(Exception exc) { HttpStatusCode httpStatusCode; string restStatus; if (AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) { if (Logger.IsVerbose2) Logger.Verbose2("DeleteReminderEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus); if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false; } throw; } } #region Table operations internal async Task DeleteTableEntries() { if (ServiceId.Equals(Guid.Empty) && DeploymentId == null) { await DeleteTableAsync(); } else { List<Tuple<ReminderTableEntry, string>> entries = await FindAllReminderEntries(); // return manager.DeleteTableEntries(entries); // this doesnt work as entries can be across partitions, which is not allowed // group by grain hashcode so each query goes to different partition var tasks = new List<Task>(); var groupedByHash = entries .Where(tuple => tuple.Item1.ServiceId.Equals(ReminderTableEntry.ConstructServiceIdStr(ServiceId))) .Where(tuple => tuple.Item1.DeploymentId.Equals(DeploymentId)) // delete only entries that belong to our DeploymentId. .GroupBy(x => x.Item1.GrainRefConsistentHash).ToDictionary(g => g.Key, g => g.ToList()); foreach (var entriesPerPartition in groupedByHash.Values) { foreach (var batch in entriesPerPartition.BatchIEnumerable(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS)) { tasks.Add(DeleteTableEntriesAsync(batch)); } } await Task.WhenAll(tasks); } } #endregion } }
using System; using System.Diagnostics; namespace Lucene.Net.Util.Fst { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Can next() and advance() through the terms in an FST /// /// @lucene.experimental /// </summary> public abstract class FSTEnum<T> { protected internal readonly FST<T> Fst; protected internal FST<T>.Arc<T>[] Arcs = new FST<T>.Arc<T>[10]; // outputs are cumulative protected internal T[] Output = new T[10]; protected internal readonly T NO_OUTPUT; protected internal readonly FST<T>.BytesReader FstReader; protected internal readonly FST<T>.Arc<T> ScratchArc = new FST<T>.Arc<T>(); protected internal int Upto; protected internal int TargetLength; /// <summary> /// doFloor controls the behavior of advance: if it's true /// doFloor is true, advance positions to the biggest /// term before target. /// </summary> protected internal FSTEnum(FST<T> fst) { this.Fst = fst; FstReader = fst.BytesReader; NO_OUTPUT = fst.Outputs.NoOutput; fst.GetFirstArc(GetArc(0)); Output[0] = NO_OUTPUT; } protected internal abstract int TargetLabel { get; } protected internal abstract int CurrentLabel { get; set; } protected internal abstract void Grow(); /// <summary> /// Rewinds enum state to match the shared prefix between /// current term and target term /// </summary> protected internal void RewindPrefix() { if (Upto == 0) { //System.out.println(" init"); Upto = 1; Fst.ReadFirstTargetArc(GetArc(0), GetArc(1), FstReader); return; } //System.out.println(" rewind upto=" + upto + " vs targetLength=" + targetLength); int currentLimit = Upto; Upto = 1; while (Upto < currentLimit && Upto <= TargetLength + 1) { int cmp = CurrentLabel - TargetLabel; if (cmp < 0) { // seek forward //System.out.println(" seek fwd"); break; } else if (cmp > 0) { // seek backwards -- reset this arc to the first arc FST<T>.Arc<T> arc = GetArc(Upto); Fst.ReadFirstTargetArc(GetArc(Upto - 1), arc, FstReader); //System.out.println(" seek first arc"); break; } Upto++; } //System.out.println(" fall through upto=" + upto); } protected internal virtual void DoNext() { //System.out.println("FE: next upto=" + upto); if (Upto == 0) { //System.out.println(" init"); Upto = 1; Fst.ReadFirstTargetArc(GetArc(0), GetArc(1), FstReader); } else { // pop //System.out.println(" check pop curArc target=" + arcs[upto].target + " label=" + arcs[upto].label + " isLast?=" + arcs[upto].isLast()); while (Arcs[Upto].Last) { Upto--; if (Upto == 0) { //System.out.println(" eof"); return; } } Fst.ReadNextArc(Arcs[Upto], FstReader); } PushFirst(); } // TODO: should we return a status here (SEEK_FOUND / SEEK_NOT_FOUND / // SEEK_END)? saves the eq check above? /// <summary> /// Seeks to smallest term that's >= target. </summary> protected internal virtual void DoSeekCeil() { //System.out.println(" advance len=" + target.length + " curlen=" + current.length); // TODO: possibly caller could/should provide common // prefix length? ie this work may be redundant if // caller is in fact intersecting against its own // automaton //System.out.println("FE.seekCeil upto=" + upto); // Save time by starting at the end of the shared prefix // b/w our current term & the target: RewindPrefix(); //System.out.println(" after rewind upto=" + upto); FST<T>.Arc<T> arc = GetArc(Upto); int targetLabel = TargetLabel; //System.out.println(" init targetLabel=" + targetLabel); // Now scan forward, matching the new suffix of the target while (true) { //System.out.println(" cycle upto=" + upto + " arc.label=" + arc.label + " (" + (char) arc.label + ") vs targetLabel=" + targetLabel); if (arc.BytesPerArc != 0 && arc.Label != -1) { // Arcs are fixed array -- use binary search to find // the target. FST<T>.BytesReader @in = Fst.BytesReader; int low = arc.ArcIdx; int high = arc.NumArcs - 1; int mid = 0; //System.out.println("do arc array low=" + low + " high=" + high + " targetLabel=" + targetLabel); bool found = false; while (low <= high) { mid = (int)((uint)(low + high) >> 1); @in.Position = arc.PosArcsStart; @in.SkipBytes(arc.BytesPerArc * mid + 1); int midLabel = Fst.ReadLabel(@in); int cmp = midLabel - targetLabel; //System.out.println(" cycle low=" + low + " high=" + high + " mid=" + mid + " midLabel=" + midLabel + " cmp=" + cmp); if (cmp < 0) { low = mid + 1; } else if (cmp > 0) { high = mid - 1; } else { found = true; break; } } // NOTE: this code is dup'd w/ the code below (in // the outer else clause): if (found) { // Match arc.ArcIdx = mid - 1; Fst.ReadNextRealArc(arc, @in); Debug.Assert(arc.ArcIdx == mid); Debug.Assert(arc.Label == targetLabel, "arc.label=" + arc.Label + " vs targetLabel=" + targetLabel + " mid=" + mid); Output[Upto] = Fst.Outputs.Add(Output[Upto - 1], arc.Output); if (targetLabel == FST<T>.END_LABEL) { return; } CurrentLabel = arc.Label; Incr(); arc = Fst.ReadFirstTargetArc(arc, GetArc(Upto), FstReader); targetLabel = TargetLabel; continue; } else if (low == arc.NumArcs) { // Dead end arc.ArcIdx = arc.NumArcs - 2; Fst.ReadNextRealArc(arc, @in); Debug.Assert(arc.Last); // Dead end (target is after the last arc); // rollback to last fork then push Upto--; while (true) { if (Upto == 0) { return; } FST<T>.Arc<T> prevArc = GetArc(Upto); //System.out.println(" rollback upto=" + upto + " arc.label=" + prevArc.label + " isLast?=" + prevArc.isLast()); if (!prevArc.Last) { Fst.ReadNextArc(prevArc, FstReader); PushFirst(); return; } Upto--; } } else { arc.ArcIdx = (low > high ? low : high) - 1; Fst.ReadNextRealArc(arc, @in); Debug.Assert(arc.Label > targetLabel); PushFirst(); return; } } else { // Arcs are not array'd -- must do linear scan: if (arc.Label == targetLabel) { // recurse Output[Upto] = Fst.Outputs.Add(Output[Upto - 1], arc.Output); if (targetLabel == FST<T>.END_LABEL) { return; } CurrentLabel = arc.Label; Incr(); arc = Fst.ReadFirstTargetArc(arc, GetArc(Upto), FstReader); targetLabel = TargetLabel; } else if (arc.Label > targetLabel) { PushFirst(); return; } else if (arc.Last) { // Dead end (target is after the last arc); // rollback to last fork then push Upto--; while (true) { if (Upto == 0) { return; } FST<T>.Arc<T> prevArc = GetArc(Upto); //System.out.println(" rollback upto=" + upto + " arc.label=" + prevArc.label + " isLast?=" + prevArc.isLast()); if (!prevArc.Last) { Fst.ReadNextArc(prevArc, FstReader); PushFirst(); return; } Upto--; } } else { // keep scanning //System.out.println(" next scan"); Fst.ReadNextArc(arc, FstReader); } } } } // TODO: should we return a status here (SEEK_FOUND / SEEK_NOT_FOUND / // SEEK_END)? saves the eq check above? /// <summary> /// Seeks to largest term that's <= target. </summary> protected internal virtual void DoSeekFloor() { // TODO: possibly caller could/should provide common // prefix length? ie this work may be redundant if // caller is in fact intersecting against its own // automaton //System.out.println("FE: seek floor upto=" + upto); // Save CPU by starting at the end of the shared prefix // b/w our current term & the target: RewindPrefix(); //System.out.println("FE: after rewind upto=" + upto); FST<T>.Arc<T> arc = GetArc(Upto); int targetLabel = TargetLabel; //System.out.println("FE: init targetLabel=" + targetLabel); // Now scan forward, matching the new suffix of the target while (true) { //System.out.println(" cycle upto=" + upto + " arc.label=" + arc.label + " (" + (char) arc.label + ") targetLabel=" + targetLabel + " isLast?=" + arc.isLast() + " bba=" + arc.bytesPerArc); if (arc.BytesPerArc != 0 && arc.Label != FST<T>.END_LABEL) { // Arcs are fixed array -- use binary search to find // the target. FST<T>.BytesReader @in = Fst.BytesReader; int low = arc.ArcIdx; int high = arc.NumArcs - 1; int mid = 0; //System.out.println("do arc array low=" + low + " high=" + high + " targetLabel=" + targetLabel); bool found = false; while (low <= high) { mid = (int)((uint)(low + high) >> 1); @in.Position = arc.PosArcsStart; @in.SkipBytes(arc.BytesPerArc * mid + 1); int midLabel = Fst.ReadLabel(@in); int cmp = midLabel - targetLabel; //System.out.println(" cycle low=" + low + " high=" + high + " mid=" + mid + " midLabel=" + midLabel + " cmp=" + cmp); if (cmp < 0) { low = mid + 1; } else if (cmp > 0) { high = mid - 1; } else { found = true; break; } } // NOTE: this code is dup'd w/ the code below (in // the outer else clause): if (found) { // Match -- recurse //System.out.println(" match! arcIdx=" + mid); arc.ArcIdx = mid - 1; Fst.ReadNextRealArc(arc, @in); Debug.Assert(arc.ArcIdx == mid); Debug.Assert(arc.Label == targetLabel, "arc.label=" + arc.Label + " vs targetLabel=" + targetLabel + " mid=" + mid); Output[Upto] = Fst.Outputs.Add(Output[Upto - 1], arc.Output); if (targetLabel == FST<T>.END_LABEL) { return; } CurrentLabel = arc.Label; Incr(); arc = Fst.ReadFirstTargetArc(arc, GetArc(Upto), FstReader); targetLabel = TargetLabel; continue; } else if (high == -1) { //System.out.println(" before first"); // Very first arc is after our target // TODO: if each arc could somehow read the arc just // before, we can save this re-scan. The ceil case // doesn't need this because it reads the next arc // instead: while (true) { // First, walk backwards until we find a first arc // that's before our target label: Fst.ReadFirstTargetArc(GetArc(Upto - 1), arc, FstReader); if (arc.Label < targetLabel) { // Then, scan forwards to the arc just before // the targetLabel: while (!arc.Last && Fst.ReadNextArcLabel(arc, @in) < targetLabel) { Fst.ReadNextArc(arc, FstReader); } PushLast(); return; } Upto--; if (Upto == 0) { return; } targetLabel = TargetLabel; arc = GetArc(Upto); } } else { // There is a floor arc: arc.ArcIdx = (low > high ? high : low) - 1; //System.out.println(" hasFloor arcIdx=" + (arc.arcIdx+1)); Fst.ReadNextRealArc(arc, @in); Debug.Assert(arc.Last || Fst.ReadNextArcLabel(arc, @in) > targetLabel); Debug.Assert(arc.Label < targetLabel, "arc.label=" + arc.Label + " vs targetLabel=" + targetLabel); PushLast(); return; } } else { if (arc.Label == targetLabel) { // Match -- recurse Output[Upto] = Fst.Outputs.Add(Output[Upto - 1], arc.Output); if (targetLabel == FST<T>.END_LABEL) { return; } CurrentLabel = arc.Label; Incr(); arc = Fst.ReadFirstTargetArc(arc, GetArc(Upto), FstReader); targetLabel = TargetLabel; } else if (arc.Label > targetLabel) { // TODO: if each arc could somehow read the arc just // before, we can save this re-scan. The ceil case // doesn't need this because it reads the next arc // instead: while (true) { // First, walk backwards until we find a first arc // that's before our target label: Fst.ReadFirstTargetArc(GetArc(Upto - 1), arc, FstReader); if (arc.Label < targetLabel) { // Then, scan forwards to the arc just before // the targetLabel: while (!arc.Last && Fst.ReadNextArcLabel(arc, FstReader) < targetLabel) { Fst.ReadNextArc(arc, FstReader); } PushLast(); return; } Upto--; if (Upto == 0) { return; } targetLabel = TargetLabel; arc = GetArc(Upto); } } else if (!arc.Last) { //System.out.println(" check next label=" + fst.readNextArcLabel(arc) + " (" + (char) fst.readNextArcLabel(arc) + ")"); if (Fst.ReadNextArcLabel(arc, FstReader) > targetLabel) { PushLast(); return; } else { // keep scanning Fst.ReadNextArc(arc, FstReader); } } else { PushLast(); return; } } } } /// <summary> /// Seeks to exactly target term. </summary> protected internal virtual bool DoSeekExact() { // TODO: possibly caller could/should provide common // prefix length? ie this work may be redundant if // caller is in fact intersecting against its own // automaton //System.out.println("FE: seek exact upto=" + upto); // Save time by starting at the end of the shared prefix // b/w our current term & the target: RewindPrefix(); //System.out.println("FE: after rewind upto=" + upto); FST<T>.Arc<T> arc = GetArc(Upto - 1); int targetLabel = TargetLabel; FST<T>.BytesReader fstReader = Fst.BytesReader; while (true) { //System.out.println(" cycle target=" + (targetLabel == -1 ? "-1" : (char) targetLabel)); FST<T>.Arc<T> nextArc = Fst.FindTargetArc(targetLabel, arc, GetArc(Upto), fstReader); if (nextArc == null) { // short circuit //upto--; //upto = 0; Fst.ReadFirstTargetArc(arc, GetArc(Upto), fstReader); //System.out.println(" no match upto=" + upto); return false; } // Match -- recurse: Output[Upto] = Fst.Outputs.Add(Output[Upto - 1], nextArc.Output); if (targetLabel == FST<T>.END_LABEL) { //System.out.println(" return found; upto=" + upto + " output=" + output[upto] + " nextArc=" + nextArc.isLast()); return true; } CurrentLabel = targetLabel; Incr(); targetLabel = TargetLabel; arc = nextArc; } } private void Incr() { Upto++; Grow(); if (Arcs.Length <= Upto) { FST<T>.Arc<T>[] newArcs = new FST<T>.Arc<T>[ArrayUtil.Oversize(1 + Upto, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; Array.Copy(Arcs, 0, newArcs, 0, Arcs.Length); Arcs = newArcs; } if (Output.Length <= Upto) { T[] newOutput = new T[ArrayUtil.Oversize(1 + Upto, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; Array.Copy(Output, 0, newOutput, 0, Output.Length); Output = newOutput; } } // Appends current arc, and then recurses from its target, // appending first arc all the way to the final node private void PushFirst() { FST<T>.Arc<T> arc = Arcs[Upto]; Debug.Assert(arc != null); while (true) { Output[Upto] = Fst.Outputs.Add(Output[Upto - 1], arc.Output); if (arc.Label == FST<T>.END_LABEL) { // Final node break; } //System.out.println(" pushFirst label=" + (char) arc.label + " upto=" + upto + " output=" + fst.outputs.outputToString(output[upto])); CurrentLabel = arc.Label; Incr(); FST<T>.Arc<T> nextArc = GetArc(Upto); Fst.ReadFirstTargetArc(arc, nextArc, FstReader); arc = nextArc; } } // Recurses from current arc, appending last arc all the // way to the first final node private void PushLast() { FST<T>.Arc<T> arc = Arcs[Upto]; Debug.Assert(arc != null); while (true) { CurrentLabel = arc.Label; Output[Upto] = Fst.Outputs.Add(Output[Upto - 1], arc.Output); if (arc.Label == FST<T>.END_LABEL) { // Final node break; } Incr(); arc = Fst.ReadLastTargetArc(arc, GetArc(Upto), FstReader); } } private FST<T>.Arc<T> GetArc(int idx) { if (Arcs[idx] == null) { Arcs[idx] = new FST<T>.Arc<T>(); } return Arcs[idx]; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Xml; using System.Xml.Xsl; using System.Xml.XPath; using System.Xml.Serialization; namespace Hydra.Framework.RssToolkit.Rss { /// <summary> /// Helper class /// </summary> public static class RssXmlHelper { private const string TimeZoneCacheKey = "DateTimeParser"; /// <summary> /// Resolves the app relative link to URL. /// </summary> /// <param name="link">The link.</param> /// <returns>string</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings")] public static string ResolveAppRelativeLinkToUrl(string link) { if (string.IsNullOrEmpty(link)) { throw new ArgumentException(string.Format(Resources.RssToolkit.Culture, Resources.RssToolkit.ArgmentException, "link")); } if (!string.IsNullOrEmpty(link) && link.StartsWith("~/")) { HttpContext context = HttpContext.Current; if (context != null) { string query = string.Empty; int iquery = link.IndexOf('?'); if (iquery >= 0) { query = link.Substring(iquery); link = link.Substring(0, iquery); } link = VirtualPathUtility.ToAbsolute(link); link = new Uri(context.Request.Url, link).ToString() + query; } } return link; } /// <summary> /// Deserialize from XML using string reader. /// </summary> /// <param name="xml">The XML.</param> /// <typeparam name="T">RssDocumentBase</typeparam> /// <returns>T</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] public static T DeserializeFromXmlUsingStringReader<T>(string xml) where T : RssDocumentBase { if (string.IsNullOrEmpty(xml)) { throw new ArgumentException(string.Format(Resources.RssToolkit.Culture, Resources.RssToolkit.ArgmentException, "xml")); } XmlSerializer serializer = new XmlSerializer(typeof(T)); using (StringReader reader = new StringReader(xml)) { return (T)serializer.Deserialize(reader); } } /// <summary> /// Returns XML of the Generic Type. /// </summary> /// <param name="rssDocument">The RSS document.</param> /// <typeparam name="T">RssDocumentBase</typeparam> /// <returns>string</returns> public static string ToRssXml<T>(T rssDocument) where T : RssDocumentBase { if (rssDocument == null) { throw new ArgumentNullException("rssDocument"); } using (StringWriter output = new StringWriter(new StringBuilder(), CultureInfo.InvariantCulture)) { XmlSerializer serializer = new XmlSerializer(typeof(T)); serializer.Serialize(output, rssDocument); return output.ToString().Replace("utf-16", "utf-8"); } } /// <summary> /// Gets the type of the document. /// </summary> /// <param name="nodeName">Node StateName</param> /// <returns>RssDocument</returns> public static DocumentType GetDocumentType(string nodeName) { if (string.IsNullOrEmpty(nodeName)) { throw new ArgumentException(string.Format(Resources.RssToolkit.Culture, Resources.RssToolkit.ArgmentException, "nodeName")); } if (nodeName.Equals("rss", StringComparison.OrdinalIgnoreCase)) { return DocumentType.Rss; } else if (nodeName.Equals("opml", StringComparison.OrdinalIgnoreCase)) { return DocumentType.Opml; } else if (nodeName.Equals("feed", StringComparison.OrdinalIgnoreCase)) { return DocumentType.Atom; } else if (nodeName.Equals("rdf", StringComparison.OrdinalIgnoreCase)) { return DocumentType.Rdf; } return DocumentType.Unknown; } /// <summary> /// Converts to RSS XML. /// </summary> /// <param name="input">The input.</param> /// <returns>Xml string in Rss Format</returns> public static string ConvertToRssXml(string input) { using (StringReader stringReader = new StringReader(input)) { using (XmlTextReader reader = new XmlTextReader(stringReader)) { return ConvertToRssXml(reader); } } } /// <summary> /// Converts to RSS XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>Xml string in Rss Format</returns> public static string ConvertToRssXml(XmlReader reader) { if (reader == null) { throw new ArgumentNullException("reader"); } string rssXml = string.Empty; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { DocumentType feedType = RssXmlHelper.GetDocumentType(reader.LocalName); string outerXml = reader.ReadOuterXml(); switch (feedType) { case DocumentType.Rss: rssXml = outerXml; break; case DocumentType.Opml: RssAggregator aggregator = new RssAggregator(); aggregator.Load(outerXml); rssXml = aggregator.RssXml; break; case DocumentType.Atom: rssXml = DoXslTransform(outerXml, GetStreamFromResource(Constants.AtomToRssXsl)); break; case DocumentType.Rdf: rssXml = DoXslTransform(outerXml, GetStreamFromResource(Constants.RdfToRssXsl)); break; } break; } } return rssXml; } /// <summary> /// Gets the data set. /// </summary> /// <value>The data set.</value> /// <param name="xml">XML</param> /// <returns>DataSet</returns> public static DataSet ToDataSet(string xml) { if (string.IsNullOrEmpty(xml)) { throw new ArgumentException(string.Format(Resources.RssToolkit.Culture, Resources.RssToolkit.ArgmentException, "xml")); } DataSet dataset = new DataSet(); dataset.Locale = CultureInfo.InvariantCulture; using (StringReader stringReader = new StringReader(xml)) { dataset.ReadXml(stringReader); } return dataset; } /// <summary> /// Loads the RSS from opml URL. /// </summary> /// <param name="url">The URL.</param> /// <typeparam name="T">RssDocumentBase</typeparam> /// <returns>Generic of RssDocumentBase</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")] public static T LoadRssFromOpmlUrl<T>(string url) where T : RssDocumentBase { if (string.IsNullOrEmpty(url)) { throw new ArgumentException(string.Format(Resources.RssToolkit.Culture, Resources.RssToolkit.ArgmentException, "url")); } // resolve app-relative URLs url = RssXmlHelper.ResolveAppRelativeLinkToUrl(url); RssAggregator aggregator = new RssAggregator(); aggregator.Load(new System.Uri(url)); string rssXml = aggregator.RssXml; return RssXmlHelper.DeserializeFromXmlUsingStringReader<T>(rssXml); } /// <summary> /// Parse is able to parse RFC2822/RFC822 formatted dates. /// It has a fallback mechanism: if the string does not match, /// the normal DateTime.Parse() function is called. /// /// Copyright of RssBandit.org /// Author - t_rendelmann /// </summary> /// <param name="dateTime">Date Time to parse</param> /// <returns>DateTime instance</returns> /// <exception cref="FormatException">On format errors parsing the DateTime</exception> public static DateTime Parse(string dateTime) { DateTime dt = DateTime.Now; Regex rfc2822 = new Regex(@"\s*(?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s*,\s*)?(\d{1,2})\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+(\d{2,})\s+(\d{2})\s*:\s*(\d{2})\s*(?::\s*(\d{2}))?\s+([+\-]\d{4}|UT|GMT|EST|EDT|CST|CDT|MST|MDT|PST|PDT|[A-IK-Z])", RegexOptions.Compiled); ArrayList months = new ArrayList(new string[] { "ZeroIndex", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }); if (dateTime == null) { return DateTime.Now.ToUniversalTime(); } if (dateTime.Trim().Length == 0) { return DateTime.Now.ToUniversalTime(); } Match m = rfc2822.Match(dateTime); if (m.Success) { try { int dd = Int32.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture); int mth = months.IndexOf(m.Groups[2].Value); int yy = Int32.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture); //// following year completion is compliant with RFC 2822. yy = (yy < 50 ? 2000 + yy : (yy < 1000 ? 1900 + yy : yy)); int hh = Int32.Parse(m.Groups[4].Value, CultureInfo.InvariantCulture); int mm = Int32.Parse(m.Groups[5].Value, CultureInfo.InvariantCulture); int ss = Int32.Parse(m.Groups[6].Value, CultureInfo.InvariantCulture); string zone = m.Groups[7].Value; DateTime xd = new DateTime(yy, mth, dd, hh, mm, ss); try { dt = xd.AddHours(RFCTimeZoneToGMTBias(zone) * -1); } catch (Exception) { dt = DateTime.Parse(dateTime); } } catch (FormatException e) { throw new FormatException(string.Format(Resources.RssToolkit.Culture, Resources.RssToolkit.RssText, e.GetType().Name), e); } } else { // fall-back, if regex does not match: try { dt = DateTime.Parse(dateTime, CultureInfo.InvariantCulture); } catch (Exception) { dt = Convert.ToDateTime(dateTime); } } return dt; } /// <summary> /// Converts a DateTime to a valid RFC 2822/822 string /// </summary> /// <param name="dt">The DateTime to convert, recognizes Zulu/GMT</param> /// <returns>Returns the local time in RFC format with the time offset properly appended</returns> public static string ToRfc822(DateTime dt) { string timeZone; if (dt.Kind == DateTimeKind.Utc) { timeZone = "Z"; } else { TimeSpan offset = TimeZone.CurrentTimeZone.GetUtcOffset(dt); if (offset.Ticks < 0) { offset = -offset; timeZone = "-"; } else { timeZone = "+"; } timeZone += offset.Hours.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0'); timeZone += offset.Minutes.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0'); } return dt.ToString("ddd, dd MMM yyyy HH:mm:ss " + timeZone, CultureInfo.InvariantCulture); } /// <summary> /// Does the XSL transform. /// </summary> /// <param name="inputXml">The input XML.</param> /// <param name="xslResource">The XSL resource.</param> /// <returns></returns> public static string DoXslTransform(string inputXml, Stream xslResource) { ///TODO Make the culture an argument using (StringWriter outputWriter = new StringWriter(System.Threading.Thread.CurrentThread.CurrentUICulture)) { using (StringReader stringReader = new StringReader(inputXml)) { XPathDocument xpathDoc = new XPathDocument(stringReader); XslCompiledTransform transform = new XslCompiledTransform(); using (XmlTextReader styleSheetReader = new XmlTextReader(xslResource)) { transform.Load(styleSheetReader); transform.Transform(xpathDoc, null, outputWriter); } } return outputWriter.ToString(); } } /// <summary> /// Changes Time zone based on GMT /// /// Copyright of RssBandit.org /// Author - t_rendelmann /// </summary> /// <param name="zone">The zone.</param> /// <returns>RFCTimeZoneToGMTBias</returns> private static double RFCTimeZoneToGMTBias(string zone) { Dictionary<string, int> timeZones = null; if (HttpContext.Current != null) { timeZones = HttpContext.Current.Cache[TimeZoneCacheKey] as Dictionary<string, int>; } if (timeZones == null) { timeZones = new Dictionary<string, int>(); timeZones.Add("GMT", 0); timeZones.Add("UT", 0); timeZones.Add("EST", -5 * 60); timeZones.Add("EDT", -4 * 60); timeZones.Add("CST", -6 * 60); timeZones.Add("CDT", -5 * 60); timeZones.Add("MST", -7 * 60); timeZones.Add("MDT", -6 * 60); timeZones.Add("PST", -8 * 60); timeZones.Add("PDT", -7 * 60); timeZones.Add("Z", 0); timeZones.Add("A", -1 * 60); timeZones.Add("B", -2 * 60); timeZones.Add("C", -3 * 60); timeZones.Add("D", -4 * 60); timeZones.Add("E", -5 * 60); timeZones.Add("F", -6 * 60); timeZones.Add("G", -7 * 60); timeZones.Add("H", -8 * 60); timeZones.Add("I", -9 * 60); timeZones.Add("K", -10 * 60); timeZones.Add("L", -11 * 60); timeZones.Add("M", -12 * 60); timeZones.Add("N", 1 * 60); timeZones.Add("O", 2 * 60); timeZones.Add("P", 3 * 60); timeZones.Add("Q", 4 * 60); timeZones.Add("R", 3 * 60); timeZones.Add("S", 6 * 60); timeZones.Add("T", 3 * 60); timeZones.Add("U", 8 * 60); timeZones.Add("V", 3 * 60); timeZones.Add("W", 10 * 60); timeZones.Add("X", 3 * 60); timeZones.Add("Y", 12 * 60); if (HttpContext.Current != null) { HttpContext.Current.Cache.Insert(TimeZoneCacheKey, timeZones); } } if (zone.IndexOfAny(new char[] { '+', '-' }) == 0) // +hhmm format { int sign = (zone[0] == '-' ? -1 : 1); string s = zone.Substring(1).TrimEnd(); int hh = Math.Min(23, Int32.Parse(s.Substring(0, 2), CultureInfo.InvariantCulture)); int mm = Math.Min(59, Int32.Parse(s.Substring(2, 2), CultureInfo.InvariantCulture)); return sign * (hh + (mm / 60.0)); } else { // named format string s = zone.ToUpper(CultureInfo.InvariantCulture).Trim(); foreach (string key in timeZones.Keys) { if (key.Equals(s)) { return timeZones[key] / 60.0; } } } return 0.0; } /// <summary> /// Converts the atom to RSS. /// </summary> /// <param name="documentType">Rss Document Type</param> /// <param name="inputXml">The input XML.</param> /// <returns>string</returns> public static string ConvertRssTo(DocumentType ouputType, string rssXml) { if (string.IsNullOrEmpty(rssXml)) { return null; } switch (ouputType) { case DocumentType.Rss: return rssXml; case DocumentType.Atom: using (Stream stream = GetStreamFromResource(Constants.RssToAtomXsl)) { return RssXmlHelper.DoXslTransform(rssXml, stream); } case DocumentType.Rdf: using (Stream stream = GetStreamFromResource(Constants.RssToRdfXsl)) { return RssXmlHelper.DoXslTransform(rssXml, stream); } case DocumentType.Opml: using (Stream stream = GetStreamFromResource(Constants.RssToOpmlXsl)) { return RssXmlHelper.DoXslTransform(rssXml, stream); } default: return null; } } private static Stream GetStreamFromResource(string resourceFileName) { Assembly assembly = Assembly.GetExecutingAssembly(); if (assembly != null) { return assembly.GetManifestResourceStream(resourceFileName); } return null; } } }
namespace YAMP.Io { using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Text; using YAMP.Exceptions; [Description("Loads compatible files into YAMP.")] [Kind(PopularKinds.System)] sealed class LoadFunction : SystemFunction { const Double rfactor = 256 * 256; const Double gfactor = 256; const Double bfactor = 1; public LoadFunction(ParseContext context) : base(context) { } [Description("Loads all variables found in the file, if the file contains YAMP variables. Else it treats the file as an ASCII data table or an image file and stores the content as a matrix with the name \"data\" or \"image\".")] [Example("load(\"myfile.mat\")", "Opens the file myfile.mat and reads out all variables.", true)] public void Function(StringValue filename) { if (!File.Exists(filename.Value)) { throw new YAMPFileNotFoundException(filename.Value); } var error = false; var v = Load(filename.Value, out error); var count = 0; if(!error) { foreach (var key in v.Keys) { Context.AssignVariable(key, v[key]); } count = v.Count; } if (error) { var table = ImageLoad(filename.Value, out error); if (!error) { var suffix = -1; var name = "image"; do { suffix++; } while (Context.Variables.ContainsKey(name + suffix)); Context.AssignVariable(name + suffix, table); count = 1; } } if (error) { var table = ASCIILoad(filename.Value, out error); if (!error) { var suffix = -1; var name = "data"; do { suffix++; } while (Context.Variables.ContainsKey(name + suffix)); Context.AssignVariable(name + suffix, table); count = 1; } } if (error) { throw new YAMPFileFormatNotSupportedException(filename.Value); } Notify(count); } [Description("Tries to load the file as the specified file type.")] [Example("load(\"myfile.mat\", \"binary\")", "Opens the file myfile.mat and reads out all variables.", true)] [Example("load(\"myfile.bmp\", \"image\")", "Opens the image myfile.bmp and transforms the data to a matrix.", true)] [Example("load(\"myfile.txt\", \"text\")", "Opens the textfile myfile.txt converts the data to a matrix.", true)] public void Function(StringValue filename, StringValue filetype) { var type = (FileType)(new YAMP.Converter.StringToEnumConverter(typeof(FileType)).Convert(filetype)); var error = false; var count = 0; switch (type) { case FileType.Text: var table = ASCIILoad(filename.Value, out error); if (!error) { var suffix = -1; var name = "data"; do { suffix++; } while (Context.Variables.ContainsKey(name + suffix)); Context.AssignVariable(name + suffix, table); count = 1; } break; case FileType.Image: var data = ImageLoad(filename.Value, out error); if (!error) { var suffix = -1; var name = "image"; do { suffix++; } while (Context.Variables.ContainsKey(name + suffix)); Context.AssignVariable(name + suffix, data); count = 1; } break; case FileType.Binary: var v = Load(filename.Value, out error); if(!error) { foreach (var key in v.Keys) Context.AssignVariable(key, v[key]); count = v.Count; } break; } if (error) { throw new YAMPFileFormatNotSupportedException(filename.Value); } Notify(count); } [Description("Loads specified variables found in the file, if the file contains YAMP variables. Else it treats the file as an ASCII data table or an image file and stores the content as a matrix with the name of the first variable.")] [Example("load(\"myfile.mat\", \"x\", \"y\", \"z\")", "Opens the file myfile.mat and reads out variables that have been named x, y and z.", true)] [Arguments(1, 1)] public void Function(StringValue filename, ArgumentsValue args) { if (!File.Exists(filename.Value)) throw new YAMPFileNotFoundException(filename.Value); var error = false; var v = Load(filename.Value, out error); var count = 0; if(!error) { foreach (var arg in args.Values) { if (arg is StringValue) { var name = (arg as StringValue).Value; if (v.ContainsKey(name)) { Context.AssignVariable(name, v[name] as Value); count++; } } } } if (error) { var table = ImageLoad(filename.Value, out error); if (!error) { var name = "image"; if (args.Length > 0 && args.Values[0] is StringValue) { name = (args.Values[0] as StringValue).Value; } else { var suffix = -1; do { suffix++; } while (Context.Variables.ContainsKey(name + suffix)); name = name + suffix; } Context.AssignVariable(name, table); count = 1; } } if (error) { var table = ASCIILoad(filename.Value, out error); if (!error) { var name = "data"; if (args.Length > 0 && args.Values[0] is StringValue) { name = (args.Values[0] as StringValue).Value; } else { var suffix = -1; do { suffix++; } while (Context.Variables.ContainsKey(name + suffix)); name = name + suffix; } Context.AssignVariable(name, table); count = 1; } } if (error) { throw new YAMPFileFormatNotSupportedException(filename.Value); } Notify(count); } #region Helpers void Notify(Int32 count) { RaiseNotification(NotificationType.Success, count + " objects loaded."); } static IDictionary<String, Value> Load(String filename, out Boolean error) { var ht = new Dictionary<String, Value>(); var lenbuffer = new Byte[4]; var ctnbuffer = new Byte[0]; error = false; using (var fs = File.Open(filename, FileMode.Open)) { while (fs.Position < fs.Length) { fs.Read(lenbuffer, 0, lenbuffer.Length); var length = BitConverter.ToInt32(lenbuffer, 0); if (fs.Position + length > fs.Length || length < 0) { error = true; break; } ctnbuffer = new Byte[length]; fs.Read(ctnbuffer, 0, ctnbuffer.Length); var name = Encoding.Unicode.GetString(ctnbuffer); fs.Read(lenbuffer, 0, lenbuffer.Length); length = BitConverter.ToInt32(lenbuffer, 0); if (fs.Position + length > fs.Length || length < 0) { error = true; break; } ctnbuffer = new Byte[length]; fs.Read(ctnbuffer, 0, ctnbuffer.Length); var header = Encoding.ASCII.GetString(ctnbuffer); fs.Read(lenbuffer, 0, lenbuffer.Length); length = BitConverter.ToInt32(lenbuffer, 0); if (fs.Position + length > fs.Length || length < 0) { error = true; break; } ctnbuffer = new Byte[length]; fs.Read(ctnbuffer, 0, ctnbuffer.Length); var value = Value.Deserialize(header, ctnbuffer); ht.Add(name, value); } } if (error) { ht.Add("FileParsingError", Value.Empty); } return ht; } MatrixValue ASCIILoad(String filename, out Boolean error) { error = false; using (var fs = File.Open(filename, FileMode.Open)) { var file_bytes = new Byte[fs.Length]; fs.Read(file_bytes, 0, file_bytes.Length); var file_string = Encoding.ASCII.GetString(file_bytes); var lines = file_string.Split('\n').Select(line => line.Split(new [] { ' ', '\t', ',', '\r' }, StringSplitOptions.RemoveEmptyEntries)).ToList(); var numberOfLines = lines.Count; var parseResult = 0.0; var numberOfHeaderLines = 0; var numberOfFooterLines = 0; while (numberOfHeaderLines < numberOfLines && !Double.TryParse(lines[numberOfHeaderLines].FirstOrDefault(), out parseResult)) { numberOfHeaderLines++; } while (numberOfFooterLines < numberOfLines - numberOfHeaderLines && !Double.TryParse(lines[numberOfLines - 1 - numberOfFooterLines].FirstOrDefault(), out parseResult)) { numberOfFooterLines++; } if (numberOfLines <= numberOfHeaderLines + numberOfFooterLines) { error = true; return new MatrixValue(); } var tokensPerLine = lines.Select(line => line.Length).SkipWhile((item, index) => index < numberOfHeaderLines).Reverse().SkipWhile((item, index) => index < numberOfFooterLines).Reverse().ToList(); var numberOfColumns = tokensPerLine.Max(); var numberOfRows = numberOfLines - numberOfHeaderLines - numberOfFooterLines; var result = new MatrixValue(numberOfRows, numberOfColumns); for (var i = 0; i < numberOfRows; i++) { for (var j = 0; j < tokensPerLine[i]; j++) { if (Double.TryParse(lines[numberOfHeaderLines + i][j], NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture.NumberFormat, out parseResult)) { result[i + 1, j + 1] = new ScalarValue(parseResult); } else { result[i + 1, j + 1] = new ScalarValue(Double.NaN); } } } return result; } } MatrixValue ImageLoad(String filename, out Boolean error, Double coarsening = Double.NaN) { error = false; var imageType = String.Empty; using (var fs = File.Open(filename, FileMode.Open)) { var file_bytes = new Byte[fs.Length]; fs.Read(file_bytes, 0, 8); var png_magic_number = new Byte[] { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a }; if (!file_bytes.Take(8).Select((b, i) => b == png_magic_number[i]).Contains(false)) imageType = "png"; var tiff_magic_number_0 = new Byte[] { 0x49, 0x49, 0x2a, 0x00 }; if (!file_bytes.Take(4).Select((b, i) => b == tiff_magic_number_0[i]).Contains(false)) imageType = "tiff"; var tiff_magic_number_1 = new Byte[] { 0x4d, 0x4d, 0x2a, 0x00 }; if (!file_bytes.Take(4).Select((b, i) => b == tiff_magic_number_1[i]).Contains(false)) imageType = "tiff"; var bmp_magic_number = new Byte[] { 0x42, 0x4D }; if (!file_bytes.Take(2).Select((b, i) => b == bmp_magic_number[i]).Contains(false)) imageType = "bmp"; var gif_magic_number_0 = new Byte[] { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 }; if (!file_bytes.Take(6).Select((b, i) => b == gif_magic_number_0[i]).Contains(false)) imageType = "gif"; var gif_magic_number_1 = new Byte[] { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 }; if (!file_bytes.Take(6).Select((b, i) => b == gif_magic_number_1[i]).Contains(false)) imageType = "gif"; var jpg_magic_number = new Byte[] { 0xff, 0xd8 }; if (!file_bytes.Take(2).Select((b, i) => b == jpg_magic_number[i]).Contains(false)) imageType = "jpg"; } if (imageType == String.Empty) { error = true; return new MatrixValue(); } using (var bmp = new Bitmap(filename)) { var result = default(MatrixValue); if (bmp == null) { error = true; result = new MatrixValue(); } else { var height = bmp.Height; var width = bmp.Width; var rect = new Rectangle(0, 0, bmp.Width, bmp.Height); var bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat); var ptr = bmpData.Scan0; var bytes = Math.Abs(bmpData.Stride) * bmp.Height; var rgbValues = new Byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); bmp.UnlockBits(bmpData); var bytesPerPixel = 0; if (bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Canonical || bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb || bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppPArgb || bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppRgb) { bytesPerPixel = 4; } else if (bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb) { bytesPerPixel = 3; } else { throw new YAMPPixelFormatNotSupportedException(filename); } if (Double.IsNaN(coarsening)) { const Double maxPixelPerDirection = 100.0; if (width > maxPixelPerDirection || height > maxPixelPerDirection) { coarsening = Math.Max(width / maxPixelPerDirection, height / maxPixelPerDirection); } else { coarsening = 1.0; } } if (coarsening < 1.0) { throw new YAMPArgumentInvalidException("Load", "ImageCoarsening"); } var cI = 1.0 / coarsening; var finalWidth = (Int32)(width * cI); var finalHeight = (Int32)(height * cI); var count = new Byte[finalHeight, finalWidth]; var rvalues = new Double[finalHeight, finalWidth]; var gvalues = new Double[finalHeight, finalWidth]; var bvalues = new Double[finalHeight, finalWidth]; for (var i = 0; i < width; i++) { var idx = (Int32)(i * cI); if (idx >= finalWidth) { idx = finalWidth - 1; } for (var j = 0; j < height; j++) { var jdx = (Int32)(j * cI); if (jdx >= finalHeight) { jdx = finalHeight - 1; } rvalues[jdx, idx] += rgbValues[(j * width + i) * bytesPerPixel + 2]; gvalues[jdx, idx] += rgbValues[(j * width + i) * bytesPerPixel + 1]; bvalues[jdx, idx] += rgbValues[(j * width + i) * bytesPerPixel + 0]; count[jdx, idx]++; } } for (var i = 0; i < finalHeight; i++) { for (var j = 0; j < finalWidth; j++) { var cinv = 1.0 / count[i, j]; rvalues[i, j] *= cinv; gvalues[i, j] *= cinv; bvalues[i, j] *= cinv; } } for (var i = 0; i < finalHeight; i++) { for (var j = 0; j < finalWidth; j++) { rvalues[i, j] = (Int32)rvalues[i, j]; gvalues[i, j] = (Int32)gvalues[i, j]; bvalues[i, j] = (Int32)bvalues[i, j]; rvalues[i, j] *= rfactor; gvalues[i, j] *= gfactor; bvalues[i, j] *= bfactor; rvalues[i, j] += gvalues[i, j] + bvalues[i, j]; } } return new MatrixValue(rvalues); } return result; } } //TODO This will MOST probably be cleaned up in future released... //Possible Changes: extract all the files to special YAMP File Types and include //Methods like Detect() and Extract() for investigating if a certain file //has a specific structure. //Probably also replace the dependency of System.Drawing with custom routines... //This, however, could be too much. enum FileType { Binary, Text, Image } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using System.Xml; using Tao.OpenGl; using Tao.Platform.Windows; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenMetaverse.Rendering; namespace AvatarPreview { public partial class frmAvatar : Form { GridClient _client = new GridClient(); Dictionary<string, GLMesh> _meshes = new Dictionary<string, GLMesh>(); bool _wireframe = true; bool _showSkirt = false; public frmAvatar() { InitializeComponent(); glControl.InitializeContexts(); Gl.glShadeModel(Gl.GL_SMOOTH); Gl.glClearColor(0f, 0f, 0f, 0f); Gl.glClearDepth(1.0f); Gl.glEnable(Gl.GL_DEPTH_TEST); Gl.glDepthMask(Gl.GL_TRUE); Gl.glDepthFunc(Gl.GL_LEQUAL); Gl.glHint(Gl.GL_PERSPECTIVE_CORRECTION_HINT, Gl.GL_NICEST); glControl_Resize(null, null); } private void lindenLabMeshToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "avatar_lad.xml|avatar_lad.xml"; if (dialog.ShowDialog() == DialogResult.OK) { _meshes.Clear(); try { // Parse through avatar_lad.xml to find all of the mesh references XmlDocument lad = new XmlDocument(); lad.Load(dialog.FileName); XmlNodeList meshes = lad.GetElementsByTagName("mesh"); foreach (XmlNode meshNode in meshes) { string type = meshNode.Attributes.GetNamedItem("type").Value; int lod = Int32.Parse(meshNode.Attributes.GetNamedItem("lod").Value); string fileName = meshNode.Attributes.GetNamedItem("file_name").Value; string minPixelWidth = meshNode.Attributes.GetNamedItem("min_pixel_width").Value; // Mash up the filename with the current path fileName = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(dialog.FileName), fileName); GLMesh mesh = (_meshes.ContainsKey(type) ? _meshes[type] : new GLMesh(type)); if (lod == 0) { mesh.LoadMesh(fileName); } else { mesh.LoadLODMesh(lod, fileName); } _meshes[type] = mesh; glControl_Resize(null, null); glControl.Invalidate(); } } catch (Exception ex) { MessageBox.Show("Failed to load avatar mesh: " + ex.Message); } } } private void textureToolStripMenuItem_Click(object sender, EventArgs e) { } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { } private void wireframeToolStripMenuItem_Click(object sender, EventArgs e) { wireframeToolStripMenuItem.Checked = !wireframeToolStripMenuItem.Checked; _wireframe = wireframeToolStripMenuItem.Checked; glControl.Invalidate(); } private void skirtToolStripMenuItem_Click(object sender, EventArgs e) { skirtToolStripMenuItem.Checked = !skirtToolStripMenuItem.Checked; _showSkirt = skirtToolStripMenuItem.Checked; glControl.Invalidate(); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show( "Written by John Hurliman <jhurliman@jhurliman.org> (http://www.jhurliman.org/)"); } private void glControl_Paint(object sender, PaintEventArgs e) { Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_DEPTH_BUFFER_BIT); Gl.glLoadIdentity(); // Setup wireframe or solid fill drawing mode if (_wireframe) Gl.glPolygonMode(Gl.GL_FRONT_AND_BACK, Gl.GL_LINE); else Gl.glPolygonMode(Gl.GL_FRONT, Gl.GL_FILL); // Push the world matrix Gl.glPushMatrix(); Gl.glEnableClientState(Gl.GL_VERTEX_ARRAY); Gl.glEnableClientState(Gl.GL_TEXTURE_COORD_ARRAY); // World rotations Gl.glRotatef((float)scrollRoll.Value, 1f, 0f, 0f); Gl.glRotatef((float)scrollPitch.Value, 0f, 1f, 0f); Gl.glRotatef((float)scrollYaw.Value, 0f, 0f, 1f); if (_meshes.Count > 0) { foreach (GLMesh mesh in _meshes.Values) { if (!_showSkirt && mesh.Name == "skirtMesh") continue; Gl.glColor3f(1f, 1f, 1f); // Individual prim matrix Gl.glPushMatrix(); //Gl.glTranslatef(mesh.Position.X, mesh.Position.Y, mesh.Position.Z); Gl.glRotatef(mesh.RotationAngles.X, 1f, 0f, 0f); Gl.glRotatef(mesh.RotationAngles.Y, 0f, 1f, 0f); Gl.glRotatef(mesh.RotationAngles.Z, 0f, 0f, 1f); Gl.glScalef(mesh.Scale.X, mesh.Scale.Y, mesh.Scale.Z); // TODO: Texturing Gl.glTexCoordPointer(2, Gl.GL_FLOAT, 0, mesh.RenderData.TexCoords); Gl.glVertexPointer(3, Gl.GL_FLOAT, 0, mesh.RenderData.Vertices); Gl.glDrawElements(Gl.GL_TRIANGLES, mesh.RenderData.Indices.Length, Gl.GL_UNSIGNED_SHORT, mesh.RenderData.Indices); } } // Pop the world matrix Gl.glPopMatrix(); Gl.glDisableClientState(Gl.GL_TEXTURE_COORD_ARRAY); Gl.glDisableClientState(Gl.GL_VERTEX_ARRAY); Gl.glFlush(); } private void glControl_Resize(object sender, EventArgs e) { //Gl.glClearColor(0.39f, 0.58f, 0.93f, 1.0f); // Cornflower blue anyone? Gl.glClearColor(0f, 0f, 0f, 1f); Gl.glPushMatrix(); Gl.glMatrixMode(Gl.GL_PROJECTION); Gl.glLoadIdentity(); Gl.glViewport(0, 0, glControl.Width, glControl.Height); Glu.gluPerspective(50.0d, 1.0d, 0.001d, 50d); Vector3 center = Vector3.Zero; GLMesh head, lowerBody; if (_meshes.TryGetValue("headMesh", out head) && _meshes.TryGetValue("lowerBodyMesh", out lowerBody)) center = (head.RenderData.Center + lowerBody.RenderData.Center) / 2f; Glu.gluLookAt( center.X, (double)scrollZoom.Value * 0.1d + center.Y, center.Z, center.X, (double)scrollZoom.Value * 0.1d + center.Y + 1d, center.Z, 0d, 0d, 1d); Gl.glMatrixMode(Gl.GL_MODELVIEW); } private void scroll_ValueChanged(object sender, EventArgs e) { glControl_Resize(null, null); glControl.Invalidate(); } private void pic_MouseClick(object sender, MouseEventArgs e) { PictureBox control = (PictureBox)sender; OpenFileDialog dialog = new OpenFileDialog(); // TODO: Setup a dialog.Filter for supported image types if (dialog.ShowDialog() == DialogResult.OK) { try { System.Drawing.Image image = System.Drawing.Image.FromFile(dialog.FileName); #region Dimensions Check if (control == picEyesBake) { // Eyes texture is 128x128 if (Width != 128 || Height != 128) { Bitmap resized = new Bitmap(128, 128, image.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(image, 0, 0, 128, 128); image.Dispose(); image = resized; } } else { // Other textures are 512x512 if (Width != 128 || Height != 128) { Bitmap resized = new Bitmap(512, 512, image.PixelFormat); Graphics graphics = Graphics.FromImage(resized); graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(image, 0, 0, 512, 512); image.Dispose(); image = resized; } } #endregion Dimensions Check // Set the control image control.Image = image; } catch (Exception ex) { MessageBox.Show("Failed to load image: " + ex.Message); } } else { control.Image = null; } #region Baking Dictionary<int, float> paramValues = GetParamValues(); Dictionary<AppearanceManager.TextureIndex, AssetTexture> layers = new Dictionary<AppearanceManager.TextureIndex, AssetTexture>(); int textureCount = 0; if ((string)control.Tag == "Head") { if (picHair.Image != null) { layers.Add(AppearanceManager.TextureIndex.Hair, new AssetTexture(new ManagedImage((Bitmap)picHair.Image))); ++textureCount; } if (picHeadBodypaint.Image != null) { layers.Add(AppearanceManager.TextureIndex.HeadBodypaint, new AssetTexture(new ManagedImage((Bitmap)picHeadBodypaint.Image))); ++textureCount; } // Compute the head bake Baker baker = new Baker( _client, AppearanceManager.BakeType.Head, textureCount, paramValues); foreach (KeyValuePair<AppearanceManager.TextureIndex, AssetTexture> kvp in layers) baker.AddTexture(kvp.Key, kvp.Value, false); if (baker.BakedTexture != null) { AssetTexture bakeAsset = baker.BakedTexture; // Baked textures use the alpha layer for other purposes, so we need to not use it bakeAsset.Image.Channels = ManagedImage.ImageChannels.Color; picHeadBake.Image = LoadTGAClass.LoadTGA(new MemoryStream(bakeAsset.Image.ExportTGA())); } else { MessageBox.Show("Failed to create the bake layer, unknown error"); } } else if ((string)control.Tag == "Upper") { if (picUpperBodypaint.Image != null) { layers.Add(AppearanceManager.TextureIndex.UpperBodypaint, new AssetTexture(new ManagedImage((Bitmap)picUpperBodypaint.Image))); ++textureCount; } if (picUpperGloves.Image != null) { layers.Add(AppearanceManager.TextureIndex.UpperGloves, new AssetTexture(new ManagedImage((Bitmap)picUpperGloves.Image))); ++textureCount; } if (picUpperUndershirt.Image != null) { layers.Add(AppearanceManager.TextureIndex.UpperUndershirt, new AssetTexture(new ManagedImage((Bitmap)picUpperUndershirt.Image))); ++textureCount; } if (picUpperShirt.Image != null) { layers.Add(AppearanceManager.TextureIndex.UpperShirt, new AssetTexture(new ManagedImage((Bitmap)picUpperShirt.Image))); ++textureCount; } if (picUpperJacket.Image != null) { layers.Add(AppearanceManager.TextureIndex.UpperJacket, new AssetTexture(new ManagedImage((Bitmap)picUpperJacket.Image))); ++textureCount; } // Compute the upper body bake Baker baker = new Baker( _client, AppearanceManager.BakeType.UpperBody, textureCount, paramValues); foreach (KeyValuePair<AppearanceManager.TextureIndex, AssetTexture> kvp in layers) baker.AddTexture(kvp.Key, kvp.Value, false); if (baker.BakedTexture != null) { AssetTexture bakeAsset = baker.BakedTexture; // Baked textures use the alpha layer for other purposes, so we need to not use it bakeAsset.Image.Channels = ManagedImage.ImageChannels.Color; picUpperBodyBake.Image = LoadTGAClass.LoadTGA(new MemoryStream(bakeAsset.Image.ExportTGA())); } else { MessageBox.Show("Failed to create the bake layer, unknown error"); } } else if ((string)control.Tag == "Lower") { if (picLowerBodypaint.Image != null) { layers.Add(AppearanceManager.TextureIndex.LowerBodypaint, new AssetTexture(new ManagedImage((Bitmap)picLowerBodypaint.Image))); ++textureCount; } if (picLowerUnderpants.Image != null) { layers.Add(AppearanceManager.TextureIndex.LowerUnderpants, new AssetTexture(new ManagedImage((Bitmap)picLowerUnderpants.Image))); ++textureCount; } if (picLowerSocks.Image != null) { layers.Add(AppearanceManager.TextureIndex.LowerSocks, new AssetTexture(new ManagedImage((Bitmap)picLowerSocks.Image))); ++textureCount; } if (picLowerShoes.Image != null) { layers.Add(AppearanceManager.TextureIndex.LowerShoes, new AssetTexture(new ManagedImage((Bitmap)picLowerShoes.Image))); ++textureCount; } if (picLowerPants.Image != null) { layers.Add(AppearanceManager.TextureIndex.LowerPants, new AssetTexture(new ManagedImage((Bitmap)picLowerPants.Image))); ++textureCount; } // Compute the lower body bake Baker baker = new Baker( _client, AppearanceManager.BakeType.LowerBody, textureCount, paramValues); foreach (KeyValuePair<AppearanceManager.TextureIndex, AssetTexture> kvp in layers) baker.AddTexture(kvp.Key, kvp.Value, false); if (baker.BakedTexture != null) { AssetTexture bakeAsset = baker.BakedTexture; // Baked textures use the alpha layer for other purposes, so we need to not use it bakeAsset.Image.Channels = ManagedImage.ImageChannels.Color; picLowerBodyBake.Image = LoadTGAClass.LoadTGA(new MemoryStream(bakeAsset.Image.ExportTGA())); } else { MessageBox.Show("Failed to create the bake layer, unknown error"); } } else if ((string)control.Tag == "Bake") { // Bake image has been set manually, no need to manually calculate a bake // FIXME: } #endregion Baking } private Dictionary<int, float> GetParamValues() { Dictionary<int, float> paramValues = new Dictionary<int, float>(VisualParams.Params.Count); foreach (KeyValuePair<int, VisualParam> kvp in VisualParams.Params) { VisualParam vp = kvp.Value; paramValues.Add(vp.ParamID, vp.DefaultValue); } return paramValues; } private static System.Drawing.Image ConvertToRGB(System.Drawing.Image image) { int width = image.Width; int height = image.Height; Bitmap noAlpha = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb); Graphics graphics = Graphics.FromImage(noAlpha); graphics.DrawImage(image, 0, 0, width, height); return noAlpha; } private static bool IsPowerOfTwo(uint n) { return (n & (n - 1)) == 0 && n != 0; } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace ServerSideCSOMWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted add-in. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; using System.Security.Cryptography.X509Certificates; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { /// <summary> /// Defines the base class from which all signature commands /// are derived. /// </summary> public abstract class SignatureCommandsBase : PSCmdlet { /// <summary> /// Gets or sets the path to the file for which to get or set the /// digital signature. /// </summary> [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] public string[] FilePath { get { return _path; } set { _path = value; } } private string[] _path; /// <summary> /// Gets or sets the literal path to the file for which to get or set the /// digital signature. /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] [Alias("PSPath")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] LiteralPath { get { return _path; } set { _path = value; _isLiteralPath = true; } } private bool _isLiteralPath = false; /// <summary> /// Gets or sets the digital signature to be written to /// the output pipeline. /// </summary> protected Signature Signature { get { return _signature; } set { _signature = value; } } private Signature _signature; /// <summary> /// Gets or sets the file type of the byte array containing the content with /// digital signature. /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByContent")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] SourcePathOrExtension { get { return _sourcePathOrExtension; } set { _sourcePathOrExtension = value; } } private string[] _sourcePathOrExtension; /// <summary> /// File contents as a byte array. /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByContent")] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public byte[] Content { get { return _content; } set { _content = value; } } private byte[] _content; // // name of this command // private readonly string _commandName; /// <summary> /// Initializes a new instance of the SignatureCommandsBase class, /// using the given command name. /// </summary> /// <param name="name"> /// The name of the command. /// </param> protected SignatureCommandsBase(string name) : base() { _commandName = name; } // // hide default ctor // private SignatureCommandsBase() : base() { } /// <summary> /// Processes records from the input pipeline. /// For each input object, the command gets or /// sets the digital signature on the object, and /// and exports the object. /// </summary> protected override void ProcessRecord() { if (Content == null) { // // this cannot happen as we have specified the Path // property to be mandatory parameter // Dbg.Assert((FilePath != null) && (FilePath.Length > 0), "GetSignatureCommand: Param binder did not bind path"); foreach (string p in FilePath) { Collection<string> paths = new(); // Expand wildcard characters if (_isLiteralPath) { paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p)); } else { try { foreach (PathInfo tempPath in SessionState.Path.GetResolvedPSPathFromPSPath(p)) { paths.Add(tempPath.ProviderPath); } } catch (ItemNotFoundException) { WriteError( SecurityUtils.CreateFileNotFoundErrorRecord( SignatureCommands.FileNotFound, "SignatureCommandsBaseFileNotFound", p)); } } if (paths.Count == 0) continue; bool foundFile = false; foreach (string path in paths) { if (!System.IO.Directory.Exists(path)) { foundFile = true; string resolvedFilePath = SecurityUtils.GetFilePathOfExistingFile(this, path); if (resolvedFilePath == null) { WriteError(SecurityUtils.CreateFileNotFoundErrorRecord( SignatureCommands.FileNotFound, "SignatureCommandsBaseFileNotFound", path)); } else { if ((Signature = PerformAction(resolvedFilePath)) != null) { WriteObject(Signature); } } } } if (!foundFile) { WriteError(SecurityUtils.CreateFileNotFoundErrorRecord( SignatureCommands.CannotRetrieveFromContainer, "SignatureCommandsBaseCannotRetrieveFromContainer")); } } } else { foreach (string sourcePathOrExtension in SourcePathOrExtension) { if ((Signature = PerformAction(sourcePathOrExtension, Content)) != null) { WriteObject(Signature); } } } } /// <summary> /// Performs the action (ie: get signature, or set signature) /// on the specified file. /// </summary> /// <param name="filePath"> /// The name of the file on which to perform the action. /// </param> protected abstract Signature PerformAction(string filePath); /// <summary> /// Performs the action (ie: get signature, or set signature) /// on the specified contents. /// </summary> /// <param name="fileName"> /// The filename used for type if content is specified. /// </param> /// <param name="content"> /// The file contents on which to perform the action. /// </param> protected abstract Signature PerformAction(string fileName, byte[] content); } /// <summary> /// Defines the implementation of the 'get-AuthenticodeSignature' cmdlet. /// This cmdlet extracts the digital signature from the given file. /// </summary> [Cmdlet(VerbsCommon.Get, "AuthenticodeSignature", DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096823")] [OutputType(typeof(Signature))] public sealed class GetAuthenticodeSignatureCommand : SignatureCommandsBase { /// <summary> /// Initializes a new instance of the GetSignatureCommand class. /// </summary> public GetAuthenticodeSignatureCommand() : base("Get-AuthenticodeSignature") { } /// <summary> /// Gets the signature from the specified file. /// </summary> /// <param name="filePath"> /// The name of the file on which to perform the action. /// </param> /// <returns> /// The signature on the specified file. /// </returns> protected override Signature PerformAction(string filePath) { return SignatureHelper.GetSignature(filePath, null); } /// <summary> /// Gets the signature from the specified file contents. /// </summary> /// <param name="sourcePathOrExtension">The file type associated with the contents.</param> /// <param name="content"> /// The contents of the file on which to perform the action. /// </param> /// <returns> /// The signature on the specified file contents. /// </returns> protected override Signature PerformAction(string sourcePathOrExtension, byte[] content) { return SignatureHelper.GetSignature(sourcePathOrExtension, System.Text.Encoding.Unicode.GetString(content)); } } /// <summary> /// Defines the implementation of the 'set-AuthenticodeSignature' cmdlet. /// This cmdlet sets the digital signature on a given file. /// </summary> [Cmdlet(VerbsCommon.Set, "AuthenticodeSignature", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096919")] [OutputType(typeof(Signature))] public sealed class SetAuthenticodeSignatureCommand : SignatureCommandsBase { /// <summary> /// Initializes a new instance of the SetAuthenticodeSignatureCommand class. /// </summary> public SetAuthenticodeSignatureCommand() : base("set-AuthenticodeSignature") { } /// <summary> /// Gets or sets the certificate with which to sign the /// file. /// </summary> [Parameter(Position = 1, Mandatory = true)] public X509Certificate2 Certificate { get { return _certificate; } set { _certificate = value; } } private X509Certificate2 _certificate; /// <summary> /// Gets or sets the additional certificates to /// include in the digital signature. /// Use 'signer' to include only the signer's certificate. /// Use 'notroot' to include all certificates in the certificate /// chain, except for the root authority. /// Use 'all' to include all certificates in the certificate chain. /// /// Defaults to 'notroot'. /// </summary> [Parameter(Mandatory = false)] [ValidateSet("signer", "notroot", "all")] public string IncludeChain { get { return _includeChain; } set { _includeChain = value; } } private string _includeChain = "notroot"; /// <summary> /// Gets or sets the Url of the time stamping server. /// The time stamping server certifies the exact time /// that the certificate was added to the file. /// </summary> [Parameter(Mandatory = false)] public string TimestampServer { get { return _timestampServer; } set { if (value == null) { value = string.Empty; } _timestampServer = value; } } private string _timestampServer = string.Empty; /// <summary> /// Gets or sets the hash algorithm used for signing. /// This string value must represent the name of a Cryptographic Algorithm /// Identifier supported by Windows. /// </summary> [Parameter(Mandatory = false)] public string HashAlgorithm { get { return _hashAlgorithm; } set { _hashAlgorithm = value; } } private string _hashAlgorithm = null; /// <summary> /// Property that sets force parameter. /// </summary> [Parameter()] public SwitchParameter Force { get { return _force; } set { _force = value; } } private bool _force; /// <summary> /// Sets the digital signature on the specified file. /// </summary> /// <param name="filePath"> /// The name of the file on which to perform the action. /// </param> /// <returns> /// The signature on the specified file. /// </returns> protected override Signature PerformAction(string filePath) { SigningOption option = GetSigningOption(IncludeChain); if (Certificate == null) { throw PSTraceSource.NewArgumentNullException("certificate"); } // // if the cert is not good for signing, we cannot // process any more files. Exit the command. // if (!SecuritySupport.CertIsGoodForSigning(Certificate)) { Exception e = PSTraceSource.NewArgumentException( "certificate", SignatureCommands.CertNotGoodForSigning); throw e; } if (!ShouldProcess(filePath)) return null; FileInfo readOnlyFileInfo = null; try { if (this.Force) { try { // remove readonly attributes on the file FileInfo fInfo = new(filePath); if (fInfo != null) { // Save some disk write time by checking whether file is readonly.. if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { // remember to reset the read-only attribute later readOnlyFileInfo = fInfo; // Make sure the file is not read only fInfo.Attributes &= ~(FileAttributes.ReadOnly); } } } // These are the known exceptions for File.Load and StreamWriter.ctor catch (ArgumentException e) { ErrorRecord er = new( e, "ForceArgumentException", ErrorCategory.WriteError, filePath); WriteError(er); return null; } catch (IOException e) { ErrorRecord er = new( e, "ForceIOException", ErrorCategory.WriteError, filePath); WriteError(er); return null; } catch (UnauthorizedAccessException e) { ErrorRecord er = new( e, "ForceUnauthorizedAccessException", ErrorCategory.PermissionDenied, filePath); WriteError(er); return null; } catch (NotSupportedException e) { ErrorRecord er = new( e, "ForceNotSupportedException", ErrorCategory.WriteError, filePath); WriteError(er); return null; } catch (System.Security.SecurityException e) { ErrorRecord er = new( e, "ForceSecurityException", ErrorCategory.PermissionDenied, filePath); WriteError(er); return null; } } // // ProcessRecord() code in base class has already // ascertained that filePath really represents an existing // file. Thus we can safely call GetFileSize() below. // if (SecurityUtils.GetFileSize(filePath) < 4) { // Note that the message param comes first string message = string.Format( System.Globalization.CultureInfo.CurrentCulture, UtilsStrings.FileSmallerThan4Bytes, filePath); PSArgumentException e = new(message, nameof(filePath)); ErrorRecord er = SecurityUtils.CreateInvalidArgumentErrorRecord( e, "SignatureCommandsBaseFileSmallerThan4Bytes" ); WriteError(er); return null; } return SignatureHelper.SignFile(option, filePath, Certificate, TimestampServer, _hashAlgorithm); } finally { // reset the read-only attribute if (readOnlyFileInfo != null) { readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; } } } /// <summary> /// Not implemented. /// </summary> protected override Signature PerformAction(string sourcePathOrExtension, byte[] content) { throw new NotImplementedException(); } private struct SigningOptionInfo { internal SigningOption option; internal string optionName; internal SigningOptionInfo(SigningOption o, string n) { option = o; optionName = n; } } /// <summary> /// Association between SigningOption.* values and the /// corresponding string names. /// </summary> private static readonly SigningOptionInfo[] s_sigOptionInfo = { new SigningOptionInfo(SigningOption.AddOnlyCertificate, "signer"), new SigningOptionInfo(SigningOption.AddFullCertificateChainExceptRoot, "notroot"), new SigningOptionInfo(SigningOption.AddFullCertificateChain, "all") }; /// <summary> /// Get SigningOption value corresponding to a string name. /// </summary> /// <param name="optionName">Name of option.</param> /// <returns>SigningOption.</returns> private static SigningOption GetSigningOption(string optionName) { foreach (SigningOptionInfo si in s_sigOptionInfo) { if (string.Equals(optionName, si.optionName, StringComparison.OrdinalIgnoreCase)) { return si.option; } } return SigningOption.AddFullCertificateChainExceptRoot; } } }
// PCB-Investigator Automation Script // Created on 2016-02-17 // Autor support@easylogix.de // www.pcb-investigator.com // SDK online reference http://www.pcb-investigator.com/sites/default/files/documents/InterfaceDocumentation/Index.html // SDK http://www.pcb-investigator.com/en/sdk-participate // Split Drills depending on attributes. //----------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; using PCBI.Plugin; using PCBI.Plugin.Interfaces; using System.Windows.Forms; using System.Drawing; using PCBI.Automation; using System.IO; using System.Drawing.Drawing2D; using PCBI.MathUtils; using System.Reflection; namespace PCBIScript { public class PScript : IPCBIScript { public PScript() { } public void Execute(IPCBIWindow parent) { bool withRoutChecked = true; SplitDrillWorker worker = new SplitDrillWorker(); worker.doWork(parent, withRoutChecked, false); } class SplitDrillWorker { List<IODBObject> drill_ = new List<IODBObject>(); List<IODBObject> drillPlatedNormal = new List<IODBObject>(); List<IODBObject> drillNonPlatedNormal = new List<IODBObject>(); List<IODBObject> drillViaNormal = new List<IODBObject>(); List<IODBObject> drillRout = new List<IODBObject>(); List<IODBObject> drillPlatedRout = new List<IODBObject>(); List<IODBObject> drillNonPlatedRout = new List<IODBObject>(); List<IODBObject> drillViaRout = new List<IODBObject>(); bool withRout = false; bool activateNewCreatedLayer = false; bool skipLayerWasAlreadySplitted = false; bool noAttributesPadsLayerNameCreated = false; bool noAttributesNotPadsLayerNameCreated = false; bool platedLayerNameCreatedRout = false; bool nonPlatedLayerNameCreatedRout = false; bool viaLayerNameCreatedRout = false; bool platedLayerNameCreatedNormal = false; bool nonPlatedLayerNameCreatedNormal = false; bool viaLayerNameCreatedNormal = false; internal void doWork(IPCBIWindow parent, bool splitRoutItem, bool activateNewLayer) { IStep step = parent.GetCurrentStep(); IMatrix matrix = parent.GetMatrix(); IFilter filter = new IFilter(parent); //if true the new layer need to be activated activateNewCreatedLayer = activateNewLayer; //sets the bool if rout should be used withRout = splitRoutItem; foreach (string currLayerName in matrix.GetAllDrillLayerNames()) { Dictionary<string, List<IODBObject>> allNewLayerDict = new Dictionary<string, List<IODBObject>>(); drill_ = new List<IODBObject>(); drillPlatedNormal = new List<IODBObject>(); drillNonPlatedNormal = new List<IODBObject>(); drillViaNormal = new List<IODBObject>(); drillRout = new List<IODBObject>(); drillPlatedRout = new List<IODBObject>(); drillNonPlatedRout = new List<IODBObject>(); drillViaRout = new List<IODBObject>(); noAttributesPadsLayerNameCreated = false; noAttributesNotPadsLayerNameCreated = false; platedLayerNameCreatedRout = false; nonPlatedLayerNameCreatedRout = false; viaLayerNameCreatedRout = false; platedLayerNameCreatedNormal = false; nonPlatedLayerNameCreatedNormal = false; viaLayerNameCreatedNormal = false; //only activate layer can be splitted if (activateNewCreatedLayer) { if (!step.GetActiveLayerList().Contains(step.GetLayer(currLayerName))) continue; } //checks if the layer is a splitted layer if ((currLayerName.Length > 7 && currLayerName.Substring(currLayerName.Length - 7, 7).Equals("_plated")) || (currLayerName.Length > 4 && currLayerName.Substring(currLayerName.Length - 4, 4).Equals("_via"))) { continue; } //checks if the new layer wasn't already splitted last time foreach (string allOtherLayerName in matrix.GetAllDrillLayerNames()) { if (activateNewCreatedLayer) { string searchedLayerName = currLayerName.ToLower() + "_plated"; if (allOtherLayerName.ToLower().Equals(searchedLayerName)) step.GetLayer(searchedLayerName).EnableLayer(true); searchedLayerName = currLayerName.ToLower() + "_non_plated"; if (allOtherLayerName.ToLower().Equals(searchedLayerName)) step.GetLayer(searchedLayerName).EnableLayer(true); searchedLayerName = currLayerName.ToLower() + "_via"; if (allOtherLayerName.ToLower().Equals(searchedLayerName)) step.GetLayer(searchedLayerName).EnableLayer(true); } if (allOtherLayerName.ToLower().Equals(currLayerName.ToLower() + "_plated") || allOtherLayerName.ToLower().Equals(currLayerName.ToLower() + "_non_plated") || allOtherLayerName.ToLower().Equals(currLayerName.ToLower() + "_via")) { skipLayerWasAlreadySplitted = true; continue; } } //if it was already splitted then skip it if (skipLayerWasAlreadySplitted) { skipLayerWasAlreadySplitted = false; continue; } //checks if layer is a drilllayer if (matrix.GetMatrixLayerType(currLayerName) == MatrixLayerType.Drill) { ILayer lay = step.GetLayer(currLayerName); List<IObject> objects = lay.GetAllLayerObjects(); foreach (IODBObject currObj in objects) { Dictionary<PCBI.FeatureAttributeEnum, string> objDict = currObj.GetAttributesDictionary(); if (objDict.Count != 0) { if (objDict.ContainsKey(PCBI.FeatureAttributeEnum.drill)) { if (currObj.Type == IObjectType.Pad) { #region Rout if (withRout) { if (objDict[PCBI.FeatureAttributeEnum.drill] == "non_plated") { drillNonPlatedNormal.Add(currObj); if (!nonPlatedLayerNameCreatedNormal) { allNewLayerDict.Add(currLayerName + "_non_plated", drillNonPlatedNormal); nonPlatedLayerNameCreatedNormal = true; } } else if (objDict[PCBI.FeatureAttributeEnum.drill] == "plated") { drillPlatedNormal.Add(currObj); if (!platedLayerNameCreatedNormal) { allNewLayerDict.Add(currLayerName + "_plated", drillPlatedNormal); platedLayerNameCreatedNormal = true; } } else if (objDict[PCBI.FeatureAttributeEnum.drill] == "via") { drillViaNormal.Add(currObj); if (!viaLayerNameCreatedNormal) { allNewLayerDict.Add(currLayerName + "_via", drillViaNormal); viaLayerNameCreatedNormal = true; } } else { drill_.Add(currObj); if (!noAttributesPadsLayerNameCreated) { allNewLayerDict.Add(currLayerName + "_", drill_); noAttributesPadsLayerNameCreated = true; } } } #endregion #region Without Rout else { if (objDict[PCBI.FeatureAttributeEnum.drill] == "non_plated") { drillNonPlatedRout.Add(currObj); if (!nonPlatedLayerNameCreatedRout) { allNewLayerDict.Add(currLayerName + "_non_plated_rout", drillNonPlatedRout); nonPlatedLayerNameCreatedRout = true; } } else if (objDict[PCBI.FeatureAttributeEnum.drill] == "plated") { drillPlatedRout.Add(currObj); if (!platedLayerNameCreatedRout) { allNewLayerDict.Add(currLayerName + "_plated_rout", drillPlatedRout); platedLayerNameCreatedRout = true; } } else if (objDict[PCBI.FeatureAttributeEnum.drill] == "via") { drillViaRout.Add(currObj); if (!viaLayerNameCreatedRout) { allNewLayerDict.Add(currLayerName + "_via_rout", drillViaRout); viaLayerNameCreatedRout = true; } } else { drill_.Add(currObj); if (!noAttributesPadsLayerNameCreated) { allNewLayerDict.Add(currLayerName + "_", drill_); noAttributesPadsLayerNameCreated = true; } } } #endregion } else if (withRout) { #region Line-Arcs-Surfaces-Text + Rout if (objDict[PCBI.FeatureAttributeEnum.drill] == "non_plated") { drillNonPlatedRout.Add(currObj); if (!nonPlatedLayerNameCreatedRout) { allNewLayerDict.Add("rout_" + currLayerName + "_non_plated", drillNonPlatedRout); nonPlatedLayerNameCreatedRout = true; } } else if (objDict[PCBI.FeatureAttributeEnum.drill] == "plated") { drillPlatedRout.Add(currObj); if (!platedLayerNameCreatedRout) { allNewLayerDict.Add("rout_" + currLayerName + "_plated", drillPlatedRout); platedLayerNameCreatedRout = true; } } else if (objDict[PCBI.FeatureAttributeEnum.drill] == "via") { drillViaRout.Add(currObj); if (!viaLayerNameCreatedRout) { allNewLayerDict.Add("rout_" + currLayerName + "_via", drillViaRout); viaLayerNameCreatedRout = true; } } else { drillRout.Add(currObj); if (!noAttributesNotPadsLayerNameCreated) { allNewLayerDict.Add("rout_" + currLayerName, drillRout); noAttributesNotPadsLayerNameCreated = true; } } #endregion } } } else { #region No Attributes + Rout if (withRout) { if (currObj.Type == IObjectType.Pad) { drill_.Add(currObj); if (!noAttributesPadsLayerNameCreated) { allNewLayerDict.Add(currLayerName + "_", drill_); noAttributesPadsLayerNameCreated = true; } } else { drillRout.Add(currObj); if (!noAttributesNotPadsLayerNameCreated) { allNewLayerDict.Add("rout_" + currLayerName, drillRout); noAttributesNotPadsLayerNameCreated = true; } } } #endregion #region No Attributes Without Rout else { if (currObj.Type == IObjectType.Pad) { drill_.Add(currObj); if (!noAttributesPadsLayerNameCreated) { allNewLayerDict.Add(currLayerName + "_", drill_); noAttributesPadsLayerNameCreated = true; } } } #endregion } } if (allNewLayerDict.Count > 1) //wenn alle vom gleichen Typ sind muss nicht gesplittet werden! { foreach (string currNewLayerName in allNewLayerDict.Keys) { filter = new IFilter(parent); CreateNewDrillODBLayer(filter, currNewLayerName, parent, allNewLayerDict[currNewLayerName], activateNewCreatedLayer); } } } } matrix.UpdateDataAndList(); } private void CreateNewDrillODBLayer(PCBI.Automation.IFilter filter, string newLayerName, IPCBIWindow parent, List<IODBObject> currIODBObjectList, bool activateLayer) { if (currIODBObjectList.Count == 0) return; IODBLayer layer = filter.CreateEmptyODBLayer(newLayerName, parent.GetCurrentStep().Name); Dictionary<string, int> shapeList = new Dictionary<string, int>(); foreach (IODBObject obj in currIODBObjectList) { if (obj.Type == IObjectType.Pad) { IPadSpecificsD specPad = (IPadSpecificsD)obj.GetSpecificsD(); if (!shapeList.ContainsKey(specPad.ODBSymbol_String)) { int newShapeIndex = IFilter.AddToolFromODBString(layer, specPad.ODBSymbol_String, shapeList.Count); shapeList.Add(specPad.ODBSymbol_String, newShapeIndex); } IODBObject pad = filter.CreatePad(layer); IPadSpecificsD padInfosD = (IPadSpecificsD)obj.GetSpecificsD(); padInfosD.ShapeIndex = shapeList[specPad.ODBSymbol_String]; pad.SetSpecifics(padInfosD, shapeList[specPad.ODBSymbol_String]); } else if (obj.Type == IObjectType.Line) { ILineSpecificsD specLine = (ILineSpecificsD)obj.GetSpecificsD(); if (!shapeList.ContainsKey(specLine.ODBSymbol_String)) { int newShapeIndex = IFilter.AddToolFromODBString(layer, specLine.ODBSymbol_String, shapeList.Count); shapeList.Add(specLine.ODBSymbol_String, newShapeIndex); } IODBObject line = filter.CreateLine(layer); ILineSpecificsD lineSpecificsD = (ILineSpecificsD)obj.GetSpecificsD(); lineSpecificsD.ShapeIndex = shapeList[specLine.ODBSymbol_String]; line.SetSpecifics(lineSpecificsD); } else if (obj.Type == IObjectType.Arc) { IArcSpecificsD specArc = (IArcSpecificsD)obj.GetSpecificsD(); if (!shapeList.ContainsKey(specArc.ODBSymbol_String)) { int newShapeIndex = IFilter.AddToolFromODBString(layer, specArc.ODBSymbol_String, shapeList.Count); shapeList.Add(specArc.ODBSymbol_String, newShapeIndex); } IODBObject arc = filter.CreateArc(layer); IArcSpecificsD specificsArcD = (IArcSpecificsD)obj.GetSpecificsD(); specificsArcD.ShapeIndex = shapeList[specArc.ODBSymbol_String]; arc.SetSpecifics(specificsArcD); } else if (obj.Type == IObjectType.Surface) { IODBObject surface = filter.CreatePolygon(layer); ISurfaceSpecificsD surfaceSpecificsD = (ISurfaceSpecificsD)obj.GetSpecificsD(); surface.SetSpecifics(surfaceSpecificsD); } else if (obj.Type == IObjectType.Text) { IODBObject text = filter.CreateText(layer); ITextSpecificsD textSpecificsD = (ITextSpecificsD)obj.GetSpecificsD(); text.SetSpecifics(textSpecificsD); } } if (activateLayer) layer.EnableLayer(true); IMatrix matrix = parent.GetMatrix(); matrix.SetMatrixLayerType(layer.LayerName, MatrixLayerType.Drill); matrix.SetMatrixLayerContext(layer.LayerName, MatrixLayerContext.Board); } } } }
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 SendSMS.WebAPI.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; } } }
// // Import.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2011 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Collections.Generic; using SR = System.Reflection; using Mono.Cecil.Metadata; namespace Mono.Cecil { enum ImportGenericKind { Definition, Open, } struct ImportGenericContext { Collection<IGenericParameterProvider> stack; public bool IsEmpty { get { return stack == null; } } public ImportGenericContext (IGenericParameterProvider provider) { stack = null; Push (provider); } public void Push (IGenericParameterProvider provider) { if (stack == null) stack = new Collection<IGenericParameterProvider> (1) { provider }; else stack.Add (provider); } public void Pop () { stack.RemoveAt (stack.Count - 1); } public TypeReference MethodParameter (string method, int position) { for (int i = stack.Count - 1; i >= 0; i--) { var candidate = stack [i] as MethodReference; if (candidate == null) continue; if (method != candidate.Name) continue; return candidate.GenericParameters [position]; } throw new InvalidOperationException (); } public TypeReference TypeParameter (string type, int position) { for (int i = stack.Count - 1; i >= 0; i--) { var candidate = GenericTypeFor (stack [i]); if (candidate.FullName != type) continue; return candidate.GenericParameters [position]; } throw new InvalidOperationException (); } static TypeReference GenericTypeFor (IGenericParameterProvider context) { var type = context as TypeReference; if (type != null) return type.GetElementType (); var method = context as MethodReference; if (method != null) return method.DeclaringType.GetElementType (); throw new InvalidOperationException (); } } class MetadataImporter { readonly ModuleDefinition module; public MetadataImporter (ModuleDefinition module) { this.module = module; } #if !CF static readonly Dictionary<Type, ElementType> type_etype_mapping = new Dictionary<Type, ElementType> (18) { { typeof (void), ElementType.Void }, { typeof (bool), ElementType.Boolean }, { typeof (char), ElementType.Char }, { typeof (sbyte), ElementType.I1 }, { typeof (byte), ElementType.U1 }, { typeof (short), ElementType.I2 }, { typeof (ushort), ElementType.U2 }, { typeof (int), ElementType.I4 }, { typeof (uint), ElementType.U4 }, { typeof (long), ElementType.I8 }, { typeof (ulong), ElementType.U8 }, { typeof (float), ElementType.R4 }, { typeof (double), ElementType.R8 }, { typeof (string), ElementType.String }, { typeof (TypedReference), ElementType.TypedByRef }, { typeof (IntPtr), ElementType.I }, { typeof (UIntPtr), ElementType.U }, { typeof (object), ElementType.Object }, }; public TypeReference ImportType (Type type, ImportGenericContext context) { return ImportType (type, context, ImportGenericKind.Open); } public TypeReference ImportType (Type type, ImportGenericContext context, ImportGenericKind import_kind) { if (IsTypeSpecification (type) || ImportOpenGenericType (type, import_kind)) return ImportTypeSpecification (type, context); var reference = new TypeReference ( string.Empty, type.Name, module, ImportScope (type.Assembly), type.IsValueType); reference.etype = ImportElementType (type); if (IsNestedType (type)) reference.DeclaringType = ImportType (type.DeclaringType, context, import_kind); else reference.Namespace = type.Namespace ?? string.Empty; if (type.IsGenericType) ImportGenericParameters (reference, type.GetGenericArguments ()); return reference; } static bool ImportOpenGenericType (Type type, ImportGenericKind import_kind) { return type.IsGenericType && type.IsGenericTypeDefinition && import_kind == ImportGenericKind.Open; } static bool ImportOpenGenericMethod (SR.MethodBase method, ImportGenericKind import_kind) { return method.IsGenericMethod && method.IsGenericMethodDefinition && import_kind == ImportGenericKind.Open; } static bool IsNestedType (Type type) { #if !SILVERLIGHT return type.IsNested; #else return type.DeclaringType != null; #endif } TypeReference ImportTypeSpecification (Type type, ImportGenericContext context) { if (type.IsByRef) return new ByReferenceType (ImportType (type.GetElementType (), context)); if (type.IsPointer) return new PointerType (ImportType (type.GetElementType (), context)); if (type.IsArray) return new ArrayType (ImportType (type.GetElementType (), context), type.GetArrayRank ()); if (type.IsGenericType) return ImportGenericInstance (type, context); if (type.IsGenericParameter) return ImportGenericParameter (type, context); throw new NotSupportedException (type.FullName); } static TypeReference ImportGenericParameter (Type type, ImportGenericContext context) { if (context.IsEmpty) throw new InvalidOperationException (); if (type.DeclaringMethod != null) return context.MethodParameter (type.DeclaringMethod.Name, type.GenericParameterPosition); if (type.DeclaringType != null) return context.TypeParameter (NormalizedFullName (type.DeclaringType), type.GenericParameterPosition); throw new InvalidOperationException(); } private static string NormalizedFullName (Type type) { if (IsNestedType (type)) return NormalizedFullName (type.DeclaringType) + "/" + type.Name; return type.FullName; } TypeReference ImportGenericInstance (Type type, ImportGenericContext context) { var element_type = ImportType (type.GetGenericTypeDefinition (), context, ImportGenericKind.Definition); var instance = new GenericInstanceType (element_type); var arguments = type.GetGenericArguments (); var instance_arguments = instance.GenericArguments; context.Push (element_type); try { for (int i = 0; i < arguments.Length; i++) instance_arguments.Add (ImportType (arguments [i], context)); return instance; } finally { context.Pop (); } } static bool IsTypeSpecification (Type type) { return type.HasElementType || IsGenericInstance (type) || type.IsGenericParameter; } static bool IsGenericInstance (Type type) { return type.IsGenericType && !type.IsGenericTypeDefinition; } static ElementType ImportElementType (Type type) { ElementType etype; if (!type_etype_mapping.TryGetValue (type, out etype)) return ElementType.None; return etype; } AssemblyNameReference ImportScope (SR.Assembly assembly) { AssemblyNameReference scope; #if !SILVERLIGHT var name = assembly.GetName (); if (TryGetAssemblyNameReference (name, out scope)) return scope; scope = new AssemblyNameReference (name.Name, name.Version) { Culture = name.CultureInfo.Name, PublicKeyToken = name.GetPublicKeyToken (), HashAlgorithm = (AssemblyHashAlgorithm) name.HashAlgorithm, }; module.AssemblyReferences.Add (scope); return scope; #else var name = AssemblyNameReference.Parse (assembly.FullName); if (TryGetAssemblyNameReference (name, out scope)) return scope; module.AssemblyReferences.Add (name); return name; #endif } #if !SILVERLIGHT bool TryGetAssemblyNameReference (SR.AssemblyName name, out AssemblyNameReference assembly_reference) { var references = module.AssemblyReferences; for (int i = 0; i < references.Count; i++) { var reference = references [i]; if (name.FullName != reference.FullName) // TODO compare field by field continue; assembly_reference = reference; return true; } assembly_reference = null; return false; } #endif public FieldReference ImportField (SR.FieldInfo field, ImportGenericContext context) { var declaring_type = ImportType (field.DeclaringType, context); if (IsGenericInstance (field.DeclaringType)) field = ResolveFieldDefinition (field); context.Push (declaring_type); try { return new FieldReference { Name = field.Name, DeclaringType = declaring_type, FieldType = ImportType (field.FieldType, context), }; } finally { context.Pop (); } } static SR.FieldInfo ResolveFieldDefinition (SR.FieldInfo field) { #if !SILVERLIGHT return field.Module.ResolveField (field.MetadataToken); #else return field.DeclaringType.GetGenericTypeDefinition ().GetField (field.Name, SR.BindingFlags.Public | SR.BindingFlags.NonPublic | (field.IsStatic ? SR.BindingFlags.Static : SR.BindingFlags.Instance)); #endif } public MethodReference ImportMethod (SR.MethodBase method, ImportGenericContext context, ImportGenericKind import_kind) { if (IsMethodSpecification (method) || ImportOpenGenericMethod (method, import_kind)) return ImportMethodSpecification (method, context); var declaring_type = ImportType (method.DeclaringType, context); if (IsGenericInstance (method.DeclaringType)) method = method.Module.ResolveMethod (method.MetadataToken); var reference = new MethodReference { Name = method.Name, HasThis = HasCallingConvention (method, SR.CallingConventions.HasThis), ExplicitThis = HasCallingConvention (method, SR.CallingConventions.ExplicitThis), DeclaringType = ImportType (method.DeclaringType, context, ImportGenericKind.Definition), }; if (HasCallingConvention (method, SR.CallingConventions.VarArgs)) reference.CallingConvention &= MethodCallingConvention.VarArg; if (method.IsGenericMethod) ImportGenericParameters (reference, method.GetGenericArguments ()); context.Push (reference); try { var method_info = method as SR.MethodInfo; reference.ReturnType = method_info != null ? ImportType (method_info.ReturnType, context) : ImportType (typeof (void), default (ImportGenericContext)); var parameters = method.GetParameters (); var reference_parameters = reference.Parameters; for (int i = 0; i < parameters.Length; i++) reference_parameters.Add ( new ParameterDefinition (ImportType (parameters [i].ParameterType, context))); reference.DeclaringType = declaring_type; return reference; } finally { context.Pop (); } } static void ImportGenericParameters (IGenericParameterProvider provider, Type [] arguments) { var provider_parameters = provider.GenericParameters; for (int i = 0; i < arguments.Length; i++) provider_parameters.Add (new GenericParameter (arguments [i].Name, provider)); } static bool IsMethodSpecification (SR.MethodBase method) { return method.IsGenericMethod && !method.IsGenericMethodDefinition; } MethodReference ImportMethodSpecification (SR.MethodBase method, ImportGenericContext context) { var method_info = method as SR.MethodInfo; if (method_info == null) throw new InvalidOperationException (); var element_method = ImportMethod (method_info.GetGenericMethodDefinition (), context, ImportGenericKind.Definition); var instance = new GenericInstanceMethod (element_method); var arguments = method.GetGenericArguments (); var instance_arguments = instance.GenericArguments; context.Push (element_method); try { for (int i = 0; i < arguments.Length; i++) instance_arguments.Add (ImportType (arguments [i], context)); return instance; } finally { context.Pop (); } } static bool HasCallingConvention (SR.MethodBase method, SR.CallingConventions conventions) { return (method.CallingConvention & conventions) != 0; } #endif public TypeReference ImportType (TypeReference type, ImportGenericContext context) { if (type.IsTypeSpecification ()) return ImportTypeSpecification (type, context); var reference = new TypeReference ( type.Namespace, type.Name, module, ImportScope (type.Scope), type.IsValueType); MetadataSystem.TryProcessPrimitiveTypeReference (reference); if (type.IsNested) reference.DeclaringType = ImportType (type.DeclaringType, context); if (type.HasGenericParameters) ImportGenericParameters (reference, type); return reference; } IMetadataScope ImportScope (IMetadataScope scope) { switch (scope.MetadataScopeType) { case MetadataScopeType.AssemblyNameReference: return ImportAssemblyName ((AssemblyNameReference) scope); case MetadataScopeType.ModuleDefinition: return ImportAssemblyName (((ModuleDefinition) scope).Assembly.Name); case MetadataScopeType.ModuleReference: throw new NotImplementedException (); } throw new NotSupportedException (); } AssemblyNameReference ImportAssemblyName (AssemblyNameReference name) { AssemblyNameReference reference; if (TryGetAssemblyNameReference (name, out reference)) return reference; reference = new AssemblyNameReference (name.Name, name.Version) { Culture = name.Culture, HashAlgorithm = name.HashAlgorithm, }; var pk_token = !name.PublicKeyToken.IsNullOrEmpty () ? new byte [name.PublicKeyToken.Length] : Empty<byte>.Array; if (pk_token.Length > 0) Buffer.BlockCopy (name.PublicKeyToken, 0, pk_token, 0, pk_token.Length); reference.PublicKeyToken = pk_token; module.AssemblyReferences.Add (reference); return reference; } bool TryGetAssemblyNameReference (AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference) { var references = module.AssemblyReferences; for (int i = 0; i < references.Count; i++) { var reference = references [i]; if (name_reference.FullName != reference.FullName) // TODO compare field by field continue; assembly_reference = reference; return true; } assembly_reference = null; return false; } static void ImportGenericParameters (IGenericParameterProvider imported, IGenericParameterProvider original) { var parameters = original.GenericParameters; var imported_parameters = imported.GenericParameters; for (int i = 0; i < parameters.Count; i++) imported_parameters.Add (new GenericParameter (parameters [i].Name, imported)); } TypeReference ImportTypeSpecification (TypeReference type, ImportGenericContext context) { switch (type.etype) { case ElementType.SzArray: var vector = (ArrayType) type; return new ArrayType (ImportType (vector.ElementType, context)); case ElementType.Ptr: var pointer = (PointerType) type; return new PointerType (ImportType (pointer.ElementType, context)); case ElementType.ByRef: var byref = (ByReferenceType) type; return new ByReferenceType (ImportType (byref.ElementType, context)); case ElementType.Pinned: var pinned = (PinnedType) type; return new PinnedType (ImportType (pinned.ElementType, context)); case ElementType.Sentinel: var sentinel = (SentinelType) type; return new SentinelType (ImportType (sentinel.ElementType, context)); case ElementType.CModOpt: var modopt = (OptionalModifierType) type; return new OptionalModifierType ( ImportType (modopt.ModifierType, context), ImportType (modopt.ElementType, context)); case ElementType.CModReqD: var modreq = (RequiredModifierType) type; return new RequiredModifierType ( ImportType (modreq.ModifierType, context), ImportType (modreq.ElementType, context)); case ElementType.Array: var array = (ArrayType) type; var imported_array = new ArrayType (ImportType (array.ElementType, context)); if (array.IsVector) return imported_array; var dimensions = array.Dimensions; var imported_dimensions = imported_array.Dimensions; imported_dimensions.Clear (); for (int i = 0; i < dimensions.Count; i++) { var dimension = dimensions [i]; imported_dimensions.Add (new ArrayDimension (dimension.LowerBound, dimension.UpperBound)); } return imported_array; case ElementType.GenericInst: var instance = (GenericInstanceType) type; var element_type = ImportType (instance.ElementType, context); var imported_instance = new GenericInstanceType (element_type); var arguments = instance.GenericArguments; var imported_arguments = imported_instance.GenericArguments; for (int i = 0; i < arguments.Count; i++) imported_arguments.Add (ImportType (arguments [i], context)); return imported_instance; case ElementType.Var: var var_parameter = (GenericParameter) type; return context.TypeParameter (type.DeclaringType.FullName, var_parameter.Position); case ElementType.MVar: var mvar_parameter = (GenericParameter) type; return context.MethodParameter (mvar_parameter.DeclaringMethod.Name, mvar_parameter.Position); } throw new NotSupportedException (type.etype.ToString ()); } public FieldReference ImportField (FieldReference field, ImportGenericContext context) { var declaring_type = ImportType (field.DeclaringType, context); context.Push (declaring_type); try { return new FieldReference { Name = field.Name, DeclaringType = declaring_type, FieldType = ImportType (field.FieldType, context), }; } finally { context.Pop (); } } public MethodReference ImportMethod (MethodReference method, ImportGenericContext context) { if (method.IsGenericInstance) return ImportMethodSpecification (method, context); var declaring_type = ImportType (method.DeclaringType, context); var reference = new MethodReference { Name = method.Name, HasThis = method.HasThis, ExplicitThis = method.ExplicitThis, DeclaringType = declaring_type, CallingConvention = method.CallingConvention, }; if (method.HasGenericParameters) ImportGenericParameters (reference, method); context.Push (reference); try { reference.ReturnType = ImportType (method.ReturnType, context); if (!method.HasParameters) return reference; var reference_parameters = reference.Parameters; var parameters = method.Parameters; for (int i = 0; i < parameters.Count; i++) reference_parameters.Add ( new ParameterDefinition (ImportType (parameters [i].ParameterType, context))); return reference; } finally { context.Pop(); } } MethodSpecification ImportMethodSpecification (MethodReference method, ImportGenericContext context) { if (!method.IsGenericInstance) throw new NotSupportedException (); var instance = (GenericInstanceMethod) method; var element_method = ImportMethod (instance.ElementMethod, context); var imported_instance = new GenericInstanceMethod (element_method); var arguments = instance.GenericArguments; var imported_arguments = imported_instance.GenericArguments; for (int i = 0; i < arguments.Count; i++) imported_arguments.Add (ImportType (arguments [i], context)); return imported_instance; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; internal static class IOInputs { public static bool SupportsSettingCreationTime { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } } public static bool SupportsGettingCreationTime { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) | RuntimeInformation.IsOSPlatform(OSPlatform.OSX); } } // Max path length (minus trailing \0). Unix values vary system to system; just using really long values here likely to be more than on the average system. public static readonly int MaxPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 259 : 10000; // Windows specific, this is the maximum length that can be passed using extended syntax. Does not include the trailing \0. public static readonly int MaxExtendedPath = short.MaxValue - 1; // Same as MaxPath on Unix public static readonly int MaxLongPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? MaxExtendedPath : MaxPath; // Windows specific, this is the maximum length that can be passed to APIs taking directory names, such as Directory.CreateDirectory & Directory.Move. // Does not include the trailing \0. // We now do the appropriate wrapping to allow creating longer directories. Like MaxPath, this is a legacy restriction. public static readonly int MaxDirectory = 247; public const int MaxComponent = 255; public const string ExtendedPrefix = @"\\?\"; public const string ExtendedUncPrefix = @"\\?\UNC\"; public static IEnumerable<string> GetValidPathComponentNames() { yield return Path.GetRandomFileName(); yield return "!@#$%^&"; yield return "\x65e5\x672c\x8a9e"; yield return "A"; yield return " A"; yield return " A"; yield return "FileName"; yield return "FileName.txt"; yield return " FileName"; yield return " FileName.txt"; yield return " FileName"; yield return " FileName.txt"; yield return "This is a valid component name"; yield return "This is a valid component name.txt"; yield return "V1.0.0.0000"; } public static IEnumerable<string> GetControlWhiteSpace() { yield return "\t"; yield return "\t\t"; yield return "\t\t\t"; yield return "\n"; yield return "\n\n"; yield return "\n\n\n"; yield return "\t\n"; yield return "\t\n\t\n"; yield return "\n\t\n"; yield return "\n\t\n\t"; } public static IEnumerable<string> GetSimpleWhiteSpace() { yield return " "; yield return " "; yield return " "; yield return " "; yield return " "; } public static IEnumerable<string> GetWhiteSpace() { return GetControlWhiteSpace().Concat(GetSimpleWhiteSpace()); } public static IEnumerable<string> GetUncPathsWithoutShareName() { foreach (char slash in new[] { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar }) { if (!PlatformDetection.IsWindows && slash == '/') // Unc paths must start with '\' on Unix { continue; } string slashes = new string(slash, 2); yield return slashes; yield return slashes + " "; yield return slashes + new string(slash, 5); yield return slashes + "S"; yield return slashes + "S "; yield return slashes + "LOCALHOST"; yield return slashes + "LOCALHOST " + slash; yield return slashes + "LOCALHOST " + new string(slash, 2); yield return slashes + "LOCALHOST" + slash + " "; yield return slashes + "LOCALHOST" + slash + slash + " "; } } public static IEnumerable<string> GetPathsWithReservedDeviceNames() { string root = Path.GetPathRoot(Directory.GetCurrentDirectory()); foreach (string deviceName in GetReservedDeviceNames()) { yield return deviceName; yield return Path.Combine(root, deviceName); yield return Path.Combine(root, "Directory", deviceName); yield return Path.Combine(new string(Path.DirectorySeparatorChar, 2), "LOCALHOST", deviceName); } } public static IEnumerable<string> GetPathsWithAlternativeDataStreams() { yield return @"AA:"; yield return @"AAA:"; yield return @"AA:A"; yield return @"AAA:A"; yield return @"AA:AA"; yield return @"AAA:AA"; yield return @"AA:AAA"; yield return @"AAA:AAA"; yield return @"AA:FileName"; yield return @"AAA:FileName"; yield return @"AA:FileName.txt"; yield return @"AAA:FileName.txt"; yield return @"A:FileName.txt:"; yield return @"AA:FileName.txt:AA"; yield return @"AAA:FileName.txt:AAA"; yield return @"C:\:"; yield return @"C:\:FileName"; yield return @"C:\:FileName.txt"; yield return @"C:\fileName:"; yield return @"C:\fileName:FileName.txt"; yield return @"C:\fileName:FileName.txt:"; yield return @"C:\fileName:FileName.txt:AA"; yield return @"C:\fileName:FileName.txt:AAA"; yield return @"ftp://fileName:FileName.txt:AAA"; } public static IEnumerable<string> GetPathsWithComponentLongerThanMaxComponent() { // While paths themselves can be up to and including 32,000 characters, most volumes // limit each component of the path to a total of 255 characters. string component = new string('s', MaxComponent + 1); yield return string.Format(@"C:\{0}", component); yield return string.Format(@"C:\{0}\Filename.txt", component); yield return string.Format(@"C:\{0}\Filename.txt\", component); yield return string.Format(@"\\{0}\Share", component); yield return string.Format(@"\\LOCALHOST\{0}", component); yield return string.Format(@"\\LOCALHOST\{0}\FileName.txt", component); yield return string.Format(@"\\LOCALHOST\Share\{0}", component); } public static IEnumerable<string> GetPathsLongerThanMaxDirectory(string rootPath) { yield return GetLongPath(rootPath, MaxDirectory + 1); yield return GetLongPath(rootPath, MaxDirectory + 2); yield return GetLongPath(rootPath, MaxDirectory + 3); } public static IEnumerable<string> GetPathsLongerThanMaxPath(string rootPath, bool useExtendedSyntax = false) { yield return GetLongPath(rootPath, MaxPath + 1, useExtendedSyntax); yield return GetLongPath(rootPath, MaxPath + 2, useExtendedSyntax); yield return GetLongPath(rootPath, MaxPath + 3, useExtendedSyntax); } public static IEnumerable<string> GetPathsLongerThanMaxLongPath(string rootPath, bool useExtendedSyntax = false) { yield return GetLongPath(rootPath, MaxExtendedPath + 1, useExtendedSyntax); yield return GetLongPath(rootPath, MaxExtendedPath + 2, useExtendedSyntax); } private static string GetLongPath(string rootPath, int characterCount, bool extended = false) { return IOServices.GetPath(rootPath, characterCount, extended).FullPath; } public static IEnumerable<string> GetReservedDeviceNames() { // See: http://msdn.microsoft.com/en-us/library/aa365247.aspx yield return "CON"; yield return "AUX"; yield return "NUL"; yield return "PRN"; yield return "COM1"; yield return "COM2"; yield return "COM3"; yield return "COM4"; yield return "COM5"; yield return "COM6"; yield return "COM7"; yield return "COM8"; yield return "COM9"; yield return "LPT1"; yield return "LPT2"; yield return "LPT3"; yield return "LPT4"; yield return "LPT5"; yield return "LPT6"; yield return "LPT7"; yield return "LPT8"; yield return "LPT9"; } }
namespace Demo { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region 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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.label1 = new System.Windows.Forms.Label(); this.comboBoxCustomers = new System.Windows.Forms.ComboBox(); this.labelMatches = new System.Windows.Forms.Label(); this.textBoxFilter = new System.Windows.Forms.TextBox(); this.dataGridView = new System.Windows.Forms.DataGridView(); this.columnOrderId = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnEmployeeId = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnOrderDate = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnRequiredDate = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnShippedDate = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnShipVia = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnFreight = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnShipName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnShipAddress = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnShipCity = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnShipRegion = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnShipPostalCode = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnShipCountry = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.label2 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.textBoxConnectionString = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.buttonGetData = new System.Windows.Forms.Button(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.label4 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(17, 57); this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(69, 16); this.label1.TabIndex = 3; this.label1.Text = "Company:"; // // comboBoxCustomers // this.comboBoxCustomers.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.comboBoxCustomers.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBoxCustomers.FlatStyle = System.Windows.Forms.FlatStyle.System; this.comboBoxCustomers.FormattingEnabled = true; this.comboBoxCustomers.Location = new System.Drawing.Point(97, 54); this.comboBoxCustomers.Margin = new System.Windows.Forms.Padding(4); this.comboBoxCustomers.Name = "comboBoxCustomers"; this.comboBoxCustomers.Size = new System.Drawing.Size(309, 24); this.comboBoxCustomers.TabIndex = 4; this.comboBoxCustomers.SelectedValueChanged += new System.EventHandler(this.comboBoxCustomers_SelectedValueChanged); // // labelMatches // this.labelMatches.AutoSize = true; this.labelMatches.Location = new System.Drawing.Point(975, 33); this.labelMatches.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.labelMatches.Name = "labelMatches"; this.labelMatches.Size = new System.Drawing.Size(0, 16); this.labelMatches.TabIndex = 2; // // textBoxFilter // this.textBoxFilter.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.textBoxFilter.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.textBoxFilter.Enabled = false; this.textBoxFilter.Location = new System.Drawing.Point(97, 22); this.textBoxFilter.Margin = new System.Windows.Forms.Padding(4); this.textBoxFilter.Name = "textBoxFilter"; this.textBoxFilter.Size = new System.Drawing.Size(161, 22); this.textBoxFilter.TabIndex = 2; this.textBoxFilter.TextChanged += new System.EventHandler(this.textBoxFilter_TextChanged); // // dataGridView // this.dataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells; this.dataGridView.ColumnHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single; this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.columnOrderId, this.columnEmployeeId, this.columnOrderDate, this.columnRequiredDate, this.columnShippedDate, this.columnShipVia, this.columnFreight, this.columnShipName, this.columnShipAddress, this.columnShipCity, this.columnShipRegion, this.columnShipPostalCode, this.columnShipCountry}); this.dataGridView.Location = new System.Drawing.Point(13, 259); this.dataGridView.Margin = new System.Windows.Forms.Padding(4); this.dataGridView.Name = "dataGridView"; this.dataGridView.RowHeadersBorderStyle = System.Windows.Forms.DataGridViewHeaderBorderStyle.Single; this.dataGridView.RowHeadersWidth = 25; this.dataGridView.Size = new System.Drawing.Size(669, 193); this.dataGridView.TabIndex = 5; // // columnOrderId // this.columnOrderId.DataPropertyName = "OrderId"; this.columnOrderId.HeaderText = "Order ID"; this.columnOrderId.Name = "columnOrderId"; this.columnOrderId.Width = 83; // // columnEmployeeId // this.columnEmployeeId.DataPropertyName = "EmployeeId"; this.columnEmployeeId.HeaderText = "Employee ID"; this.columnEmployeeId.Name = "columnEmployeeId"; this.columnEmployeeId.Width = 111; // // columnOrderDate // this.columnOrderDate.DataPropertyName = "OrderDate"; this.columnOrderDate.HeaderText = "Ordered"; this.columnOrderDate.Name = "columnOrderDate"; this.columnOrderDate.Width = 83; // // columnRequiredDate // this.columnRequiredDate.DataPropertyName = "RequiredDate"; this.columnRequiredDate.HeaderText = "Required"; this.columnRequiredDate.Name = "columnRequiredDate"; this.columnRequiredDate.Width = 89; // // columnShippedDate // this.columnShippedDate.DataPropertyName = "ShippedDate"; this.columnShippedDate.HeaderText = "Shipped"; this.columnShippedDate.Name = "columnShippedDate"; this.columnShippedDate.Width = 84; // // columnShipVia // this.columnShipVia.DataPropertyName = "ShipVia"; this.columnShipVia.HeaderText = "Ship Via"; this.columnShipVia.Name = "columnShipVia"; this.columnShipVia.Width = 83; // // columnFreight // this.columnFreight.HeaderText = "Freight"; this.columnFreight.Name = "columnFreight"; this.columnFreight.Width = 74; // // columnShipName // this.columnShipName.DataPropertyName = "ShipName"; this.columnShipName.HeaderText = "Name"; this.columnShipName.Name = "columnShipName"; this.columnShipName.Width = 70; // // columnShipAddress // this.columnShipAddress.DataPropertyName = "ShipAddress"; this.columnShipAddress.HeaderText = "Address"; this.columnShipAddress.Name = "columnShipAddress"; this.columnShipAddress.Width = 84; // // columnShipCity // this.columnShipCity.DataPropertyName = "ShipCity"; this.columnShipCity.HeaderText = "City"; this.columnShipCity.Name = "columnShipCity"; this.columnShipCity.Width = 55; // // columnShipRegion // this.columnShipRegion.DataPropertyName = "ShipRegion"; this.columnShipRegion.HeaderText = "State"; this.columnShipRegion.Name = "columnShipRegion"; this.columnShipRegion.Width = 64; // // columnShipPostalCode // this.columnShipPostalCode.DataPropertyName = "ShipPostalCode"; this.columnShipPostalCode.HeaderText = "Zip Code"; this.columnShipPostalCode.Name = "columnShipPostalCode"; this.columnShipPostalCode.Width = 88; // // columnShipCountry // this.columnShipCountry.DataPropertyName = "ShipCountry"; this.columnShipCountry.HeaderText = "Country"; this.columnShipCountry.Name = "columnShipCountry"; this.columnShipCountry.Width = 78; // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(47, 25); this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(40, 16); this.label2.TabIndex = 1; this.label2.Text = "Filter:"; // // groupBox1 // this.groupBox1.Controls.Add(this.textBoxConnectionString); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.buttonGetData); this.groupBox1.Location = new System.Drawing.Point(13, 15); this.groupBox1.Margin = new System.Windows.Forms.Padding(4); this.groupBox1.Name = "groupBox1"; this.groupBox1.Padding = new System.Windows.Forms.Padding(4); this.groupBox1.Size = new System.Drawing.Size(420, 108); this.groupBox1.TabIndex = 0; this.groupBox1.TabStop = false; this.groupBox1.Text = "Data Source"; // // textBoxConnectionString // this.textBoxConnectionString.Location = new System.Drawing.Point(136, 29); this.textBoxConnectionString.Name = "textBoxConnectionString"; this.textBoxConnectionString.Size = new System.Drawing.Size(277, 22); this.textBoxConnectionString.TabIndex = 7; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(17, 32); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(113, 16); this.label3.TabIndex = 6; this.label3.Text = "Connection string:"; // // buttonGetData // this.buttonGetData.FlatStyle = System.Windows.Forms.FlatStyle.System; this.buttonGetData.Location = new System.Drawing.Point(20, 64); this.buttonGetData.Margin = new System.Windows.Forms.Padding(4); this.buttonGetData.Name = "buttonGetData"; this.buttonGetData.Size = new System.Drawing.Size(100, 28); this.buttonGetData.TabIndex = 5; this.buttonGetData.Text = "Get Data"; this.buttonGetData.UseVisualStyleBackColor = true; this.buttonGetData.Click += new System.EventHandler(this.buttonGetData_Click); // // groupBox2 // this.groupBox2.Controls.Add(this.textBoxFilter); this.groupBox2.Controls.Add(this.label1); this.groupBox2.Controls.Add(this.label2); this.groupBox2.Controls.Add(this.comboBoxCustomers); this.groupBox2.Location = new System.Drawing.Point(13, 130); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(413, 96); this.groupBox2.TabIndex = 6; this.groupBox2.TabStop = false; this.groupBox2.Text = "Company"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(12, 239); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(52, 16); this.label4.TabIndex = 7; this.label4.Text = "Orders:"; // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(695, 465); this.Controls.Add(this.label4); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.dataGridView); this.Controls.Add(this.labelMatches); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Margin = new System.Windows.Forms.Padding(4); this.Name = "MainForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "ObjectListView Demo"; ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox comboBoxCustomers; private System.Windows.Forms.Label labelMatches; private System.Windows.Forms.TextBox textBoxFilter; private System.Windows.Forms.DataGridView dataGridView; private System.Windows.Forms.Label label2; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button buttonGetData; private System.Windows.Forms.TextBox textBoxConnectionString; private System.Windows.Forms.Label label3; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Label label4; private System.Windows.Forms.DataGridViewTextBoxColumn columnOrderId; private System.Windows.Forms.DataGridViewTextBoxColumn columnEmployeeId; private System.Windows.Forms.DataGridViewTextBoxColumn columnOrderDate; private System.Windows.Forms.DataGridViewTextBoxColumn columnRequiredDate; private System.Windows.Forms.DataGridViewTextBoxColumn columnShippedDate; private System.Windows.Forms.DataGridViewTextBoxColumn columnShipVia; private System.Windows.Forms.DataGridViewTextBoxColumn columnFreight; private System.Windows.Forms.DataGridViewTextBoxColumn columnShipName; private System.Windows.Forms.DataGridViewTextBoxColumn columnShipAddress; private System.Windows.Forms.DataGridViewTextBoxColumn columnShipCity; private System.Windows.Forms.DataGridViewTextBoxColumn columnShipRegion; private System.Windows.Forms.DataGridViewTextBoxColumn columnShipPostalCode; private System.Windows.Forms.DataGridViewTextBoxColumn columnShipCountry; } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Globalization; using System.Management.Automation; namespace Microsoft.PowerShell.Commands.Internal.Format { internal static class DisplayCondition { internal static bool Evaluate(PSObject obj, MshExpression ex, out MshExpressionResult expressionResult) { expressionResult = null; List<MshExpressionResult> res = ex.GetValues(obj); if (res.Count == 0) return false; if (res[0].Exception != null) { expressionResult = res[0]; return false; } return LanguagePrimitives.IsTrue(res[0].Result); } } /// <summary> /// helper object holding a generic object and the related /// "applies to" object. /// It is used in by the inheritance based type match algorithm /// </summary> internal sealed class TypeMatchItem { internal TypeMatchItem(object obj, AppliesTo a) { Item = obj; AppliesTo = a; } internal TypeMatchItem(object obj, AppliesTo a, PSObject currentObject) { Item = obj; AppliesTo = a; CurrentObject = currentObject; } internal object Item { get; } internal AppliesTo AppliesTo { get; } internal PSObject CurrentObject { get; } } /// <summary> /// algorithm to execute a type match on a list of entities /// having an "applies to" associated object /// </summary> internal sealed class TypeMatch { #region tracer [TraceSource("TypeMatch", "F&O TypeMatch")] private static readonly PSTraceSource s_classTracer = PSTraceSource.GetTracer("TypeMatch", "F&O TypeMatch"); private static PSTraceSource s_activeTracer = null; private static PSTraceSource ActiveTracer { get { return s_activeTracer ?? s_classTracer; } } internal static void SetTracer(PSTraceSource t) { s_activeTracer = t; } internal static void ResetTracer() { s_activeTracer = s_classTracer; } #endregion tracer internal TypeMatch(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection<string> typeNames) { _expressionFactory = expressionFactory; _db = db; _typeNameHierarchy = typeNames; _useInheritance = true; } internal TypeMatch(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection<string> typeNames, bool useInheritance) { _expressionFactory = expressionFactory; _db = db; _typeNameHierarchy = typeNames; _useInheritance = useInheritance; } internal bool PerfectMatch(TypeMatchItem item) { int match = ComputeBestMatch(item.AppliesTo, item.CurrentObject); if (match == BestMatchIndexUndefined) return false; if (_bestMatchIndex == BestMatchIndexUndefined || match < _bestMatchIndex) { _bestMatchIndex = match; _bestMatchItem = item; } return _bestMatchIndex == BestMatchIndexPerfect; } internal object BestMatch { get { if (_bestMatchItem == null) return null; return _bestMatchItem.Item; } } private int ComputeBestMatch(AppliesTo appliesTo, PSObject currentObject) { int best = BestMatchIndexUndefined; foreach (TypeOrGroupReference r in appliesTo.referenceList) { MshExpression ex = null; if (r.conditionToken != null) { ex = _expressionFactory.CreateFromExpressionToken(r.conditionToken); } int currentMatch = BestMatchIndexUndefined; TypeReference tr = r as TypeReference; if (tr != null) { // we have a type currentMatch = MatchTypeIndex(tr.name, currentObject, ex); } else { // we have a type group reference TypeGroupReference tgr = r as TypeGroupReference; // find the type group definition the reference points to TypeGroupDefinition tgd = DisplayDataQuery.FindGroupDefinition(_db, tgr.name); if (tgd != null) { // we found the group, see if the group has the type currentMatch = ComputeBestMatchInGroup(tgd, currentObject, ex); } } if (currentMatch == BestMatchIndexPerfect) return currentMatch; if (best == BestMatchIndexUndefined || best < currentMatch) { best = currentMatch; } } return best; } private int ComputeBestMatchInGroup(TypeGroupDefinition tgd, PSObject currentObject, MshExpression ex) { int best = BestMatchIndexUndefined; int k = 0; foreach (TypeReference tr in tgd.typeReferenceList) { int currentMatch = MatchTypeIndex(tr.name, currentObject, ex); if (currentMatch == BestMatchIndexPerfect) return currentMatch; if (best == BestMatchIndexUndefined || best < currentMatch) { best = currentMatch; } k++; } return best; } private int MatchTypeIndex(string typeName, PSObject currentObject, MshExpression ex) { if (string.IsNullOrEmpty(typeName)) return BestMatchIndexUndefined; int k = 0; foreach (string name in _typeNameHierarchy) { if (string.Equals(name, typeName, StringComparison.OrdinalIgnoreCase) && MatchCondition(currentObject, ex)) { return k; } if (k == 0 && !_useInheritance) break; k++; } return BestMatchIndexUndefined; } private bool MatchCondition(PSObject currentObject, MshExpression ex) { if (ex == null) return true; MshExpressionResult expressionResult; bool retVal = DisplayCondition.Evaluate(currentObject, ex, out expressionResult); if (expressionResult != null && expressionResult.Exception != null) { _failedResultsList.Add(expressionResult); } return retVal; } private MshExpressionFactory _expressionFactory; private TypeInfoDataBase _db; private Collection<string> _typeNameHierarchy; private bool _useInheritance; private List<MshExpressionResult> _failedResultsList = new List<MshExpressionResult>(); private int _bestMatchIndex = BestMatchIndexUndefined; private TypeMatchItem _bestMatchItem; private const int BestMatchIndexUndefined = -1; private const int BestMatchIndexPerfect = 0; } internal static class DisplayDataQuery { #region tracer [TraceSource("DisplayDataQuery", "DisplayDataQuery")] private static readonly PSTraceSource s_classTracer = PSTraceSource.GetTracer("DisplayDataQuery", "DisplayDataQuery"); private static PSTraceSource s_activeTracer = null; private static PSTraceSource ActiveTracer { get { return s_activeTracer ?? s_classTracer; } } internal static void SetTracer(PSTraceSource t) { s_activeTracer = t; } internal static void ResetTracer() { s_activeTracer = s_classTracer; } #endregion tracer internal static EnumerableExpansion GetEnumerableExpansionFromType(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection<string> typeNames) { TypeMatch match = new TypeMatch(expressionFactory, db, typeNames); foreach (EnumerableExpansionDirective expansionDirective in db.defaultSettingsSection.enumerableExpansionDirectiveList) { if (match.PerfectMatch(new TypeMatchItem(expansionDirective, expansionDirective.appliesTo))) { return expansionDirective.enumerableExpansion; } } if (match.BestMatch != null) { return ((EnumerableExpansionDirective)(match.BestMatch)).enumerableExpansion; } else { Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (null != typesWithoutPrefix) { EnumerableExpansion result = GetEnumerableExpansionFromType(expressionFactory, db, typesWithoutPrefix); return result; } // return a default value if no matches were found return EnumerableExpansion.EnumOnly; } } internal static FormatShape GetShapeFromType(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection<string> typeNames) { ShapeSelectionDirectives shapeDirectives = db.defaultSettingsSection.shapeSelectionDirectives; TypeMatch match = new TypeMatch(expressionFactory, db, typeNames); foreach (FormatShapeSelectionOnType shapeSelOnType in shapeDirectives.formatShapeSelectionOnTypeList) { if (match.PerfectMatch(new TypeMatchItem(shapeSelOnType, shapeSelOnType.appliesTo))) { return shapeSelOnType.formatShape; } } if (match.BestMatch != null) { return ((FormatShapeSelectionOnType)(match.BestMatch)).formatShape; } else { Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (null != typesWithoutPrefix) { FormatShape result = GetShapeFromType(expressionFactory, db, typesWithoutPrefix); return result; } // return a default value if no matches were found return FormatShape.Undefined; } } internal static FormatShape GetShapeFromPropertyCount(TypeInfoDataBase db, int propertyCount) { if (propertyCount <= db.defaultSettingsSection.shapeSelectionDirectives.PropertyCountForTable) return FormatShape.Table; return FormatShape.List; } internal static ViewDefinition GetViewByShapeAndType(MshExpressionFactory expressionFactory, TypeInfoDataBase db, FormatShape shape, Collection<string> typeNames, string viewName) { if (shape == FormatShape.Undefined) { return GetDefaultView(expressionFactory, db, typeNames); } // map the FormatShape to a type derived from ViewDefinition System.Type t = null; if (shape == FormatShape.Table) { t = typeof(TableControlBody); } else if (shape == FormatShape.List) { t = typeof(ListControlBody); } else if (shape == FormatShape.Wide) { t = typeof(WideControlBody); } else if (shape == FormatShape.Complex) { t = typeof(ComplexControlBody); } else { Diagnostics.Assert(false, "unknown shape: this should never happen unless a new shape is added"); return null; } return GetView(expressionFactory, db, t, typeNames, viewName); } internal static ViewDefinition GetOutOfBandView(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection<string> typeNames) { TypeMatch match = new TypeMatch(expressionFactory, db, typeNames); foreach (ViewDefinition vd in db.viewDefinitionsSection.viewDefinitionList) { if (!IsOutOfBandView(vd)) continue; if (match.PerfectMatch(new TypeMatchItem(vd, vd.appliesTo))) { return vd; } } // this is the best match we had ViewDefinition result = match.BestMatch as ViewDefinition; // we were unable to find a best match so far..try // to get rid of Deserialization prefix and see if a // match can be found. if (null == result) { Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (null != typesWithoutPrefix) { result = GetOutOfBandView(expressionFactory, db, typesWithoutPrefix); } } return result; } private static ViewDefinition GetView(MshExpressionFactory expressionFactory, TypeInfoDataBase db, System.Type mainControlType, Collection<string> typeNames, string viewName) { TypeMatch match = new TypeMatch(expressionFactory, db, typeNames); foreach (ViewDefinition vd in db.viewDefinitionsSection.viewDefinitionList) { if (vd == null || mainControlType != vd.mainControl.GetType()) { ActiveTracer.WriteLine( "NOT MATCH {0} NAME: {1}", ControlBase.GetControlShapeName(vd.mainControl), (null != vd ? vd.name : string.Empty)); continue; } if (IsOutOfBandView(vd)) { ActiveTracer.WriteLine( "NOT MATCH OutOfBand {0} NAME: {1}", ControlBase.GetControlShapeName(vd.mainControl), vd.name); continue; } if (vd.appliesTo == null) { ActiveTracer.WriteLine( "NOT MATCH {0} NAME: {1} No applicable types", ControlBase.GetControlShapeName(vd.mainControl), vd.name); continue; } // first make sure we match on name: // if not, we do not try a match at all if (viewName != null && !string.Equals(vd.name, viewName, StringComparison.OrdinalIgnoreCase)) { ActiveTracer.WriteLine( "NOT MATCH {0} NAME: {1}", ControlBase.GetControlShapeName(vd.mainControl), vd.name); continue; } // check if we have a perfect match // if so, we are done try { TypeMatch.SetTracer(ActiveTracer); if (match.PerfectMatch(new TypeMatchItem(vd, vd.appliesTo))) { TraceHelper(vd, true); return vd; } } finally { TypeMatch.ResetTracer(); } TraceHelper(vd, false); } // this is the best match we had ViewDefinition result = GetBestMatch(match); // we were unable to find a best match so far..try // to get rid of Deserialization prefix and see if a // match can be found. if (null == result) { Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (null != typesWithoutPrefix) { result = GetView(expressionFactory, db, mainControlType, typesWithoutPrefix, viewName); } } return result; } private static void TraceHelper(ViewDefinition vd, bool isMatched) { if ((ActiveTracer.Options & PSTraceSourceOptions.WriteLine) != 0) { foreach (TypeOrGroupReference togr in vd.appliesTo.referenceList) { StringBuilder sb = new StringBuilder(); TypeReference tr = togr as TypeReference; sb.Append(isMatched ? "MATCH FOUND" : "NOT MATCH"); if (tr != null) { sb.AppendFormat(CultureInfo.InvariantCulture, " {0} NAME: {1} TYPE: {2}", ControlBase.GetControlShapeName(vd.mainControl), vd.name, tr.name); } else { TypeGroupReference tgr = togr as TypeGroupReference; sb.AppendFormat(CultureInfo.InvariantCulture, " {0} NAME: {1} GROUP: {2}", ControlBase.GetControlShapeName(vd.mainControl), vd.name, tgr.name); } ActiveTracer.WriteLine(sb.ToString()); } } } private static ViewDefinition GetBestMatch(TypeMatch match) { ViewDefinition bestMatchedVD = match.BestMatch as ViewDefinition; if (bestMatchedVD != null) { TraceHelper(bestMatchedVD, true); } return bestMatchedVD; } private static ViewDefinition GetDefaultView(MshExpressionFactory expressionFactory, TypeInfoDataBase db, Collection<string> typeNames) { TypeMatch match = new TypeMatch(expressionFactory, db, typeNames); foreach (ViewDefinition vd in db.viewDefinitionsSection.viewDefinitionList) { if (vd == null) continue; if (IsOutOfBandView(vd)) { ActiveTracer.WriteLine( "NOT MATCH OutOfBand {0} NAME: {1}", ControlBase.GetControlShapeName(vd.mainControl), vd.name); continue; } if (vd.appliesTo == null) { ActiveTracer.WriteLine( "NOT MATCH {0} NAME: {1} No applicable types", ControlBase.GetControlShapeName(vd.mainControl), vd.name); continue; } try { TypeMatch.SetTracer(ActiveTracer); if (match.PerfectMatch(new TypeMatchItem(vd, vd.appliesTo))) { TraceHelper(vd, true); return vd; } } finally { TypeMatch.ResetTracer(); } TraceHelper(vd, false); } // this is the best match we had ViewDefinition result = GetBestMatch(match); // we were unable to find a best match so far..try // to get rid of Deserialization prefix and see if a // match can be found. if (null == result) { Collection<string> typesWithoutPrefix = Deserializer.MaskDeserializationPrefix(typeNames); if (null != typesWithoutPrefix) { result = GetDefaultView(expressionFactory, db, typesWithoutPrefix); } } return result; } private static bool IsOutOfBandView(ViewDefinition vd) { return (vd.mainControl is ComplexControlBody || vd.mainControl is ListControlBody) && vd.outOfBand; } /// <summary> /// given an appliesTo list, it finds all the types that are contained (following type /// group references) /// </summary> /// <param name="db">database to use</param> /// <param name="appliesTo">object to lookup</param> /// <returns></returns> internal static AppliesTo GetAllApplicableTypes(TypeInfoDataBase db, AppliesTo appliesTo) { Hashtable allTypes = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach (TypeOrGroupReference r in appliesTo.referenceList) { // if it is a type reference, just add the type name TypeReference tr = r as TypeReference; if (tr != null) { if (!allTypes.ContainsKey(tr.name)) allTypes.Add(tr.name, null); } else { // check if we have a type group reference TypeGroupReference tgr = r as TypeGroupReference; if (tgr == null) continue; // find the type group definition the reference points to TypeGroupDefinition tgd = FindGroupDefinition(db, tgr.name); if (tgd == null) continue; // we found the group, go over it foreach (TypeReference x in tgd.typeReferenceList) { if (!allTypes.ContainsKey(x.name)) allTypes.Add(x.name, null); } } } AppliesTo retVal = new AppliesTo(); foreach (DictionaryEntry x in allTypes) { retVal.AddAppliesToType(x.Key as string); } return retVal; } internal static TypeGroupDefinition FindGroupDefinition(TypeInfoDataBase db, string groupName) { foreach (TypeGroupDefinition tgd in db.typeGroupSection.typeGroupDefinitionList) { if (string.Equals(tgd.name, groupName, StringComparison.OrdinalIgnoreCase)) return tgd; } return null; } internal static ControlBody ResolveControlReference(TypeInfoDataBase db, List<ControlDefinition> viewControlDefinitionList, ControlReference controlReference) { // first tri to resolve the reference at the view level ControlBody controlBody = ResolveControlReferenceInList(controlReference, viewControlDefinitionList); if (controlBody != null) return controlBody; // fall back to the global definitions return ResolveControlReferenceInList(controlReference, db.formatControlDefinitionHolder.controlDefinitionList); } private static ControlBody ResolveControlReferenceInList(ControlReference controlReference, List<ControlDefinition> controlDefinitionList) { foreach (ControlDefinition x in controlDefinitionList) { if (x.controlBody.GetType() != controlReference.controlType) continue; if (String.Compare(controlReference.name, x.name, StringComparison.OrdinalIgnoreCase) == 0) return x.controlBody; } return null; } } }
#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; using System.Reflection; using System.Runtime.Serialization; using Spring.Util; #endregion namespace Spring.Aop.Support { /// <summary> /// <see cref="Spring.Aop.IPointcut"/> implementation that matches methods /// that have been decorated with a specified <see cref="System.Attribute"/>. /// </summary> /// <author>Aleksandar Seovic</author> /// <author>Ronald Wildenberg</author> [Serializable] public class AttributeMatchMethodPointcut : StaticMethodMatcherPointcut, ISerializable { private Type _attribute; private bool _inherit = true; private bool _checkInterfaces = false; /// <summary> /// Creates a new instance of the /// <see cref="Spring.Aop.Support.AttributeMatchMethodPointcut"/> class. /// </summary> public AttributeMatchMethodPointcut() { } /// <summary> /// Creates a new instance of the /// <see cref="Spring.Aop.Support.AttributeMatchMethodPointcut"/> class. /// </summary> /// <param name="attribute"> /// The <see cref="System.Attribute"/> to match. /// </param> public AttributeMatchMethodPointcut(Type attribute) : this(attribute, true, false) { } /// <summary> /// Creates a new instance of the /// <see cref="Spring.Aop.Support.AttributeMatchMethodPointcut"/> /// class. /// </summary> /// <param name="attribute"> /// The <see cref="System.Attribute"/> to match. /// </param> /// <param name="inherit"> /// Flag that controls whether or not the inheritance tree of the /// method to be included in the search for the <see cref="Attribute"/>? /// </param> public AttributeMatchMethodPointcut(Type attribute, bool inherit) : this(attribute, inherit, false) { } /// <summary> /// Creates a new instance of the /// <see cref="Spring.Aop.Support.AttributeMatchMethodPointcut"/> /// class. /// </summary> /// <param name="attribute"> /// The <see cref="System.Attribute"/> to match. /// </param> /// <param name="inherit"> /// Flag that controls whether or not the inheritance tree of the /// method to be included in the search for the <see cref="Attribute"/>? /// </param> /// <param name="checkInterfaces"> /// Flag that controls whether or not interfaces attributes of the /// method to be included in the search for the <see cref="Attribute"/>? /// </param> public AttributeMatchMethodPointcut(Type attribute, bool inherit, bool checkInterfaces) { Attribute = attribute; Inherit = inherit; CheckInterfaces = checkInterfaces; } /// <inheritdoc /> protected AttributeMatchMethodPointcut(SerializationInfo info, StreamingContext context) { Inherit = info.GetBoolean("Inherit"); CheckInterfaces = info.GetBoolean("CheckInterfaces"); var type = info.GetString("Attribute"); Attribute = type != null ? Type.GetType(type) : null; } /// <inheritdoc /> public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Attribute", Attribute?.AssemblyQualifiedName); info.AddValue("Inherit", Inherit); info.AddValue("CheckInterfaces", CheckInterfaces); } /// <summary> /// The <see cref="System.Attribute"/> to match. /// </summary> /// <exception cref="System.ArgumentException"> /// If the supplied value is not a <see cref="System.Type"/> that /// derives from the <see cref="System.Attribute"/> class. /// </exception> public virtual Type Attribute { get { return _attribute; } set { if (value != null) { if (!typeof (Attribute).IsAssignableFrom(value)) { throw new ArgumentException( string.Format( "The [{0}] Type must be derived from the [System.Attribute] class.", value)); } } _attribute = value; } } /// <summary> /// Is the inheritance tree of the method to be included in the search for the /// <see cref="Attribute"/>? /// </summary> /// <remarks> /// <p> /// The default is <see langword="true"/>. /// </p> /// </remarks> public virtual bool Inherit { get { return _inherit; } set { _inherit = value; } } /// <summary> /// Is the interfaces attributes of the method to be included in the search for theg /// <see cref="Attribute"/>? /// </summary> /// <remarks> /// <p> /// The default is <see langword="false"/>. /// </p> /// </remarks> public virtual bool CheckInterfaces { get { return _checkInterfaces; } set { _checkInterfaces = value; } } /// <summary> /// Does the supplied <paramref name="method"/> satisfy this matcher? /// </summary> /// <param name="method">The candidate method.</param> /// <param name="targetType"> /// The target <see cref="System.Type"/> (may be <see langword="null"/>, /// in which case the candidate <see cref="System.Type"/> must be taken /// to be the <paramref name="method"/>'s declaring class). /// </param> /// <returns> /// <see langword="true"/> if this this method matches statically. /// </returns> public override bool Matches(MethodInfo method, Type targetType) { if (method.IsDefined(Attribute, Inherit)) { // Checks whether the attribute is defined on the method or a super definition of the method // but does not check attributes on implemented interfaces. return true; } else { if (CheckInterfaces) { // Also check whether the attribute is defined on a method implemented from an interface. // First find all interfaces for the type that contains the method. // Next, check each interface for the presence of the attribute on the corresponding // method from the interface. Type[] parameterTypes = ReflectionUtils.GetParameterTypes(method); foreach (Type interfaceType in method.DeclaringType.GetInterfaces()) { // The method may be implemented explicitly, so the method name // will include the interface name also string methodName = method.Name; if (methodName.IndexOf('.') != -1) { if (methodName.StartsWith(interfaceType.FullName.Replace('+', '.'))) { methodName = methodName.Remove(0, interfaceType.FullName.Length + 1); } } MethodInfo intfMethod = interfaceType.GetMethod(methodName, parameterTypes); if (intfMethod != null && intfMethod.IsDefined(Attribute, Inherit)) { return true; } } } return false; } } } }
using System; using System.Text; using ICSharpCode.NRefactory.Parser.AST; using System.Collections; using System.Collections.Generic; namespace ClassDynamizer { class Dynamizer { /// <summary> /// Dynamizes a given compile unit. /// </summary> public CompilationUnit Dynamize(CompilationUnit unit) { CompilationUnit out_unit = new CompilationUnit(); // add Phalanger imports Utility.AddImport(unit, out_unit, "PHP.Core"); Utility.AddImport(unit, out_unit, "PHP.Core.Reflection"); foreach (INode node in unit.Children) { // add all original imports if (node is UsingDeclaration) out_unit.Children.Add(node); // process namespaces NamespaceDeclaration ns_decl = node as NamespaceDeclaration; if (ns_decl != null) { NamespaceDeclaration out_ns_decl = new NamespaceDeclaration(ns_decl.Name); out_unit.Children.Add(out_ns_decl); foreach (INode subnode in ns_decl.Children) { TypeDeclaration type_decl = subnode as TypeDeclaration; if (type_decl != null) { type_decl = Dynamize(type_decl); if (type_decl != null) out_ns_decl.Children.Add(type_decl); } } } // as well as top-level types without namespaces TypeDeclaration bare_type_decl = node as TypeDeclaration; if (bare_type_decl != null) { bare_type_decl = Dynamize(bare_type_decl); if (bare_type_decl != null) out_unit.Children.Add(bare_type_decl); } } return out_unit; } /// <summary> /// Dynamizes a given type. /// </summary> private TypeDeclaration Dynamize(TypeDeclaration type) { if (!Utility.IsDecoratedByAttribute(type, "PHP.Core.ImplementsType")) return null; TypeDeclaration out_type = new TypeDeclaration(type.Modifier, new List<AttributeSection>()); out_type.Name = type.Name; AddSerializibility(type, out_type); FixInheritance(type, out_type); DynamizeMembers(type, out_type); return out_type; } #region Serializibility & Inheritance /// <summary> /// Makes sure that the PHP-visible type is serializable. /// </summary> private void AddSerializibility(TypeDeclaration type, TypeDeclaration outType) { // make the type serializable if (!Utility.IsDecoratedByAttribute(type, "System.SerializableAttribute")) { AttributeSection section = new AttributeSection(); section.Attributes.Add(new ICSharpCode.NRefactory.Parser.AST.Attribute("Serializable", null, null)); outType.Attributes.Add(section); ConstructorDeclaration ctor = new ConstructorDeclaration(type.Name, ((type.Modifier & Modifier.Sealed) == Modifier.Sealed ? Modifier.Private : Modifier.Protected), new List<ParameterDeclarationExpression>(), null); ctor.Parameters.Add( new ParameterDeclarationExpression(new TypeReference("System.Runtime.Serialization.SerializationInfo"), "info")); ctor.Parameters.Add( new ParameterDeclarationExpression(new TypeReference("System.Runtime.Serialization.StreamingContext"), "context")); ctor.ConstructorInitializer = new ConstructorInitializer(); ctor.ConstructorInitializer.ConstructorInitializerType = ConstructorInitializerType.Base; ctor.ConstructorInitializer.Arguments.Add(new IdentifierExpression("info")); ctor.ConstructorInitializer.Arguments.Add(new IdentifierExpression("context")); ctor.Body = new BlockStatement(); outType.AddChild(ctor); } } /// <summary> /// Makes sure that the PHP-visible type derives from PhpObject and adds appropriate constructors. /// </summary> private void FixInheritance(TypeDeclaration type, TypeDeclaration outType) { // make the type inherit from PhpObject bool has_base = false; foreach (TypeReference base_type in type.BaseTypes) { // TODO: base this decision on an attribute? if (!base_type.Type.StartsWith("I") && !base_type.Type.StartsWith("SPL.")) { has_base = true; break; } } if (!has_base) outType.BaseTypes.Add(new TypeReference("PhpObject")); // add the necessary constructors bool has_short_ctor = false; bool has_long_ctor = false; BlockStatement default_ctor_body = null; foreach (INode member in type.Children) { ConstructorDeclaration ctor = member as ConstructorDeclaration; if (ctor != null) { if (ctor.Parameters.Count == 2 && Utility.IsType(ctor.Parameters[0].TypeReference, "PHP.Core.ScriptContext")) { if (Utility.IsType(ctor.Parameters[1].TypeReference, "System.Boolean")) has_short_ctor = true; if (Utility.IsType(ctor.Parameters[1].TypeReference, "PHP.Core.Reflection.DTypeDesc")) has_long_ctor = true; } else if (ctor.Parameters.Count == 0) { default_ctor_body = ctor.Body; } } } if (!has_short_ctor) { ConstructorDeclaration ctor = new ConstructorDeclaration(type.Name, Modifier.Public, new List<ParameterDeclarationExpression>(), null); ctor.Parameters.Add(new ParameterDeclarationExpression(new TypeReference("ScriptContext"), "context")); ctor.Parameters.Add(new ParameterDeclarationExpression(new TypeReference("Boolean"), "newInstance")); ctor.ConstructorInitializer = new ConstructorInitializer(); ctor.ConstructorInitializer.ConstructorInitializerType = ConstructorInitializerType.Base; ctor.ConstructorInitializer.Arguments.Add(new IdentifierExpression("context")); ctor.ConstructorInitializer.Arguments.Add(new IdentifierExpression("newInstance")); if (default_ctor_body == null) ctor.Body = new BlockStatement(); else ctor.Body = default_ctor_body; Utility.MakeNonBrowsable(ctor); outType.AddChild(ctor); } if (!has_long_ctor) { ConstructorDeclaration ctor = new ConstructorDeclaration(type.Name, Modifier.Public, new List<ParameterDeclarationExpression>(), null); ctor.Parameters.Add(new ParameterDeclarationExpression(new TypeReference("ScriptContext"), "context")); ctor.Parameters.Add(new ParameterDeclarationExpression(new TypeReference("DTypeDesc"), "caller")); IdentifierExpression context_param = new IdentifierExpression("context"); IdentifierExpression caller_param = new IdentifierExpression("caller"); ctor.ConstructorInitializer = new ConstructorInitializer(); ctor.ConstructorInitializer.ConstructorInitializerType = ConstructorInitializerType.This; ctor.ConstructorInitializer.Arguments.Add(context_param); ctor.ConstructorInitializer.Arguments.Add(new PrimitiveExpression(true, String.Empty)); InvocationExpression invocation = new InvocationExpression( new FieldReferenceExpression(new ThisReferenceExpression(), "InvokeConstructor"), new ArrayList()); invocation.Arguments.Add(context_param); invocation.Arguments.Add(caller_param); ctor.Body = new BlockStatement(); ctor.Body.AddChild(new StatementExpression(invocation)); Utility.MakeNonBrowsable(ctor); outType.AddChild(ctor); } } #endregion /// <summary> /// Adds argfull and argless stubs for all PHP visible members. /// </summary> private void DynamizeMembers(TypeDeclaration type, TypeDeclaration outType) { List<Statement> populate_statements = new List<Statement>(); foreach (INode member in type.Children) { AttributedNode node = member as AttributedNode; if (node != null && Utility.IsDecoratedByAttribute(node, "PHP.Core.PhpVisibleAttribute")) { MethodDeclaration method_decl; PropertyDeclaration prop_decl; if ((method_decl = member as MethodDeclaration) != null) { populate_statements.Add(DynamizeMethod(method_decl, outType)); } else if ((prop_decl = member as PropertyDeclaration) != null) { populate_statements.Add(DynamizeProperty(prop_decl, outType)); } else throw new InvalidOperationException("PhpVisible applied to invalid member"); } } // add the __PopulateTypeDesc method MethodDeclaration populator = new MethodDeclaration( "__PopulateTypeDesc", Modifier.Private | Modifier.Static, new TypeReference("void", "System.Void"), new List<ParameterDeclarationExpression>(), null); populator.Parameters.Add(new ParameterDeclarationExpression(new TypeReference("PhpTypeDesc"), "desc")); populator.Body = new BlockStatement(); foreach (Statement stmt in populate_statements) { if (stmt != null) populator.Body.AddChild(stmt); } outType.AddChild(populator); } #region Method dynamization /// <summary> /// Adds stubs for a PhpVisible method. /// </summary> private Statement DynamizeMethod(MethodDeclaration method, TypeDeclaration outType) { bool has_this; MethodDeclaration argfull = CreateArgfull(method, false, out has_this); if (has_this) { outType.AddChild(argfull); argfull = CreateArgfull(method, true, out has_this); } outType.AddChild(argfull); MethodDeclaration argless = CreateArgless(method); outType.AddChild(argless); // return an expression to be put to __PopulateTypeDesc ArrayList parameters = new ArrayList(); parameters.Add(new PrimitiveExpression(method.Name, method.Name)); parameters.Add(Utility.ModifierToMemberAttributes(argfull.Modifier)); ArrayList del_params = new ArrayList(); del_params.Add(new FieldReferenceExpression( new TypeReferenceExpression(((TypeDeclaration)method.Parent).Name), method.Name)); parameters.Add(new ObjectCreateExpression(new TypeReference("RoutineDelegate"), del_params)); return new StatementExpression(new InvocationExpression( new FieldReferenceExpression(new IdentifierExpression("desc"), "AddMethod"), parameters)); } /// <summary> /// Creates an argfull stub for the specified implementation method. /// </summary> private MethodDeclaration CreateArgfull(MethodDeclaration template, bool skipThisParams, out bool hasThisParams) { hasThisParams = false; MethodDeclaration method = new MethodDeclaration(template.Name, template.Modifier, new TypeReference("Object"), new List<ParameterDeclarationExpression>(), new List<AttributeSection>()); method.Body = new BlockStatement(); Expression[] arguments = new Expression[template.Parameters.Count]; // prepend a ScriptContext parameter and make all parameters Objects // (TODO: PhpReferences for ref parameters) method.Parameters.Add(new ParameterDeclarationExpression(new TypeReference("ScriptContext"), "__context")); int arg_counter = 0; foreach (ParameterDeclarationExpression param in template.Parameters) { ParameterDeclarationExpression new_param = new ParameterDeclarationExpression(new TypeReference("Object"), param.ParameterName); bool optional = false; if (Utility.IsDecoratedByAttribute(param.Attributes, Utility.OptionalAttrType)) { AttributeSection section = new AttributeSection(); new_param.Attributes.Add(section); section.Attributes.Add(new ICSharpCode.NRefactory.Parser.AST.Attribute(Utility.OptionalAttrType, null, null)); optional = true; } bool this_param = Utility.IsDecoratedByAttribute(param.Attributes, "PHP.Core.ThisAttribute"); if (this_param) hasThisParams = true; if (this_param && skipThisParams) { arguments[arg_counter++] = new PrimitiveExpression(null, String.Empty); } else { // generate conversion arguments[arg_counter++] = Convertor.ConvertTo( template.Name, new IdentifierExpression(param.ParameterName), param.TypeReference, method.Body, new ReturnStatement(new PrimitiveExpression(null, String.Empty)), Utility.IsDecoratedByAttribute(param.Attributes, "PHP.Core.NullableAttribute") || this_param, optional, arg_counter); method.Parameters.Add(new_param); } } // invoke the template method InvocationExpression invocation = new InvocationExpression(new IdentifierExpression(template.Name), new ArrayList(arguments)); if (template.TypeReference.SystemType == "System.Void") { method.Body.AddChild(new StatementExpression(invocation)); method.Body.AddChild(new ReturnStatement(new PrimitiveExpression(null, String.Empty))); } else method.Body.AddChild(new ReturnStatement(invocation)); if (!hasThisParams || skipThisParams) Utility.MakeNonBrowsable(method); return method; } /// <summary> /// Creates an argless stub for the specified implementation method. /// </summary> private MethodDeclaration CreateArgless(MethodDeclaration template) { MethodDeclaration method = new MethodDeclaration(template.Name, Modifier.Public | Modifier.Static, new TypeReference("Object"), new List<ParameterDeclarationExpression>(), new List<AttributeSection>()); method.Parameters.Add(new ParameterDeclarationExpression(new TypeReference("Object"), "instance")); method.Parameters.Add(new ParameterDeclarationExpression(new TypeReference("PhpStack"), "stack")); method.Body = new BlockStatement(); // stack.CalleeName = <template name> method.Body.AddChild(new StatementExpression(new AssignmentExpression(new FieldReferenceExpression( new IdentifierExpression("stack"), "CalleeName"), AssignmentOperatorType.Assign, new PrimitiveExpression(template.Name, template.Name)))); // peek arguments int arg_counter = 0, shift = 0; foreach (ParameterDeclarationExpression param in template.Parameters) { arg_counter++; LocalVariableDeclaration arg_local = new LocalVariableDeclaration(new TypeReference("Object")); Expression initializer; if (Utility.IsDecoratedByAttribute(param.Attributes, "PHP.Core.ThisAttribute")) { initializer = new IdentifierExpression("instance"); shift++; } else { ArrayList peek_params = new ArrayList(); peek_params.Add(new PrimitiveExpression(arg_counter - shift, String.Empty)); if (Utility.IsDecoratedByAttribute(param.Attributes, Utility.OptionalAttrType)) { initializer = new InvocationExpression(new FieldReferenceExpression( new IdentifierExpression("stack"), "PeekValueOptional"), peek_params); } else { initializer = new InvocationExpression(new FieldReferenceExpression( new IdentifierExpression("stack"), "PeekValue"), peek_params); } } arg_local.Variables.Add(new VariableDeclaration(String.Format("arg{0}", arg_counter), initializer)); method.Body.AddChild(arg_local); } // stack.RemoveFrame() method.Body.AddChild(new StatementExpression(new InvocationExpression(new FieldReferenceExpression( new IdentifierExpression("stack"), "RemoveFrame"), new ArrayList()))); // return [invoke argfull] ArrayList argfull_params = new ArrayList(); argfull_params.Add(new FieldReferenceExpression(new IdentifierExpression("stack"), "Context")); for (int i = 0; i < template.Parameters.Count; i++) { argfull_params.Add(new IdentifierExpression(String.Format("arg{0}", i + 1))); } if ((template.Modifier & Modifier.Static) == Modifier.Static) { method.Body.AddChild(new ReturnStatement(new InvocationExpression(new IdentifierExpression( template.Name), argfull_params))); } else { method.Body.AddChild(new ReturnStatement(new InvocationExpression( new FieldReferenceExpression(new ParenthesizedExpression( new CastExpression(new TypeReference(((TypeDeclaration)template.Parent).Name), new IdentifierExpression("instance"))), template.Name), argfull_params))); } Utility.MakeNonBrowsable(method); return method; } #endregion #region Property dynamization /// <summary> /// Adds stubs for a PhpVisible property. /// </summary> private Statement DynamizeProperty(PropertyDeclaration property, TypeDeclaration outType) { MethodDeclaration getter = null, setter = null; if (property.HasGetRegion) { // add the getter stub getter = new MethodDeclaration( "__get_" + property.Name, Modifier.Private | Modifier.Static, new TypeReference("Object"), new List<ParameterDeclarationExpression>(), new List<AttributeSection>()); getter.Parameters.Add(new ParameterDeclarationExpression(new TypeReference("Object"), "instance")); getter.Body = new BlockStatement(); getter.Body.AddChild(new ReturnStatement(new FieldReferenceExpression(new ParenthesizedExpression( new CastExpression(new TypeReference(((TypeDeclaration)property.Parent).Name), new IdentifierExpression("instance"))), property.Name))); outType.AddChild(getter); } if (property.HasSetRegion) { // add the setter stub setter = new MethodDeclaration( "__set_" + property.Name, Modifier.Private | Modifier.Static, new TypeReference("void", "System.Void"), new List<ParameterDeclarationExpression>(), new List<AttributeSection>()); setter.Parameters.Add(new ParameterDeclarationExpression(new TypeReference("Object"), "instance")); setter.Parameters.Add(new ParameterDeclarationExpression(new TypeReference("Object"), "value")); setter.Body = new BlockStatement(); Expression rhs = Convertor.ConvertTo( property.Name, new IdentifierExpression("value"), property.TypeReference, setter.Body, new ReturnStatement(NullExpression.Instance), false, false, 1); setter.Body.AddChild(new StatementExpression(new AssignmentExpression( (new FieldReferenceExpression(new ParenthesizedExpression( new CastExpression(new TypeReference(((TypeDeclaration)property.Parent).Name), new IdentifierExpression("instance"))), property.Name)), AssignmentOperatorType.Assign, rhs))); outType.AddChild(setter); } // return an expression to be put to __PopulateTypeDesc ArrayList parameters = new ArrayList(); parameters.Add(new PrimitiveExpression(property.Name, property.Name)); parameters.Add(Utility.ModifierToMemberAttributes(property.Modifier)); if (getter != null) { ArrayList del_params = new ArrayList(); del_params.Add(new FieldReferenceExpression( new TypeReferenceExpression(((TypeDeclaration)property.Parent).Name), getter.Name)); parameters.Add(new ObjectCreateExpression(new TypeReference("GetterDelegate"), del_params)); } else parameters.Add(new PrimitiveExpression(null, String.Empty)); if (setter != null) { ArrayList del_params = new ArrayList(); del_params.Add(new FieldReferenceExpression( new TypeReferenceExpression(((TypeDeclaration)property.Parent).Name), setter.Name)); parameters.Add(new ObjectCreateExpression(new TypeReference("SetterDelegate"), del_params)); } else parameters.Add(new PrimitiveExpression(null, String.Empty)); return new StatementExpression(new InvocationExpression( new FieldReferenceExpression(new IdentifierExpression("desc"), "AddProperty"), parameters)); } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedInstancesClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceRequest request = new GetInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; Instance expectedResponse = new Instance { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Tags = new Tags(), Zone = "zone255f4ea8", ShieldedInstanceConfig = new ShieldedInstanceConfig(), ResourcePolicies = { "resource_policiesdff15734", }, CreationTimestamp = "creation_timestamp235e59a1", PrivateIpv6GoogleAccess = Instance.Types.PrivateIpv6GoogleAccess.InheritFromSubnetwork, NetworkInterfaces = { new NetworkInterface(), }, Metadata = new Metadata(), Disks = { new AttachedDisk(), }, StartRestricted = true, ReservationAffinity = new ReservationAffinity(), ShieldedInstanceIntegrityPolicy = new ShieldedInstanceIntegrityPolicy(), LabelFingerprint = "label_fingerprint06ccff3a", Status = Instance.Types.Status.Provisioning, MachineType = "machine_type68ce40fa", Fingerprint = "fingerprint009e6052", Hostname = "hostnamef4ac9708", MinCpuPlatform = "min_cpu_platformf71ffa67", DisplayDevice = new DisplayDevice(), ServiceAccounts = { new ServiceAccount(), }, StatusMessage = "status_message2c618f86", LastSuspendedTimestamp = "last_suspended_timestamp1e59392b", Scheduling = new Scheduling(), AdvancedMachineFeatures = new AdvancedMachineFeatures(), CpuPlatform = "cpu_platformd5794042", LastStopTimestamp = "last_stop_timestampd336a8f1", Description = "description2cf9da67", LastStartTimestamp = "last_start_timestampe26bd347", SelfLink = "self_link7e87f12d", DeletionProtection = false, GuestAccelerators = { new AcceleratorConfig(), }, CanIpForward = true, SatisfiesPzs = false, ConfidentialInstanceConfig = new ConfidentialInstanceConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); Instance response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceRequest request = new GetInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; Instance expectedResponse = new Instance { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Tags = new Tags(), Zone = "zone255f4ea8", ShieldedInstanceConfig = new ShieldedInstanceConfig(), ResourcePolicies = { "resource_policiesdff15734", }, CreationTimestamp = "creation_timestamp235e59a1", PrivateIpv6GoogleAccess = Instance.Types.PrivateIpv6GoogleAccess.InheritFromSubnetwork, NetworkInterfaces = { new NetworkInterface(), }, Metadata = new Metadata(), Disks = { new AttachedDisk(), }, StartRestricted = true, ReservationAffinity = new ReservationAffinity(), ShieldedInstanceIntegrityPolicy = new ShieldedInstanceIntegrityPolicy(), LabelFingerprint = "label_fingerprint06ccff3a", Status = Instance.Types.Status.Provisioning, MachineType = "machine_type68ce40fa", Fingerprint = "fingerprint009e6052", Hostname = "hostnamef4ac9708", MinCpuPlatform = "min_cpu_platformf71ffa67", DisplayDevice = new DisplayDevice(), ServiceAccounts = { new ServiceAccount(), }, StatusMessage = "status_message2c618f86", LastSuspendedTimestamp = "last_suspended_timestamp1e59392b", Scheduling = new Scheduling(), AdvancedMachineFeatures = new AdvancedMachineFeatures(), CpuPlatform = "cpu_platformd5794042", LastStopTimestamp = "last_stop_timestampd336a8f1", Description = "description2cf9da67", LastStartTimestamp = "last_start_timestampe26bd347", SelfLink = "self_link7e87f12d", DeletionProtection = false, GuestAccelerators = { new AcceleratorConfig(), }, CanIpForward = true, SatisfiesPzs = false, ConfidentialInstanceConfig = new ConfidentialInstanceConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Instance>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); Instance responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Instance responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceRequest request = new GetInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; Instance expectedResponse = new Instance { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Tags = new Tags(), Zone = "zone255f4ea8", ShieldedInstanceConfig = new ShieldedInstanceConfig(), ResourcePolicies = { "resource_policiesdff15734", }, CreationTimestamp = "creation_timestamp235e59a1", PrivateIpv6GoogleAccess = Instance.Types.PrivateIpv6GoogleAccess.InheritFromSubnetwork, NetworkInterfaces = { new NetworkInterface(), }, Metadata = new Metadata(), Disks = { new AttachedDisk(), }, StartRestricted = true, ReservationAffinity = new ReservationAffinity(), ShieldedInstanceIntegrityPolicy = new ShieldedInstanceIntegrityPolicy(), LabelFingerprint = "label_fingerprint06ccff3a", Status = Instance.Types.Status.Provisioning, MachineType = "machine_type68ce40fa", Fingerprint = "fingerprint009e6052", Hostname = "hostnamef4ac9708", MinCpuPlatform = "min_cpu_platformf71ffa67", DisplayDevice = new DisplayDevice(), ServiceAccounts = { new ServiceAccount(), }, StatusMessage = "status_message2c618f86", LastSuspendedTimestamp = "last_suspended_timestamp1e59392b", Scheduling = new Scheduling(), AdvancedMachineFeatures = new AdvancedMachineFeatures(), CpuPlatform = "cpu_platformd5794042", LastStopTimestamp = "last_stop_timestampd336a8f1", Description = "description2cf9da67", LastStartTimestamp = "last_start_timestampe26bd347", SelfLink = "self_link7e87f12d", DeletionProtection = false, GuestAccelerators = { new AcceleratorConfig(), }, CanIpForward = true, SatisfiesPzs = false, ConfidentialInstanceConfig = new ConfidentialInstanceConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); Instance response = client.Get(request.Project, request.Zone, request.Instance); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetInstanceRequest request = new GetInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; Instance expectedResponse = new Instance { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Tags = new Tags(), Zone = "zone255f4ea8", ShieldedInstanceConfig = new ShieldedInstanceConfig(), ResourcePolicies = { "resource_policiesdff15734", }, CreationTimestamp = "creation_timestamp235e59a1", PrivateIpv6GoogleAccess = Instance.Types.PrivateIpv6GoogleAccess.InheritFromSubnetwork, NetworkInterfaces = { new NetworkInterface(), }, Metadata = new Metadata(), Disks = { new AttachedDisk(), }, StartRestricted = true, ReservationAffinity = new ReservationAffinity(), ShieldedInstanceIntegrityPolicy = new ShieldedInstanceIntegrityPolicy(), LabelFingerprint = "label_fingerprint06ccff3a", Status = Instance.Types.Status.Provisioning, MachineType = "machine_type68ce40fa", Fingerprint = "fingerprint009e6052", Hostname = "hostnamef4ac9708", MinCpuPlatform = "min_cpu_platformf71ffa67", DisplayDevice = new DisplayDevice(), ServiceAccounts = { new ServiceAccount(), }, StatusMessage = "status_message2c618f86", LastSuspendedTimestamp = "last_suspended_timestamp1e59392b", Scheduling = new Scheduling(), AdvancedMachineFeatures = new AdvancedMachineFeatures(), CpuPlatform = "cpu_platformd5794042", LastStopTimestamp = "last_stop_timestampd336a8f1", Description = "description2cf9da67", LastStartTimestamp = "last_start_timestampe26bd347", SelfLink = "self_link7e87f12d", DeletionProtection = false, GuestAccelerators = { new AcceleratorConfig(), }, CanIpForward = true, SatisfiesPzs = false, ConfidentialInstanceConfig = new ConfidentialInstanceConfig(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Instance>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); Instance responseCallSettings = await client.GetAsync(request.Project, request.Zone, request.Instance, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Instance responseCancellationToken = await client.GetAsync(request.Project, request.Zone, request.Instance, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetEffectiveFirewallsRequestObject() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetEffectiveFirewallsInstanceRequest request = new GetEffectiveFirewallsInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", NetworkInterface = "network_interfaceb50da44f", }; InstancesGetEffectiveFirewallsResponse expectedResponse = new InstancesGetEffectiveFirewallsResponse { Firewalls = { new Firewall(), }, FirewallPolicys = { new InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy(), }, }; mockGrpcClient.Setup(x => x.GetEffectiveFirewalls(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); InstancesGetEffectiveFirewallsResponse response = client.GetEffectiveFirewalls(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetEffectiveFirewallsRequestObjectAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetEffectiveFirewallsInstanceRequest request = new GetEffectiveFirewallsInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", NetworkInterface = "network_interfaceb50da44f", }; InstancesGetEffectiveFirewallsResponse expectedResponse = new InstancesGetEffectiveFirewallsResponse { Firewalls = { new Firewall(), }, FirewallPolicys = { new InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy(), }, }; mockGrpcClient.Setup(x => x.GetEffectiveFirewallsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstancesGetEffectiveFirewallsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); InstancesGetEffectiveFirewallsResponse responseCallSettings = await client.GetEffectiveFirewallsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); InstancesGetEffectiveFirewallsResponse responseCancellationToken = await client.GetEffectiveFirewallsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetEffectiveFirewalls() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetEffectiveFirewallsInstanceRequest request = new GetEffectiveFirewallsInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", NetworkInterface = "network_interfaceb50da44f", }; InstancesGetEffectiveFirewallsResponse expectedResponse = new InstancesGetEffectiveFirewallsResponse { Firewalls = { new Firewall(), }, FirewallPolicys = { new InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy(), }, }; mockGrpcClient.Setup(x => x.GetEffectiveFirewalls(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); InstancesGetEffectiveFirewallsResponse response = client.GetEffectiveFirewalls(request.Project, request.Zone, request.Instance, request.NetworkInterface); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetEffectiveFirewallsAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetEffectiveFirewallsInstanceRequest request = new GetEffectiveFirewallsInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", NetworkInterface = "network_interfaceb50da44f", }; InstancesGetEffectiveFirewallsResponse expectedResponse = new InstancesGetEffectiveFirewallsResponse { Firewalls = { new Firewall(), }, FirewallPolicys = { new InstancesGetEffectiveFirewallsResponseEffectiveFirewallPolicy(), }, }; mockGrpcClient.Setup(x => x.GetEffectiveFirewallsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<InstancesGetEffectiveFirewallsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); InstancesGetEffectiveFirewallsResponse responseCallSettings = await client.GetEffectiveFirewallsAsync(request.Project, request.Zone, request.Instance, request.NetworkInterface, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); InstancesGetEffectiveFirewallsResponse responseCancellationToken = await client.GetEffectiveFirewallsAsync(request.Project, request.Zone, request.Instance, request.NetworkInterface, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetGuestAttributesRequestObject() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGuestAttributesInstanceRequest request = new GetGuestAttributesInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", VariableKey = "variable_key1c249a45", Project = "projectaa6ff846", QueryPath = "query_pathf44da93a", }; GuestAttributes expectedResponse = new GuestAttributes { Kind = "kindf7aa39d9", VariableValue = "variable_value61cc0fab", QueryValue = new GuestAttributesValue(), VariableKey = "variable_key1c249a45", QueryPath = "query_pathf44da93a", SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.GetGuestAttributes(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); GuestAttributes response = client.GetGuestAttributes(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetGuestAttributesRequestObjectAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGuestAttributesInstanceRequest request = new GetGuestAttributesInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", VariableKey = "variable_key1c249a45", Project = "projectaa6ff846", QueryPath = "query_pathf44da93a", }; GuestAttributes expectedResponse = new GuestAttributes { Kind = "kindf7aa39d9", VariableValue = "variable_value61cc0fab", QueryValue = new GuestAttributesValue(), VariableKey = "variable_key1c249a45", QueryPath = "query_pathf44da93a", SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.GetGuestAttributesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GuestAttributes>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); GuestAttributes responseCallSettings = await client.GetGuestAttributesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GuestAttributes responseCancellationToken = await client.GetGuestAttributesAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetGuestAttributes() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGuestAttributesInstanceRequest request = new GetGuestAttributesInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; GuestAttributes expectedResponse = new GuestAttributes { Kind = "kindf7aa39d9", VariableValue = "variable_value61cc0fab", QueryValue = new GuestAttributesValue(), VariableKey = "variable_key1c249a45", QueryPath = "query_pathf44da93a", SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.GetGuestAttributes(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); GuestAttributes response = client.GetGuestAttributes(request.Project, request.Zone, request.Instance); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetGuestAttributesAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGuestAttributesInstanceRequest request = new GetGuestAttributesInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; GuestAttributes expectedResponse = new GuestAttributes { Kind = "kindf7aa39d9", VariableValue = "variable_value61cc0fab", QueryValue = new GuestAttributesValue(), VariableKey = "variable_key1c249a45", QueryPath = "query_pathf44da93a", SelfLink = "self_link7e87f12d", }; mockGrpcClient.Setup(x => x.GetGuestAttributesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GuestAttributes>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); GuestAttributes responseCallSettings = await client.GetGuestAttributesAsync(request.Project, request.Zone, request.Instance, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GuestAttributes responseCancellationToken = await client.GetGuestAttributesAsync(request.Project, request.Zone, request.Instance, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyRequestObject() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyInstanceRequest request = new GetIamPolicyInstanceRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", OptionsRequestedPolicyVersion = -1471234741, }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); Policy response = client.GetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyRequestObjectAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyInstanceRequest request = new GetIamPolicyInstanceRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", OptionsRequestedPolicyVersion = -1471234741, }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicy() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyInstanceRequest request = new GetIamPolicyInstanceRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); Policy response = client.GetIamPolicy(request.Project, request.Zone, request.Resource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyInstanceRequest request = new GetIamPolicyInstanceRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetIamPolicyAsync(request.Project, request.Zone, request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Project, request.Zone, request.Resource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetScreenshotRequestObject() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetScreenshotInstanceRequest request = new GetScreenshotInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; Screenshot expectedResponse = new Screenshot { Kind = "kindf7aa39d9", Contents = "contents8c7dbf98", }; mockGrpcClient.Setup(x => x.GetScreenshot(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); Screenshot response = client.GetScreenshot(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetScreenshotRequestObjectAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetScreenshotInstanceRequest request = new GetScreenshotInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; Screenshot expectedResponse = new Screenshot { Kind = "kindf7aa39d9", Contents = "contents8c7dbf98", }; mockGrpcClient.Setup(x => x.GetScreenshotAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Screenshot>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); Screenshot responseCallSettings = await client.GetScreenshotAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Screenshot responseCancellationToken = await client.GetScreenshotAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetScreenshot() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetScreenshotInstanceRequest request = new GetScreenshotInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; Screenshot expectedResponse = new Screenshot { Kind = "kindf7aa39d9", Contents = "contents8c7dbf98", }; mockGrpcClient.Setup(x => x.GetScreenshot(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); Screenshot response = client.GetScreenshot(request.Project, request.Zone, request.Instance); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetScreenshotAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetScreenshotInstanceRequest request = new GetScreenshotInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; Screenshot expectedResponse = new Screenshot { Kind = "kindf7aa39d9", Contents = "contents8c7dbf98", }; mockGrpcClient.Setup(x => x.GetScreenshotAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Screenshot>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); Screenshot responseCallSettings = await client.GetScreenshotAsync(request.Project, request.Zone, request.Instance, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Screenshot responseCancellationToken = await client.GetScreenshotAsync(request.Project, request.Zone, request.Instance, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetSerialPortOutputRequestObject() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetSerialPortOutputInstanceRequest request = new GetSerialPortOutputInstanceRequest { Port = -78310000, Zone = "zone255f4ea8", Instance = "instance99a62371", Start = -5616678393427383318L, Project = "projectaa6ff846", }; SerialPortOutput expectedResponse = new SerialPortOutput { Kind = "kindf7aa39d9", Next = 9139246809011047120L, Start = -5616678393427383318L, SelfLink = "self_link7e87f12d", Contents = "contents8c7dbf98", }; mockGrpcClient.Setup(x => x.GetSerialPortOutput(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); SerialPortOutput response = client.GetSerialPortOutput(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSerialPortOutputRequestObjectAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetSerialPortOutputInstanceRequest request = new GetSerialPortOutputInstanceRequest { Port = -78310000, Zone = "zone255f4ea8", Instance = "instance99a62371", Start = -5616678393427383318L, Project = "projectaa6ff846", }; SerialPortOutput expectedResponse = new SerialPortOutput { Kind = "kindf7aa39d9", Next = 9139246809011047120L, Start = -5616678393427383318L, SelfLink = "self_link7e87f12d", Contents = "contents8c7dbf98", }; mockGrpcClient.Setup(x => x.GetSerialPortOutputAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SerialPortOutput>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); SerialPortOutput responseCallSettings = await client.GetSerialPortOutputAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SerialPortOutput responseCancellationToken = await client.GetSerialPortOutputAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetSerialPortOutput() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetSerialPortOutputInstanceRequest request = new GetSerialPortOutputInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; SerialPortOutput expectedResponse = new SerialPortOutput { Kind = "kindf7aa39d9", Next = 9139246809011047120L, Start = -5616678393427383318L, SelfLink = "self_link7e87f12d", Contents = "contents8c7dbf98", }; mockGrpcClient.Setup(x => x.GetSerialPortOutput(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); SerialPortOutput response = client.GetSerialPortOutput(request.Project, request.Zone, request.Instance); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetSerialPortOutputAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetSerialPortOutputInstanceRequest request = new GetSerialPortOutputInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; SerialPortOutput expectedResponse = new SerialPortOutput { Kind = "kindf7aa39d9", Next = 9139246809011047120L, Start = -5616678393427383318L, SelfLink = "self_link7e87f12d", Contents = "contents8c7dbf98", }; mockGrpcClient.Setup(x => x.GetSerialPortOutputAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SerialPortOutput>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); SerialPortOutput responseCallSettings = await client.GetSerialPortOutputAsync(request.Project, request.Zone, request.Instance, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SerialPortOutput responseCancellationToken = await client.GetSerialPortOutputAsync(request.Project, request.Zone, request.Instance, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetShieldedInstanceIdentityRequestObject() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetShieldedInstanceIdentityInstanceRequest request = new GetShieldedInstanceIdentityInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; ShieldedInstanceIdentity expectedResponse = new ShieldedInstanceIdentity { Kind = "kindf7aa39d9", SigningKey = new ShieldedInstanceIdentityEntry(), EncryptionKey = new ShieldedInstanceIdentityEntry(), }; mockGrpcClient.Setup(x => x.GetShieldedInstanceIdentity(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); ShieldedInstanceIdentity response = client.GetShieldedInstanceIdentity(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetShieldedInstanceIdentityRequestObjectAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetShieldedInstanceIdentityInstanceRequest request = new GetShieldedInstanceIdentityInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; ShieldedInstanceIdentity expectedResponse = new ShieldedInstanceIdentity { Kind = "kindf7aa39d9", SigningKey = new ShieldedInstanceIdentityEntry(), EncryptionKey = new ShieldedInstanceIdentityEntry(), }; mockGrpcClient.Setup(x => x.GetShieldedInstanceIdentityAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ShieldedInstanceIdentity>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); ShieldedInstanceIdentity responseCallSettings = await client.GetShieldedInstanceIdentityAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ShieldedInstanceIdentity responseCancellationToken = await client.GetShieldedInstanceIdentityAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetShieldedInstanceIdentity() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetShieldedInstanceIdentityInstanceRequest request = new GetShieldedInstanceIdentityInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; ShieldedInstanceIdentity expectedResponse = new ShieldedInstanceIdentity { Kind = "kindf7aa39d9", SigningKey = new ShieldedInstanceIdentityEntry(), EncryptionKey = new ShieldedInstanceIdentityEntry(), }; mockGrpcClient.Setup(x => x.GetShieldedInstanceIdentity(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); ShieldedInstanceIdentity response = client.GetShieldedInstanceIdentity(request.Project, request.Zone, request.Instance); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetShieldedInstanceIdentityAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetShieldedInstanceIdentityInstanceRequest request = new GetShieldedInstanceIdentityInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; ShieldedInstanceIdentity expectedResponse = new ShieldedInstanceIdentity { Kind = "kindf7aa39d9", SigningKey = new ShieldedInstanceIdentityEntry(), EncryptionKey = new ShieldedInstanceIdentityEntry(), }; mockGrpcClient.Setup(x => x.GetShieldedInstanceIdentityAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ShieldedInstanceIdentity>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); ShieldedInstanceIdentity responseCallSettings = await client.GetShieldedInstanceIdentityAsync(request.Project, request.Zone, request.Instance, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ShieldedInstanceIdentity responseCancellationToken = await client.GetShieldedInstanceIdentityAsync(request.Project, request.Zone, request.Instance, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SendDiagnosticInterruptRequestObject() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SendDiagnosticInterruptInstanceRequest request = new SendDiagnosticInterruptInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; SendDiagnosticInterruptInstanceResponse expectedResponse = new SendDiagnosticInterruptInstanceResponse { }; mockGrpcClient.Setup(x => x.SendDiagnosticInterrupt(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); SendDiagnosticInterruptInstanceResponse response = client.SendDiagnosticInterrupt(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SendDiagnosticInterruptRequestObjectAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SendDiagnosticInterruptInstanceRequest request = new SendDiagnosticInterruptInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; SendDiagnosticInterruptInstanceResponse expectedResponse = new SendDiagnosticInterruptInstanceResponse { }; mockGrpcClient.Setup(x => x.SendDiagnosticInterruptAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SendDiagnosticInterruptInstanceResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); SendDiagnosticInterruptInstanceResponse responseCallSettings = await client.SendDiagnosticInterruptAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SendDiagnosticInterruptInstanceResponse responseCancellationToken = await client.SendDiagnosticInterruptAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SendDiagnosticInterrupt() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SendDiagnosticInterruptInstanceRequest request = new SendDiagnosticInterruptInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; SendDiagnosticInterruptInstanceResponse expectedResponse = new SendDiagnosticInterruptInstanceResponse { }; mockGrpcClient.Setup(x => x.SendDiagnosticInterrupt(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); SendDiagnosticInterruptInstanceResponse response = client.SendDiagnosticInterrupt(request.Project, request.Zone, request.Instance); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SendDiagnosticInterruptAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SendDiagnosticInterruptInstanceRequest request = new SendDiagnosticInterruptInstanceRequest { Zone = "zone255f4ea8", Instance = "instance99a62371", Project = "projectaa6ff846", }; SendDiagnosticInterruptInstanceResponse expectedResponse = new SendDiagnosticInterruptInstanceResponse { }; mockGrpcClient.Setup(x => x.SendDiagnosticInterruptAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<SendDiagnosticInterruptInstanceResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); SendDiagnosticInterruptInstanceResponse responseCallSettings = await client.SendDiagnosticInterruptAsync(request.Project, request.Zone, request.Instance, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); SendDiagnosticInterruptInstanceResponse responseCancellationToken = await client.SendDiagnosticInterruptAsync(request.Project, request.Zone, request.Instance, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyRequestObject() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyInstanceRequest request = new SetIamPolicyInstanceRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); Policy response = client.SetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyRequestObjectAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyInstanceRequest request = new SetIamPolicyInstanceRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicy() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyInstanceRequest request = new SetIamPolicyInstanceRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); Policy response = client.SetIamPolicy(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyInstanceRequest request = new SetIamPolicyInstanceRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.SetIamPolicyAsync(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsInstanceRequest request = new TestIamPermissionsInstanceRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsInstanceRequest request = new TestIamPermissionsInstanceRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsInstanceRequest request = new TestIamPermissionsInstanceRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<Instances.InstancesClient> mockGrpcClient = new moq::Mock<Instances.InstancesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsInstanceRequest request = new TestIamPermissionsInstanceRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); InstancesClient client = new InstancesClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// 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 program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in. // It is available from http://www.codeplex.com/hyperAddin #if !PLATFORM_UNIX #define FEATURE_MANAGED_ETW #if !ES_BUILD_STANDALONE #define FEATURE_ACTIVITYSAMPLING #endif #endif // PLATFORM_UNIX #if ES_BUILD_STANDALONE #define FEATURE_MANAGED_ETW_CHANNELS // #define FEATURE_ADVANCED_MANAGED_ETW_CHANNELS #endif #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; using EventDescriptor = Microsoft.Diagnostics.Tracing.EventDescriptor; #endif using System; using System.Runtime.InteropServices; using System.Security; using System.Collections.ObjectModel; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; using System.Collections.Generic; using System.Text; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; using System.Collections.Generic; using System.Text; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { public partial class EventSource { #if FEATURE_MANAGED_ETW private byte[] providerMetadata; #endif /// <summary> /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API). /// </summary> /// <param name="eventSourceName"> /// The name of the event source. Must not be null. /// </param> public EventSource( string eventSourceName) : this(eventSourceName, EventSourceSettings.EtwSelfDescribingEventFormat) { } /// <summary> /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API). /// </summary> /// <param name="eventSourceName"> /// The name of the event source. Must not be null. /// </param> /// <param name="config"> /// Configuration options for the EventSource as a whole. /// </param> public EventSource( string eventSourceName, EventSourceSettings config) : this(eventSourceName, config, null) { } /// <summary> /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API). /// /// Also specify a list of key-value pairs called traits (you must pass an even number of strings). /// The first string is the key and the second is the value. These are not interpreted by EventSource /// itself but may be interprated the listeners. Can be fetched with GetTrait(string). /// </summary> /// <param name="eventSourceName"> /// The name of the event source. Must not be null. /// </param> /// <param name="config"> /// Configuration options for the EventSource as a whole. /// </param> /// <param name="traits">A collection of key-value strings (must be an even number).</param> public EventSource( string eventSourceName, EventSourceSettings config, params string[] traits) : this( eventSourceName == null ? new Guid() : GenerateGuidFromName(eventSourceName.ToUpperInvariant()), eventSourceName, config, traits) { if (eventSourceName == null) { throw new ArgumentNullException(nameof(eventSourceName)); } Contract.EndContractBlock(); } /// <summary> /// Writes an event with no fields and default options. /// (Native API: EventWriteTransfer) /// </summary> /// <param name="eventName">The name of the event. Must not be null.</param> public unsafe void Write(string eventName) { if (eventName == null) { throw new ArgumentNullException(nameof(eventName)); } Contract.EndContractBlock(); if (!this.IsEnabled()) { return; } var options = new EventSourceOptions(); this.WriteImpl(eventName, ref options, null, null, null, SimpleEventTypes<EmptyStruct>.Instance); } /// <summary> /// Writes an event with no fields. /// (Native API: EventWriteTransfer) /// </summary> /// <param name="eventName">The name of the event. Must not be null.</param> /// <param name="options"> /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> public unsafe void Write(string eventName, EventSourceOptions options) { if (eventName == null) { throw new ArgumentNullException(nameof(eventName)); } Contract.EndContractBlock(); if (!this.IsEnabled()) { return; } this.WriteImpl(eventName, ref options, null, null, null, SimpleEventTypes<EmptyStruct>.Instance); } /// <summary> /// Writes an event. /// (Native API: EventWriteTransfer) /// </summary> /// <typeparam name="T"> /// The type that defines the event and its payload. This must be an /// anonymous type or a type with an [EventData] attribute. /// </typeparam> /// <param name="eventName"> /// The name for the event. If null, the event name is automatically /// determined based on T, either from the Name property of T's EventData /// attribute or from typeof(T).Name. /// </param> /// <param name="data"> /// The object containing the event payload data. The type T must be /// an anonymous type or a type with an [EventData] attribute. The /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> public unsafe void Write<T>( string eventName, T data) { if (!this.IsEnabled()) { return; } var options = new EventSourceOptions(); this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance); } /// <summary> /// Writes an event. /// (Native API: EventWriteTransfer) /// </summary> /// <typeparam name="T"> /// The type that defines the event and its payload. This must be an /// anonymous type or a type with an [EventData] attribute. /// </typeparam> /// <param name="eventName"> /// The name for the event. If null, the event name is automatically /// determined based on T, either from the Name property of T's EventData /// attribute or from typeof(T).Name. /// </param> /// <param name="options"> /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> /// <param name="data"> /// The object containing the event payload data. The type T must be /// an anonymous type or a type with an [EventData] attribute. The /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> public unsafe void Write<T>( string eventName, EventSourceOptions options, T data) { if (!this.IsEnabled()) { return; } this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance); } /// <summary> /// Writes an event. /// This overload is for use with extension methods that wish to efficiently /// forward the options or data parameter without performing an extra copy. /// (Native API: EventWriteTransfer) /// </summary> /// <typeparam name="T"> /// The type that defines the event and its payload. This must be an /// anonymous type or a type with an [EventData] attribute. /// </typeparam> /// <param name="eventName"> /// The name for the event. If null, the event name is automatically /// determined based on T, either from the Name property of T's EventData /// attribute or from typeof(T).Name. /// </param> /// <param name="options"> /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> /// <param name="data"> /// The object containing the event payload data. The type T must be /// an anonymous type or a type with an [EventData] attribute. The /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> public unsafe void Write<T>( string eventName, ref EventSourceOptions options, ref T data) { if (!this.IsEnabled()) { return; } this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance); } /// <summary> /// Writes an event. /// This overload is meant for clients that need to manipuate the activityId /// and related ActivityId for the event. /// </summary> /// <typeparam name="T"> /// The type that defines the event and its payload. This must be an /// anonymous type or a type with an [EventData] attribute. /// </typeparam> /// <param name="eventName"> /// The name for the event. If null, the event name is automatically /// determined based on T, either from the Name property of T's EventData /// attribute or from typeof(T).Name. /// </param> /// <param name="options"> /// Options for the event, such as the level, keywords, and opcode. Unset /// options will be set to default values. /// </param> /// <param name="activityId"> /// The GUID of the activity associated with this event. /// </param> /// <param name="relatedActivityId"> /// The GUID of another activity that is related to this activity, or Guid.Empty /// if there is no related activity. Most commonly, the Start operation of a /// new activity specifies a parent activity as its related activity. /// </param> /// <param name="data"> /// The object containing the event payload data. The type T must be /// an anonymous type or a type with an [EventData] attribute. The /// public instance properties of data will be written recursively to /// create the fields of the event. /// </param> public unsafe void Write<T>( string eventName, ref EventSourceOptions options, ref Guid activityId, ref Guid relatedActivityId, ref T data) { if (!this.IsEnabled()) { return; } fixed (Guid* pActivity = &activityId, pRelated = &relatedActivityId) { this.WriteImpl( eventName, ref options, data, pActivity, relatedActivityId == Guid.Empty ? null : pRelated, SimpleEventTypes<T>.Instance); } } /// <summary> /// Writes an extended event, where the values of the event are the /// combined properties of any number of values. This method is /// intended for use in advanced logging scenarios that support a /// dynamic set of event context providers. /// This method does a quick check on whether this event is enabled. /// </summary> /// <param name="eventName"> /// The name for the event. If null, the name from eventTypes is used. /// (Note that providing the event name via the name parameter is slightly /// less efficient than using the name from eventTypes.) /// </param> /// <param name="options"> /// Optional overrides for the event, such as the level, keyword, opcode, /// activityId, and relatedActivityId. Any settings not specified by options /// are obtained from eventTypes. /// </param> /// <param name="eventTypes"> /// Information about the event and the types of the values in the event. /// Must not be null. Note that the eventTypes object should be created once and /// saved. It should not be recreated for each event. /// </param> /// <param name="activityID"> /// A pointer to the activity ID GUID to log /// </param> /// <param name="childActivityID"> /// A pointer to the child activity ID to log (can be null) </param> /// <param name="values"> /// The values to include in the event. Must not be null. The number and types of /// the values must match the number and types of the fields described by the /// eventTypes parameter. /// </param> private unsafe void WriteMultiMerge( string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, Guid* childActivityID, params object[] values) { if (!this.IsEnabled()) { return; } byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0 ? options.level : eventTypes.level; EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0 ? options.keywords : eventTypes.keywords; if (this.IsEnabled((EventLevel)level, keywords)) { WriteMultiMergeInner(eventName, ref options, eventTypes, activityID, childActivityID, values); } } /// <summary> /// Writes an extended event, where the values of the event are the /// combined properties of any number of values. This method is /// intended for use in advanced logging scenarios that support a /// dynamic set of event context providers. /// Attention: This API does not check whether the event is enabled or not. /// Please use WriteMultiMerge to avoid spending CPU cycles for events that are /// not enabled. /// </summary> /// <param name="eventName"> /// The name for the event. If null, the name from eventTypes is used. /// (Note that providing the event name via the name parameter is slightly /// less efficient than using the name from eventTypes.) /// </param> /// <param name="options"> /// Optional overrides for the event, such as the level, keyword, opcode, /// activityId, and relatedActivityId. Any settings not specified by options /// are obtained from eventTypes. /// </param> /// <param name="eventTypes"> /// Information about the event and the types of the values in the event. /// Must not be null. Note that the eventTypes object should be created once and /// saved. It should not be recreated for each event. /// </param> /// <param name="activityID"> /// A pointer to the activity ID GUID to log /// </param> /// <param name="childActivityID"> /// A pointer to the child activity ID to log (can be null) /// </param> /// <param name="values"> /// The values to include in the event. Must not be null. The number and types of /// the values must match the number and types of the fields described by the /// eventTypes parameter. /// </param> private unsafe void WriteMultiMergeInner( string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, Guid* childActivityID, params object[] values) { #if FEATURE_MANAGED_ETW int identity = 0; byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0 ? options.level : eventTypes.level; byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0 ? options.opcode : eventTypes.opcode; EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0 ? options.tags : eventTypes.Tags; EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0 ? options.keywords : eventTypes.keywords; var nameInfo = eventTypes.GetNameInfo(eventName ?? eventTypes.Name, tags); if (nameInfo == null) { return; } identity = nameInfo.identity; EventDescriptor descriptor = new EventDescriptor(identity, level, opcode, (long)keywords); var pinCount = eventTypes.pinCount; var scratch = stackalloc byte[eventTypes.scratchSize]; var descriptors = stackalloc EventData[eventTypes.dataCount + 3]; var pins = stackalloc GCHandle[pinCount]; fixed (byte* pMetadata0 = providerMetadata, pMetadata1 = nameInfo.nameMetadata, pMetadata2 = eventTypes.typeMetadata) { descriptors[0].SetMetadata(pMetadata0, providerMetadata.Length, 2); descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1); descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1); #if (!ES_BUILD_PCL && !PROJECTN) System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif try { DataCollector.ThreadInstance.Enable( scratch, eventTypes.scratchSize, descriptors + 3, eventTypes.dataCount, pins, pinCount); for (int i = 0; i < eventTypes.typeInfos.Length; i++) { var info = eventTypes.typeInfos[i]; info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(values[i])); } this.WriteEventRaw( eventName, ref descriptor, activityID, childActivityID, (int)(DataCollector.ThreadInstance.Finish() - descriptors), (IntPtr)descriptors); } finally { this.WriteCleanup(pins, pinCount); } } #endif // FEATURE_MANAGED_ETW } /// <summary> /// Writes an extended event, where the values of the event have already /// been serialized in "data". /// </summary> /// <param name="eventName"> /// The name for the event. If null, the name from eventTypes is used. /// (Note that providing the event name via the name parameter is slightly /// less efficient than using the name from eventTypes.) /// </param> /// <param name="options"> /// Optional overrides for the event, such as the level, keyword, opcode, /// activityId, and relatedActivityId. Any settings not specified by options /// are obtained from eventTypes. /// </param> /// <param name="eventTypes"> /// Information about the event and the types of the values in the event. /// Must not be null. Note that the eventTypes object should be created once and /// saved. It should not be recreated for each event. /// </param> /// <param name="activityID"> /// A pointer to the activity ID GUID to log /// </param> /// <param name="childActivityID"> /// A pointer to the child activity ID to log (can be null) /// </param> /// <param name="data"> /// The previously serialized values to include in the event. Must not be null. /// The number and types of the values must match the number and types of the /// fields described by the eventTypes parameter. /// </param> internal unsafe void WriteMultiMerge( string eventName, ref EventSourceOptions options, TraceLoggingEventTypes eventTypes, Guid* activityID, Guid* childActivityID, EventData* data) { #if FEATURE_MANAGED_ETW if (!this.IsEnabled()) { return; } fixed (EventSourceOptions* pOptions = &options) { EventDescriptor descriptor; var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor); if (nameInfo == null) { return; } // We make a descriptor for each EventData, and because we morph strings to counted strings // we may have 2 for each arg, so we allocate enough for this. var descriptors = stackalloc EventData[eventTypes.dataCount + eventTypes.typeInfos.Length * 2 + 3]; fixed (byte* pMetadata0 = providerMetadata, pMetadata1 = nameInfo.nameMetadata, pMetadata2 = eventTypes.typeMetadata) { descriptors[0].SetMetadata(pMetadata0, providerMetadata.Length, 2); descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1); descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1); int numDescrs = 3; for (int i = 0; i < eventTypes.typeInfos.Length; i++) { // Until M3, we need to morph strings to a counted representation // When TDH supports null terminated strings, we can remove this. if (eventTypes.typeInfos[i].DataType == typeof(string)) { // Write out the size of the string descriptors[numDescrs].m_Ptr = (long)&descriptors[numDescrs + 1].m_Size; descriptors[numDescrs].m_Size = 2; numDescrs++; descriptors[numDescrs].m_Ptr = data[i].m_Ptr; descriptors[numDescrs].m_Size = data[i].m_Size - 2; // Remove the null terminator numDescrs++; } else { descriptors[numDescrs].m_Ptr = data[i].m_Ptr; descriptors[numDescrs].m_Size = data[i].m_Size; // old conventions for bool is 4 bytes, but meta-data assumes 1. if (data[i].m_Size == 4 && eventTypes.typeInfos[i].DataType == typeof(bool)) descriptors[numDescrs].m_Size = 1; numDescrs++; } } this.WriteEventRaw( eventName, ref descriptor, activityID, childActivityID, numDescrs, (IntPtr)descriptors); } } #endif // FEATURE_MANAGED_ETW } private unsafe void WriteImpl( string eventName, ref EventSourceOptions options, object data, Guid* pActivityId, Guid* pRelatedActivityId, TraceLoggingEventTypes eventTypes) { try { fixed (EventSourceOptions* pOptions = &options) { EventDescriptor descriptor; options.Opcode = options.IsOpcodeSet ? options.Opcode : GetOpcodeWithDefault(options.Opcode, eventName); var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor); if (nameInfo == null) { return; } #if FEATURE_MANAGED_ETW var pinCount = eventTypes.pinCount; var scratch = stackalloc byte[eventTypes.scratchSize]; var descriptors = stackalloc EventData[eventTypes.dataCount + 3]; var pins = stackalloc GCHandle[pinCount]; fixed (byte* pMetadata0 = providerMetadata, pMetadata1 = nameInfo.nameMetadata, pMetadata2 = eventTypes.typeMetadata) { descriptors[0].SetMetadata(pMetadata0, providerMetadata.Length, 2); descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1); descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1); #endif // FEATURE_MANAGED_ETW #if (!ES_BUILD_PCL && !PROJECTN) System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif EventOpcode opcode = (EventOpcode)descriptor.Opcode; Guid activityId = Guid.Empty; Guid relatedActivityId = Guid.Empty; if (pActivityId == null && pRelatedActivityId == null && ((options.ActivityOptions & EventActivityOptions.Disable) == 0)) { if (opcode == EventOpcode.Start) { m_activityTracker.OnStart(m_name, eventName, 0, ref activityId, ref relatedActivityId, options.ActivityOptions); } else if (opcode == EventOpcode.Stop) { m_activityTracker.OnStop(m_name, eventName, 0, ref activityId); } if (activityId != Guid.Empty) pActivityId = &activityId; if (relatedActivityId != Guid.Empty) pRelatedActivityId = &relatedActivityId; } try { #if FEATURE_MANAGED_ETW DataCollector.ThreadInstance.Enable( scratch, eventTypes.scratchSize, descriptors + 3, eventTypes.dataCount, pins, pinCount); var info = eventTypes.typeInfos[0]; info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(data)); this.WriteEventRaw( eventName, ref descriptor, pActivityId, pRelatedActivityId, (int)(DataCollector.ThreadInstance.Finish() - descriptors), (IntPtr)descriptors); #endif // FEATURE_MANAGED_ETW // TODO enable filtering for listeners. if (m_Dispatchers != null) { var eventData = (EventPayload)(eventTypes.typeInfos[0].GetData(data)); WriteToAllListeners(eventName, ref descriptor, nameInfo.tags, pActivityId, eventData); } } catch (Exception ex) { if (ex is EventSourceException) throw; else ThrowEventSourceException(eventName, ex); } #if FEATURE_MANAGED_ETW finally { this.WriteCleanup(pins, pinCount); } } #endif // FEATURE_MANAGED_ETW } } catch (Exception ex) { if (ex is EventSourceException) throw; else ThrowEventSourceException(eventName, ex); } } private unsafe void WriteToAllListeners(string eventName, ref EventDescriptor eventDescriptor, EventTags tags, Guid* pActivityId, EventPayload payload) { EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this); eventCallbackArgs.EventName = eventName; eventCallbackArgs.m_level = (EventLevel)eventDescriptor.Level; eventCallbackArgs.m_keywords = (EventKeywords)eventDescriptor.Keywords; eventCallbackArgs.m_opcode = (EventOpcode)eventDescriptor.Opcode; eventCallbackArgs.m_tags = tags; // Self described events do not have an id attached. We mark it internally with -1. eventCallbackArgs.EventId = -1; if (pActivityId != null) eventCallbackArgs.RelatedActivityId = *pActivityId; if (payload != null) { eventCallbackArgs.Payload = new ReadOnlyCollection<object>((IList<object>)payload.Values); eventCallbackArgs.PayloadNames = new ReadOnlyCollection<string>((IList<string>)payload.Keys); } DispatchToAllListeners(-1, pActivityId, eventCallbackArgs); } #if (!ES_BUILD_PCL && !PROJECTN) [System.Runtime.ConstrainedExecution.ReliabilityContract( System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState, System.Runtime.ConstrainedExecution.Cer.Success)] #endif [NonEvent] private unsafe void WriteCleanup(GCHandle* pPins, int cPins) { DataCollector.ThreadInstance.Disable(); for (int i = 0; i != cPins; i++) { if (IntPtr.Zero != (IntPtr)pPins[i]) { pPins[i].Free(); } } } private void InitializeProviderMetadata() { #if FEATURE_MANAGED_ETW if (m_traits != null) { List<byte> traitMetaData = new List<byte>(100); for (int i = 0; i < m_traits.Length - 1; i += 2) { if (m_traits[i].StartsWith("ETW_", StringComparison.Ordinal)) { string etwTrait = m_traits[i].Substring(4); byte traitNum; if (!byte.TryParse(etwTrait, out traitNum)) { if (etwTrait == "GROUP") { traitNum = 1; } else { throw new ArgumentException(Resources.GetResourceString("UnknownEtwTrait", etwTrait), "traits"); } } string value = m_traits[i + 1]; int lenPos = traitMetaData.Count; traitMetaData.Add(0); // Emit size (to be filled in later) traitMetaData.Add(0); traitMetaData.Add(traitNum); // Emit Trait number var valueLen = AddValueToMetaData(traitMetaData, value) + 3; // Emit the value bytes +3 accounts for 3 bytes we emited above. traitMetaData[lenPos] = unchecked((byte)valueLen); // Fill in size traitMetaData[lenPos + 1] = unchecked((byte)(valueLen >> 8)); } } providerMetadata = Statics.MetadataForString(this.Name, 0, traitMetaData.Count, 0); int startPos = providerMetadata.Length - traitMetaData.Count; foreach (var b in traitMetaData) providerMetadata[startPos++] = b; } else providerMetadata = Statics.MetadataForString(this.Name, 0, 0, 0); #endif //FEATURE_MANAGED_ETW } private static int AddValueToMetaData(List<byte> metaData, string value) { if (value.Length == 0) return 0; int startPos = metaData.Count; char firstChar = value[0]; if (firstChar == '@') metaData.AddRange(Encoding.UTF8.GetBytes(value.Substring(1))); else if (firstChar == '{') metaData.AddRange(new Guid(value).ToByteArray()); else if (firstChar == '#') { for (int i = 1; i < value.Length; i++) { if (value[i] != ' ') // Skip spaces between bytes. { if (!(i + 1 < value.Length)) { throw new ArgumentException(Resources.GetResourceString("EvenHexDigits"), "traits"); } metaData.Add((byte)(HexDigit(value[i]) * 16 + HexDigit(value[i + 1]))); i++; } } } else if ('A' <= firstChar || ' ' == firstChar) // Is it alphabetic or space (excludes digits and most punctuation). { metaData.AddRange(Encoding.UTF8.GetBytes(value)); } else { throw new ArgumentException(Resources.GetResourceString("IllegalValue", value), "traits"); } return metaData.Count - startPos; } /// <summary> /// Returns a value 0-15 if 'c' is a hexadecimal digit. If it throws an argument exception. /// </summary> private static int HexDigit(char c) { if ('0' <= c && c <= '9') { return (c - '0'); } if ('a' <= c) { c = unchecked((char)(c - ('a' - 'A'))); // Convert to lower case } if ('A' <= c && c <= 'F') { return (c - 'A' + 10); } throw new ArgumentException(Resources.GetResourceString("BadHexDigit", c), "traits"); } private NameInfo UpdateDescriptor( string name, TraceLoggingEventTypes eventInfo, ref EventSourceOptions options, out EventDescriptor descriptor) { NameInfo nameInfo = null; int identity = 0; byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0 ? options.level : eventInfo.level; byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0 ? options.opcode : eventInfo.opcode; EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0 ? options.tags : eventInfo.Tags; EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0 ? options.keywords : eventInfo.keywords; if (this.IsEnabled((EventLevel)level, keywords)) { nameInfo = eventInfo.GetNameInfo(name ?? eventInfo.Name, tags); identity = nameInfo.identity; } descriptor = new EventDescriptor(identity, level, opcode, (long)keywords); return nameInfo; } } }
/* Copyright 2014 Clarius Consulting SA 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 */ namespace TracerHub.Diagnostics { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using System.Xml.XPath; /// <summary> /// Implements the common tracer interface using <see cref="TraceSource"/> instances. /// </summary> /// <remarks> /// All tracing is performed asynchronously transparently for faster speed. /// </remarks> /// <nuget id="Tracer.SystemDiagnostics" /> partial class TracerManager : ITracerManager, IDisposable { /// <summary> /// Implicit default trace source name which can be used to setup /// global tracing and listeners. /// </summary> public const string DefaultSourceName = "*"; // To handle concurrency for the async tracing. private BlockingCollection<Tuple<ExecutionContext, Action>> traceQueue = new BlockingCollection<Tuple<ExecutionContext, Action>>(); private CancellationTokenSource cancellation = new CancellationTokenSource(); /// <summary> /// Initializes a new instance of the <see cref="TracerManager"/> class. /// </summary> public TracerManager() { // Note we have only one async task to perform all tracing. This // is an optimization, so that we don't consume too much resources // from the running app for this. Task.Factory.StartNew(DoTrace, cancellation.Token, TaskCreationOptions.LongRunning, TaskScheduler.Current); InitializeConfiguredSources(); } private void InitializeConfiguredSources() { var configFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; if (!File.Exists(configFile)) return; var sourceNames = from diagnostics in XDocument.Load(configFile).Root.Elements("system.diagnostics") from sources in diagnostics.Elements("sources") from source in sources.Elements("source") select source.Attribute("name").Value; foreach (var sourceName in sourceNames) { // Cause eager initialization, which is needed for the trace source configuration // to be properly read. GetSource(sourceName); } } /// <summary> /// Gets a tracer instance with the specified name. /// </summary> public ITracer Get(string name) { return new AggregateTracer(this, name, CompositeFor(name) .Select(tracerName => new DiagnosticsTracer( this.GetOrAdd(tracerName, sourceName => CreateSource(sourceName))))); } /// <summary> /// Gets the underlying <see cref="TraceSource"/> for the given name. /// </summary> public TraceSource GetSource(string name) { return this.GetOrAdd(name, sourceName => CreateSource(sourceName)); } /// <summary> /// Adds a listener to the source with the given <paramref name="sourceName"/>. /// </summary> public void AddListener(string sourceName, TraceListener listener) { this.GetOrAdd(sourceName, name => CreateSource(name)).Listeners.Add(listener); } /// <summary> /// Removes a listener from the source with the given <paramref name="sourceName"/>. /// </summary> public void RemoveListener(string sourceName, TraceListener listener) { this.GetOrAdd(sourceName, name => CreateSource(name)).Listeners.Remove(listener); } /// <summary> /// Removes a listener from the source with the given <paramref name="sourceName"/>. /// </summary> public void RemoveListener(string sourceName, string listenerName) { this.GetOrAdd(sourceName, name => CreateSource(name)).Listeners.Remove(listenerName); } /// <summary> /// Sets the tracing level for the source with the given <paramref name="sourceName"/> /// </summary> public void SetTracingLevel(string sourceName, SourceLevels level) { this.GetOrAdd(sourceName, name => CreateSource(name)).Switch.Level = level; } /// <summary> /// Cleans up the manager, cancelling any pending tracing /// messages. /// </summary> public void Dispose() { cancellation.Cancel(); traceQueue.Dispose(); } /// <summary> /// Enqueues the specified trace action to be executed by the trace /// async task. /// </summary> internal void Enqueue(Action traceAction) { traceQueue.Add(Tuple.Create(ExecutionContext.Capture(), traceAction)); } private TraceSource CreateSource(string name) { var source = new TraceSource(name); source.TraceInformation("Initialized with initial level {0}", source.Switch.Level); return source; } private void DoTrace() { foreach (var action in traceQueue.GetConsumingEnumerable()) { if (cancellation.IsCancellationRequested) break; // Tracing should never cause the app to fail. // Since this is async, it might if we don't catch. try { ExecutionContext.Run(action.Item1, state => action.Item2(), null); } catch { } } } /// <summary> /// Gets the list of trace source names that are used to inherit trace source logging for the given <paramref name="name"/>. /// </summary> private static IEnumerable<string> CompositeFor(string name) { if (name != DefaultSourceName) yield return DefaultSourceName; var indexOfGeneric = name.IndexOf('<'); var indexOfLastDot = name.LastIndexOf('.'); if (indexOfGeneric == -1 && indexOfLastDot == -1) { yield return name; yield break; } var parts = default(string[]); if (indexOfGeneric == -1) parts = name .Substring(0, name.LastIndexOf('.')) .Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); else parts = name .Substring(0, indexOfGeneric) .Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 1; i <= parts.Length; i++) { yield return string.Join(".", parts, 0, i); } yield return name; } /// <summary> /// Gets an AppDomain-cached trace source of the given name, or creates it. /// This means that even if multiple libraries are using their own /// trace manager instance, they will all still share the same /// underlying sources. /// </summary> private TraceSource GetOrAdd(string sourceName, Func<string, TraceSource> factory) { var cachedSources = AppDomain.CurrentDomain.GetData<ConcurrentDictionary<string, TraceSource>>(); if (cachedSources == null) { // This lock guarantees that throughout the current // app domain, only a single root trace source is // created ever. lock (AppDomain.CurrentDomain) { cachedSources = AppDomain.CurrentDomain.GetData<ConcurrentDictionary<string, TraceSource>>(); if (cachedSources == null) { cachedSources = new ConcurrentDictionary<string, TraceSource>(); AppDomain.CurrentDomain.SetData(cachedSources); } } } return cachedSources.GetOrAdd(sourceName, factory); } /// <summary> /// Logs to multiple tracers simulateously. Used for the /// source "inheritance" /// </summary> private class AggregateTracer : ITracer { private TracerManager manager; private List<DiagnosticsTracer> tracers; private string name; public AggregateTracer(TracerManager manager, string name, IEnumerable<DiagnosticsTracer> tracers) { this.manager = manager; this.name = name; this.tracers = tracers.ToList(); } /// <summary> /// Traces the specified message with the given <see cref="TraceEventType"/>. /// </summary> public void Trace(TraceEventType type, object message) { manager.Enqueue(() => tracers.AsParallel().ForAll(tracer => tracer.Trace(name, type, message))); } /// <summary> /// Traces the specified formatted message with the given <see cref="TraceEventType"/>. /// </summary> public void Trace(TraceEventType type, string format, params object[] args) { manager.Enqueue(() => tracers.AsParallel().ForAll(tracer => tracer.Trace(name, type, format, args))); } /// <summary> /// Traces an exception with the specified message and <see cref="TraceEventType"/>. /// </summary> public void Trace(TraceEventType type, Exception exception, object message) { manager.Enqueue(() => tracers.AsParallel().ForAll(tracer => tracer.Trace(name, type, exception, message))); } /// <summary> /// Traces an exception with the specified formatted message and <see cref="TraceEventType"/>. /// </summary> public void Trace(TraceEventType type, Exception exception, string format, params object[] args) { manager.Enqueue(() => tracers.AsParallel().ForAll(tracer => tracer.Trace(name, type, exception, format, args))); } public override string ToString() { return "Aggregate for " + this.name; } } partial class DiagnosticsTracer { private TraceSource source; public DiagnosticsTracer(TraceSource source) { this.source = source; } public void Trace(string sourceName, TraceEventType type, object message) { // Because we know there is a single tracer thread executing these, // we know it's safe to replace the name without locking. using (new SourceNameReplacer(source, sourceName)) { // Add support for Xml-based Service Trace Viewer-compatible // activity tracing. var data = message as XPathNavigator; // Transfers with a Guid payload should instead trace a transfer // with that as the related Guid. var guid = message as Guid?; if (data != null) source.TraceData(type, 0, data); else if (guid != null && type == TraceEventType.Transfer) source.TraceTransfer(0, "", guid.Value); else source.TraceEvent(type, 0, message.ToString()); } } public void Trace(string sourceName, TraceEventType type, string format, params object[] args) { // Because we know there is a single tracer thread executing these, // we know it's safe to replace the name without locking. using (new SourceNameReplacer(source, sourceName)) { source.TraceEvent(type, 0, format, args); } } public void Trace(string sourceName, TraceEventType type, Exception exception, object message) { // Because we know there is a single tracer thread executing these, // we know it's safe to replace the name without locking. using (new SourceNameReplacer(source, sourceName)) { source.TraceEvent(type, 0, message.ToString() + Environment.NewLine + exception); } } public void Trace(string sourceName, TraceEventType type, Exception exception, string format, params object[] args) { // Because we know there is a single tracer thread executing these, // we know it's safe to replace the name without locking. using (new SourceNameReplacer(source, sourceName)) { source.TraceEvent(type, 0, string.Format(format, args) + Environment.NewLine + exception); } } /// <summary> /// The TraceSource instance name matches the name of each of the "segments" /// we built the aggregate source from. This means that when we trace, we issue /// multiple trace statements, one for each. If a listener is added to (say) "*" /// source name, all traces done through it will appear as coming from the source /// "*", rather than (say) "Foo.Bar" which might be the actual source class. /// This diminishes the usefulness of hierarchical loggers significantly, since /// it now means that you need to add listeners too all trace sources you're /// interested in receiving messages from, and all its "children" potentially, /// some of them which might not have been created even yet. This is not feasible. /// Instead, since we issue the trace call to each trace source (which is what /// enables the configurability of all those sources in the app.config file), /// we need to fix the source name right before tracing, so that a configured /// listener at "*" still receives as the source name the original (aggregate) one, /// and not "*". This requires some private reflection, and a lock to guarantee /// proper logging, but this decreases its performance. However, since we log /// asynchronously, it's fine. /// </summary> private class SourceNameReplacer : IDisposable { // Private reflection needed here in order to make the inherited source names still // log as if the original source name was the one logging, so as not to lose the // originating class name. private static readonly FieldInfo sourceNameField = typeof(TraceSource).GetField("sourceName", BindingFlags.Instance | BindingFlags.NonPublic); private TraceSource source; private string originalName; public SourceNameReplacer(TraceSource source, string sourceName) { this.source = source; this.originalName = source.Name; // Transient change of the source name while the trace call // is issued. Multi-threading might still cause messages to come // out with wrong source names :( sourceNameField.SetValue(source, sourceName); } public void Dispose() { sourceNameField.SetValue(source, originalName); } } } } }
// // System.IO.BinaryWriter // // Authors: // Matt Kimball (matt@kimball.net) // Marek Safar (marek.safar@gmail.com) // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // Copyright 2011 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Text; using System.Globalization; using System.Runtime.InteropServices; using Java.Io; using Java.Util; namespace System.IO { [Serializable] [ComVisible (true)] public class BinaryWriter : IDisposable { // Null is a BinaryWriter with no backing store. public static readonly BinaryWriter Null = new BinaryWriter (); protected Stream OutStream; private Encoding m_encoding; private byte [] buffer; byte [] stringBuffer; int maxCharsPerRound; bool disposed; protected BinaryWriter() : this (Stream.Null, Encoding.UTF8) { } public BinaryWriter(Stream output) : this(output, Encoding.UTF8) { } #if NET_4_5 readonly bool leave_open; public BinaryWriter(Stream output, Encoding encoding) : this (output, encoding, false) { } public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen) #else const bool leave_open = false; public BinaryWriter(Stream output, Encoding encoding) #endif { if (output == null) throw new ArgumentNullException("output"); if (encoding == null) throw new ArgumentNullException("encoding"); if (!output.CanWrite) throw new ArgumentException("Stream does not support writing or already closed."); #if NET_4_5 leave_open = leaveOpen; #endif OutStream = output; m_encoding = encoding; buffer = new byte [16]; } public virtual Stream BaseStream { get { Flush (); return OutStream; } } public virtual void Close() { Dispose (true); } #if NET_4_0 public void Dispose () #else void IDisposable.Dispose() #endif { Dispose (true); } protected virtual void Dispose (bool disposing) { if (disposing && OutStream != null && !leave_open) OutStream.Close(); buffer = null; m_encoding = null; disposed = true; } public virtual void Flush() { OutStream.Flush(); } public virtual long Seek(int offset, SeekOrigin origin) { return OutStream.Seek(offset, origin); } public virtual void Write(bool value) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); buffer [0] = (byte) (value ? 1 : 0); OutStream.Write(buffer, 0, 1); } public virtual void Write(byte value) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); OutStream.WriteByte(value); } public virtual void Write(byte[] buffer) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); if (buffer == null) throw new ArgumentNullException("buffer"); OutStream.Write(buffer, 0, buffer.Length); } public virtual void Write(byte[] buffer, int index, int count) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); if (buffer == null) throw new ArgumentNullException("buffer"); OutStream.Write(buffer, index, count); } public virtual void Write(char ch) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); char[] dec = new char[1]; dec[0] = ch; byte[] enc = m_encoding.GetBytes(dec, 0, 1); OutStream.Write(enc, 0, enc.Length); } public virtual void Write(char[] chars) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); if (chars == null) throw new ArgumentNullException("chars"); byte[] enc = m_encoding.GetBytes(chars, 0, chars.Length); OutStream.Write(enc, 0, enc.Length); } public virtual void Write(char[] chars, int index, int count) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); if (chars == null) throw new ArgumentNullException("chars"); byte[] enc = m_encoding.GetBytes(chars, index, count); OutStream.Write(enc, 0, enc.Length); } public virtual void Write(decimal value) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); var bits = decimal.GetBits(value); Write(bits[0]); Write(bits[1]); Write(bits[2]); Write(bits[3]); } public virtual void Write(double value) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); var byteArrayOutputStream = new ByteArrayOutputStream(); var dataOutputStream = new DataOutputStream(byteArrayOutputStream); dataOutputStream.WriteDouble(value); byteArrayOutputStream.Flush(); WriteSwapped(byteArrayOutputStream.ToByteArray(), 8); byteArrayOutputStream.Close(); dataOutputStream.Close(); } public virtual void Write(short value) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); buffer [0] = (byte) value; buffer [1] = (byte) (value >> 8); OutStream.Write(buffer, 0, 2); } public virtual void Write(int value) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); buffer [0] = (byte) value; buffer [1] = (byte) (value >> 8); buffer [2] = (byte) (value >> 16); buffer [3] = (byte) (value >> 24); OutStream.Write(buffer, 0, 4); } public virtual void Write(long value) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); for (int i = 0, sh = 0; i < 8; i++, sh += 8) buffer [i] = (byte) (value >> sh); OutStream.Write(buffer, 0, 8); } [CLSCompliant(false)] public virtual void Write(sbyte value) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); buffer [0] = (byte) value; OutStream.Write(buffer, 0, 1); } public virtual void Write(float value) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); var byteArrayOutputStream = new ByteArrayOutputStream(); var dataOutputStream = new DataOutputStream(byteArrayOutputStream); dataOutputStream.WriteFloat(value); byteArrayOutputStream.Flush(); WriteSwapped(byteArrayOutputStream.ToByteArray(), 4); byteArrayOutputStream.Close(); dataOutputStream.Close(); } private void WriteSwapped(byte[] bytes, int count) { var swappedBytes = new byte[count]; for (int i = 0, j = count - 1; i < count; i++, j--) swappedBytes[i] = bytes[j]; OutStream.Write(swappedBytes, 0, count); } public virtual void Write(string value) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); int len = m_encoding.GetByteCount (value); Write7BitEncodedInt (len); if (stringBuffer == null) { stringBuffer = new byte [512]; maxCharsPerRound = 512 / m_encoding.GetMaxByteCount (1); } int chpos = 0; int chrem = value.Length; while (chrem > 0) { int cch = (chrem > maxCharsPerRound) ? maxCharsPerRound : chrem; int blen = m_encoding.GetBytes (value, chpos, cch, stringBuffer, 0); OutStream.Write (stringBuffer, 0, blen); chpos += cch; chrem -= cch; } } [CLSCompliant(false)] public virtual void Write(ushort value) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); buffer [0] = (byte) value; buffer [1] = (byte) (value >> 8); OutStream.Write(buffer, 0, 2); } [CLSCompliant(false)] public virtual void Write(uint value) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); buffer [0] = (byte) value; buffer [1] = (byte) (value >> 8); buffer [2] = (byte) (value >> 16); buffer [3] = (byte) (value >> 24); OutStream.Write(buffer, 0, 4); } [CLSCompliant(false)] public virtual void Write(ulong value) { if (disposed) throw new ObjectDisposedException ("BinaryWriter", "Cannot write to a closed BinaryWriter"); for (int i = 0, sh = 0; i < 8; i++, sh += 8) buffer [i] = (byte) (value >> sh); OutStream.Write(buffer, 0, 8); } protected void Write7BitEncodedInt(int value) { do { int high = (value >> 7) & 0x01ffffff; byte b = (byte)(value & 0x7f); if (high != 0) { b = (byte)(b | 0x80); } Write(b); value = high; } while(value != 0); } } }
using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Threading; using System.Collections.Concurrent; using System.IO; namespace ViewNet { /// <summary> /// A top level manager that manage multiple connections and servers to allow /// cross delegation communication between service managers while utilizing the /// fundamental security measures such as User/Group permission and roles /// </summary> public class DomainManager { const string CacheFileName = "ViewNet.cache"; TcpListener TCPServer { get; set; } Dictionary<IPEndPoint, ServiceManager> ActiveViewNetManagers { get; set; } volatile bool _IsHosting; Thread serverThread { get; set; } const int StandardPort = 10030; const ushort RetriesMax = 3; byte[] PrivateKey { get; set; } const CryptoStandard DefaultStandard = CryptoStandard.DHAES256; ConcurrentQueue<IPEndPoint> DisconnectedClients = new ConcurrentQueue<IPEndPoint> (); PrimaryCache manageCache = new PrimaryCache (); ConcurrentDictionary<User, bool> UserToLock = new ConcurrentDictionary<User, bool> (); /// <summary> /// Gets a value indicating whether this instance is hosting. /// </summary> /// <value><c>true</c> if this instance is hosting; otherwise, <c>false</c>.</value> public bool IsHosting { get { return _IsHosting; } } /// <summary> /// Initializes a new instance of the <see cref="ViewNet.DomainManager"/> class. /// </summary> public DomainManager () { InitializeObjects (); } /// <summary> /// Initializes the objects. /// </summary> void InitializeObjects () { ActiveViewNetManagers = new Dictionary<IPEndPoint, ServiceManager> (); } /// <summary> /// Starts the hosting. /// </summary> /// <param name="ip">Ip.</param> public void StartHosting (IPAddress ip) { StartHosting (ip, StandardPort); } /// <summary> /// Loads the cache. /// </summary> /// <param name="key">Key.</param> public void LoadCache (string key) { if (!File.Exists (CacheFileName)) return; var buffer = File.ReadAllBytes (CacheFileName); manageCache.Import (buffer, key); var enumerate = manageCache.Users.GetEnumerator (); while (enumerate.MoveNext ()) UserToLock.TryAdd (enumerate.Current.Value, false); } /// <summary> /// Saves the cache. /// </summary> /// <param name="key">Key.</param> public void SaveCache (string key) { File.WriteAllBytes (CacheFileName, manageCache.Export (key)); } /// <summary> /// Starts the hosting. /// </summary> /// <param name="ip">Ip.</param> /// <param name="port">Port.</param> public void StartHosting (IPAddress ip, int port) { if (_IsHosting) return; try { TCPServer = new TcpListener (ip, port); TCPServer.Start (); _IsHosting = true; serverThread = new Thread (new ThreadStart (ListenProcess)); serverThread.Name = "Domain Hosting Thread"; serverThread.Start (); } catch (Exception) { if (TCPServer != null) { TCPServer.Stop (); TCPServer = null; } if (serverThread != null) { serverThread.Join (); serverThread = null; } throw; } } /// <summary> /// Stops the hosting. /// </summary> public void StopHosting () { if (!_IsHosting) return; _IsHosting = false; serverThread.Join (); serverThread = null; if (TCPServer != null) lock (TCPServer) { TCPServer.Stop (); TCPServer = null; } lock (ActiveViewNetManagers) { if (ActiveViewNetManagers.Count > 0) { foreach (var manager in ActiveViewNetManagers) manager.Value.Stop (); ActiveViewNetManagers.Clear (); } } } /// <summary> /// Connects to a host. /// </summary> /// <param name="ip">Ip.</param> /// <param name="standard">Standard.</param> public void ConnectToHost (IPAddress ip, CryptoStandard standard) { ConnectToHost (ip, StandardPort, standard); } /// <summary> /// Connects to a host. /// </summary> /// <param name="ip">Ip.</param> /// <param name="port">Port.</param> /// <param name="standard">Standard.</param> public void ConnectToHost (IPAddress ip, int port, CryptoStandard standard) { var endPoint = new IPEndPoint (ip, port); lock (ActiveViewNetManagers) { ActiveViewNetManagers.Add (endPoint, new ServiceManager ( endPoint, manageCache, standard, RetriesMax )); } } /// <summary> /// Connects to a host. /// </summary> /// <param name="ip">Ip.</param> /// <param name="port">Port.</param> public void ConnectToHost (IPAddress ip, int port) { var endPoint = new IPEndPoint (ip, port); lock (ActiveViewNetManagers) { ActiveViewNetManagers.Add (endPoint, new ServiceManager ( endPoint, manageCache, CryptoStandard.DHAES256, RetriesMax )); } } /// <summary> /// Connects to a host. /// </summary> /// <param name="ip">Ip.</param> public void ConnectToHost (IPAddress ip) { var endPoint = new IPEndPoint (ip, StandardPort); lock (ActiveViewNetManagers) { ActiveViewNetManagers.Add (endPoint, new ServiceManager ( endPoint, manageCache, CryptoStandard.DHAES256, RetriesMax )); } } /// <summary> /// Gets a list of connected clients. /// </summary> /// <returns>The list of connected clients.</returns> public IPEndPoint[] GetListOfConnectedClients () { var clients = new List<IPEndPoint> (); lock (ActiveViewNetManagers) { var enumerate = ActiveViewNetManagers.GetEnumerator (); while (enumerate.MoveNext ()) clients.Add (enumerate.Current.Key); } return clients.ToArray (); } //TODO: Re-Do Service Management on Domain Level /* public bool AddDomainService (IPEndPoint ipend, IDomainService service) { throw new NotImplementedException (); var services = service.AddConnection (ipend); ActiveViewNetManagers [ipend].AddNewServices (ref services); return false; } */ /// <summary> /// Add a service to a node. /// </summary> /// <returns><c>true</c>, if service to node was added, <c>false</c> otherwise.</returns> /// <param name="ipend">Ipend.</param> /// <param name="service">Service.</param> public bool AddServiceToNode (IPEndPoint ipend, IService service) { lock (ActiveViewNetManagers) { if (!ActiveViewNetManagers.ContainsKey (ipend)) return false; ActiveViewNetManagers [ipend].AddNewService (ref service); } return true; } void ListenProcess () { while (_IsHosting) { // Check for any pending connection requests lock (TCPServer) if (TCPServer.Pending ()) { lock (ActiveViewNetManagers) { var newSocket = TCPServer.AcceptTcpClient (); ActiveViewNetManagers.Add ((IPEndPoint)newSocket.Client.RemoteEndPoint, new ServiceManager ( newSocket, manageCache, DefaultStandard, RetriesMax)); } } // Check if any client has been disconnected lock (ActiveViewNetManagers) { var enumerate = ActiveViewNetManagers.GetEnumerator (); while (enumerate.MoveNext ()) { if (!enumerate.Current.Value.IsRunning ()) { DisconnectedClients.Enqueue (enumerate.Current.Key); } } } if (DisconnectedClients.Count > 0) lock (ActiveViewNetManagers) { while (true) { IPEndPoint currentDisconnection; var check = DisconnectedClients.TryDequeue (out currentDisconnection); if (!check) break; ActiveViewNetManagers.Remove (currentDisconnection); } } Thread.Sleep (1); } } /// <summary> /// Checks the state of connection. /// </summary> /// <returns><c>true</c>, if state of connection was checked, <c>false</c> otherwise.</returns> /// <param name="ipendpoint">Ipendpoint.</param> public bool CheckStateOfConnection (IPEndPoint ipendpoint) { bool result = false; lock (ActiveViewNetManagers) if (ActiveViewNetManagers.ContainsKey (ipendpoint)) result = ActiveViewNetManagers [ipendpoint].IsRunning (); return result; } /// <summary> /// Checks the state of the host. /// </summary> /// <returns><c>true</c>, if host state was checked, <c>false</c> otherwise.</returns> public bool CheckHostState () { return serverThread.ThreadState == ThreadState.Running; } /// <summary> /// Stop the entire domain connection/hosting. /// </summary> public void Stop () { StopHosting (); lock (ActiveViewNetManagers) { var enumerate = ActiveViewNetManagers.GetEnumerator (); while (enumerate.MoveNext ()) { enumerate.Current.Value.Stop (); } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Threading; using BTDB.StreamLayer; using Microsoft.Win32.SafeHandles; namespace BTDB.KVDBLayer { public class OnDiskFileCollection : IFileCollection { public IDeleteFileCollectionStrategy DeleteFileCollectionStrategy { get { return _deleteFileCollectionStrategy ?? (_deleteFileCollectionStrategy = new JustDeleteFileCollectionStrategy()); } set { _deleteFileCollectionStrategy = value; } } readonly string _directory; // disable invalid warning about using volatile inside Interlocked.CompareExchange #pragma warning disable 420 volatile Dictionary<uint, File> _files = new Dictionary<uint, File>(); int _maxFileId; IDeleteFileCollectionStrategy _deleteFileCollectionStrategy; sealed class File : IFileCollectionFile { readonly OnDiskFileCollection _owner; readonly uint _index; readonly string _fileName; readonly FileStream _stream; readonly SafeFileHandle _handle; readonly Writer _writer; readonly ReaderWriterLockSlim _readerWriterLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); public File(OnDiskFileCollection owner, uint index, string fileName) { _owner = owner; _index = index; _fileName = fileName; _stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, 1, FileOptions.None); _handle = _stream.SafeFileHandle; _writer = new Writer(this); } internal void Dispose() { _writer.FlushBuffer(); _handle.Dispose(); _stream.Dispose(); } public uint Index => _index; sealed class Reader : AbstractBufferedReader { readonly File _owner; readonly ulong _valueSize; ulong _ofs; public Reader(File owner) { _owner = owner; _valueSize = _owner.GetSize(); _ofs = 0; Buf = new byte[32768]; FillBuffer(); } protected override void FillBuffer() { if (_ofs == _valueSize) { Pos = -1; End = -1; return; } End = (int) PlatformMethods.Instance.PRead(_owner._handle, Buf.AsSpan(0, Buf.Length), _ofs); _ofs += (ulong) End; Pos = 0; } public override void ReadBlock(Span<byte> data) { if (data.Length < Buf.Length) { base.ReadBlock(data); return; } var l = End - Pos; Buf.AsSpan(Pos, l).CopyTo(data); data = data.Slice(l); Pos += l; var read = PlatformMethods.Instance.PRead(_owner._handle, data, _ofs); if (read != data.Length) { throw new EndOfStreamException(); } _ofs += read; } public override void SkipBlock(int length) { if (length < Buf.Length) { base.SkipBlock(length); return; } if (GetCurrentPosition() + length > (long) _valueSize) { _ofs = _valueSize; Pos = 0; End = -1; throw new EndOfStreamException(); } var l = End - Pos; Pos = End; length -= l; _ofs += (ulong) length; } public override long GetCurrentPosition() { return (long) _ofs - End + Pos; } } sealed class Writer : AbstractBufferedWriter { readonly File _file; internal ulong Ofs; public Writer(File file) { _file = file; Buf = new byte[32768]; End = Buf.Length; using (_file._readerWriterLock.WriteLock()) { Ofs = (ulong) _file._stream.Length; } } public override void FlushBuffer() { if (Pos != 0) { PlatformMethods.Instance.PWrite(_file._handle, Buf.AsSpan(0, Pos), Ofs); using (_file._readerWriterLock.WriteLock()) { Ofs += (ulong) Pos; Pos = 0; } } } public override void WriteBlock(ReadOnlySpan<byte> data) { if (data.Length < Buf.Length) { base.WriteBlock(data); return; } FlushBuffer(); PlatformMethods.Instance.PWrite(_file._handle, data, Ofs); using (_file._readerWriterLock.WriteLock()) { Ofs += (ulong) data.Length; } } public override long GetCurrentPosition() { return (long) (Ofs + (ulong) Pos); } internal byte[] GetBuffer() { return Buf; } } public AbstractBufferedReader GetExclusiveReader() { return new Reader(this); } public void AdvisePrefetch() { } public void RandomRead(Span<byte> data, ulong position, bool doNotCache) { using (_readerWriterLock.ReadLock()) { if (data.Length > 0 && position < _writer.Ofs) { var read = data.Length; if (_writer.Ofs - position < (ulong) read) read = (int) (_writer.Ofs - position); if (PlatformMethods.Instance.PRead(_handle, data.Slice(0, read), position) != read) throw new EndOfStreamException(); data = data.Slice(read); position += (ulong) read; } if (data.Length == 0) return; if ((ulong) _writer.GetCurrentPosition() < position + (ulong) data.Length) throw new EndOfStreamException(); _writer.GetBuffer().AsSpan((int) (position - _writer.Ofs), data.Length).CopyTo(data); } } public AbstractBufferedWriter GetAppenderWriter() { return _writer; } public AbstractBufferedWriter GetExclusiveAppenderWriter() { return _writer; } public void Flush() { _writer.FlushBuffer(); } public void HardFlush() { _writer.FlushBuffer(); _stream.Flush(true); } public void SetSize(long size) { } public void Truncate() { } public void HardFlushTruncateSwitchToReadOnlyMode() { HardFlush(); } public void HardFlushTruncateSwitchToDisposedMode() { HardFlush(); } public ulong GetSize() { using (_readerWriterLock.ReadLock()) { return (ulong) _writer.GetCurrentPosition(); } } public void Remove() { Dictionary<uint, File> newFiles; Dictionary<uint, File> oldFiles; do { oldFiles = _owner._files; File value; if (!oldFiles.TryGetValue(_index, out value)) return; newFiles = new Dictionary<uint, File>(oldFiles); newFiles.Remove(_index); } while (Interlocked.CompareExchange(ref _owner._files, newFiles, oldFiles) != oldFiles); _stream.Dispose(); _owner.DeleteFileCollectionStrategy.DeleteFile(_fileName); } } public OnDiskFileCollection(string directory) { _directory = directory; _maxFileId = 0; foreach (var filePath in Directory.EnumerateFiles(directory)) { var id = GetFileId(Path.GetFileNameWithoutExtension(filePath)); if (id == 0) continue; var file = new File(this, id, filePath); _files.Add(id, file); if (id > _maxFileId) _maxFileId = (int) id; } } static uint GetFileId(string fileName) { uint result; if (uint.TryParse(fileName, out result)) { return result; } return 0; } public IFileCollectionFile AddFile(string humanHint) { var index = (uint) Interlocked.Increment(ref _maxFileId); var fileName = index.ToString("D8") + "." + (humanHint ?? ""); var file = new File(this, index, Path.Combine(_directory, fileName)); Dictionary<uint, File> newFiles; Dictionary<uint, File> oldFiles; do { oldFiles = _files; newFiles = new Dictionary<uint, File>(oldFiles) {{index, file}}; } while (Interlocked.CompareExchange(ref _files, newFiles, oldFiles) != oldFiles); return file; } public uint GetCount() { return (uint) _files.Count; } public IFileCollectionFile GetFile(uint index) { File value; return _files.TryGetValue(index, out value) ? value : null; } public IEnumerable<IFileCollectionFile> Enumerate() { return _files.Values; } public void ConcurrentTemporaryTruncate(uint index, uint offset) { // Nothing to do } public void Dispose() { foreach (var file in _files.Values) { file.Dispose(); } } } }
using Vanara.Extensions; using Vanara.PInvoke; using static Vanara.PInvoke.User32; namespace NetDimension.NanUI.HostWindow; internal partial class _FackUnusedClass { } internal partial class BorderlessWindow { [StructLayout(LayoutKind.Sequential)] public struct NCCALCSIZE_PARAMS { public RECT rgrc0, rgrc1, rgrc2; public WINDOWPOS lppos; } internal protected bool IsApplicationForeground { get; private set; } protected override void WndProc(ref Message m) { switch (m.Msg) { case (int)WindowMessage.WM_CREATE: if (!WmCreate(ref m)) { base.WndProc(ref m); } break; case (int)WindowMessage.WM_NCCALCSIZE: { if (!WmNCCalcSize(ref m)) { base.WndProc(ref m); } } break; case (int)WindowMessage.WM_NCPAINT: { if (!WmNCPaint(ref m)) { base.WndProc(ref m); } } break; case (int)WindowMessage.WM_SIZE: { if (!WmSize(ref m)) { base.WndProc(ref m); } } break; case (int)WindowMessage.WM_WINDOWPOSCHANGED: { if (!WmWindowPosChanged(ref m)) { base.WndProc(ref m); } } break; case (int)WindowMessage.WM_ACTIVATEAPP: { InvalidateNonClientArea(); SendFrameChangedMessage(); if (!WmActiveApp(ref m)) { base.WndProc(ref m); } } break; case (int)WindowMessage.WM_NCACTIVATE: { if (!WmNCActive(ref m)) { base.WndProc(ref m); } } break; case (int)WindowMessage.WM_NCHITTEST: { var x = Macros.GET_X_LPARAM(m.LParam); var y = Macros.GET_Y_LPARAM(m.LParam); var pt = new Point(x, y); ScreenToClient(hWnd, ref pt); var mode = HitTest(pt); if (mode == HitTestValues.HTCLIENT) mode = HitTestValues.HTCAPTION; m.Result = (IntPtr)mode; base.WndProc(ref m); } break; case (int)WindowMessage.WM_NCMOUSEMOVE: case (int)WindowMessage.WM_NCMOUSELEAVE: case (int)WindowMessage.WM_NCLBUTTONDOWN: case (int)WindowMessage.WM_NCRBUTTONDOWN: case (int)WindowMessage.WM_NCLBUTTONDBLCLK: case (int)WindowMessage.WM_NCRBUTTONDBLCLK: { InvalidateNonClientArea(); SendFrameChangedMessage(); base.WndProc(ref m); } break; case 0x00AE: //WM_NCUAHDRAWCAPTION: case 0x00AF: //WM_NCUAHDRAWFRAME: case 0xC1BC: //WM_UNKNOWN_GHOST { InvalidateNonClientArea(); SendFrameChangedMessage(); m.Result = TRUE; } break; case (int)WindowMessage.WM_DPICHANGED: { if (!WmDpiChanged(ref m)) { base.WndProc(ref m); } } break; default: base.WndProc(ref m); break; } } private bool WmActiveApp(ref Message m) { if (m.WParam == IntPtr.Zero) { IsApplicationForeground = false; KillApplicationFocus(); } else { IsApplicationForeground = true; SetApplicationFocus(); if (WindowState == FormWindowState.Normal) { using var roundedRect = GetWindowBorderPath(); SetWindowRegion(roundedRect); } } return false; } private bool WmNCActive(ref Message m) { var isActive = IsWindowFocused = (m.WParam == TRUE); if (MinMaxState == FormWindowState.Minimized) { DefWndProc(ref m); } else { m.Result = MESSAGE_HANDLED; InvalidateNonClientArea(); SendFrameChangedMessage(); if (isActive) { SetWindowFocus(); } else { KillWindowFocus(); } UpdateShadowZOrder(); } return true; } private bool WmWindowPosChanged(ref Message m) { var windowpos = m.LParam.ToStructure<WINDOWPOS>(); if (!IsIconic(hWnd)) { UpdateShadowPos(windowpos); } return false; } private bool WmSize(ref Message m) { if (!_isLoaded) return false; if (WindowState == FormWindowState.Maximized) { _shouldPerformMaximiazedState = true; var screen = Screen.FromHandle(Handle); var bounds = FormBorderStyle == FormBorderStyle.None ? screen.Bounds : screen.WorkingArea; var regionBounds = new Rectangle(bounds.X - Bounds.X, bounds.Y - Bounds.Y, Bounds.Width - (Bounds.Width - bounds.Width), Bounds.Height - (Bounds.Height - bounds.Height)); SetWindowRegion(regionBounds); } else if (WindowState == FormWindowState.Normal) { using var roundedRect = GetWindowBorderPath(); SetWindowRegion(roundedRect); } else { RemoveWindowRegion(); } SendFrameChangedMessage(); ResizeShadow(ref m); return false; } private bool WmCreate(ref Message _) { GetWindowRect(hWnd, out var rcClient); SetWindowPos(hWnd, HWND.NULL, rcClient.left, rcClient.top, rcClient.Width, rcClient.Height, SetWindowPosFlags.SWP_FRAMECHANGED); return false; } private bool WmNCCalcSize(ref Message m) { if (m.WParam == TRUE) { var nccsp = Marshal.PtrToStructure<NCCALCSIZE_PARAMS>(m.LParam); if (WindowState != FormWindowState.Maximized && WindowState != FormWindowState.Minimized) { m.Result = MESSAGE_PROCESS; return true; } else if (WindowState == FormWindowState.Maximized) { var ncBorders = GetNonClientAeraBorders(); nccsp.rgrc0.top -= ncBorders.Top; nccsp.rgrc0.top += ncBorders.Bottom; Marshal.StructureToPtr(nccsp, m.LParam, false); m.Result = MESSAGE_PROCESS; } } return false; } private bool WmNCPaint(ref Message m) { if (!IsHandleCreated) { return false; } m.Result = MESSAGE_PROCESS; return true; } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Threading.Tasks; using NUnit.Framework; using Xamarin.Forms.Internals; namespace Xamarin.Forms.Core.UnitTests { [TestFixture] public class ViewUnitTests : BaseTestFixture { [SetUp] public override void Setup () { base.Setup (); Device.PlatformServices = new MockPlatformServices (); } [TearDown] public override void TearDown () { base.TearDown (); Device.PlatformServices = null; } [Test] public void TestLayout () { View view = new View (); view.Layout (new Rectangle (50, 25, 100, 200)); Assert.AreEqual (view.X, 50); Assert.AreEqual (view.Y, 25); Assert.AreEqual (view.Width, 100); Assert.AreEqual (view.Height, 200); } [Test] public void TestPreferredSize () { View view = new View { IsPlatformEnabled = true, Platform = new UnitPlatform () }; bool fired = false; view.MeasureInvalidated += (sender, e) => fired = true; view.WidthRequest = 200; view.HeightRequest = 300; Assert.True (fired); var result = view.GetSizeRequest (double.PositiveInfinity, double.PositiveInfinity).Request; Assert.AreEqual (new Size (200, 300), result); } [Test] public void TestSizeChangedEvent () { View view = new View (); bool fired = false; view.SizeChanged += (sender, e) => fired = true; view.Layout (new Rectangle (0, 0, 100, 100)); Assert.True (fired); } [Test] public void TestOpacityClamping () { var view = new View (); view.Opacity = -1; Assert.AreEqual (0, view.Opacity); view.Opacity = 2; Assert.AreEqual (1, view.Opacity); } [Test] public void TestMeasureInvalidatedFiredOnVisibilityChanged () { var view = new View {IsVisible = false}; bool signaled = false; view.MeasureInvalidated += (sender, e) => { signaled = true; }; view.IsVisible = true; Assert.True (signaled); } [Test] public void TestOnPlatformiOS () { var view = new View (); bool ios = false; bool android = false; bool winphone = false; Device.OS = TargetPlatform.iOS; Device.OnPlatform ( iOS: () => ios = true, Android: () => android = true, WinPhone: () => winphone = true); Assert.True (ios); Assert.False (android); Assert.False (winphone); } [Test] public void TestOnPlatformAndroid () { var view = new View (); bool ios = false; bool android = false; bool winphone = false; Device.OS = TargetPlatform.Android; Device.OnPlatform ( iOS: () => ios = true, Android: () => android = true, WinPhone: () => winphone = true); Assert.False (ios); Assert.True (android); Assert.False (winphone); } [Test] public void TestOnPlatformWinPhone () { var view = new View (); bool ios = false; bool android = false; bool winphone = false; Device.OS = TargetPlatform.WinPhone; Device.OnPlatform ( iOS: () => ios = true, Android: () => android = true, WinPhone: () => winphone = true); Assert.False (ios); Assert.False (android); Assert.True (winphone); } [Test] public void TestOnPlatformDefault () { var view = new View (); bool ios = false; bool android = false; Device.OS = TargetPlatform.Android; Device.OnPlatform ( iOS: () => ios = false, Default: () => android = true); Assert.False (ios); Assert.True (android); } [Test] public void TestOnPlatformNoOpWithoutDefault () { bool any = false; Device.OS = TargetPlatform.Other; Device.OnPlatform ( iOS: () => any = true, Android: () => any = true, WinPhone: () => any = true); Assert.False (any); } [Test] public void TestDefaultOniOS () { bool defaultExecuted = false; Device.OS = TargetPlatform.iOS; Device.OnPlatform ( Android: () => { }, WinPhone: () => { }, Default:() => defaultExecuted = true); Assert.True (defaultExecuted); } [Test] public void TestDefaultOnAndroid () { bool defaultExecuted = false; Device.OS = TargetPlatform.Android; Device.OnPlatform ( iOS: () => { }, WinPhone: () => { }, Default:() => defaultExecuted = true); Assert.True (defaultExecuted); } [Test] public void TestDefaultOnWinPhone () { bool defaultExecuted = false; Device.OS = TargetPlatform.WinPhone; Device.OnPlatform ( iOS: () => { }, Android: () => { }, Default:() => defaultExecuted = true); Assert.True (defaultExecuted); } [Test] public void TestDefaultOnOther () { bool defaultExecuted = false; Device.OS = TargetPlatform.Other; Device.OnPlatform ( iOS: () => { }, Android: () => { }, WinPhone: () => { }, Default:() => defaultExecuted = true); Assert.True (defaultExecuted); } [Test] public void TestNativeStateConsistent () { var view = new View { IsPlatformEnabled = true }; Assert.True (view.IsNativeStateConsistent); view.IsNativeStateConsistent = false; Assert.False (view.IsNativeStateConsistent); bool sizeChanged = false; view.MeasureInvalidated += (sender, args) => { sizeChanged = true; }; view.IsNativeStateConsistent = true; Assert.True (sizeChanged); sizeChanged = false; view.IsNativeStateConsistent = true; Assert.False (sizeChanged); } [Test] public void TestFadeTo () { var view = new View {IsPlatformEnabled = true, Platform = new UnitPlatform ()}; Ticker.Default = new BlockingTicker (); view.FadeTo (0.1); Assert.True (Math.Abs (0.1 - view.Opacity) < 0.001); } [Test] public void TestTranslateTo () { var view = new View {IsPlatformEnabled = true, Platform = new UnitPlatform ()}; Ticker.Default = new BlockingTicker (); view.TranslateTo (100, 50); Assert.AreEqual (100, view.TranslationX); Assert.AreEqual (50, view.TranslationY); } [Test] public void ScaleTo () { var view = new View {IsPlatformEnabled = true, Platform = new UnitPlatform ()}; Ticker.Default = new BlockingTicker (); view.ScaleTo (2); Assert.AreEqual (2, view.Scale); } [Test] public void TestNativeSizeChanged () { var view = new View (); bool sizeChanged = false; view.MeasureInvalidated += (sender, args) => sizeChanged = true; ((IVisualElementController)view).NativeSizeChanged (); Assert.True (sizeChanged); } [Test] public void TestRotateTo () { var view = new View {IsPlatformEnabled = true, Platform = new UnitPlatform ()}; Ticker.Default = new BlockingTicker (); view.RotateTo (25); Assert.That (view.Rotation, Is.EqualTo (25).Within (0.001)); } [Test] public void TestRotateYTo () { var view = new View {IsPlatformEnabled = true, Platform = new UnitPlatform ()}; Ticker.Default = new BlockingTicker (); view.RotateYTo (25); Assert.That (view.RotationY, Is.EqualTo (25).Within (0.001)); } [Test] public void TestRotateXTo () { var view = new View {IsPlatformEnabled = true, Platform = new UnitPlatform ()}; Ticker.Default = new BlockingTicker (); view.RotateXTo (25); Assert.That (view.RotationX, Is.EqualTo (25).Within (0.001)); } [Test] public void TestRelRotateTo () { var view = new View {Rotation = 30, IsPlatformEnabled = true, Platform = new UnitPlatform ()}; Ticker.Default = new BlockingTicker (); view.RelRotateTo (20); Assert.That (view.Rotation, Is.EqualTo (50).Within (0.001)); } [Test] public void TestRelScaleTo () { var view = new View {Scale = 1, IsPlatformEnabled = true, Platform = new UnitPlatform ()}; Ticker.Default = new BlockingTicker (); view.RelScaleTo (1); Assert.That (view.Scale, Is.EqualTo (2).Within (0.001)); } class ParentSignalView : View { public bool ParentSet { get; set; } protected override void OnParentSet () { ParentSet = true; base.OnParentSet (); } } [Test] public void TestDoubleSetParent () { var view = new ParentSignalView (); var parent = new NaiveLayout {Children = {view}}; view.ParentSet = false; view.Parent = parent; Assert.False (view.ParentSet, "OnParentSet should not be called in the event the parent is already properly set"); } [Test] public void TestAncestorAdded () { var child = new NaiveLayout (); var view = new NaiveLayout {Children = {child}}; bool added = false; view.DescendantAdded += (sender, arg) => added = true; child.Children.Add (new View ()); Assert.True (added, "AncestorAdded must fire when adding a child to an ancestor of a view."); } [Test] public void TestAncestorRemoved () { var ancestor = new View (); var child = new NaiveLayout {Children = {ancestor}}; var view = new NaiveLayout {Children = {child}}; bool removed = false; view.DescendantRemoved += (sender, arg) => removed = true; child.Children.Remove (ancestor); Assert.True (removed, "AncestorRemoved must fire when removing a child from an ancestor of a view."); } [Test] public void TestOnPlatformGeneric () { Device.OS = TargetPlatform.WinPhone; Assert.AreEqual (3, Device.OnPlatform (1, 2, 3)); Device.OS = TargetPlatform.iOS; Assert.AreEqual (1, Device.OnPlatform (1, 2, 3)); Device.OS = TargetPlatform.Android; Assert.AreEqual (2, Device.OnPlatform (1, 2, 3)); Device.OS = TargetPlatform.Other; Assert.AreEqual (1, Device.OnPlatform (1, 2, 3)); } [Test] public void TestBatching () { var view = new View (); bool committed = false; view.BatchCommitted += (sender, arg) => committed = true; view.BatchBegin (); Assert.True (view.Batched); view.BatchBegin (); Assert.True (view.Batched); view.BatchCommit (); Assert.True (view.Batched); Assert.False (committed); view.BatchCommit (); Assert.False (view.Batched); Assert.True (committed); } [Test] public void IsPlatformEnabled () { var view = new View (); Assert.False (view.IsPlatformEnabled); view.IsPlatformEnabled = true; Assert.True (view.IsPlatformEnabled); view.IsPlatformEnabled = false; Assert.False (view.IsPlatformEnabled); } [Test] public void TestBindingContextChaining () { View child; var group = new NaiveLayout { Children = { (child = new View ()) } }; var context = new object (); group.BindingContext = context; Assert.AreEqual (context, child.BindingContext); } [Test] public void FocusWithoutSubscriber () { var view = new View (); Assert.False (view.Focus ()); } [Test] public void FocusWithSubscriber ([Values(true, false)] bool result) { var view = new View (); view.FocusChangeRequested += (sender, arg) => arg.Result = result; Assert.True (view.Focus () == result); } [Test] public void DoNotSignalWhenAlreadyFocused () { var view = new View (); view.SetValueCore (VisualElement.IsFocusedPropertyKey, true); bool signaled = false; view.FocusChangeRequested += (sender, args) => signaled = true; Assert.True (view.Focus (), "View.Focus returned false"); Assert.False (signaled, "FocusRequested was raised"); } [Test] public void UnFocus () { var view = new View (); view.SetValueCore (VisualElement.IsFocusedPropertyKey, true); var requested = false; view.FocusChangeRequested += (sender, args) => { requested = !args.Focus; }; view.Unfocus (); Assert.True (requested); } [Test] public void UnFocusDoesNotFireWhenNotFocused () { var view = new View (); view.SetValueCore (VisualElement.IsFocusedPropertyKey, false); var requested = false; view.FocusChangeRequested += (sender, args) => { requested = args.Focus; }; view.Unfocus (); Assert.False (requested); } [Test] public void PlatformSet () { var view = new View (); bool set = false; view.PlatformSet += (sender, args) => set = true; view.Platform = new UnitPlatform (); Assert.True (set); } [Test] public void TestFocusedEvent () { var view = new View (); bool fired = false; view.Focused += (sender, args) => fired = true; view.SetValueCore (VisualElement.IsFocusedPropertyKey, true); Assert.True (fired); } [Test] public void TestUnFocusedEvent () { var view = new View (); view.SetValueCore (VisualElement.IsFocusedPropertyKey, true); bool fired = false; view.Unfocused += (sender, args) => fired = true; view.SetValueCore (VisualElement.IsFocusedPropertyKey, false); Assert.True (fired); } [Test] public void TestBeginInvokeOnMainThread () { Device.PlatformServices = new MockPlatformServices (invokeOnMainThread: action => action ()); bool invoked = false; Device.BeginInvokeOnMainThread (() => invoked = true); Assert.True (invoked); } [Test] public void InvokeOnMainThreadThrowsWhenNull () { Device.PlatformServices = null; Assert.Throws<InvalidOperationException>(() => Device.BeginInvokeOnMainThread (() => { })); } [Test] public void TestOpenUriAction () { var uri = new Uri ("http://www.xamarin.com/"); var invoked = false; Device.PlatformServices = new MockPlatformServices (openUriAction: u => { Assert.AreSame (uri, u); invoked = true; }); Device.OpenUri (uri); Assert.True (invoked); } [Test] public void OpenUriThrowsWhenNull () { Device.PlatformServices = null; var uri = new Uri ("http://www.xamarin.com/"); Assert.Throws<InvalidOperationException> (() => Device.OpenUri (uri)); } [Test] public void MinimumWidthRequest () { var view = new View (); bool signaled = false; view.MeasureInvalidated += (sender, args) => signaled = true; view.MinimumWidthRequest = 10; Assert.True (signaled); Assert.AreEqual (10, view.MinimumWidthRequest); signaled = false; view.MinimumWidthRequest = 10; Assert.False (signaled); } [Test] public void MinimumHeightRequest () { var view = new View (); bool signaled = false; view.MeasureInvalidated += (sender, args) => signaled = true; view.MinimumHeightRequest = 10; Assert.True (signaled); Assert.AreEqual (10, view.MinimumHeightRequest); signaled = false; view.MinimumHeightRequest = 10; Assert.False (signaled); } [Test] public void MinimumWidthRequestInSizeRequest () { var view = new View { Platform = new UnitPlatform (), IsPlatformEnabled = true }; view.HeightRequest = 20; view.WidthRequest = 200; view.MinimumWidthRequest = 100; var result = view.GetSizeRequest (double.PositiveInfinity, double.PositiveInfinity); Assert.AreEqual (new Size (200, 20), result.Request); Assert.AreEqual (new Size (100, 20), result.Minimum); } [Test] public void MinimumHeightRequestInSizeRequest () { var view = new View { Platform = new UnitPlatform (), IsPlatformEnabled = true }; view.HeightRequest = 200; view.WidthRequest = 20; view.MinimumHeightRequest = 100; var result = view.GetSizeRequest (double.PositiveInfinity, double.PositiveInfinity); Assert.AreEqual (new Size (20, 200), result.Request); Assert.AreEqual (new Size (20, 100), result.Minimum); } [Test] public void StartTimerSimple () { Device.PlatformServices = new MockPlatformServices (); var task = new TaskCompletionSource<bool> (); Task.Factory.StartNew (() => Device.StartTimer (TimeSpan.FromMilliseconds (200), () => { task.SetResult (false); return false; })); task.Task.Wait (); Assert.False (task.Task.Result); Device.PlatformServices = null; } [Test] public void StartTimerMultiple () { Device.PlatformServices = new MockPlatformServices (); var task = new TaskCompletionSource<int> (); int steps = 0; Task.Factory.StartNew (() => Device.StartTimer (TimeSpan.FromMilliseconds (200), () => { steps++; if (steps < 2) return true; task.SetResult (steps); return false; })); task.Task.Wait (); Assert.AreEqual (2, task.Task.Result); Device.PlatformServices = null; } [Test] public void BindingsApplyAfterViewAddedToParentWithContextSet() { var parent = new NaiveLayout(); parent.BindingContext = new MockViewModel { Text = "test" }; var child = new Entry(); child.SetBinding (Entry.TextProperty, new Binding ("Text")); parent.Children.Add (child); Assert.That (child.BindingContext, Is.SameAs (parent.BindingContext)); Assert.That (child.Text, Is.EqualTo ("test")); } [Test] public void IdIsUnique () { var view1 = new View (); var view2 = new View (); Assert.True (view1.Id != view2.Id); } [Test] public void MockBounds () { var view = new View (); view.Layout (new Rectangle (10, 20, 30, 40)); bool changed = false; view.PropertyChanged += (sender, args) => { if (args.PropertyName == View.XProperty.PropertyName || args.PropertyName == View.YProperty.PropertyName || args.PropertyName == View.WidthProperty.PropertyName || args.PropertyName == View.HeightProperty.PropertyName) changed = true; }; view.SizeChanged += (sender, args) => changed = true; view.MockBounds (new Rectangle (5, 10, 15, 20)); Assert.AreEqual (new Rectangle (5, 10, 15, 20), view.Bounds); Assert.False (changed); view.UnmockBounds (); Assert.AreEqual (new Rectangle (10, 20, 30, 40), view.Bounds); Assert.False (changed); } [Test] public void AddGestureRecognizer () { var view = new View (); var gestureRecognizer = new TapGestureRecognizer (); view.GestureRecognizers.Add (gestureRecognizer); Assert.True (view.GestureRecognizers.Contains (gestureRecognizer)); } [Test] public void AddGestureRecognizerSetsParent () { var view = new View (); var gestureRecognizer = new TapGestureRecognizer (); view.GestureRecognizers.Add (gestureRecognizer); Assert.AreEqual (view, gestureRecognizer.Parent); } [Test] public void RemoveGestureRecognizerUnsetsParent () { var view = new View (); var gestureRecognizer = new TapGestureRecognizer (); view.GestureRecognizers.Add (gestureRecognizer); view.GestureRecognizers.Remove (gestureRecognizer); Assert.Null (gestureRecognizer.Parent); } [Test] public void WidthRequestEffectsGetSizeRequest () { var view = new View (); view.IsPlatformEnabled = true; view.Platform = new UnitPlatform ((ve, widthConstraint, heightConstraint) => { if (widthConstraint < 30) return new SizeRequest (new Size (40, 50)); return new SizeRequest(new Size(20, 100)); }); view.WidthRequest = 20; var request = view.GetSizeRequest (double.PositiveInfinity, double.PositiveInfinity); Assert.AreEqual (new Size (20, 50), request.Request); } [Test] public void HeightRequestEffectsGetSizeRequest () { var view = new View (); view.IsPlatformEnabled = true; view.Platform = new UnitPlatform ((ve, widthConstraint, heightConstraint) => { if (heightConstraint < 30) return new SizeRequest (new Size (40, 50)); return new SizeRequest(new Size(20, 100)); }); view.HeightRequest = 20; var request = view.GetSizeRequest (double.PositiveInfinity, double.PositiveInfinity); Assert.AreEqual (new Size (40, 20), request.Request); } } }
using System; using System.Collections.Generic; using System.Compiler; using System.Diagnostics.Contracts; using System.Linq; using System.Threading.Tasks; using Microsoft.Contracts.Foxtrot.Utils; namespace Microsoft.Contracts.Foxtrot { /// <summary> /// Visitor that creates special closure type for async postconditions. /// </summary> /// <remarks> /// /// Current class generate AsyncClosure with CheckMethod and CheckException methods. /// /// Following transformation are applied to the original async method: /// /// // This is oroginal task, generated by the AsyncTaskMethodBuilder /// var originalTask = t_builder.Task; /// /// var closure = new AsyncClosure(); /// var task2 = originalTask.ContinueWith(closure.CheckPost).Unwrap(); /// return task2; /// /// There are 2 cases: /// 1) Task has no return value. /// In this case only EnsuresOnThrow could be used, and we emit: /// Task CheckMethod(Task t) /// { /// if (t.Status == TaskStatus.Faulted) /// { /// // CheckException will throw if EnsuresOnThrow is not held /// CheckException(t.Exception); /// } /// /// return t; /// } /// /// 2) Task(T) reutrns a T value. /// In this case both EnsuresOnThrow and Contract.Ensures(Contract.Result) could be used. /// We emit: /// /// Task&lt;int> CheckMethod(Task&lt;int> t) /// { /// if (t.Status == TaskStatus.Faulted) /// { /// // CheckException will throw if EnsuresOnThrow is not held /// CheckException(t.Exception); /// } /// /// if (t.Status == TaskStatus.RanToCompletion) /// { /// // Check ensures /// } /// } /// </remarks> internal class EmitAsyncClosure : StandardVisitor { /// <summary> /// Class that maps generic arguments of the enclosed class/method to the generic arguments of the closure. /// </summary> /// <remarks> /// The problem. /// Original implementation of the Code Contract didn't support async postconditions in generics. /// Here is why: /// Suppose we have following function (in class <c>Foo</c>: /// <code><![CDATA[ /// public static Task<T> FooAsync() where T: class /// { /// Contract.Ensures(Contract.Result<T>() != null); /// } /// ]]></code> /// In this case, ccrewrite will generate async closure class called <c>Foo.AsyncContractClosure_0&lt;T&gt;</c> /// with following structure: /// <code><![CDATA[ /// [CompilerGenerated] /// private class <Foo>AsyncContractClosure_0<T> where T : class /// { /// public Task<T> CheckPost(Task<T> task) /// { /// TaskStatus status = task.Status; /// if (status == TaskStatus.RanToCompletion) /// { /// RewriterMethods.Ensures(task.Result != null, null, "Contract.Result<T>() != null"); /// } /// return task; /// } /// } /// ]]> /// </code> /// The code looks good, but the IL could be invalid (without the trick that this class provides). /// Postcondition of the method in our case is declared in the generic method (in <code>FooAsync</code>) /// but ccrewrite moves it into non-generic method (<code>CheckPost</code>) of the generic class (closure). /// /// But on IL level there is different instructions for referencing method generic arguments and type generic arguments. /// /// After changing <code>Contract.Result</code> to <code>task.Result</code> and moving postcondition to <code>CheckPost</code> /// method, following IL would be generated: /// /// <code> <![CDATA[ /// IL_0011: call instance !0 class [mscorlib]System.Threading.Tasks.Task`1<!T>::get_Result() /// IL_0016: box !!0 // <-- here is our problem! /// ]]> /// </code> /// /// This means that method <code>CheckPost</code> would contains a reference to generic method argument of the /// original method. /// /// The goal of this class is to store a mapping between enclosing generic types and closure generic types. /// </remarks> private class GenericTypeMapper { class TypeNodePair { public TypeNodePair(TypeNode enclosingGenericType, TypeNode closureGenericType) { EnclosingGenericType = enclosingGenericType; ClosureGenericType = closureGenericType; } public TypeNode EnclosingGenericType { get; private set; } public TypeNode ClosureGenericType { get; private set; } } // Mapping between enclosing generic type and closure generic type. // This is a simple list not a dictionary, because number of generic arguments is very small. // So linear complexity will not harm performance. private List<TypeNodePair> typeParametersMapping = new List<TypeNodePair>(); public bool IsEmpty { get { return typeParametersMapping.Count == 0; } } public void AddMapping(TypeNode enclosingGenericType, TypeNode closureGenericType) { typeParametersMapping.Add(new TypeNodePair(enclosingGenericType, closureGenericType)); } /// <summary> /// Returns associated generic type of the closure class by enclosing generic type (for instance, by /// generic type of the enclosing generic method that uses current closure). /// </summary> /// <remarks> /// Function returns the same argument if the matching argument does not exists. /// </remarks> public TypeNode GetClosureTypeParameterByEnclosingTypeParameter(TypeNode enclosingType) { if (enclosingType == null) { return null; } var gen = enclosingType; if (gen.ConsolidatedTemplateParameters != null && gen.ConsolidatedTemplateParameters.Count != 0) { gen = gen.ConsolidatedTemplateParameters[0]; } var candidate = typeParametersMapping.FirstOrDefault(t => t.EnclosingGenericType == enclosingType); return candidate != null ? candidate.ClosureGenericType : enclosingType; } /// <summary> /// Returns associated generic type of the closure class by enclosing generic type (for instance, by /// generic type of the enclosing generic method that uses current closure). /// </summary> /// <remarks> /// Function returns the same argument if the matching argument does not exists. /// </remarks> public TypeNode GetEnclosingTypeParameterByClosureTypeParameter(TypeNode closureType) { if (closureType == null) { return null; } var candidate = typeParametersMapping.FirstOrDefault(t => t.ClosureGenericType == closureType); return candidate != null ? candidate.EnclosingGenericType : closureType; } } // This assembly should be in this class but not in the SystemTypes from System.CompilerCC. // Moving this type there will lead to test failures and assembly resolution errors. private static readonly AssemblyNode/*!*/ SystemCoreAssembly = SystemTypes.GetSystemCoreAssembly(false, true); private static TypeNode TaskExtensionsTypeNode = HelperMethods.FindType( SystemCoreAssembly, Identifier.For("System.Threading.Tasks"), Identifier.For("TaskExtensions")); private static readonly Identifier CheckExceptionMethodId = Identifier.For("CheckException"); private static readonly Identifier CheckMethodId = Identifier.For("CheckPost"); private readonly Cache<TypeNode> aggregateExceptionType; private readonly Cache<TypeNode> func2Type; private readonly Dictionary<Local, MemberBinding> closureLocals = new Dictionary<Local, MemberBinding>(); private readonly List<SourceContext> contractResultCapturedInStaticContext = new List<SourceContext>(); private readonly Rewriter rewriter; private readonly TypeNode declaringType; private readonly Class closureClass; private readonly Class closureClassInstance; private readonly Specializer /*?*/ forwarder; private readonly Local closureLocal; // Fields for the CheckMethod generation private Method checkPostMethod; private StatementList checkPostBody; // Holds a copy of CheckMethod argument private Local originalResultLocal; private Parameter checkMethodTaskParameter; private readonly TypeNode checkMethodTaskType; private readonly GenericTypeMapper genericTypeMapper = new GenericTypeMapper(); public EmitAsyncClosure(Method from, Rewriter rewriter) { Contract.Requires(from != null); Contract.Requires(from.DeclaringType != null); Contract.Requires(rewriter != null); if (TaskExtensionsTypeNode == null) { throw new InvalidOperationException( "Can't generate async closure because System.Threading.Tasks.TaskExceptions class is unavailable."); } this.rewriter = rewriter; this.declaringType = from.DeclaringType; var closureName = HelperMethods.NextUnusedMemberName(declaringType, "<" + from.Name.Name + ">AsyncContractClosure"); this.closureClass = new Class( declaringModule: declaringType.DeclaringModule, declaringType: declaringType, attributes: null, flags: TypeFlags.NestedPrivate, Namespace: null, name: Identifier.For(closureName), baseClass: SystemTypes.Object, interfaces: null, members: null); declaringType.Members.Add(this.closureClass); RewriteHelper.TryAddCompilerGeneratedAttribute(this.closureClass); var taskType = from.ReturnType; this.aggregateExceptionType = new Cache<TypeNode>(() => HelperMethods.FindType(rewriter.AssemblyBeingRewritten, StandardIds.System, Identifier.For("AggregateException"))); this.func2Type = new Cache<TypeNode>(() => HelperMethods.FindType(SystemTypes.SystemAssembly, StandardIds.System, Identifier.For("Func`2"))); // Should distinguish between generic enclosing method and non-generic method in enclosing type. // In both cases generated closure should be generic. var enclosingTemplateParameters = GetGenericTypesFrom(from); if (!enclosingTemplateParameters.IsNullOrEmpty()) { this.closureClass.TemplateParameters = CreateTemplateParameters(closureClass, enclosingTemplateParameters, declaringType); this.closureClass.IsGeneric = true; this.closureClass.EnsureMangledName(); this.forwarder = new Specializer( targetModule: this.declaringType.DeclaringModule, pars: enclosingTemplateParameters, args: this.closureClass.TemplateParameters); this.forwarder.VisitTypeParameterList(this.closureClass.TemplateParameters); taskType = this.forwarder.VisitTypeReference(taskType); for (int i = 0; i < enclosingTemplateParameters.Count; i++) { this.genericTypeMapper.AddMapping(enclosingTemplateParameters[i], closureClass.TemplateParameters[i]); } } else { this.closureClassInstance = this.closureClass; } this.checkMethodTaskType = taskType; // Emiting CheckPost method declaration EmitCheckPostMethodCore(checkMethodTaskType); // Generate closure constructor. // Constructor should be generated AFTER visiting type parameters in // the previous block of code. Otherwise current class would not have // appropriate number of generic arguments! var ctor = CreateConstructor(closureClass); closureClass.Members.Add(ctor); // Now that we added the ctor and the check method, let's instantiate the closure class if necessary if (this.closureClassInstance == null) { var consArgs = new TypeNodeList(); var args = new TypeNodeList(); var parentCount = this.closureClass.DeclaringType.ConsolidatedTemplateParameters == null ? 0 : this.closureClass.DeclaringType.ConsolidatedTemplateParameters.Count; for (int i = 0; i < parentCount; i++) { consArgs.Add(this.closureClass.DeclaringType.ConsolidatedTemplateParameters[i]); } if (!enclosingTemplateParameters.IsNullOrEmpty()) { for (int i = 0; i < enclosingTemplateParameters.Count; i++) { consArgs.Add(enclosingTemplateParameters[i]); args.Add(enclosingTemplateParameters[i]); } } this.closureClassInstance = (Class) this.closureClass.GetConsolidatedTemplateInstance(this.rewriter.AssemblyBeingRewritten, closureClass.DeclaringType, closureClass.DeclaringType, args, consArgs); } // create closure initializer for context method this.closureLocal = new Local(this.ClosureClass); this.ClosureInitializer = new Block(new StatementList()); // Generate constructor call that initializes closure instance this.ClosureInitializer.Statements.Add( new AssignmentStatement( this.closureLocal, new Construct(new MemberBinding(null, this.Ctor), new ExpressionList()))); } /// <summary> /// Add postconditions for the task-based methods. /// </summary> /// <remarks> /// Method inserts all required logic to the <paramref name="returnBlock"/> calling /// ContinueWith method on the <paramref name="taskBasedResult"/>. /// </remarks> public void AddAsyncPostconditions(List<Ensures> asyncPostconditions, Block returnBlock, Local taskBasedResult) { Contract.Requires(asyncPostconditions != null); Contract.Requires(returnBlock != null); Contract.Requires(taskBasedResult != null); Contract.Requires(asyncPostconditions.Count > 0); // Async postconditions are impelemented using custom closure class // with CheckPost method that checks postconditions when the task // is finished. // Add Async postconditions to the AsyncClosure AddAsyncPost(asyncPostconditions); // Add task.ContinueWith().Unwrap(); method call to returnBlock AddContinueWithMethodToReturnBlock(returnBlock, taskBasedResult); } /// <summary> /// Returns a list of source spans where non-capturing lambdas were used. /// </summary> public IList<SourceContext> ContractResultCapturedInStaticContext { get { return contractResultCapturedInStaticContext; } } /// <summary> /// Instance used in calling method context /// </summary> public Class ClosureClass { get { return this.closureClassInstance; } } /// <summary> /// Local instance of the async closure class /// </summary> public Local ClosureLocal { get { return this.closureLocal; } } /// <summary> /// Block of code, responsible for closure instance initialization /// </summary> public Block ClosureInitializer { get; private set; } private InstanceInitializer Ctor { get { return (InstanceInitializer)this.closureClassInstance.GetMembersNamed(StandardIds.Ctor)[0]; } } private static TypeNodeList GetGenericTypesFrom(Method method) { if (method.IsGeneric) { return method.TemplateParameters; } if (method.DeclaringType.IsGeneric) { return GetFirstNonEmptyGenericListWalkingUpDeclaringTypes(method.DeclaringType); } return null; } private static TypeNodeList GetFirstNonEmptyGenericListWalkingUpDeclaringTypes(TypeNode node) { if (node == null) { return null; } if (node.TemplateParameters != null && node.TemplateParameters.Count != 0) { return node.TemplateParameters; } return GetFirstNonEmptyGenericListWalkingUpDeclaringTypes(node.DeclaringType); } [Pure] private static TypeNodeList CreateTemplateParameters(Class closureClass, TypeNodeList inputTemplateParameters, TypeNode declaringType) { Contract.Requires(closureClass != null); Contract.Requires(inputTemplateParameters != null); Contract.Requires(declaringType != null); var dup = new Duplicator(declaringType.DeclaringModule, declaringType); var templateParameters = new TypeNodeList(); var parentCount = declaringType.ConsolidatedTemplateParameters.CountOrDefault(); for (int i = 0; i < inputTemplateParameters.Count; i++) { var tp = HelperMethods.NewEqualTypeParameter( dup, (ITypeParameter)inputTemplateParameters[i], closureClass, parentCount + i); templateParameters.Add(tp); } return templateParameters; } private void AddContinueWithMethodToReturnBlock(Block returnBlock, Local taskBasedResult) { Contract.Requires(returnBlock != null); Contract.Requires(taskBasedResult != null); var taskType = taskBasedResult.Type; // To find appropriate ContinueWith method task type should be unwrapped var taskTemplate = HelperMethods.Unspecialize(taskType); var continueWithMethodLocal = GetContinueWithMethod(closureClass, taskTemplate, taskType); // TODO: not sure that this is possible situation when continueWith method is null. // Maybe Contract.Assert(continueWithMethod != null) should be used instead! if (continueWithMethodLocal != null) { // We need to create delegate instance that should be passed to ContinueWith method var funcType = continueWithMethodLocal.Parameters[0].Type; var funcCtor = funcType.GetConstructor(SystemTypes.Object, SystemTypes.IntPtr); Contract.Assume(funcCtor != null); var funcLocal = new Local(funcCtor.DeclaringType); // Creating a method pointer to the AsyncClosure.CheckMethod // In this case we can't use checkMethod field. // Getting CheckMethod from clsoureClassInstance will provide correct (potentially updated) // generic arguments for enclosing type. var checkMethodFromClosureInstance = (Method) closureClassInstance.GetMembersNamed(CheckMethodId)[0]; Contract.Assume(checkMethodFromClosureInstance != null); var ldftn = new UnaryExpression( new MemberBinding(null, checkMethodFromClosureInstance), NodeType.Ldftn, CoreSystemTypes.IntPtr); // Creating delegate that would be used as a continuation for original task returnBlock.Statements.Add( new AssignmentStatement(funcLocal, new Construct(new MemberBinding(null, funcCtor), new ExpressionList(closureLocal, ldftn)))); // Wrapping continuation into TaskExtensions.Unwrap method // (this helps to preserve original exception and original result of the task, // but allows to throw postconditions violations). // Generating: result.ContinueWith(closure.CheckPost); var taskContinuationOption = new Literal(TaskContinuationOptions.ExecuteSynchronously); var continueWithCall = new MethodCall( new MemberBinding(taskBasedResult, continueWithMethodLocal), new ExpressionList(funcLocal, taskContinuationOption)); // Generating: TaskExtensions.Unwrap(result.ContinueWith(...)) var unwrapMethod = GetUnwrapMethod(checkMethodTaskType); var unwrapCall = new MethodCall( new MemberBinding(null, unwrapMethod), new ExpressionList(continueWithCall)); // Generating: result = Unwrap(...); var resultAssignment = new AssignmentStatement(taskBasedResult, unwrapCall); returnBlock.Statements.Add(resultAssignment); } } /// <summary> /// Method generates core part of the CheckMethod /// </summary> private void EmitCheckPostMethodCore(TypeNode taskType) { Contract.Requires(taskType != null); this.checkMethodTaskParameter = new Parameter(Identifier.For("task"), taskType); // TODO ST: can I switch to new Local(taskType.Type)?!? In this case this initialization // could be moved outside this method this.originalResultLocal = new Local(new Identifier("taskLocal"), checkMethodTaskParameter.Type); // Generate: public Task<T> CheckPost(Task<T> task) where T is taskType or // public Task CheckPost(Task task) for non-generic task. checkPostMethod = new Method( declaringType: this.closureClass, attributes: null, name: CheckMethodId, parameters: new ParameterList(checkMethodTaskParameter), // was: taskType.TemplateArguments[0] when hasResult was true and SystemTypes.Void otherwise returnType: taskType, body: null); checkPostMethod.CallingConvention = CallingConventionFlags.HasThis; checkPostMethod.Flags |= MethodFlags.Public; this.checkPostBody = new StatementList(); this.closureClass.Members.Add(this.checkPostMethod); if (taskType.IsGeneric) { // Assign taskParameter to originalResultLocal because // this field is used in a postcondition checkPostBody.Add(new AssignmentStatement(this.originalResultLocal, checkMethodTaskParameter)); } } [ContractVerification(false)] private void AddAsyncPost(List<Ensures> asyncPostconditions) { var origBody = new Block(this.checkPostBody); origBody.HasLocals = true; var newBodyBlock = new Block(new StatementList()); newBodyBlock.HasLocals = true; var methodBody = new StatementList(); var methodBodyBlock = new Block(methodBody); methodBodyBlock.HasLocals = true; checkPostMethod.Body = methodBodyBlock; methodBody.Add(newBodyBlock); Block newExitBlock = new Block(); methodBody.Add(newExitBlock); // Map closure locals to fields and initialize closure fields foreach (Ensures e in asyncPostconditions) { if (e == null) continue; this.Visit(e); if (this.forwarder != null) { this.forwarder.Visit(e); } ReplaceResult repResult = new ReplaceResult( this.checkPostMethod, this.originalResultLocal, this.rewriter.AssemblyBeingRewritten); repResult.Visit(e); if (repResult.ContractResultWasCapturedInStaticContext) { this.contractResultCapturedInStaticContext.Add(e.Assertion.SourceContext); } // now need to initialize closure result fields foreach (var target in repResult.NecessaryResultInitializationAsync(this.closureLocals)) { // note: target here methodBody.Add(new AssignmentStatement(target, this.originalResultLocal)); } } // Emit normal postconditions SourceContext? lastEnsuresSourceContext = null; var ensuresChecks = new StatementList(); Method contractEnsuresMethod = this.rewriter.RuntimeContracts.EnsuresMethod; // For generic types need to 'fix' generic type parameters that are used in the closure method. // See comment to the GenericTypeMapper for more details. TypeParameterFixerVisitor fixer = null; if (!this.genericTypeMapper.IsEmpty) { fixer = new TypeParameterFixerVisitor(genericTypeMapper); } foreach (Ensures e in GetTaskResultBasedEnsures(asyncPostconditions)) { // TODO: Not sure that 'break' is enough! It seems that this is possible // only when something is broken, because normal postconditions // are using Contract.Result<T>() and this is possible only for // generic tasks. if (IsVoidTask()) break; // something is wrong in the original contract lastEnsuresSourceContext = e.SourceContext; // // Call Contract.RewriterEnsures // ExpressionList args = new ExpressionList(); if (fixer != null) { fixer.Visit(e.PostCondition); } args.Add(e.PostCondition); args.Add(e.UserMessage ?? Literal.Null); args.Add(e.SourceConditionText ?? Literal.Null); ensuresChecks.Add( new ExpressionStatement( new MethodCall( new MemberBinding(null, contractEnsuresMethod), args, NodeType.Call, SystemTypes.Void), e.SourceContext)); } this.rewriter.CleanUpCodeCoverage.VisitStatementList(ensuresChecks); // // Normal postconditions // // Wrapping normal ensures into following if statement // if (task.Status == TaskStatus.RanToCompletion) // { postcondition check } // // Implementation of this stuff is a bit tricky because if-statements // are inverse in the IL. // Basically, we need to generate following code: // if (!(task.Status == Task.Status.RanToCompletion)) // goto EndOfNormalPostcondition; // {postcondition check} // EndOfNormalPostcondition: // {other Code} // Marker for EndOfNormalPostcondition Block endOfNormalPostcondition = new Block(); // Generate: if (task.Status != RanToCompletion) goto endOfNormalPostcondition; StatementList checkStatusStatements = CreateIfTaskResultIsEqualsTo( checkMethodTaskParameter, TaskStatus.RanToCompletion, endOfNormalPostcondition); methodBodyBlock.Statements.Add(new Block(checkStatusStatements)); // Emit a check for __ContractsRuntime.insideContractEvaluation around Ensures // TODO ST: there is no sense to add recursion check in async postcondition that can be checked in different thread! methodBodyBlock.Statements.Add(new Block(ensuresChecks)); // Emit a check for __ContractsRuntime.insideContractEvaluation around Ensures //this.rewriter.EmitRecursionGuardAroundChecks(this.checkPostMethod, methodBodyBlock, ensuresChecks); // Now, normal postconditions are written to the method body. // We need to add endOfNormalPostcondition block as a marker. methodBodyBlock.Statements.Add(endOfNormalPostcondition); // // Exceptional postconditions // var exceptionalPostconditions = GetExceptionalEnsures(asyncPostconditions).ToList(); if (exceptionalPostconditions.Count > 0) { // For exceptional postconditions we need to generate CheckException method first Method checkExceptionMethod = CreateCheckExceptionMethod(); EmitCheckExceptionBody(checkExceptionMethod, exceptionalPostconditions); this.closureClass.Members.Add(checkExceptionMethod); // Then, we're using the same trick as for normal postconditions: // wrapping exceptional postconditions only when task.Status is TaskStatus.Faulted Block checkExceptionBlock = new Block(new StatementList()); // Marker for endOfExceptionPostcondition Block endOfExceptionPostcondition = new Block(); StatementList checkStatusIsException = CreateIfTaskResultIsEqualsTo( checkMethodTaskParameter, TaskStatus.Faulted, endOfExceptionPostcondition); checkExceptionBlock.Statements.Add(new Block(checkStatusIsException)); // Now we need to emit actuall check for exceptional postconditions // Emit: var ae = task.Exception; var aeLocal = new Local(aggregateExceptionType.Value); checkExceptionBlock.Statements.Add( new AssignmentStatement(aeLocal, new MethodCall( new MemberBinding(checkMethodTaskParameter, GetTaskProperty(checkMethodTaskParameter, "get_Exception")), new ExpressionList()))); // Emit: CheckException(ae); // Need to store method result somewhere, otherwise stack would be corrupted var checkResultLocal = new Local(SystemTypes.Boolean); checkExceptionBlock.Statements.Add( new AssignmentStatement(checkResultLocal, new MethodCall(new MemberBinding(null, checkExceptionMethod), new ExpressionList(checkExceptionMethod.ThisParameter, aeLocal)))); checkExceptionBlock.Statements.Add(endOfExceptionPostcondition); methodBody.Add(checkExceptionBlock); } // Copy original block to body statement for both: normal and exceptional postconditions. newBodyBlock.Statements.Add(origBody); Block returnBlock = CreateReturnBlock(checkMethodTaskParameter, lastEnsuresSourceContext); methodBody.Add(returnBlock); } /// <summary> /// Helper visitor class that changes all references to type parameters to appropriate once. /// </summary> private class TypeParameterFixerVisitor : StandardVisitor { private readonly GenericTypeMapper genericParametersMapping; public TypeParameterFixerVisitor(GenericTypeMapper genericParametersMapping) { Contract.Requires(genericParametersMapping != null); this.genericParametersMapping = genericParametersMapping; } public override Expression VisitAddressDereference(AddressDereference addr) { // Replacing initobj !!0 to initobj !0 var newType = genericParametersMapping.GetClosureTypeParameterByEnclosingTypeParameter(addr.Type); if (newType != addr.Type) { return new AddressDereference(addr.Address, newType, addr.Volatile, addr.Alignment, addr.SourceContext); } return base.VisitAddressDereference(addr); } // Literal is used when contract result compares to null: Contract.Result<T>() != null public override Expression VisitLiteral(Literal literal) { var origin = literal.Value as TypeNode; if (origin == null) { return base.VisitLiteral(literal); } var newLiteralType = this.genericParametersMapping.GetClosureTypeParameterByEnclosingTypeParameter(origin); if (newLiteralType != origin) { return new Literal(newLiteralType); } return base.VisitLiteral(literal); } public override TypeNode VisitTypeParameter(TypeNode typeParameter) { var fixedVersion = this.genericParametersMapping.GetClosureTypeParameterByEnclosingTypeParameter(typeParameter); if (fixedVersion != typeParameter) { return fixedVersion; } return base.VisitTypeParameter(typeParameter); } public override TypeNode VisitTypeReference(TypeNode type) { var fixedVersion = this.genericParametersMapping.GetClosureTypeParameterByEnclosingTypeParameter(type); if (fixedVersion != type) { return fixedVersion; } return base.VisitTypeReference(type); } public override TypeNode VisitTypeNode(TypeNode typeNode) { var fixedVersion = this.genericParametersMapping.GetClosureTypeParameterByEnclosingTypeParameter(typeNode); if (fixedVersion != typeNode) { return fixedVersion; } return base.VisitTypeNode(typeNode); } } private static IEnumerable<Ensures> GetTaskResultBasedEnsures(List<Ensures> asyncPostconditions) { return asyncPostconditions.Where(post => !(post is EnsuresExceptional)); } private static IEnumerable<EnsuresExceptional> GetExceptionalEnsures(List<Ensures> asyncPostconditions) { return asyncPostconditions.OfType<EnsuresExceptional>(); } /// <summary> /// Returns TaskExtensions.Unwrap method. /// </summary> [Pure] private Member GetUnwrapMethod(TypeNode checkMethodTaskType) { Contract.Requires(checkMethodTaskType != null); Contract.Ensures(Contract.Result<Member>() != null); Contract.Assert(TaskExtensionsTypeNode != null, "Can't find System.Threading.Tasks.TaskExtensions type"); var unwrapCandidates = TaskExtensionsTypeNode.GetMembersNamed(Identifier.For("Unwrap")); Contract.Assert(unwrapCandidates != null, "Can't find Unwrap method in the TaskExtensions type"); // Should be only two methods. If that is not true, we need to change this code to reflect this! Contract.Assume(unwrapCandidates.Count == 2, "Should be exactly two candidate Unwrap methods."); // We need to find appropriate Unwrap method based on CheckMethod argument type. var firstMethod = (Method)unwrapCandidates[0]; var secondMethod = (Method)unwrapCandidates[1]; Contract.Assume(firstMethod != null && secondMethod != null); var genericUnwrapCandidate = firstMethod.IsGeneric ? firstMethod : secondMethod; var nonGenericUnwrapCandidate = firstMethod.IsGeneric ? secondMethod : firstMethod; if (checkMethodTaskType.IsGeneric) { // We need to "instantiate" generic first. // I.e. for Task<int> we need to have Unwrap(Task<Task<int>>): Task<int> // In this case we need to map back generic types. // CheckPost method is a non-generic method from (potentially) generic closure class. // In this case, if enclosing method is generic we need to map generic types back // and use !!0 (reference to method template arg) instead of using !0 (which is reference // to closure class template arg). var enclosingGeneritType = this.genericTypeMapper.GetEnclosingTypeParameterByClosureTypeParameter( checkMethodTaskType.TemplateArguments[0]); return genericUnwrapCandidate.GetTemplateInstance(null, enclosingGeneritType); } return nonGenericUnwrapCandidate; } /// <summary> /// Factory method that creates bool CheckException(Exception e) /// </summary> [Pure] private Method CreateCheckExceptionMethod() { Contract.Ensures(Contract.Result<Method>() != null); var exnParameter = new Parameter(Identifier.For("e"), SystemTypes.Exception); var checkExceptionMethod = new Method( declaringType: this.closureClass, attributes: null, name: CheckExceptionMethodId, parameters: new ParameterList(exnParameter), returnType: SystemTypes.Boolean, body: new Block(new StatementList())); checkExceptionMethod.Body.HasLocals = true; checkExceptionMethod.CallingConvention = CallingConventionFlags.HasThis; checkExceptionMethod.Flags |= MethodFlags.Public; if (checkExceptionMethod.ExceptionHandlers == null) checkExceptionMethod.ExceptionHandlers = new ExceptionHandlerList(); return checkExceptionMethod; } private void EmitCheckExceptionBody(Method checkExceptionMethod, List<EnsuresExceptional> exceptionalPostconditions) { Contract.Requires(checkExceptionMethod != null); Contract.Requires(exceptionalPostconditions != null); Contract.Requires(exceptionalPostconditions.Count > 0); // We emit the following method: // bool CheckException(Exception e) { // var ex = e as C1; // if (ex != null) { // EnsuresOnThrow(predicate) // } // else { // var ex2 = e as AggregateException; // if (ex2 != null) { // ex2.Handle(CheckException); // } // } // // // Method always returns true. This is by design! // // We need to check all exceptions in the AggregateException // // and fail in EnsuresOnThrow if the postcondition is not met. // return true; // handled var body = checkExceptionMethod.Body.Statements; var returnBlock = new Block(new StatementList()); foreach (var e in exceptionalPostconditions) { // The catchBlock contains the catchBody, and then // an empty block that is used in the EH. // TODO ST: name is confusing because there is no catch blocks in this method! Block catchBlock = new Block(new StatementList()); // local is: var ex1 = e as C1; Local localEx = new Local(e.Type); body.Add( new AssignmentStatement(localEx, new BinaryExpression(checkExceptionMethod.Parameters[0], new MemberBinding(null, e.Type), NodeType.Isinst))); Block skipBlock = new Block(); body.Add(new Branch(new UnaryExpression(localEx, NodeType.LogicalNot), skipBlock)); body.Add(catchBlock); body.Add(skipBlock); // call Contract.EnsuresOnThrow ExpressionList args = new ExpressionList(); args.Add(e.PostCondition); args.Add(e.UserMessage ?? Literal.Null); args.Add(e.SourceConditionText ?? Literal.Null); args.Add(localEx); var checks = new StatementList(); checks.Add( new ExpressionStatement( new MethodCall( new MemberBinding(null, this.rewriter.RuntimeContracts.EnsuresOnThrowMethod), args, NodeType.Call, SystemTypes.Void), e.SourceContext)); this.rewriter.CleanUpCodeCoverage.VisitStatementList(checks); // TODO ST: actually I can't see this recursion guard check in the resulting IL!! rewriter.EmitRecursionGuardAroundChecks(checkExceptionMethod, catchBlock, checks); catchBlock.Statements.Add(new Branch(null, returnBlock)); } // recurse on AggregateException itself { // var ae = e as AggregateException; // if (ae != null) { // ae.Handle(this.CheckException); // } Block catchBlock = new Block(new StatementList()); var aggregateType = aggregateExceptionType.Value; // var ex2 = e as AggregateException; Local localEx2 = new Local(aggregateType); body.Add( new AssignmentStatement(localEx2, new BinaryExpression( checkExceptionMethod.Parameters[0], new MemberBinding(null, aggregateType), NodeType.Isinst))); Block skipBlock = new Block(); body.Add(new Branch(new UnaryExpression(localEx2, NodeType.LogicalNot), skipBlock)); body.Add(catchBlock); body.Add(skipBlock); var funcType = func2Type.Value; funcType = funcType.GetTemplateInstance(this.rewriter.AssemblyBeingRewritten, SystemTypes.Exception, SystemTypes.Boolean); var handleMethod = aggregateType.GetMethod(Identifier.For("Handle"), funcType); var funcLocal = new Local(funcType); var ldftn = new UnaryExpression( new MemberBinding(null, checkExceptionMethod), NodeType.Ldftn, CoreSystemTypes.IntPtr); catchBlock.Statements.Add( new AssignmentStatement(funcLocal, new Construct( new MemberBinding(null, funcType.GetConstructor(SystemTypes.Object, SystemTypes.IntPtr)), new ExpressionList(checkExceptionMethod.ThisParameter, ldftn)))); catchBlock.Statements.Add( new ExpressionStatement(new MethodCall(new MemberBinding(localEx2, handleMethod), new ExpressionList(funcLocal)))); } // add return true to CheckException method body.Add(returnBlock); body.Add(new Return(Literal.True)); } /// <summary> /// Returns property for the task object. /// </summary> private static Method GetTaskProperty(Parameter taskParameter, string propertyName) { Contract.Requires(taskParameter != null); Contract.Ensures(Contract.Result<Method>() != null); // For generic task Status property defined in the base class. // That's why we need to check what the taskParameter type is - is it generic or not. // If the taskParameter is generic we need to use base type (because Task<T> : Task). var taskTypeWithStatusProperty = taskParameter.Type.IsGeneric ? taskParameter.Type.BaseType : taskParameter.Type; return taskTypeWithStatusProperty.GetMethod(Identifier.For(propertyName)); } /// <summary> /// Method returns a list of statements that checks task status. /// </summary> private static StatementList CreateIfTaskResultIsEqualsTo( Parameter taskParameterToCheck, TaskStatus expectedStatus, Block endBlock) { Contract.Ensures(Contract.Result<StatementList>() != null); var result = new StatementList(); // If-statement is slightly different in IL. // To get `if (condition) {statements}` // we need to generate: // if (!condition) goto endBLock; statements; endBlock: // This method emits a check that simplifies CheckMethod implementation. var statusProperty = GetTaskProperty(taskParameterToCheck, "get_Status"); Contract.Assert(statusProperty != null, "Can't find Task.Status property"); // Emitting: var tmpStatus = task.Status; var tmpStatus = new Local(statusProperty.ReturnType); result.Add( new AssignmentStatement(tmpStatus, new MethodCall(new MemberBinding(taskParameterToCheck, statusProperty), new ExpressionList()))); // if (tmpStatus != expectedStatus) // goto endOfMethod; // This is an inverted form of the check: if (tmpStatus == expectedStatus) {check} result.Add( new Branch( new BinaryExpression( tmpStatus, new Literal(expectedStatus), NodeType.Ne), endBlock)); return result; } private static Block CreateReturnBlock(Parameter checkPostTaskParameter, SourceContext? lastEnsuresSourceContext) { Statement returnStatement = new Return(checkPostTaskParameter); if (lastEnsuresSourceContext != null) { returnStatement.SourceContext = lastEnsuresSourceContext.Value; } Block returnBlock = new Block(new StatementList(1)); returnBlock.Statements.Add(returnStatement); return returnBlock; } /// <summary> /// Returns correct version of the ContinueWith method. /// </summary> /// <remarks> /// This function returns ContinueWith overload that takes TaskContinuationOptions. /// </remarks> private static Method GetContinueWithMethod(Class closureClass, TypeNode taskTemplate, TypeNode taskType) { var continueWithCandidates = taskTemplate.GetMembersNamed(Identifier.For("ContinueWith")); // Looking for an overload with TaskContinuationOptions const int expectedNumberOfArguments = 2; for (int i = 0; i < continueWithCandidates.Count; i++) { var cand = continueWithCandidates[i] as Method; if (cand == null) continue; // For non-generic version we're looking for ContinueWith(Action<Task>, TaskContinuationOptions) if (!taskType.IsGeneric) { if (cand.IsGeneric) continue; if (cand.ParameterCount != expectedNumberOfArguments) continue; if (cand.Parameters[0].Type.GetMetadataName() != "Action`1") continue; if (cand.Parameters[1].Type.GetMetadataName() != "TaskContinuationOptions") continue; return cand; } // For generic version we're looking for ContinueWith(Func<Task, T>, TaskContinuationOptions) if (!cand.IsGeneric) continue; if (cand.TemplateParameters.Count != 1) continue; if (cand.ParameterCount != expectedNumberOfArguments) continue; if (cand.Parameters[0].Type.GetMetadataName() != "Func`2") continue; if (cand.Parameters[1].Type.GetMetadataName() != "TaskContinuationOptions") continue; // now create instance, first of task var taskInstance = taskTemplate.GetTemplateInstance( closureClass.DeclaringModule, taskType.TemplateArguments[0]); // ST: some black magic is happening, but it seems it is required to get ContinueWith // from generic instantiated version of the task var candMethod = (Method)taskInstance.GetMembersNamed(Identifier.For("ContinueWith"))[i]; // Candidate method would have following signature: // Task<T> ContinueWith(Task<T> t) for generic version return candMethod.GetTemplateInstance(null, taskType); } return null; } private static InstanceInitializer CreateConstructor(Class closureClass) { var ctor = new InstanceInitializer(closureClass, null, null, null); ctor.CallingConvention = CallingConventionFlags.HasThis; ctor.Flags |= MethodFlags.Public | MethodFlags.HideBySig; // Regular block that calls base class constructor ctor.Body = new Block( new StatementList( new ExpressionStatement( new MethodCall(new MemberBinding(ctor.ThisParameter, SystemTypes.Object.GetConstructor()), new ExpressionList())), new Return())); return ctor; } private bool IsVoidTask() { return this.checkPostMethod.ReturnType == SystemTypes.Void; } // Visitor for changing closure locals to fields public override Expression VisitLocal(Local local) { if (HelperMethods.IsClosureType(this.declaringType, local.Type)) { MemberBinding mb; if (!closureLocals.TryGetValue(local, out mb)) { // TODO ST: not clear what's going on here! // Forwarder would be null, if enclosing method with async closure is not generic var localType = forwarder != null ? forwarder.VisitTypeReference(local.Type) : local.Type; var closureField = new Field(this.closureClass, null, FieldFlags.Public, local.Name, localType, null); this.closureClass.Members.Add(closureField); mb = new MemberBinding(this.checkPostMethod.ThisParameter, closureField); closureLocals.Add(local, mb); // initialize the closure field var instantiatedField = Rewriter.GetMemberInstanceReference(closureField, this.closureClassInstance); this.ClosureInitializer.Statements.Add( new AssignmentStatement( new MemberBinding(this.closureLocal, instantiatedField), local)); } return mb; } return local; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Dynamic.Utils; namespace System.Linq.Expressions.Compiler { // The part of the LambdaCompiler dealing with low level control flow // break, continue, return, exceptions, etc internal partial class LambdaCompiler { private LabelInfo EnsureLabel(LabelTarget node) { LabelInfo result; if (!_labelInfo.TryGetValue(node, out result)) { _labelInfo.Add(node, result = new LabelInfo(_ilg, node, false)); } return result; } private LabelInfo ReferenceLabel(LabelTarget node) { LabelInfo result = EnsureLabel(node); result.Reference(_labelBlock); return result; } private LabelInfo DefineLabel(LabelTarget node) { if (node == null) { return new LabelInfo(_ilg, null, false); } LabelInfo result = EnsureLabel(node); result.Define(_labelBlock); return result; } private void PushLabelBlock(LabelScopeKind type) { _labelBlock = new LabelScopeInfo(_labelBlock, type); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")] private void PopLabelBlock(LabelScopeKind kind) { Debug.Assert(_labelBlock != null && _labelBlock.Kind == kind); _labelBlock = _labelBlock.Parent; } private void EmitLabelExpression(Expression expr, CompilationFlags flags) { var node = (LabelExpression)expr; Debug.Assert(node.Target != null); // If we're an immediate child of a block, our label will already // be defined. If not, we need to define our own block so this // label isn't exposed except to its own child expression. LabelInfo label = null; if (_labelBlock.Kind == LabelScopeKind.Block) { _labelBlock.TryGetLabelInfo(node.Target, out label); // We're in a block but didn't find our label, try switch if (label == null && _labelBlock.Parent.Kind == LabelScopeKind.Switch) { _labelBlock.Parent.TryGetLabelInfo(node.Target, out label); } // if we're in a switch or block, we should've found the label Debug.Assert(label != null); } if (label == null) { label = DefineLabel(node.Target); } if (node.DefaultValue != null) { if (node.Target.Type == typeof(void)) { EmitExpressionAsVoid(node.DefaultValue, flags); } else { flags = UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitExpressionStart); EmitExpression(node.DefaultValue, flags); } } label.Mark(); } private void EmitGotoExpression(Expression expr, CompilationFlags flags) { var node = (GotoExpression)expr; var labelInfo = ReferenceLabel(node.Target); var tailCall = flags & CompilationFlags.EmitAsTailCallMask; if (tailCall != CompilationFlags.EmitAsNoTail) { // Since tail call flags are not passed into EmitTryExpression, CanReturn // means the goto will be emitted as Ret. Therefore we can emit the goto's // default value with tail call. This can be improved by detecting if the // target label is equivalent to the return label. tailCall = labelInfo.CanReturn ? CompilationFlags.EmitAsTail : CompilationFlags.EmitAsNoTail; flags = UpdateEmitAsTailCallFlag(flags, tailCall); } if (node.Value != null) { if (node.Target.Type == typeof(void)) { EmitExpressionAsVoid(node.Value, flags); } else { flags = UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitExpressionStart); EmitExpression(node.Value, flags); } } labelInfo.EmitJump(); EmitUnreachable(node, flags); } // We need to push default(T), unless we're emitting ourselves as // void. Even though the code is unreachable, we still have to // generate correct IL. We can get rid of this once we have better // reachability analysis. private void EmitUnreachable(Expression node, CompilationFlags flags) { if (node.Type != typeof(void) && (flags & CompilationFlags.EmitAsVoidType) == 0) { _ilg.EmitDefault(node.Type); } } private bool TryPushLabelBlock(Expression node) { // Anything that is "statement-like" -- e.g. has no associated // stack state can be jumped into, with the exception of try-blocks // We indicate this by a "Block" // // Otherwise, we push an "Expression" to indicate that it can't be // jumped into switch (node.NodeType) { default: if (_labelBlock.Kind != LabelScopeKind.Expression) { PushLabelBlock(LabelScopeKind.Expression); return true; } return false; case ExpressionType.Label: // LabelExpression is a bit special, if it's directly in a // block it becomes associate with the block's scope. Same // thing if it's in a switch case body. if (_labelBlock.Kind == LabelScopeKind.Block) { var label = ((LabelExpression)node).Target; if (_labelBlock.ContainsTarget(label)) { return false; } if (_labelBlock.Parent.Kind == LabelScopeKind.Switch && _labelBlock.Parent.ContainsTarget(label)) { return false; } } PushLabelBlock(LabelScopeKind.Statement); return true; case ExpressionType.Block: if (node is SpilledExpressionBlock) { // treat it as an expression goto default; } PushLabelBlock(LabelScopeKind.Block); // Labels defined immediately in the block are valid for // the whole block. if (_labelBlock.Parent.Kind != LabelScopeKind.Switch) { DefineBlockLabels(node); } return true; case ExpressionType.Switch: PushLabelBlock(LabelScopeKind.Switch); // Define labels inside of the switch cases so theyare in // scope for the whole switch. This allows "goto case" and // "goto default" to be considered as local jumps. var @switch = (SwitchExpression)node; foreach (SwitchCase c in @switch.Cases) { DefineBlockLabels(c.Body); } DefineBlockLabels(@switch.DefaultBody); return true; // Remove this when Convert(Void) goes away. case ExpressionType.Convert: if (node.Type != typeof(void)) { // treat it as an expression goto default; } PushLabelBlock(LabelScopeKind.Statement); return true; case ExpressionType.Conditional: case ExpressionType.Loop: case ExpressionType.Goto: PushLabelBlock(LabelScopeKind.Statement); return true; } } private void DefineBlockLabels(Expression node) { var block = node as BlockExpression; if (block == null || block is SpilledExpressionBlock) { return; } for (int i = 0, n = block.ExpressionCount; i < n; i++) { Expression e = block.GetExpression(i); var label = e as LabelExpression; if (label != null) { DefineLabel(label.Target); } } } // See if this lambda has a return label // If so, we'll create it now and mark it as allowing the "ret" opcode // This allows us to generate better IL private void AddReturnLabel(LambdaExpression lambda) { var expression = lambda.Body; while (true) { switch (expression.NodeType) { default: // Didn't find return label return; case ExpressionType.Label: // Found the label. We can directly return from this place // only if the label type is reference assignable to the lambda return type. var label = ((LabelExpression)expression).Target; _labelInfo.Add(label, new LabelInfo(_ilg, label, TypeUtils.AreReferenceAssignable(lambda.ReturnType, label.Type))); return; case ExpressionType.Block: // Look in the last significant expression of a block var body = (BlockExpression)expression; // omit empty and debuginfo at the end of the block since they // are not going to emit any IL if (body.ExpressionCount == 0) { return; } for (int i = body.ExpressionCount - 1; i >= 0; i--) { expression = body.GetExpression(i); if (Significant(expression)) { break; } } continue; } } } } }
using YAF.Lucene.Net.Index; using System; using System.Diagnostics; using BytesRef = YAF.Lucene.Net.Util.BytesRef; namespace YAF.Lucene.Net.Codecs.Lucene3x { /* * 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 FieldInfos = YAF.Lucene.Net.Index.FieldInfos; using IndexInput = YAF.Lucene.Net.Store.IndexInput; using Term = YAF.Lucene.Net.Index.Term; /// <summary> /// @lucene.experimental /// </summary> [Obsolete("(4.0)")] internal sealed class SegmentTermPositions : SegmentTermDocs { private IndexInput proxStream; private IndexInput proxStreamOrig; private int proxCount; private int position; private BytesRef payload; // the current payload length private int payloadLength; // indicates whether the payload of the current position has // been read from the proxStream yet private bool needToLoadPayload; // these variables are being used to remember information // for a lazy skip private long lazySkipPointer = -1; private int lazySkipProxCount = 0; /* SegmentTermPositions(SegmentReader p) { super(p); this.proxStream = null; // the proxStream will be cloned lazily when nextPosition() is called for the first time } */ public SegmentTermPositions(IndexInput freqStream, IndexInput proxStream, TermInfosReader tis, FieldInfos fieldInfos) : base(freqStream, tis, fieldInfos) { this.proxStreamOrig = proxStream; // the proxStream will be cloned lazily when nextPosition() is called for the first time } internal override void Seek(TermInfo ti, Term term) { base.Seek(ti, term); if (ti != null) { lazySkipPointer = ti.ProxPointer; } lazySkipProxCount = 0; proxCount = 0; payloadLength = 0; needToLoadPayload = false; } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { if (proxStream != null) { proxStream.Dispose(); } } } public int NextPosition() { if (m_indexOptions != IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) // this field does not store positions, payloads { return 0; } // perform lazy skips if necessary LazySkip(); proxCount--; return position += ReadDeltaPosition(); } private int ReadDeltaPosition() { int delta = proxStream.ReadVInt32(); if (m_currentFieldStoresPayloads) { // if the current field stores payloads then // the position delta is shifted one bit to the left. // if the LSB is set, then we have to read the current // payload length if ((delta & 1) != 0) { payloadLength = proxStream.ReadVInt32(); } delta = (int)((uint)delta >> 1); needToLoadPayload = true; } else if (delta == -1) { delta = 0; // LUCENE-1542 correction } return delta; } protected internal sealed override void SkippingDoc() { // we remember to skip a document lazily lazySkipProxCount += freq; } public sealed override bool Next() { // we remember to skip the remaining positions of the current // document lazily lazySkipProxCount += proxCount; if (base.Next()) // run super { proxCount = freq; // note frequency position = 0; // reset position return true; } return false; } public sealed override int Read(int[] docs, int[] freqs) { throw new System.NotSupportedException("TermPositions does not support processing multiple documents in one call. Use TermDocs instead."); } /// <summary> /// Called by <c>base.SkipTo()</c>. </summary> protected internal override void SkipProx(long proxPointer, int payloadLength) { // we save the pointer, we might have to skip there lazily lazySkipPointer = proxPointer; lazySkipProxCount = 0; proxCount = 0; this.payloadLength = payloadLength; needToLoadPayload = false; } private void SkipPositions(int n) { Debug.Assert(m_indexOptions == IndexOptions.DOCS_AND_FREQS_AND_POSITIONS); for (int f = n; f > 0; f--) // skip unread positions { ReadDeltaPosition(); SkipPayload(); } } private void SkipPayload() { if (needToLoadPayload && payloadLength > 0) { proxStream.Seek(proxStream.GetFilePointer() + payloadLength); } needToLoadPayload = false; } // It is not always necessary to move the prox pointer // to a new document after the freq pointer has been moved. // Consider for example a phrase query with two terms: // the freq pointer for term 1 has to move to document x // to answer the question if the term occurs in that document. But // only if term 2 also matches document x, the positions have to be // read to figure out if term 1 and term 2 appear next // to each other in document x and thus satisfy the query. // So we move the prox pointer lazily to the document // as soon as positions are requested. private void LazySkip() { if (proxStream == null) { // clone lazily proxStream = (IndexInput)proxStreamOrig.Clone(); } // we might have to skip the current payload // if it was not read yet SkipPayload(); if (lazySkipPointer != -1) { proxStream.Seek(lazySkipPointer); lazySkipPointer = -1; } if (lazySkipProxCount != 0) { SkipPositions(lazySkipProxCount); lazySkipProxCount = 0; } } public int PayloadLength { get { return payloadLength; } } public BytesRef GetPayload() { if (payloadLength <= 0) { return null; // no payload } if (needToLoadPayload) { // read payloads lazily if (payload == null) { payload = new BytesRef(payloadLength); } else { payload.Grow(payloadLength); } proxStream.ReadBytes(payload.Bytes, payload.Offset, payloadLength); payload.Length = payloadLength; needToLoadPayload = false; } return payload; } public bool IsPayloadAvailable { get { return needToLoadPayload && payloadLength > 0; } } } }
using System; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Collections.Generic; using SFML.Window; using Vector2f = SFML.Graphics.Vector2; namespace SFML { namespace Graphics { //////////////////////////////////////////////////////////// /// <summary> /// Wrapper for pixel shaders /// </summary> //////////////////////////////////////////////////////////// public class Shader : ObjectBase { //////////////////////////////////////////////////////////// /// <summary> /// Special type that can be passed to SetParameter, /// and that represents the texture of the object being drawn /// </summary> //////////////////////////////////////////////////////////// public class CurrentTextureType { } //////////////////////////////////////////////////////////// /// <summary> /// Special value that can be passed to SetParameter, /// and that represents the texture of the object being drawn /// </summary> //////////////////////////////////////////////////////////// public static readonly CurrentTextureType CurrentTexture = null; //////////////////////////////////////////////////////////// /// <summary> /// Load the vertex and fragment shaders from files /// /// This function can load both the vertex and the fragment /// shaders, or only one of them: pass NULL if you don't want to load /// either the vertex shader or the fragment shader. /// The sources must be text files containing valid shaders /// in GLSL language. GLSL is a C-like language dedicated to /// OpenGL shaders; you'll probably need to read a good documentation /// for it before writing your own shaders. /// </summary> /// <param name="vertexShaderFilename">Path of the vertex shader file to load, or null to skip this shader</param> /// <param name="fragmentShaderFilename">Path of the fragment shader file to load, or null to skip this shader</param> /// <exception cref="LoadingFailedException" /> //////////////////////////////////////////////////////////// public Shader(string vertexShaderFilename, string fragmentShaderFilename) : base(sfShader_createFromFile(vertexShaderFilename, fragmentShaderFilename)) { if (CPointer == IntPtr.Zero) throw new LoadingFailedException("shader", vertexShaderFilename + " " + fragmentShaderFilename); } //////////////////////////////////////////////////////////// /// <summary> /// Load both the vertex and fragment shaders from custom streams /// /// This function can load both the vertex and the fragment /// shaders, or only one of them: pass NULL if you don't want to load /// either the vertex shader or the fragment shader. /// The sources must be valid shaders in GLSL language. GLSL is /// a C-like language dedicated to OpenGL shaders; you'll /// probably need to read a good documentation for it before /// writing your own shaders. /// </summary> /// <param name="vertexShaderStream">Source stream to read the vertex shader from, or null to skip this shader</param> /// <param name="fragmentShaderStream">Source stream to read the fragment shader from, or null to skip this shader</param> /// <exception cref="LoadingFailedException" /> //////////////////////////////////////////////////////////// public Shader(Stream vertexShaderStream, Stream fragmentShaderStream) : base(IntPtr.Zero) { StreamAdaptor vertexAdaptor = new StreamAdaptor(vertexShaderStream); StreamAdaptor fragmentAdaptor = new StreamAdaptor(fragmentShaderStream); SetThis(sfShader_createFromStream(vertexAdaptor.InputStreamPtr, fragmentAdaptor.InputStreamPtr)); vertexAdaptor.Dispose(); fragmentAdaptor.Dispose(); if (CPointer == IntPtr.Zero) throw new LoadingFailedException("shader"); } //////////////////////////////////////////////////////////// /// <summary> /// Load both the vertex and fragment shaders from source codes in memory /// /// This function can load both the vertex and the fragment /// shaders, or only one of them: pass NULL if you don't want to load /// either the vertex shader or the fragment shader. /// The sources must be valid shaders in GLSL language. GLSL is /// a C-like language dedicated to OpenGL shaders; you'll /// probably need to read a good documentation for it before /// writing your own shaders. /// </summary> /// <param name="vertexShader">String containing the source code of the vertex shader</param> /// <param name="fragmentShader">String containing the source code of the fragment shader</param> /// <returns>New shader instance</returns> /// <exception cref="LoadingFailedException" /> //////////////////////////////////////////////////////////// public static Shader FromString(string vertexShader, string fragmentShader) { IntPtr ptr = sfShader_createFromMemory(vertexShader, fragmentShader); if (ptr == IntPtr.Zero) throw new LoadingFailedException("shader"); return new Shader(ptr); } //////////////////////////////////////////////////////////// /// <summary> /// Change a float parameter of the shader /// /// "name" is the name of the variable to change in the shader. /// The corresponding parameter in the shader must be a float /// (float GLSL type). /// </summary> /// /// <param name="name">Name of the parameter in the shader</param> /// <param name="x">Value to assign</param> /// //////////////////////////////////////////////////////////// public void SetParameter(string name, float x) { sfShader_setFloatParameter(CPointer, name, x); } //////////////////////////////////////////////////////////// /// <summary> /// Change a 2-components vector parameter of the shader /// /// "name" is the name of the variable to change in the shader. /// The corresponding parameter in the shader must be a 2x1 vector /// (vec2 GLSL type). /// </summary> /// <param name="name">Name of the parameter in the shader</param> /// <param name="x">First component of the value to assign</param> /// <param name="y">Second component of the value to assign</param> //////////////////////////////////////////////////////////// public void SetParameter(string name, float x, float y) { sfShader_setFloat2Parameter(CPointer, name, x, y); } //////////////////////////////////////////////////////////// /// <summary> /// Change a 3-components vector parameter of the shader /// /// "name" is the name of the variable to change in the shader. /// The corresponding parameter in the shader must be a 3x1 vector /// (vec3 GLSL type). /// </summary> /// <param name="name">Name of the parameter in the shader</param> /// <param name="x">First component of the value to assign</param> /// <param name="y">Second component of the value to assign</param> /// <param name="z">Third component of the value to assign</param> //////////////////////////////////////////////////////////// public void SetParameter(string name, float x, float y, float z) { sfShader_setFloat3Parameter(CPointer, name, x, y, z); } //////////////////////////////////////////////////////////// /// <summary> /// Change a 4-components vector parameter of the shader /// /// "name" is the name of the variable to change in the shader. /// The corresponding parameter in the shader must be a 4x1 vector /// (vec4 GLSL type). /// </summary> /// <param name="name">Name of the parameter in the shader</param> /// <param name="x">First component of the value to assign</param> /// <param name="y">Second component of the value to assign</param> /// <param name="z">Third component of the value to assign</param> /// <param name="w">Fourth component of the value to assign</param> //////////////////////////////////////////////////////////// public void SetParameter(string name, float x, float y, float z, float w) { sfShader_setFloat4Parameter(CPointer, name, x, y, z, w); } //////////////////////////////////////////////////////////// /// <summary> /// Change a 2-components vector parameter of the shader /// /// "name" is the name of the variable to change in the shader. /// The corresponding parameter in the shader must be a 2x1 vector /// (vec2 GLSL type). /// </summary> /// <param name="name">Name of the parameter in the shader</param> /// <param name="vector">Vector to assign</param> //////////////////////////////////////////////////////////// public void SetParameter(string name, Vector2f vector) { SetParameter(name, vector.X, vector.Y); } //////////////////////////////////////////////////////////// /// <summary> /// Change a color parameter of the shader /// /// "name" is the name of the variable to change in the shader. /// The corresponding parameter in the shader must be a 4x1 vector /// (vec4 GLSL type). /// </summary> /// <param name="name">Name of the parameter in the shader</param> /// <param name="color">Color to assign</param> //////////////////////////////////////////////////////////// public void SetParameter(string name, Color color) { sfShader_setColorParameter(CPointer, name, color); } //////////////////////////////////////////////////////////// /// <summary> /// Change a matrix parameter of the shader /// /// "name" is the name of the variable to change in the shader. /// The corresponding parameter in the shader must be a 4x4 matrix /// (mat4 GLSL type). /// </summary> /// <param name="name">Name of the parameter in the shader</param> /// <param name="transform">Transform to assign</param> //////////////////////////////////////////////////////////// public void SetParameter(string name, Transform transform) { sfShader_setTransformParameter(CPointer, name, transform); } //////////////////////////////////////////////////////////// /// <summary> /// Change a texture parameter of the shader /// /// "name" is the name of the variable to change in the shader. /// The corresponding parameter in the shader must be a 2D texture /// (sampler2D GLSL type). /// /// It is important to note that \a texture must remain alive as long /// as the shader uses it, no copy is made internally. /// /// To use the texture of the object being draw, which cannot be /// known in advance, you can pass the special value /// Shader.CurrentTexture. /// </summary> /// <param name="name">Name of the texture in the shader</param> /// <param name="texture">Texture to assign</param> //////////////////////////////////////////////////////////// public void SetParameter(string name, Texture texture) { myTextures[name] = texture; sfShader_setTextureParameter(CPointer, name, texture.CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Change a texture parameter of the shader /// /// This overload maps a shader texture variable to the /// texture of the object being drawn, which cannot be /// known in advance. The second argument must be /// sf::Shader::CurrentTexture. /// The corresponding parameter in the shader must be a 2D texture /// (sampler2D GLSL type). /// </summary> /// <param name="name">Name of the texture in the shader</param> /// <param name="current">Always pass the spacial value Shader.CurrentTexture</param> //////////////////////////////////////////////////////////// public void SetParameter(string name, CurrentTextureType current) { sfShader_setCurrentTextureParameter(CPointer, name); } //////////////////////////////////////////////////////////// /// <summary> /// Bind the shader for rendering (activate it) /// /// This function is normally for internal use only, unless /// you want to use the shader with a custom OpenGL rendering /// instead of a SFML drawable. /// </summary> //////////////////////////////////////////////////////////// public void Bind() { sfShader_bind(CPointer); } //////////////////////////////////////////////////////////// /// <summary> /// Tell whether or not the system supports shaders. /// /// This property should always be checked before using /// the shader features. If it returns false, then /// any attempt to use Shader will fail. /// </summary> //////////////////////////////////////////////////////////// public static bool IsAvailable { get { return sfShader_isAvailable(); } } //////////////////////////////////////////////////////////// /// <summary> /// Provide a string describing the object /// </summary> /// <returns>String description of the object</returns> //////////////////////////////////////////////////////////// public override string ToString() { return "[Shader]"; } //////////////////////////////////////////////////////////// /// <summary> /// Handle the destruction of the object /// </summary> /// <param name="disposing">Is the GC disposing the object, or is it an explicit call ?</param> //////////////////////////////////////////////////////////// protected override void Destroy(bool disposing) { if (!disposing) Context.Global.SetActive(true); myTextures.Clear(); sfShader_destroy(CPointer); if (!disposing) Context.Global.SetActive(false); } //////////////////////////////////////////////////////////// /// <summary> /// Construct the shader from a pointer /// </summary> /// <param name="ptr">Pointer to the shader instance</param> //////////////////////////////////////////////////////////// public Shader(IntPtr ptr) : base(ptr) { } Dictionary<string, Texture> myTextures = new Dictionary<string, Texture>(); #region Imports [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfShader_createFromFile(string vertexShaderFilename, string fragmentShaderFilename); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfShader_createFromMemory(string vertexShader, string fragmentShader); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern IntPtr sfShader_createFromStream(IntPtr vertexShaderStream, IntPtr fragmentShaderStream); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_destroy(IntPtr shader); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_setFloatParameter(IntPtr shader, string name, float x); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_setFloat2Parameter(IntPtr shader, string name, float x, float y); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_setFloat3Parameter(IntPtr shader, string name, float x, float y, float z); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_setFloat4Parameter(IntPtr shader, string name, float x, float y, float z, float w); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_setColorParameter(IntPtr shader, string name, Color color); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_setTransformParameter(IntPtr shader, string name, Transform transform); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_setTextureParameter(IntPtr shader, string name, IntPtr texture); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_setCurrentTextureParameter(IntPtr shader, string name); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern void sfShader_bind(IntPtr shader); [DllImport("csfml-graphics-2", CallingConvention = CallingConvention.Cdecl), SuppressUnmanagedCodeSecurity] static extern bool sfShader_isAvailable(); #endregion } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using LicenseSpot.Framework; namespace SubscriptionExample { public partial class MainForm : Form { private Calculator calculator; private ExtendedLicense license; public MainForm() { InitializeComponent(); this.license = ExtendedLicenseManager.GetLicense(typeof(MainForm), this, "your public key"); this.calculator = new Calculator(); this.calculator.CalculatorValueChanged += new Calculator.CalculatorValueChangedEventHandler(calculator_CalculatorValueChanged); } #region Calculator void calculator_CalculatorValueChanged(object sender, CalculatorChangedEventArgs e) { if (e.HasError) ValueLabel.Text = "err"; else if (e.OperationType == OperationType.Calculation) { UpdateValueLabel(e.Result, false); ValueLabel.Tag = null; } else if (e.OperationType == OperationType.Accumulation) { ValueLabel.Tag = null; } } private void AppendValue(string valueText) { string textValue = ValueLabel.Tag as string; if (textValue == null) { textValue = "0"; } bool hasPoint = false; if (valueText == ".") { if (textValue.IndexOf(".") < 0) { textValue += "."; hasPoint = true; } } else { textValue += valueText; } decimal value; if (decimal.TryParse(textValue, out value)) { UpdateValueLabel(value, hasPoint); } } private void UpdateValueLabel(decimal value, bool hasPoint) { if (value > 999999999m) { ValueLabel.Text = value.ToString("e"); ValueLabel.Tag = value.ToString(); } else if (hasPoint) { ValueLabel.Text += "."; ValueLabel.Tag += "."; } else { ValueLabel.Text = value.ToString(); ValueLabel.Tag = value.ToString(); } } private decimal? GetCurrentValue() { decimal value; if (decimal.TryParse(ValueLabel.Tag as string ?? ValueLabel.Text, out value)) { return value; } return null; } private void EqualButton_Click(object sender, EventArgs e) { calculator.Calculate(this.GetCurrentValue()); ValueLabel.Tag = null; } private void NumberButton_Click(object sender, EventArgs e) { this.AppendValue(((Button)sender).Text); } private void PlusButton_Click(object sender, EventArgs e) { calculator.ApplyOperation(this.GetCurrentValue(), new Sum()); } private void MinusButton_Click(object sender, EventArgs e) { calculator.ApplyOperation(this.GetCurrentValue(), new Subtract()); } private void MultiplyButton_Click(object sender, EventArgs e) { calculator.ApplyOperation(this.GetCurrentValue(), new Multiply()); } private void DivisionButton_Click(object sender, EventArgs e) { calculator.ApplyOperation(this.GetCurrentValue(), new Divide()); } private void Clear() { ValueLabel.Text = "0"; ValueLabel.Tag = null; calculator.Clear(); } private void ClearButton_Click(object sender, EventArgs e) { Clear(); } private void AllClearButton_Click(object sender, EventArgs e) { Clear(); MemoryLabel.Visible = false; calculator.AllClear(); } private void MemorySubstractButton_Click(object sender, EventArgs e) { calculator.ApplyOperation(this.GetCurrentValue(), new MemorySubtract()); MemoryLabel.Visible = true; } private void MemoryAddButton_Click(object sender, EventArgs e) { calculator.ApplyOperation(this.GetCurrentValue(), new MemoryAdd()); MemoryLabel.Visible = true; } private void MemoryRecallButton_Click(object sender, EventArgs e) { Clear(); UpdateValueLabel(calculator.Memory ?? 0,false); } private void InvertSignButton_Click(object sender, EventArgs e) { calculator.ApplyOperation(this.GetCurrentValue(), new InvertSign()); } private void copyToolStripMenuItem_Click(object sender, EventArgs e) { Clipboard.SetDataObject(ValueLabel.Text, true); } private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { IDataObject data = Clipboard.GetDataObject(); if (data.GetDataPresent(DataFormats.Text)) { string value = (string)data.GetData(DataFormats.Text); decimal res = 0; if (decimal.TryParse(value, out res)) { this.AppendValue(value); } } } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { AboutForm dialog = new AboutForm(); dialog.ShowDialog(); } #endregion private void registerToolStripMenuItem_Click(object sender, EventArgs e) { ActivationForm dialog = new ActivationForm(); dialog.ShowDialog(); if (dialog.DialogResult == DialogResult.OK) { try { Cursor.Current = Cursors.WaitCursor; license.Activate(dialog.SerialNumber); license = ExtendedLicenseManager.GetLicense(typeof(MainForm), this, "your public key"); MessageBox.Show("The application has been activated."); toolStripStatusLabel.Text = string.Empty; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { Cursor.Current = Cursors.Default; } } } private void MainForm_Load(object sender, EventArgs e) { if (license.Validate()) { //MessageBox.Show("License is valid"); } else { DialogResult activateResult = MessageBox.Show(this, "The calculator was unable to find a valid license", "Calculator", MessageBoxButtons.OK); toolStripStatusLabel.Text = "License is invalid"; } licenseGenuineTimer.Start(); } private void licenseGenuineTimer_Tick(object sender, EventArgs e) { //Timer is checking if the license subscription is active every 5 seconds just for demo purposes. You could check for this when the main form loads. try { if (license.IsSubscriptionActive) { toolStripStatusLabel.Text = "Subscription is active. It was validated against the server."; } else { toolStripStatusLabel.Text = "Subscription validation failed."; } } catch (Exception ex) { toolStripStatusLabel.Text = ex.Message; } } } }
//------------------------------------------------------------------------------ // <copyright file="_ProxyChain.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net { using System.Collections; using System.Collections.Generic; internal interface IAutoWebProxy : IWebProxy { ProxyChain GetProxies(Uri destination); } internal abstract class ProxyChain : IEnumerable<Uri>, IDisposable { private List<Uri> m_Cache = new List<Uri>(); private bool m_CacheComplete; private ProxyEnumerator m_MainEnumerator; private Uri m_Destination; private HttpAbortDelegate m_HttpAbortDelegate; protected ProxyChain(Uri destination) { m_Destination = destination; } public IEnumerator<Uri> GetEnumerator() { ProxyEnumerator enumerator = new ProxyEnumerator(this); if (m_MainEnumerator == null) { m_MainEnumerator = enumerator; } return enumerator; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public virtual void Dispose() { } internal IEnumerator<Uri> Enumerator { get { return m_MainEnumerator == null ? GetEnumerator() : m_MainEnumerator; } } internal Uri Destination { get { return m_Destination; } } // MoveNext can be time-consuming (download proxy script). This lets you abort it. internal virtual void Abort() { } internal bool HttpAbort(HttpWebRequest request, WebException webException) { Abort(); return true; } internal HttpAbortDelegate HttpAbortDelegate { get { if (m_HttpAbortDelegate == null) { m_HttpAbortDelegate = new HttpAbortDelegate(HttpAbort); } return m_HttpAbortDelegate; } } protected abstract bool GetNextProxy(out Uri proxy); // This implementation prevents DIRECT (null) from being returned more than once. private class ProxyEnumerator : IEnumerator<Uri> { private ProxyChain m_Chain; private bool m_Finished; private int m_CurrentIndex = -1; private bool m_TriedDirect; internal ProxyEnumerator(ProxyChain chain) { m_Chain = chain; } public Uri Current { get { if (m_Finished || m_CurrentIndex < 0) { throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumOpCantHappen)); } GlobalLog.Assert(m_Chain.m_Cache.Count > m_CurrentIndex, "ProxyEnumerator::Current|Not all proxies made it to the cache."); return m_Chain.m_Cache[m_CurrentIndex]; } } object IEnumerator.Current { get { return Current; } } public bool MoveNext() { if (m_Finished) { return false; } checked{m_CurrentIndex++;} if (m_Chain.m_Cache.Count > m_CurrentIndex) { return true; } if (m_Chain.m_CacheComplete) { m_Finished = true; return false; } lock (m_Chain.m_Cache) { if (m_Chain.m_Cache.Count > m_CurrentIndex) { return true; } if (m_Chain.m_CacheComplete) { m_Finished = true; return false; } Uri nextProxy; while (true) { if (!m_Chain.GetNextProxy(out nextProxy)) { m_Finished = true; m_Chain.m_CacheComplete = true; return false; } if (nextProxy == null) { if (m_TriedDirect) { continue; } m_TriedDirect = true; } break; } m_Chain.m_Cache.Add(nextProxy); GlobalLog.Assert(m_Chain.m_Cache.Count > m_CurrentIndex, "ProxyEnumerator::MoveNext|Not all proxies made it to the cache."); return true; } } public void Reset() { m_Finished = false; m_CurrentIndex = -1; } public void Dispose() { } } } // This class implements failover logic for proxy scripts. internal class ProxyScriptChain : ProxyChain { private WebProxy m_Proxy; private Uri[] m_ScriptProxies; private int m_CurrentIndex; private int m_SyncStatus; internal ProxyScriptChain(WebProxy proxy, Uri destination) : base(destination) { m_Proxy = proxy; } protected override bool GetNextProxy(out Uri proxy) { if (m_CurrentIndex < 0) { proxy = null; return false; } if (m_CurrentIndex == 0) { m_ScriptProxies = m_Proxy.GetProxiesAuto(Destination, ref m_SyncStatus); } if (m_ScriptProxies == null || m_CurrentIndex >= m_ScriptProxies.Length) { proxy = m_Proxy.GetProxyAutoFailover(Destination); m_CurrentIndex = -1; return true; } proxy = m_ScriptProxies[m_CurrentIndex++]; return true; } internal override void Abort() { m_Proxy.AbortGetProxiesAuto(ref m_SyncStatus); } } // This class says to use no proxy. internal class DirectProxy : ProxyChain { private bool m_ProxyRetrieved; internal DirectProxy(Uri destination) : base(destination) { } protected override bool GetNextProxy(out Uri proxy) { proxy = null; if (m_ProxyRetrieved) { return false; } m_ProxyRetrieved = true; return true; } } // This class says to use a single fixed proxy. internal class StaticProxy : ProxyChain { private Uri m_Proxy; internal StaticProxy(Uri destination, Uri proxy) : base(destination) { if (proxy == null) { throw new ArgumentNullException("proxy"); } m_Proxy = proxy; } protected override bool GetNextProxy(out Uri proxy) { proxy = m_Proxy; if (proxy == null) { return false; } m_Proxy = null; return true; } } }
/* New BSD License ------------------------------------------------------------------------------- Copyright (c) 2006-2012, EntitySpaces, LLC All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the EntitySpaces, LLC 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 EntitySpaces, LLC 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.Data; using Tiraggo.DynamicQuery; using Tiraggo.Interfaces; using Npgsql; using NpgsqlTypes; namespace Tiraggo.Npgsql2Provider { class Shared { static public NpgsqlCommand BuildDynamicInsertCommand(tgDataRequest request, tgEntitySavePacket packet) { string sql = String.Empty; string defaults = String.Empty; string into = String.Empty; string values = String.Empty; string comma = String.Empty; string defaultComma = String.Empty; string where = String.Empty; string autoInc = String.Empty; NpgsqlParameter p = null; Dictionary<string, NpgsqlParameter> types = Cache.GetParameters(request); NpgsqlCommand cmd = new NpgsqlCommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; tgColumnMetadataCollection cols = request.Columns; foreach (tgColumnMetadata col in cols) { bool isModified = packet.ModifiedColumns == null ? false : packet.ModifiedColumns.Contains(col.Name); if (isModified && (!col.IsAutoIncrement && !col.IsConcurrency && !col.IsTiraggoConcurrency)) { p = cmd.Parameters.Add(CloneParameter(types[col.Name])); object value = packet.CurrentValues[col.Name]; p.Value = value != null ? value : DBNull.Value; into += comma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose; values += comma + p.ParameterName; comma = ", "; } else if (col.IsAutoIncrement && request.ProviderMetadata.ContainsKey("AutoKeyText")) { string sequence = request.ProviderMetadata["AutoKeyText"].Replace("nextval", "currval"); if (sequence != null && sequence.Length > 0) { // Our identity column ... p = cmd.Parameters.Add(CloneParameter(types[col.Name])); p.Direction = ParameterDirection.Output; autoInc += " SELECT * FROM " + sequence + " as \"" + col.Name + "\""; } p = CloneParameter(types[col.Name]); p.Direction = ParameterDirection.Output; cmd.Parameters.Add(p); } else if (col.IsConcurrency) { // These columns have defaults and they weren't supplied with values, so let's // return them p = cmd.Parameters.Add(CloneParameter(types[col.Name])); p.Direction = ParameterDirection.InputOutput; defaults += defaultComma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose; defaultComma = ", "; if (col.CharacterMaxLength > 0) { p.Size = (int)col.CharacterMaxLength; } } else if (col.IsTiraggoConcurrency) { p = cmd.Parameters.Add(CloneParameter(types[col.Name])); p.Direction = ParameterDirection.Output; into += comma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose; values += comma + "1"; comma = ", "; p.Value = 1; // Seems to work, We'll take it ... } else if (col.IsComputed) { // Do nothing but leave this here } else if (cols.IsSpecialColumn(col)) { // Do nothing but leave this here } else if (col.HasDefault) { // These columns have defaults and they weren't supplied with values, so let's // return them p = cmd.Parameters.Add(CloneParameter(types[col.Name])); p.Direction = ParameterDirection.InputOutput; defaults += defaultComma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose; defaultComma = ","; if (col.CharacterMaxLength > 0) { p.Size = (int)col.CharacterMaxLength; } } if (col.IsInPrimaryKey) { p = types[col.Name]; if (where.Length > 0) where += " AND "; where += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName; if (!cmd.Parameters.Contains(p.ParameterName)) { p = CloneParameter(p); p.Direction = ParameterDirection.Output; cmd.Parameters.Add(p); } } } #region Special Column Logic if (cols.DateAdded != null && cols.DateAdded.IsServerSide && cols.FindByColumnName(cols.DateAdded.ColumnName) != null) { p = CloneParameter(types[cols.DateAdded.ColumnName]); p.Direction = ParameterDirection.Output; cmd.Parameters.Add(p); into += comma + Delimiters.ColumnOpen + cols.DateAdded.ColumnName + Delimiters.ColumnClose; values += comma + request.ProviderMetadata["DateAdded.ServerSideText"]; comma = ", "; defaults += defaultComma + cols.DateAdded.ColumnName; defaultComma = ","; } if (cols.DateModified != null && cols.DateModified.IsServerSide && cols.FindByColumnName(cols.DateModified.ColumnName) != null) { p = CloneParameter(types[cols.DateModified.ColumnName]); p.Direction = ParameterDirection.Output; cmd.Parameters.Add(p); into += comma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose; values += comma + request.ProviderMetadata["DateModified.ServerSideText"]; comma = ", "; defaults += defaultComma + cols.DateModified.ColumnName; defaultComma = ","; } if (cols.AddedBy != null && cols.AddedBy.IsServerSide && cols.FindByColumnName(cols.AddedBy.ColumnName) != null) { p = CloneParameter(types[cols.AddedBy.ColumnName]); p.Direction = ParameterDirection.Output; cmd.Parameters.Add(p); into += comma + Delimiters.ColumnOpen + cols.AddedBy.ColumnName + Delimiters.ColumnClose; values += comma + request.ProviderMetadata["AddedBy.ServerSideText"]; comma = ", "; defaults += defaultComma + cols.AddedBy.ColumnName; defaultComma = ","; tgColumnMetadata col = request.Columns[cols.ModifiedBy.ColumnName]; if (col.CharacterMaxLength > 0) { p.Size = (int)col.CharacterMaxLength; } } if (cols.ModifiedBy != null && cols.ModifiedBy.IsServerSide && cols.FindByColumnName(cols.ModifiedBy.ColumnName) != null) { p = CloneParameter(types[cols.ModifiedBy.ColumnName]); p.Direction = ParameterDirection.Output; cmd.Parameters.Add(p); into += comma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose; values += comma + request.ProviderMetadata["ModifiedBy.ServerSideText"]; comma = ", "; defaults += defaultComma + cols.ModifiedBy.ColumnName; defaultComma = ","; tgColumnMetadata col = request.Columns[cols.ModifiedBy.ColumnName]; if (col.CharacterMaxLength > 0) { p.Size = (int)col.CharacterMaxLength; } } #endregion string fullName = CreateFullName(request); sql += " INSERT INTO " + fullName; if (into.Length != 0) { sql += " (" + into + ") VALUES (" + values + ");"; } else { sql += " DEFAULT VALUES;"; } sql += autoInc; if (defaults.Length > 0) { sql += " SELECT " + defaults + " FROM " + fullName + " WHERE (" + where + ")"; } cmd.CommandText = sql + String.Empty; cmd.CommandType = CommandType.Text; return cmd; } static public NpgsqlCommand BuildDynamicUpdateCommand(tgDataRequest request, tgEntitySavePacket packet) { string where = String.Empty; string conncur = String.Empty; string scomma = String.Empty; string defaults = String.Empty; string defaultsComma = String.Empty; string and = String.Empty; string sql = "UPDATE " + CreateFullName(request) + " SET "; PropertyCollection props = new PropertyCollection(); NpgsqlParameter p = null; Dictionary<string, NpgsqlParameter> types = Cache.GetParameters(request); NpgsqlCommand cmd = new NpgsqlCommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; tgColumnMetadataCollection cols = request.Columns; foreach (tgColumnMetadata col in cols) { bool isModified = packet.ModifiedColumns == null ? false : packet.ModifiedColumns.Contains(col.Name); if (isModified && (!col.IsAutoIncrement && !col.IsConcurrency && !col.IsTiraggoConcurrency)) { p = cmd.Parameters.Add(CloneParameter(types[col.Name])); object value = packet.CurrentValues[col.Name]; p.Value = value != null ? value : DBNull.Value; sql += scomma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName; scomma = ", "; } else if (col.IsAutoIncrement) { // Nothing to do but leave this here } else if (col.IsConcurrency) { p = CloneParameter(types[col.Name]); p.SourceVersion = DataRowVersion.Original; p.Direction = ParameterDirection.InputOutput; cmd.Parameters.Add(p); conncur += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName; } else if (col.IsTiraggoConcurrency) { p = CloneParameter(types[col.Name]); p.Value = packet.OriginalValues[col.Name]; p.Direction = ParameterDirection.InputOutput; cmd.Parameters.Add(p); sql += scomma; sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName + " + 1"; conncur += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName; defaults += defaultsComma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose; defaultsComma = ","; } else if (col.IsComputed) { // Do nothing but leave this here } else if (cols.IsSpecialColumn(col)) { // Do nothing but leave this here } else if (col.HasDefault) { // defaults += defaultsComma + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose; // defaultsComma = ","; } if (col.IsInPrimaryKey) { p = CloneParameter(types[col.Name]); p.Value = packet.OriginalValues[col.Name]; cmd.Parameters.Add(p); where += and + Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName; and = " AND "; } } #region Special Column Logic if (cols.DateModified != null && cols.DateModified.IsServerSide && cols.FindByColumnName(cols.DateModified.ColumnName) != null) { p = CloneParameter(types[cols.DateModified.ColumnName]); p.Direction = ParameterDirection.Output; cmd.Parameters.Add(p); sql += scomma + Delimiters.ColumnOpen + cols.DateModified.ColumnName + Delimiters.ColumnClose + " = " + request.ProviderMetadata["DateModified.ServerSideText"]; scomma = ", "; defaults += defaultsComma + cols.DateModified.ColumnName; defaultsComma = ","; } if (cols.ModifiedBy != null && cols.ModifiedBy.IsServerSide && cols.FindByColumnName(cols.ModifiedBy.ColumnName) != null) { p = CloneParameter(types[cols.ModifiedBy.ColumnName]); p.Direction = ParameterDirection.Output; cmd.Parameters.Add(p); sql += scomma + Delimiters.ColumnOpen + cols.ModifiedBy.ColumnName + Delimiters.ColumnClose + " = " + request.ProviderMetadata["ModifiedBy.ServerSideText"]; scomma = ", "; defaults += defaultsComma + cols.ModifiedBy.ColumnName; defaultsComma = ","; tgColumnMetadata col = request.Columns[cols.ModifiedBy.ColumnName]; if (col.CharacterMaxLength > 0) { p.Size = (int)col.CharacterMaxLength; } } #endregion sql += " WHERE " + where + ""; if (conncur.Length > 0) { sql += " AND " + conncur; } if (defaults.Length > 0) { sql += "; SELECT " + defaults + " FROM " + CreateFullName(request) + " WHERE (" + where + ")"; } cmd.CommandText = sql; cmd.CommandType = CommandType.Text; return cmd; } static public NpgsqlCommand BuildDynamicDeleteCommand(tgDataRequest request, tgEntitySavePacket packet) { Dictionary<string, NpgsqlParameter> types = Cache.GetParameters(request); NpgsqlCommand cmd = new NpgsqlCommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; string sql = "DELETE FROM " + CreateFullName(request) + " "; string comma = String.Empty; comma = String.Empty; sql += " WHERE "; foreach (tgColumnMetadata col in request.Columns) { if (col.IsInPrimaryKey || col.IsTiraggoConcurrency) { NpgsqlParameter p = types[col.Name]; p = cmd.Parameters.Add(CloneParameter(p)); p.Value = packet.OriginalValues[col.Name]; sql += comma; sql += Delimiters.ColumnOpen + col.Name + Delimiters.ColumnClose + " = " + p.ParameterName; comma = " AND "; } } cmd.CommandText = sql; cmd.CommandType = CommandType.Text; return cmd; } static public NpgsqlCommand BuildStoredProcInsertCommand(tgDataRequest request, tgEntitySavePacket packet) { Dictionary<string, NpgsqlParameter> types = Cache.GetParameters(request); NpgsqlCommand cmd = new NpgsqlCommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Delimiters.StoredProcNameOpen + request.ProviderMetadata.spInsert + Delimiters.StoredProcNameClose; PopulateStoredProcParameters(cmd, request, packet); foreach (tgColumnMetadata col in request.Columns) { if (col.HasDefault && col.Default.ToLower().Contains("newid")) { NpgsqlParameter p = types[col.Name]; p = cmd.Parameters[p.ParameterName]; p.Direction = ParameterDirection.InputOutput; } else if (col.IsComputed || col.IsAutoIncrement) { NpgsqlParameter p = types[col.Name]; p = cmd.Parameters[p.ParameterName]; p.Direction = ParameterDirection.Output; } } return cmd; } static public NpgsqlCommand BuildStoredProcUpdateCommand(tgDataRequest request, tgEntitySavePacket packet) { Dictionary<string, NpgsqlParameter> types = Cache.GetParameters(request); NpgsqlCommand cmd = new NpgsqlCommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Delimiters.StoredProcNameOpen + request.ProviderMetadata.spUpdate + Delimiters.StoredProcNameClose; PopulateStoredProcParameters(cmd, request, packet); foreach (tgColumnMetadata col in request.Columns) { if (col.IsComputed) { NpgsqlParameter p = types[col.Name]; p = cmd.Parameters[p.ParameterName]; p.Direction = ParameterDirection.InputOutput; } } return cmd; } static public NpgsqlCommand BuildStoredProcDeleteCommand(tgDataRequest request, tgEntitySavePacket packet) { Dictionary<string, NpgsqlParameter> types = Cache.GetParameters(request); NpgsqlCommand cmd = new NpgsqlCommand(); if (request.CommandTimeout != null) cmd.CommandTimeout = request.CommandTimeout.Value; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = Delimiters.StoredProcNameOpen + request.ProviderMetadata.spDelete + Delimiters.StoredProcNameClose; NpgsqlParameter p; foreach (tgColumnMetadata col in request.Columns) { if (col.IsInPrimaryKey) { p = types[col.Name]; p = CloneParameter(p); p.Value = packet.OriginalValues[col.Name]; cmd.Parameters.Add(p); } else if (col.IsConcurrency || col.IsTiraggoConcurrency) { p = types[col.Name]; p = CloneParameter(p); p.Value = packet.OriginalValues[col.Name]; cmd.Parameters.Add(p); } } return cmd; } static public void PopulateStoredProcParameters(NpgsqlCommand cmd, tgDataRequest request, tgEntitySavePacket packet) { Dictionary<string, NpgsqlParameter> types = Cache.GetParameters(request); NpgsqlParameter p; foreach (tgColumnMetadata col in request.Columns) { p = types[col.Name]; p = CloneParameter(p); if (packet.CurrentValues.ContainsKey(col.Name)) { p.Value = packet.CurrentValues[col.Name]; } if (p.NpgsqlDbType == NpgsqlDbType.Timestamp) { p.Direction = ParameterDirection.InputOutput; } if (col.IsComputed && col.CharacterMaxLength > 0) { p.Size = (int)col.CharacterMaxLength; } cmd.Parameters.Add(p); } } static private NpgsqlParameter CloneParameter(NpgsqlParameter p) { ICloneable param = p as ICloneable; return param.Clone() as NpgsqlParameter; } static public string CreateFullName(tgDataRequest request, tgDynamicQuerySerializable query) { IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal; tgProviderSpecificMetadata providerMetadata = iQuery.ProviderMetadata as tgProviderSpecificMetadata; string name = String.Empty; string catalog = iQuery.Catalog ?? request.Catalog ?? providerMetadata.Catalog; string schema = iQuery.Schema ?? request.Schema ?? providerMetadata.Schema; if (catalog != null && schema != null) { name += Delimiters.TableOpen + catalog + Delimiters.TableClose + "."; } if (schema != null) { name += Delimiters.TableOpen + schema + Delimiters.TableClose + "."; } name += Delimiters.TableOpen; if (query.tg.QuerySource != null) name += query.tg.QuerySource; else name += providerMetadata.Destination; name += Delimiters.TableClose; return name; } static public string CreateFullName(tgDataRequest request) { string name = String.Empty; string catalog = request.Catalog ?? request.ProviderMetadata.Catalog; string schema = request.Schema ?? request.ProviderMetadata.Schema; if (catalog != null && schema != null) { name += Delimiters.TableOpen + catalog + Delimiters.TableClose + "."; } if (schema != null) { name += Delimiters.TableOpen + schema + Delimiters.TableClose + "."; } name += Delimiters.TableOpen; if (request.DynamicQuery != null && request.DynamicQuery.tg.QuerySource != null) name += request.DynamicQuery.tg.QuerySource; else name += request.QueryText != null ? request.QueryText : request.ProviderMetadata.Destination; name += Delimiters.TableClose; return name; } static public string CreateFullSPName(tgDataRequest request, string spName) { string name = String.Empty; if ((request.Catalog != null || request.ProviderMetadata.Catalog != null) && (request.Schema != null || request.ProviderMetadata.Schema != null)) { name += Delimiters.TableOpen; name += request.Catalog != null ? request.Catalog : request.ProviderMetadata.Catalog; name += Delimiters.TableClose + "."; } if (request.Schema != null || request.ProviderMetadata.Schema != null) { name += Delimiters.TableOpen; name += request.Schema != null ? request.Schema : request.ProviderMetadata.Schema; name += Delimiters.TableClose + "."; } name += Delimiters.StoredProcNameOpen; name += spName; name += Delimiters.StoredProcNameClose; return name; } static public tgConcurrencyException CheckForConcurrencyException(NpgsqlException ex) { tgConcurrencyException ce = null; return ce; } static public void AddParameters(NpgsqlCommand cmd, tgDataRequest request) { if (request.QueryType == tgQueryType.Text && request.QueryText != null && request.QueryText.Contains("{0}")) { int i = 0; string token = String.Empty; string sIndex = String.Empty; string param = String.Empty; foreach (tgParameter esParam in request.Parameters) { sIndex = i.ToString(); token = '{' + sIndex + '}'; param = Delimiters.Param + "p" + sIndex; request.QueryText = request.QueryText.Replace(token, param); i++; cmd.Parameters.AddWithValue(Delimiters.Param + esParam.Name, esParam.Value); } } else { NpgsqlParameter param; foreach (tgParameter esParam in request.Parameters) { param = cmd.Parameters.AddWithValue(Delimiters.Param + esParam.Name, esParam.Value); switch (esParam.Direction) { case tgParameterDirection.InputOutput: param.Direction = ParameterDirection.InputOutput; break; case tgParameterDirection.Output: param.Direction = ParameterDirection.Output; param.DbType = esParam.DbType; param.Size = esParam.Size; param.Scale = esParam.Scale; param.Precision = esParam.Precision; break; case tgParameterDirection.ReturnValue: param.Direction = ParameterDirection.ReturnValue; break; // The default is ParameterDirection.Input; } } } } static public void GatherReturnParameters(NpgsqlCommand cmd, tgDataRequest request, tgDataResponse response) { if (cmd.Parameters.Count > 0) { if (request.Parameters != null && request.Parameters.Count > 0) { response.Parameters = new tgParameters(); foreach (tgParameter esParam in request.Parameters) { if (esParam.Direction != tgParameterDirection.Input) { response.Parameters.Add(esParam); NpgsqlParameter p = cmd.Parameters[Delimiters.Param + esParam.Name]; esParam.Value = p.Value; } } } } } } }
/* Copyright (c) 2009-11, ReactionGrid Inc. http://reactiongrid.com * See License.txt for full licence information. * * SingleSceneConfiguration.cs Revision 1.4.1106.11 * Used to provide single scene configuration Jibe instances */ using UnityEngine; using System; using System.Collections; using ReactionGrid.JibeAPI; using ReactionGrid.Jibe; public class SingleSceneConfiguration : MonoBehaviour { private bool runSingleSceneConfig = false; public GUISkin guiSkin; // external data private string username = ""; private string dynamicRoomId = ""; // integer to add to the name of the rooms to which the users are connecting - used for dynamic room support (coming in next release) private int selected = -1; private IJibeServer jibeServerInstance; private IJibePlayer localPlayer; private string infoMessage = "Ready for login"; private string headerMessage = "Connecting to server..."; private bool isGuest = false; // Headshots public Texture2D[] avatarHeadPics; // Full pics of avatars public Texture2D[] avatarFullPics; public float fullPicWidth = 128; public float fullPicHeight = 128; private Color guiColor; // When an avatar thumbnail is selected a preview is shown of the full model on the right public float avatarPreviewTransparency = 0.7f; // The image to show for the login / start button (optional) public Texture2D loginButtonImage; public Texture2D backgroundImage; GameObject jibeGUI; GameObject previewCamera; public float fadeSpeed = 0.3f; private int drawDepth = -1000; private float alpha = 1.0f; private float fadeDir = -1; void Update() { if (runSingleSceneConfig) { if (jibeServerInstance == null) { return; } jibeServerInstance.Update(); } } public void RunConfiguration() { selected = PlayerPrefs.GetInt("avatar", -1); if (selected >= avatarHeadPics.Length) { selected = -1; } runSingleSceneConfig = true; ShowPreviewCamera(true); previewCamera = GameObject.Find("PreviewCameraForDesignModeOnly"); jibeGUI = GameObject.Find("JibeGUI"); ToggleGUIElements(false); alpha = 1; fadeIn(); Debug.Log("Configuring Jibe"); Cursor.visible = true; username = PlayerPrefs.GetString("username"); if (string.IsNullOrEmpty(username) || username == "Unknown user") { username = "Guest" + UnityEngine.Random.Range(0, 999); isGuest = true; PlayerPrefs.SetString("username", username); } Application.runInBackground = true; // Gather configuration JibeConfig config = GetComponent<JibeConfig>(); // add the id to each room name for the class for use in dynamic rooms if (string.IsNullOrEmpty(dynamicRoomId)) dynamicRoomId = "1"; PlayerPrefs.SetInt("DynamicRoomId", int.Parse(dynamicRoomId)); Debug.Log(config.Room + " " + config.Zone + " " + config.ServerIP + " " + config.ServerPort.ToString() + " " + config.RoomPassword + " " + config.ServerPlatform.ToString()); // Prefetch policy from designated socket server // only for web clients if (Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.OSXWebPlayer || Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.OSXEditor) { bool success = Security.PrefetchSocketPolicy(config.ServerIP, config.ServerPort); if (!success) { Debug.Log("Prefetch policy from network server failed, trying standard policy server port " + config.PolicyServerPort); Security.PrefetchSocketPolicy(config.ServerIP, config.PolicyServerPort); } else { Debug.Log("Prefetch policy succeeded from " + config.ServerPort); } } if (!JibeComms.IsInitialized()) { try { Debug.Log("Generate new Jibe instance"); // Initialize backend server switch (config.ServerPlatform) { case SupportedServers.JibePhoton: jibeServerInstance = new JibePhotonServer(config.ServerIP, config.ServerPort, config.Zone, config.Room, config.DataSendRate, config.DataSendRate, config.debugLevel, Debug.Log, Debug.LogWarning, Debug.LogError); break; case SupportedServers.JibeSFS2X: jibeServerInstance = new JibeSFS2XServer(config.ServerIP, config.ServerPort, config.Zone, config.Room, config.RoomPassword, false, config.DataSendRate, config.DataSendRate, config.debugLevel, Debug.Log, Debug.LogWarning, Debug.LogError, config.HttpPort); break; } JibeComms.Initialize(config.Room, config.Zone, config.ServerIP, config.ServerPort, config.RoomPassword, config.RoomList, config.Version, jibeServerInstance); } catch (Exception e) { Debug.Log(e.Message); } } jibeServerInstance.LoginResult += new LoginResultEventHandler(LoginResult); string message = "Connecting to server, please wait..."; headerMessage = message; Debug.Log(message); try { // Connect to Jibe localPlayer = jibeServerInstance.Connect(); } catch (Exception ex) { Debug.Log("Failed to connect!" + ex.Message + ex.StackTrace); infoMessage = ex.Message; } } void OnGUI() { if (runSingleSceneConfig) { GUI.skin = guiSkin; GUILayout.BeginArea(new Rect(0, 0, Screen.width, Screen.height)); GUILayout.BeginVertical(); GUILayout.Space(5); // Welcome prompt / header message - will show whatever text is set in headerMessage GUILayout.Label(headerMessage, "WelcomePrompt"); try { if (jibeServerInstance.IsConnected) { headerMessage = "Choose an avatar"; // Choose avatar - arrange GUI elements in an area (sized here) using layout tools GUILayout.BeginArea(new Rect(5, 30, 600, 180)); GUILayout.BeginHorizontal(); // Show the choice of avatars - default is pics laid out in rows up to 7 icons per row selected = GUILayout.SelectionGrid(selected, avatarHeadPics, 7, "PictureButtonsSmall"); GUILayout.EndHorizontal(); GUILayout.EndArea(); // we're back to vertical layout - the space here controls vertical displacement for next GUI elements (offset from top) GUILayout.Space(290); GUILayout.BeginHorizontal(); // horizontal offset from left GUILayout.Space(2); // Give the player the option to change their name GUILayoutOption[] nameoptions = { GUILayout.Width(120), GUILayout.Height(22) }; username = GUILayout.TextField(username, "UserNameField", nameoptions); if (isGuest || Application.platform == RuntimePlatform.WindowsEditor) GUILayout.Label("Edit your name here!", "InstructionLabel"); GUILayout.EndHorizontal(); GUIContent content = new GUIContent("Start", "Start!"); // check the player has selected an avatar, then show button if (selected >= 0 && GUI.Button(new Rect(2, 350, 80, 22), content, "LoginButton")) { DoLogin(selected); } } guiColor = GUI.color; guiColor.a = avatarPreviewTransparency; GUI.color = guiColor; if (selected > -1 && selected < avatarFullPics.Length) { GUI.DrawTexture(new Rect(420, 10, fullPicWidth, fullPicHeight), avatarFullPics[selected]); } guiColor.a = 1.0f; GUI.color = guiColor; // camera fade alpha += fadeDir * fadeSpeed * Time.deltaTime; alpha = Mathf.Clamp01(alpha); guiColor.a = alpha; GUI.color = guiColor; GUI.depth = drawDepth; GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), backgroundImage); guiColor.a = 1.0f; GUI.color = guiColor; } catch (Exception ex) { infoMessage = ex.Message + ": " + ex.StackTrace; Debug.Log(infoMessage); } GUILayout.Space(50); GUILayout.BeginHorizontal(); GUILayout.Space(120); GUILayout.Label(infoMessage, "InstructionLabel"); // Must always end all GUILayout elements - missing closing tags do not make unity happy GUILayout.EndHorizontal(); GUILayout.EndVertical(); GUILayout.EndArea(); } } private void DoLogin(int selected) { RetrieveClothingPreference(); Debug.Log("DoLogin"); jibeServerInstance.RequestLogin(username); } private void RetrieveClothingPreference() { // try to re-use previous clothing options string skin = PlayerPrefs.GetString("skin"); if (!string.IsNullOrEmpty(skin)) localPlayer.Skin = skin; string hair = PlayerPrefs.GetString("hair"); if (!string.IsNullOrEmpty(hair)) localPlayer.Hair = hair; } private string GetSkinName(string normalTextureName) { // We rely on naming conventions for getting the name of a skin - all assets in the resources folder must be named according to convention // and all headshots and full previews too. string skinName = normalTextureName; skinName = skinName.Substring(0, skinName.IndexOf("Head")); return skinName + "_skin"; } private void LoginResult(object sender, LoginResultEventArgs e) { if (e.Success) { fadeOut(); // Player has logged in successfully! Store some prefs PlayerPrefs.SetString("username", username); PlayerPrefs.SetInt("avatar", selected); // Update localPlayer localPlayer.AvatarModel = selected; localPlayer.Name = username; if (string.IsNullOrEmpty(localPlayer.Skin)) { localPlayer.Skin = GetSkinName(avatarHeadPics[selected].name); } // Unwire event handlers jibeServerInstance.LoginResult -= new LoginResultEventHandler(LoginResult); // Now should be ready to spawn avatars and join the room runSingleSceneConfig = false; ToggleGUIElements(true); LogLoginEvent(); GetComponent<NetworkController>().DoInitialization(); } else { Debug.Log("Login FAIL " + e.Message); infoMessage = e.Message; } } private void LogLoginEvent() { GameObject jibeObject = GameObject.Find("Jibe"); JibeActivityLog jibeLog = jibeObject.GetComponent<JibeActivityLog>(); if (jibeLog != null && jibeLog.logEnabled) { if (Application.platform == RuntimePlatform.WindowsWebPlayer || Application.platform == RuntimePlatform.OSXWebPlayer) { Debug.Log(jibeLog.TrackEvent(JibeEventType.Login, Application.absoluteURL, 0.0f, 0.0f, 0.0f, username, username, "Web Player Login")); } else if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.OSXEditor) { Debug.Log(jibeLog.TrackEvent(JibeEventType.Login, Application.dataPath, 0.0f, 0.0f, 0.0f, username, username, "Editor login")); } else if (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.OSXPlayer) { Debug.Log(jibeLog.TrackEvent(JibeEventType.Login, Application.dataPath, 0.0f, 0.0f, 0.0f, username, username, "Standalone Client login")); } else { Debug.Log(jibeLog.TrackEvent(JibeEventType.Login, Application.dataPath, 0.0f, 0.0f, 0.0f, username, username, "Other Client login")); } } } private void ToggleGUIElements(bool enabled) { if (jibeGUI != null) { jibeGUI.SetActiveRecursively(enabled); } GameObject miniMap = GameObject.Find("MiniMapCamera"); if (miniMap != null) { miniMap.GetComponent<Camera>().enabled = enabled; } } private void ShowPreviewCamera(bool enabled) { if (previewCamera != null) { Debug.Log("Preview Camera found, setting active to " + enabled); previewCamera.GetComponent<PreviewCamera>().SetActive(enabled); } } private void fadeIn() { fadeDir = -1; } private void fadeOut() { fadeDir = 1; } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Media; using System.Text; using System.Windows.Forms; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Localization; namespace OpenLiveWriter.Controls { public partial class ImageCropControl : UserControl { private const AnchorStyles ANCHOR_ALL = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right; private Bitmap bitmap; private DualRects crop; private CachedResizedBitmap crbNormal; private CachedResizedBitmap crbGrayed; private bool gridLines; private CropStrategy cropStrategy = new FreeCropStrategy(); private bool fireCropChangedOnKeyUp = false; public ImageCropControl() { SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.ResizeRedraw, true); InitializeComponent(); AccessibleName = Res.Get(StringId.CropPane); AccessibleRole = AccessibleRole.Pane; TabStop = true; } public bool GridLines { get { return gridLines; } set { if (gridLines != value) { gridLines = value; Invalidate(); } } } public event EventHandler CropRectangleChanged; private void OnCropRectangleChanged() { if (CropRectangleChanged != null) CropRectangleChanged(this, EventArgs.Empty); } public event EventHandler AspectRatioChanged; private void OnAspectRatioChanged() { if (AspectRatioChanged != null) AspectRatioChanged(this, EventArgs.Empty); } [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Rectangle CropRectangle { get { return crop.Real; } set { crop.Real = value; } } public void Crop() { Bitmap newBitmap = new Bitmap(bitmap, crop.Real.Size.Width, crop.Real.Size.Height); using (Graphics g = Graphics.FromImage(newBitmap)) { g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; g.DrawImage(bitmap, new Rectangle(0, 0, newBitmap.Width, newBitmap.Height), crop.Real, GraphicsUnit.Pixel); } Bitmap = newBitmap; } public double? AspectRatio { get { return cropStrategy.AspectRatio; } set { if (value == null) { cropStrategy = new FreeCropStrategy(); OnAspectRatioChanged(); Invalidate(); } else { cropStrategy = new FixedAspectRatioCropStrategy(value.Value); OnAspectRatioChanged(); Rectangle containerRect = crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height); Rectangle cropped = ((FixedAspectRatioCropStrategy)cropStrategy).ConformCropRectangle(containerRect, crop.Virtual); if (cropped.Right > containerRect.Right) cropped.X -= cropped.Right - containerRect.Right; if (cropped.Bottom > containerRect.Bottom) cropped.Y -= cropped.Bottom - containerRect.Bottom; if (cropped.Left < containerRect.Left) cropped.X += containerRect.Left - cropped.Left; if (cropped.Top < containerRect.Top) cropped.Y += containerRect.Top - cropped.Top; crop.Virtual = cropped; if (!cropStrategy.IsDragging) { cropStrategy.BeginDrag( crop.Virtual, new Point(crop.Virtual.Right, crop.Virtual.Bottom), AnchorStyles.Bottom | AnchorStyles.Right, crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height)); crop.Virtual = cropStrategy.GetNewBounds(new Point(crop.Virtual.Right, crop.Virtual.Bottom)); Invalidate(); Update(); OnCropRectangleChanged(); cropStrategy.EndDrag(); } } } } private void NullAndDispose<T>(ref T disposable) where T : IDisposable { IDisposable tmp = disposable; disposable = default(T); if (tmp != null) tmp.Dispose(); } public Bitmap Bitmap { get { return bitmap; } set { if (value != null) { NullAndDispose(ref crbNormal); NullAndDispose(ref crbGrayed); } bitmap = value; if (bitmap != null) { crbNormal = new CachedResizedBitmap(value, false); crbGrayed = new CachedResizedBitmap(MakeGray(value), true); crop = new DualRects(PointF.Empty, bitmap.Size); crop.Real = new Rectangle( bitmap.Width / 4, bitmap.Height / 4, Math.Max(1, bitmap.Width / 2), Math.Max(1, bitmap.Height / 2)); OnCropRectangleChanged(); } PerformLayout(); Invalidate(); } } private Bitmap MakeGray(Bitmap orig) { Bitmap grayed = new Bitmap(orig); using (Graphics g = Graphics.FromImage(grayed)) { using (Brush b = new SolidBrush(Color.FromArgb(128, Color.Gray))) g.FillRectangle(b, 0, 0, grayed.Width, grayed.Height); } return grayed; } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == MouseButtons.Left) { AnchorStyles anchor = cropStrategy.HitTest(crop.Virtual, e.Location); if (anchor != AnchorStyles.None) { cropStrategy.BeginDrag( crop.Virtual, e.Location, anchor, crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height)); Capture = true; } } } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (cropStrategy.IsDragging && e.Button == MouseButtons.Left) { cropStrategy.EndDrag(); Capture = false; OnCropRectangleChanged(); } } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (cropStrategy.IsDragging) { Rectangle originalRect = crop.Virtual; crop.Virtual = cropStrategy.GetNewBounds(PointToClient(MousePosition)); InvalidateForRectChange(originalRect, crop.Virtual); } else if (e.Button == MouseButtons.None) { Cursor = ChooseCursor(crop.Virtual, e.Location); } } private void InvalidateForRectChange(Rectangle oldRect, Rectangle newRect) { int borderWidth = BoundsWithHandles.HANDLE_SIZE * 2; InvalidateBorder(oldRect, borderWidth); InvalidateBorder(newRect, borderWidth); if (gridLines) { InvalidateGridlines(oldRect); InvalidateGridlines(newRect); } using (Region region = new Region(oldRect)) { region.Xor(newRect); Invalidate(region); } } private void InvalidateBorder(Rectangle rect, int width) { rect.Inflate(width / 2, width / 2); using (Region region = new Region(rect)) { rect.Inflate(-width, -width); region.Exclude(rect); Invalidate(region); } } private void InvalidateGridlines(Rectangle rect) { int x1, x2, y1, y2; CalculateGridlines(rect, out x1, out x2, out y1, out y2); using (Region gridRegion = new Region()) { gridRegion.MakeEmpty(); gridRegion.Union(new Rectangle(x1, rect.Top, 1, rect.Height)); gridRegion.Union(new Rectangle(x2, rect.Top, 1, rect.Height)); gridRegion.Union(new Rectangle(rect.Left, y1, rect.Width, 1)); gridRegion.Union(new Rectangle(rect.Left, y2, rect.Width, 1)); Invalidate(gridRegion); } } private Cursor ChooseCursor(Rectangle sizeRect, Point point) { AnchorStyles anchor = cropStrategy.HitTest(sizeRect, point); switch (anchor) { case AnchorStyles.Left: case AnchorStyles.Right: return Cursors.SizeWE; case AnchorStyles.Top: case AnchorStyles.Bottom: return Cursors.SizeNS; case AnchorStyles.Top | AnchorStyles.Left: case AnchorStyles.Bottom | AnchorStyles.Right: return Cursors.SizeNWSE; case AnchorStyles.Top | AnchorStyles.Right: case AnchorStyles.Bottom | AnchorStyles.Left: return Cursors.SizeNESW; case AnchorStyles.None: return Cursors.Default; case ANCHOR_ALL: return Cursors.SizeAll; default: Debug.Fail("Unexpected anchor: " + anchor); return Cursors.Default; } } protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); Invalidate(); } protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); Invalidate(); } public bool ProcessCommandKey(ref Message msg, Keys keyData) { return ProcessCmdKey(ref msg, keyData); } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { switch (keyData) { case Keys.Up | Keys.Control: case Keys.Up: return AdjustCropRectangle(0, -1, 0, 0); case Keys.Down | Keys.Control: case Keys.Down: return AdjustCropRectangle(0, 1, 0, 0); case Keys.Left | Keys.Control: case Keys.Left: return AdjustCropRectangle(-1, 0, 0, 0); case Keys.Right | Keys.Control: case Keys.Right: return AdjustCropRectangle(1, 0, 0, 0); case Keys.Left | Keys.Shift: return AdjustCropRectangle(0, 0, -1, 0); case Keys.Right | Keys.Shift: return AdjustCropRectangle(0, 0, 1, 0); case Keys.Up | Keys.Shift: return AdjustCropRectangle(0, 0, 0, -1); case Keys.Down | Keys.Shift: return AdjustCropRectangle(0, 0, 0, 1); } return base.ProcessCmdKey(ref msg, keyData); } private bool AdjustCropRectangle(int xOffset, int yOffset, int xGrow, int yGrow) { Rectangle orig = crop.Virtual; Rectangle result = cropStrategy.AdjustRectangle( crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height), orig, xOffset, yOffset, xGrow, yGrow); if (orig != result) { crop.Virtual = result; fireCropChangedOnKeyUp = true; InvalidateForRectChange(orig, result); } else { // annoying // SystemSounds.Beep.Play(); } return true; } protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); if (fireCropChangedOnKeyUp) { fireCropChangedOnKeyUp = false; OnCropRectangleChanged(); } } protected override void OnLayout(LayoutEventArgs e) { if (bitmap == null) return; float scaleFactor = Math.Min( (float)Width / bitmap.Width, (float)Height / bitmap.Height); Rectangle realRect = crop.Real; SizeF scale; PointF offset; if (scaleFactor > 1.0f) { scale = new SizeF(1, 1); offset = new PointF((Width - bitmap.Width) / 2, (Height - bitmap.Height) / 2); } else { offset = Point.Empty; scale = new SizeF(scaleFactor, scaleFactor); offset.X = (Width - (bitmap.Width * scale.Width)) / 2; offset.Y = (Height - (bitmap.Height * scale.Height)) / 2; } crop = new DualRects(offset, scale); crop.Real = realRect; Size virtualBitmapSize = crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height).Size; crbNormal.Resize(virtualBitmapSize); crbGrayed.Resize(virtualBitmapSize); } protected override void OnPaint(PaintEventArgs e) { e.Graphics.InterpolationMode = InterpolationMode.Default; e.Graphics.SmoothingMode = SmoothingMode.HighSpeed; e.Graphics.CompositingMode = CompositingMode.SourceCopy; e.Graphics.CompositingQuality = CompositingQuality.HighSpeed; using (Brush b = new SolidBrush(BackColor)) e.Graphics.FillRectangle(b, ClientRectangle); if (bitmap == null) return; Rectangle bitmapRect = crop.VirtualizeRect(0, 0, bitmap.Width, bitmap.Height); e.Graphics.DrawImage(crbGrayed.ResizedBitmap, bitmapRect); Rectangle normalSrcRect = crop.Virtual; normalSrcRect.Offset(-bitmapRect.X, -bitmapRect.Y); e.Graphics.DrawImage(crbNormal.ResizedBitmap, crop.Virtual, normalSrcRect, GraphicsUnit.Pixel); e.Graphics.CompositingMode = CompositingMode.SourceOver; Rectangle cropDrawRect = crop.Virtual; cropDrawRect.Width -= 1; cropDrawRect.Height -= 1; using (Brush b = new SolidBrush(Color.FromArgb(200, Color.White))) using (Pen p = new Pen(b, 1)) { e.Graphics.DrawRectangle(p, cropDrawRect); } if (gridLines) { int x1, x2, y1, y2; CalculateGridlines(crop.Virtual, out x1, out x2, out y1, out y2); using (Brush b = new SolidBrush(Color.FromArgb(128, Color.Gray))) using (Pen p = new Pen(b, 1)) { e.Graphics.DrawLine(p, cropDrawRect.Left, y1, cropDrawRect.Right, y1); e.Graphics.DrawLine(p, cropDrawRect.Left, y2, cropDrawRect.Right, y2); e.Graphics.DrawLine(p, x1, cropDrawRect.Top, x1, cropDrawRect.Bottom); e.Graphics.DrawLine(p, x2, cropDrawRect.Top, x2, cropDrawRect.Bottom); } } if (Focused) { Rectangle focusRect = cropDrawRect; focusRect.Inflate(2, 2); ControlPaint.DrawFocusRectangle(e.Graphics, focusRect); } BoundsWithHandles boundsWithHandles = new BoundsWithHandles(cropStrategy.AspectRatio == null ? true : false); boundsWithHandles.Bounds = cropDrawRect; using (Pen p = new Pen(SystemColors.ControlDarkDark, 1f)) { foreach (Rectangle rect in boundsWithHandles.GetHandles()) { e.Graphics.FillRectangle(SystemBrushes.Window, rect); e.Graphics.DrawRectangle(p, rect); } } } private static void CalculateGridlines(Rectangle cropDrawRect, out int x1, out int x2, out int y1, out int y2) { int yThird = cropDrawRect.Height / 3; y1 = cropDrawRect.Top + yThird; y2 = cropDrawRect.Top + yThird * 2; int xThird = cropDrawRect.Width / 3; x1 = cropDrawRect.Left + xThird; x2 = cropDrawRect.Left + xThird * 2; } private class CachedResizedBitmap : IDisposable { private readonly Bitmap original; private bool originalIsOwned; private Bitmap resized; private Size? currentSize; public CachedResizedBitmap(Bitmap original, bool takeOwnership) { this.original = original; this.originalIsOwned = takeOwnership; } public void Dispose() { Reset(); if (originalIsOwned) { originalIsOwned = false; // allows safe multiple disposal original.Dispose(); } } public void Reset() { Bitmap tmp = resized; resized = null; currentSize = null; if (tmp != null) tmp.Dispose(); } public void Resize(Size size) { size = new Size(Math.Max(size.Width, 1), Math.Max(size.Height, 1)); Reset(); Bitmap newBitmap = new Bitmap(original, size); using (Graphics g = Graphics.FromImage(newBitmap)) { g.DrawImage(original, 0, 0, newBitmap.Width, newBitmap.Height); } resized = newBitmap; currentSize = size; } public Size CurrentSize { get { return currentSize ?? original.Size; } } public Bitmap ResizedBitmap { get { return resized ?? original; } } } public abstract class CropStrategy { protected const int MIN_WIDTH = 5; protected const int MIN_HEIGHT = 5; private bool dragging = false; protected Rectangle initialBounds; protected Point initialLoc; protected AnchorStyles anchor; protected Rectangle? container; public virtual void BeginDrag(Rectangle initialBounds, Point initalLoc, AnchorStyles anchor, Rectangle? container) { dragging = true; this.initialBounds = initialBounds; this.initialLoc = initalLoc; this.anchor = anchor; this.container = container; } public virtual double? AspectRatio { get { return null; } } public virtual void EndDrag() { dragging = false; } public bool IsDragging { get { return dragging; } } public virtual Rectangle GetNewBounds(Point newLoc) { Rectangle newRect = initialBounds; if (anchor == ANCHOR_ALL) // move { newRect = DoMove(newLoc); } else // resize { newRect = DoResize(newLoc); } if (container != null) newRect.Intersect(container.Value); return newRect; } public abstract Rectangle AdjustRectangle(Rectangle cont, Rectangle rect, int xOffset, int yOffset, int xGrow, int yGrow); protected static int Round(double dblVal) { return (int)Math.Round(dblVal); } protected static int Round(float fltVal) { return (int)Math.Round(fltVal); } protected virtual Rectangle DoMove(Point newLoc) { Rectangle newRect = initialBounds; int deltaX = newLoc.X - initialLoc.X; int deltaY = newLoc.Y - initialLoc.Y; newRect.Offset(deltaX, deltaY); if (container != null) { Rectangle cont = container.Value; if (cont.Left > newRect.Left) newRect.Offset(cont.Left - newRect.Left, 0); else if (cont.Right < newRect.Right) newRect.Offset(cont.Right - newRect.Right, 0); if (cont.Top > newRect.Top) newRect.Offset(0, cont.Top - newRect.Top); else if (cont.Bottom < newRect.Bottom) newRect.Offset(0, cont.Bottom - newRect.Bottom); } return newRect; } protected abstract Rectangle DoResize(Point newLoc); [Flags] private enum HT { None = 0, Left = 1, Top = 2, Right = 4, Bottom = 8, AlmostLeft = 16, AlmostTop = 32, AlmostRight = 64, AlmostBottom = 128, Mask_Horizontal = Left | AlmostLeft | Right | AlmostRight, Mask_Vertical = Top | AlmostTop | Bottom | AlmostBottom, } public virtual AnchorStyles HitTest(Rectangle sizeRect, Point point) { sizeRect.Inflate(1, 1); if (!sizeRect.Contains(point)) return AnchorStyles.None; HT hitTest = HT.None; Test(sizeRect.Right - point.X, HT.Right, HT.AlmostRight, ref hitTest); Test(sizeRect.Bottom - point.Y, HT.Bottom, HT.AlmostBottom, ref hitTest); Test(point.X - sizeRect.Left, HT.Left, HT.AlmostLeft, ref hitTest); Test(point.Y - sizeRect.Top, HT.Top, HT.AlmostTop, ref hitTest); RemoveConflicts(ref hitTest); switch (hitTest) { case HT.Left: return AnchorStyles.Left; case HT.Top: return AnchorStyles.Top; case HT.Right: return AnchorStyles.Right; case HT.Bottom: return AnchorStyles.Bottom; case HT.Left | HT.Top: case HT.Left | HT.AlmostTop: case HT.Top | HT.AlmostLeft: return AnchorStyles.Top | AnchorStyles.Left; case HT.Right | HT.Top: case HT.Right | HT.AlmostTop: case HT.Top | HT.AlmostRight: return AnchorStyles.Top | AnchorStyles.Right; case HT.Right | HT.Bottom: case HT.Right | HT.AlmostBottom: case HT.Bottom | HT.AlmostRight: return AnchorStyles.Bottom | AnchorStyles.Right; case HT.Left | HT.Bottom: case HT.Left | HT.AlmostBottom: case HT.Bottom | HT.AlmostLeft: return AnchorStyles.Bottom | AnchorStyles.Left; default: return ANCHOR_ALL; } } private static void RemoveConflicts(ref HT hitTest) { TestClearAndSet(ref hitTest, HT.Right, HT.Mask_Horizontal); TestClearAndSet(ref hitTest, HT.Left, HT.Mask_Horizontal); TestClearAndSet(ref hitTest, HT.AlmostRight, HT.Mask_Horizontal); TestClearAndSet(ref hitTest, HT.AlmostLeft, HT.Mask_Horizontal); TestClearAndSet(ref hitTest, HT.Bottom, HT.Mask_Vertical); TestClearAndSet(ref hitTest, HT.Top, HT.Mask_Vertical); TestClearAndSet(ref hitTest, HT.AlmostBottom, HT.Mask_Vertical); TestClearAndSet(ref hitTest, HT.AlmostTop, HT.Mask_Vertical); } private static void TestClearAndSet(ref HT val, HT test, HT clearMask) { if (test == (test & val)) { val &= ~clearMask; val |= test; } } private static void Test(int distance, HT exactResult, HT fuzzyResult, ref HT hitTest) { hitTest |= distance < 0 ? 0 : distance < 5 ? exactResult : distance < 10 ? fuzzyResult : 0; } } public class FixedAspectRatioCropStrategy : FreeCropStrategy { private double aspectRatio; public FixedAspectRatioCropStrategy(double aspectRatio) { this.aspectRatio = aspectRatio; } public override double? AspectRatio { get { return aspectRatio; } } public override Rectangle AdjustRectangle(Rectangle cont, Rectangle rect, int xOffset, int yOffset, int xGrow, int yGrow) { Rectangle result = base.AdjustRectangle(cont, rect, xOffset, yOffset, xGrow, yGrow); if (xGrow != 0) { result.Height = Math.Max(MIN_HEIGHT, Round(result.Width / aspectRatio)); } else if (yGrow != 0) { result.Width = Math.Max(MIN_WIDTH, Round(result.Height * aspectRatio)); } // too far--revert! if (result.Bottom > cont.Bottom || result.Right > cont.Right) result = rect; return result; } public Rectangle ConformCropRectangle(Rectangle containerRect, Rectangle cropRect) { // try to preserve the same number of pixels int numOfPixels = cropRect.Width * cropRect.Height; PointF center = new PointF(cropRect.Left + cropRect.Width / 2f, cropRect.Top + cropRect.Height / 2f); double height = Math.Sqrt(numOfPixels / aspectRatio); double width = aspectRatio * height; PointF newLoc = new PointF(center.X - (float)width / 2f, center.Y - (float)height / 2f); return new Rectangle( Convert.ToInt32(newLoc.X), Convert.ToInt32(newLoc.Y), Convert.ToInt32(width), Convert.ToInt32(height)); } public override AnchorStyles HitTest(Rectangle sizeRect, Point point) { AnchorStyles hitTest = base.HitTest(sizeRect, point); if (AnchorStyles.None == (hitTest & (AnchorStyles.Left | AnchorStyles.Right))) { return AnchorStyles.None; } if (AnchorStyles.None == (hitTest & (AnchorStyles.Top | AnchorStyles.Bottom))) { return AnchorStyles.None; } return hitTest; } protected override Rectangle DoResize(Point newLoc) { bool up = AnchorStyles.Top == (anchor & AnchorStyles.Top); bool left = AnchorStyles.Left == (anchor & AnchorStyles.Left); PointF origin = new PointF( initialBounds.Left + (left ? initialBounds.Width : 0), initialBounds.Top + (up ? initialBounds.Height : 0)); double desiredAngle = Math.Atan2( 1d * (up ? -1 : 1), 1d * aspectRatio * (left ? -1 : 1)); double actualAngle = Math.Atan2( newLoc.Y - origin.Y, newLoc.X - origin.X); double angleDiff = Math.Abs(actualAngle - desiredAngle); if (angleDiff >= Math.PI / 2) // >=90 degrees--too much angle! return base.DoResize(new Point((int)origin.X, (int)origin.Y)); double distance = Distance(origin, newLoc); double resizeMagnitude = Math.Cos(angleDiff) * distance; double xMagnitude = resizeMagnitude * Math.Cos(desiredAngle); double yMagnitude = resizeMagnitude * Math.Sin(desiredAngle); newLoc.X = Round(origin.X + xMagnitude); newLoc.Y = Round(origin.Y + yMagnitude); Rectangle newRect = base.DoResize(newLoc); if (container != null) { Rectangle newRectConstrained = newRect; newRectConstrained.Intersect(container.Value); if (!newRectConstrained.Equals(newRect)) { int newWidth = Round(Math.Min(newRectConstrained.Width, newRectConstrained.Height * aspectRatio)); int newHeight = Round(Math.Min(newRectConstrained.Height, newRectConstrained.Width / aspectRatio)); newRect.Width = newWidth; newRect.Height = newHeight; if (left) newRect.Location = new Point(initialBounds.Right - newRect.Width, newRect.Top); if (up) newRect.Location = new Point(newRect.Left, initialBounds.Bottom - newRect.Height); } } return newRect; } private double Distance(PointF pFrom, PointF pTo) { double deltaX = Math.Abs((double)(pTo.X - pFrom.X)); double deltaY = Math.Abs((double)(pTo.Y - pFrom.Y)); return Math.Sqrt( deltaX * deltaX + deltaY * deltaY ); } private PointF Rotate(PointF origin, double angleRadians, PointF point) { float x, y; x = point.X - origin.X; y = point.Y - origin.Y; point.X = (float)(x * Math.Cos(angleRadians) - y * Math.Sin(angleRadians)); point.Y = (float)(y * Math.Cos(angleRadians) - x * Math.Sin(angleRadians)); point.X += origin.X; point.Y += origin.Y; return point; } } public class FreeCropStrategy : CropStrategy { protected override Rectangle DoResize(Point newLoc) { Rectangle newRect = initialBounds; int deltaX = newLoc.X - initialLoc.X; int deltaY = newLoc.Y - initialLoc.Y; switch (anchor & (AnchorStyles.Left | AnchorStyles.Right)) { case AnchorStyles.Left: if (MIN_WIDTH >= initialBounds.Width - deltaX) deltaX = initialBounds.Width - MIN_WIDTH; newRect.Width -= deltaX; newRect.Offset(deltaX, 0); break; case AnchorStyles.Right: if (MIN_WIDTH >= initialBounds.Width + deltaX) deltaX = -initialBounds.Width + MIN_WIDTH; newRect.Width += deltaX; break; } switch (anchor & (AnchorStyles.Top | AnchorStyles.Bottom)) { case AnchorStyles.Top: if (MIN_HEIGHT >= initialBounds.Height - deltaY) deltaY = initialBounds.Height - MIN_HEIGHT; newRect.Height -= deltaY; newRect.Offset(0, deltaY); break; case AnchorStyles.Bottom: if (MIN_HEIGHT >= initialBounds.Height + deltaY) deltaY = -initialBounds.Height + MIN_HEIGHT; newRect.Height += deltaY; break; } return newRect; } public override Rectangle AdjustRectangle(Rectangle cont, Rectangle rect, int xOffset, int yOffset, int xGrow, int yGrow) { Debug.Assert(MathHelper.Max(xOffset, yOffset, xGrow, yGrow) <= 1, "AdjustRectangle doesn't work well with values larger than 1--edge cases in FixedAspectRatioCropStrategy"); Debug.Assert(MathHelper.Min(xOffset, yOffset, xGrow, yGrow) >= -1, "AdjustRectangle doesn't work well with values larger than 1--edge cases in FixedAspectRatioCropStrategy"); Debug.Assert((xOffset == 0 && yOffset == 0) || (xGrow == 0 && yGrow == 0), "Beware of changing offset and size with the same call--weird things may happen as you approach the edges of the container"); rect.X = Math.Max(cont.X, Math.Min(cont.Right - rect.Width, rect.X + xOffset)); rect.Y = Math.Max(cont.Y, Math.Min(cont.Bottom - rect.Height, rect.Y + yOffset)); rect.Width = Math.Max(MIN_WIDTH, Math.Min(cont.Right - rect.Left, rect.Width + xGrow)); rect.Height = Math.Max(MIN_HEIGHT, Math.Min(cont.Bottom - rect.Top, rect.Height + yGrow)); return rect; } } private class DualRects { private Rectangle r; private Rectangle v; private readonly PointF offset; private readonly SizeF scale; public DualRects(PointF offset, SizeF scale) { this.offset = offset; this.scale = scale; } public Rectangle Real { get { return r; } set { r = value; v = VirtualizeRect(r.X, r.Y, r.Width, r.Height); } } public Rectangle Virtual { get { return v; } set { v = value; r = RealizeRect(v.X, v.Y, v.Width, v.Height); } } public Rectangle RealizeRect(int x, int y, int width, int height) { return new Rectangle( (int)Math.Round((x - offset.X) / scale.Width), (int)Math.Round((y - offset.Y) / scale.Height), (int)Math.Round(width / scale.Width), (int)Math.Round(height / scale.Height) ); } public Rectangle VirtualizeRect(int x, int y, int width, int height) { return new Rectangle( (int)Math.Round(x * scale.Width + offset.X), (int)Math.Round(y * scale.Height + offset.Y), (int)Math.Round(width * scale.Width), (int)Math.Round(height * scale.Height) ); } } private class BoundsWithHandles { public const int HANDLE_SIZE = 5; private readonly bool includeSideHandles; private Rectangle bounds; public BoundsWithHandles(bool includeSideHandles) { this.includeSideHandles = includeSideHandles; } public Rectangle Bounds { get { return bounds; } set { bounds = value; } } public Rectangle[] GetHandles() { List<Rectangle> handles = new List<Rectangle>(includeSideHandles ? 8 : 4); // top left handles.Add(MakeRect(bounds.Left, bounds.Top)); if (includeSideHandles) handles.Add(MakeRect((bounds.Left + bounds.Right) / 2, bounds.Top)); handles.Add(MakeRect(bounds.Right, bounds.Top)); if (includeSideHandles) { handles.Add(MakeRect(bounds.Left, (bounds.Top + bounds.Bottom) / 2)); handles.Add(MakeRect(bounds.Right, (bounds.Top + bounds.Bottom) / 2)); } handles.Add(MakeRect(bounds.Left, bounds.Bottom)); if (includeSideHandles) handles.Add(MakeRect((bounds.Left + bounds.Right) / 2, bounds.Bottom)); handles.Add(MakeRect(bounds.Right, bounds.Bottom)); return handles.ToArray(); } private static Rectangle MakeRect(int x, int y) { return new Rectangle(x - (HANDLE_SIZE / 2), y - (HANDLE_SIZE / 2), HANDLE_SIZE, HANDLE_SIZE); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace BTDB.KVDBLayer.BTreeMem { class BTreeLeafComp : IBTreeLeafNode, IBTreeNode { internal readonly long TransactionId; byte[]? _keyBytes; struct Member { internal ushort KeyOffset; internal ushort KeyLength; internal byte[] Value; } Member[] _keyValues; internal const long MaxTotalLen = ushort.MaxValue; internal const int MaxMembers = 30; BTreeLeafComp(long transactionId, int length) { TransactionId = transactionId; _keyValues = new Member[length]; } internal BTreeLeafComp(long transactionId, BTreeLeafMember[] newKeyValues) { Debug.Assert(newKeyValues.Length > 0 && newKeyValues.Length <= MaxMembers); TransactionId = transactionId; _keyBytes = new byte[newKeyValues.Sum(m => m.Key.Length)]; _keyValues = new Member[newKeyValues.Length]; ushort ofs = 0; for (var i = 0; i < newKeyValues.Length; i++) { _keyValues[i] = new Member { KeyOffset = ofs, KeyLength = (ushort)newKeyValues[i].Key.Length, Value = newKeyValues[i].Value }; Array.Copy(newKeyValues[i].Key, 0, _keyBytes, ofs, _keyValues[i].KeyLength); ofs += _keyValues[i].KeyLength; } } BTreeLeafComp(long transactionId, byte[] newKeyBytes, Member[] newKeyValues) { TransactionId = transactionId; _keyBytes = newKeyBytes; _keyValues = newKeyValues; } internal static IBTreeNode CreateFirst(ref CreateOrUpdateCtx ctx) { Debug.Assert(ctx.Key.Length <= MaxTotalLen); var result = new BTreeLeafComp(ctx.TransactionId, 1); result._keyBytes = ctx.Key.ToArray(); result._keyValues[0] = new Member { KeyOffset = 0, KeyLength = (ushort)result._keyBytes.Length, Value = ctx.Value.ToArray() }; return result; } int Find(in ReadOnlySpan<byte> key) { var left = 0; var keyValues = _keyValues; var right = keyValues.Length; var keyBytes = _keyBytes; while (left < right) { var middle = (left + right) / 2; int currentKeyOfs = keyValues[middle].KeyOffset; int currentKeyLen = keyValues[middle].KeyLength; var result = key.SequenceCompareTo(keyBytes.AsSpan(currentKeyOfs, currentKeyLen)); if (result == 0) { return middle * 2 + 1; } if (result < 0) { right = middle; } else { left = middle + 1; } } return left * 2; } public void CreateOrUpdate(ref CreateOrUpdateCtx ctx) { var index = Find(ctx.Key); if ((index & 1) == 1) { index = (int)((uint)index / 2); ctx.Created = false; ctx.KeyIndex = index; var m = _keyValues[index]; m.Value = ctx.Value.ToArray(); var leaf = this; if (ctx.TransactionId != TransactionId) { leaf = new BTreeLeafComp(ctx.TransactionId, _keyValues.Length); Array.Copy(_keyValues, leaf._keyValues, _keyValues.Length); leaf._keyBytes = _keyBytes; ctx.Node1 = leaf; ctx.Update = true; } leaf._keyValues[index] = m; ctx.Stack.Add(new NodeIdxPair { Node = leaf, Idx = index }); return; } if ((long)_keyBytes!.Length + ctx.Key.Length > MaxTotalLen) { var currentKeyValues = new BTreeLeafMember[_keyValues.Length]; for (var i = 0; i < currentKeyValues.Length; i++) { var member = _keyValues[i]; currentKeyValues[i] = new BTreeLeafMember { Key = _keyBytes.AsSpan(member.KeyOffset, member.KeyLength).ToArray(), Value = member.Value }; } new BTreeLeaf(ctx.TransactionId - 1, currentKeyValues).CreateOrUpdate(ref ctx); return; } index = index / 2; ctx.Created = true; ctx.KeyIndex = index; var newKey = ctx.Key; if (_keyValues.Length < MaxMembers) { var newKeyValues = new Member[_keyValues.Length + 1]; var newKeyBytes = new byte[_keyBytes.Length + newKey.Length]; Array.Copy(_keyValues, 0, newKeyValues, 0, index); var ofs = (ushort)(index == 0 ? 0 : newKeyValues[index - 1].KeyOffset + newKeyValues[index - 1].KeyLength); newKeyValues[index] = new Member { KeyOffset = ofs, KeyLength = (ushort)newKey.Length, Value = ctx.Value.ToArray() }; Array.Copy(_keyBytes, 0, newKeyBytes, 0, ofs); newKey.CopyTo(newKeyBytes.AsSpan(ofs)); Array.Copy(_keyBytes, ofs, newKeyBytes, ofs + newKey.Length, _keyBytes.Length - ofs); Array.Copy(_keyValues, index, newKeyValues, index + 1, _keyValues.Length - index); RecalculateOffsets(newKeyValues); var leaf = this; if (ctx.TransactionId != TransactionId) { leaf = new BTreeLeafComp(ctx.TransactionId, newKeyBytes, newKeyValues); ctx.Node1 = leaf; ctx.Update = true; } else { _keyValues = newKeyValues; _keyBytes = newKeyBytes; } ctx.Stack.Add(new NodeIdxPair { Node = leaf, Idx = index }); return; } ctx.Split = true; var keyCountLeft = (_keyValues.Length + 1) / 2; var keyCountRight = _keyValues.Length + 1 - keyCountLeft; var leftNode = new BTreeLeafComp(ctx.TransactionId, keyCountLeft); var rightNode = new BTreeLeafComp(ctx.TransactionId, keyCountRight); ctx.Node1 = leftNode; ctx.Node2 = rightNode; if (index < keyCountLeft) { Array.Copy(_keyValues, 0, leftNode._keyValues, 0, index); var ofs = (ushort)(index == 0 ? 0 : _keyValues[index - 1].KeyOffset + _keyValues[index - 1].KeyLength); leftNode._keyValues[index] = new Member { KeyOffset = ofs, KeyLength = (ushort)newKey.Length, Value = ctx.Value.ToArray() }; Array.Copy(_keyValues, index, leftNode._keyValues, index + 1, keyCountLeft - index - 1); Array.Copy(_keyValues, keyCountLeft - 1, rightNode._keyValues, 0, keyCountRight); var leftKeyBytesLen = _keyValues[keyCountLeft - 1].KeyOffset + newKey.Length; var newKeyBytes = new byte[leftKeyBytesLen]; Array.Copy(_keyBytes, 0, newKeyBytes, 0, ofs); newKey.CopyTo(newKeyBytes.AsSpan(ofs)); Array.Copy(_keyBytes, ofs, newKeyBytes, ofs + newKey.Length, leftKeyBytesLen - (ofs + newKey.Length)); leftNode._keyBytes = newKeyBytes; newKeyBytes = new byte[_keyBytes.Length + newKey.Length - leftKeyBytesLen]; Array.Copy(_keyBytes, leftKeyBytesLen - newKey.Length, newKeyBytes, 0, newKeyBytes.Length); rightNode._keyBytes = newKeyBytes; ctx.Stack.Add(new NodeIdxPair { Node = leftNode, Idx = index }); ctx.SplitInRight = false; RecalculateOffsets(leftNode._keyValues); } else { Array.Copy(_keyValues, 0, leftNode._keyValues, 0, keyCountLeft); var leftKeyBytesLen = _keyValues[keyCountLeft].KeyOffset; var newKeyBytes = new byte[leftKeyBytesLen]; Array.Copy(_keyBytes, 0, newKeyBytes, 0, leftKeyBytesLen); leftNode._keyBytes = newKeyBytes; newKeyBytes = new byte[_keyBytes.Length + newKey.Length - leftKeyBytesLen]; var ofs = (index == _keyValues.Length ? _keyBytes.Length : _keyValues[index].KeyOffset) - leftKeyBytesLen; Array.Copy(_keyBytes, leftKeyBytesLen, newKeyBytes, 0, ofs); newKey.CopyTo(newKeyBytes.AsSpan(ofs)); Array.Copy(_keyBytes, ofs + leftKeyBytesLen, newKeyBytes, ofs + newKey.Length, _keyBytes.Length - ofs - leftKeyBytesLen); rightNode._keyBytes = newKeyBytes; Array.Copy(_keyValues, keyCountLeft, rightNode._keyValues, 0, index - keyCountLeft); rightNode._keyValues[index - keyCountLeft] = new Member { KeyOffset = 0, KeyLength = (ushort)newKey.Length, Value = ctx.Value.ToArray(), }; Array.Copy(_keyValues, index, rightNode._keyValues, index - keyCountLeft + 1, keyCountLeft + keyCountRight - 1 - index); ctx.Stack.Add(new NodeIdxPair { Node = rightNode, Idx = index - keyCountLeft }); ctx.SplitInRight = true; } RecalculateOffsets(rightNode._keyValues); } public FindResult FindKey(List<NodeIdxPair> stack, out long keyIndex, in ReadOnlySpan<byte> key) { var idx = Find(key); FindResult result; if ((idx & 1) == 1) { result = FindResult.Exact; idx = (int)((uint)idx / 2); } else { result = FindResult.Previous; idx = (int)((uint)idx / 2) - 1; } stack.Add(new NodeIdxPair { Node = this, Idx = idx }); keyIndex = idx; return result; } public long CalcKeyCount() { return _keyValues.Length; } public byte[] GetLeftMostKey() { Debug.Assert(_keyValues[0].KeyOffset == 0); return _keyBytes.AsSpan(0, _keyValues[0].KeyLength).ToArray(); } public void FillStackByIndex(List<NodeIdxPair> stack, long keyIndex) { stack.Add(new NodeIdxPair { Node = this, Idx = (int)keyIndex }); } public long FindLastWithPrefix(in ReadOnlySpan<byte> prefix) { var left = 0; var keyValues = _keyValues; var right = keyValues.Length - 1; var keyBytes = _keyBytes; int result; int currentKeyOfs; int currentKeyLen; while (left < right) { var middle = (left + right) / 2; currentKeyOfs = keyValues[middle].KeyOffset; currentKeyLen = keyValues[middle].KeyLength; result = prefix.SequenceCompareTo(keyBytes.AsSpan(currentKeyOfs, Math.Min(currentKeyLen, prefix.Length))); if (result < 0) { right = middle; } else { left = middle + 1; } } currentKeyOfs = keyValues[left].KeyOffset; currentKeyLen = keyValues[left].KeyLength; result = prefix.SequenceCompareTo(keyBytes.AsSpan(currentKeyOfs, Math.Min(currentKeyLen, prefix.Length))); if (result < 0) left--; return left; } public bool NextIdxValid(int idx) { return idx + 1 < _keyValues.Length; } public void FillStackByLeftMost(List<NodeIdxPair> stack, int idx) { // Nothing to do } public void FillStackByRightMost(List<NodeIdxPair> stack, int i) { // Nothing to do } public int GetLastChildrenIdx() { return _keyValues.Length - 1; } public IBTreeNode EraseRange(long transactionId, long firstKeyIndex, long lastKeyIndex) { var newKeyValues = new Member[_keyValues.Length + firstKeyIndex - lastKeyIndex - 1]; var newKeyBytes = new byte[_keyBytes!.Length + _keyValues[firstKeyIndex].KeyOffset - _keyValues[lastKeyIndex].KeyOffset - _keyValues[lastKeyIndex].KeyLength]; Array.Copy(_keyValues, 0, newKeyValues, 0, (int)firstKeyIndex); Array.Copy(_keyValues, (int)lastKeyIndex + 1, newKeyValues, (int)firstKeyIndex, newKeyValues.Length - (int)firstKeyIndex); Array.Copy(_keyBytes, 0, newKeyBytes, 0, _keyValues[firstKeyIndex].KeyOffset); Array.Copy(_keyBytes, _keyValues[lastKeyIndex].KeyOffset + _keyValues[lastKeyIndex].KeyLength, newKeyBytes, _keyValues[firstKeyIndex].KeyOffset, newKeyBytes.Length - _keyValues[firstKeyIndex].KeyOffset); RecalculateOffsets(newKeyValues); if (TransactionId == transactionId) { _keyValues = newKeyValues; _keyBytes = newKeyBytes; return this; } return new BTreeLeafComp(transactionId, newKeyBytes, newKeyValues); } public IBTreeNode EraseOne(long transactionId, long keyIndex) { var newKeyValues = new Member[_keyValues.Length - 1]; var newKeyBytes = new byte[_keyBytes!.Length - _keyValues[keyIndex].KeyLength]; Array.Copy(_keyValues, 0, newKeyValues, 0, (int)keyIndex); Array.Copy(_keyValues, (int)keyIndex + 1, newKeyValues, (int)keyIndex, newKeyValues.Length - (int)keyIndex); Array.Copy(_keyBytes, 0, newKeyBytes, 0, _keyValues[keyIndex].KeyOffset); Array.Copy(_keyBytes, _keyValues[keyIndex].KeyOffset + _keyValues[keyIndex].KeyLength, newKeyBytes, _keyValues[keyIndex].KeyOffset, newKeyBytes.Length - _keyValues[keyIndex].KeyOffset); RecalculateOffsets(newKeyValues); if (TransactionId == transactionId) { _keyValues = newKeyValues; _keyBytes = newKeyBytes; return this; } return new BTreeLeafComp(transactionId, newKeyBytes, newKeyValues); } static void RecalculateOffsets(Member[] keyValues) { ushort ofs = 0; for (var i = 0; i < keyValues.Length; i++) { keyValues[i].KeyOffset = ofs; ofs += keyValues[i].KeyLength; } } public ReadOnlySpan<byte> GetKey(int idx) { return _keyBytes.AsSpan(_keyValues[idx].KeyOffset, _keyValues[idx].KeyLength); } public ReadOnlySpan<byte> GetMemberValue(int idx) { return _keyValues[idx].Value; } public void SetMemberValue(int idx, in ReadOnlySpan<byte> value) { _keyValues[idx].Value = value.ToArray(); } } }
using System; using Anotar.MetroLog; public class ClassWithLogging { public bool IsTraceEnabled() { return LogTo.IsTraceEnabled; } public void Trace() { LogTo.Trace(); } public void TraceString() { LogTo.Trace("TheMessage"); } public void TraceStringFunc() { LogTo.Trace(()=>"TheMessage"); } public void TraceStringParams() { LogTo.Trace("TheMessage {0}", 1); } public void TraceStringException() { LogTo.TraceException("TheMessage", new Exception()); } public void TraceStringExceptionFunc() { LogTo.TraceException(()=>"TheMessage", new Exception()); } public bool IsDebugEnabled() { return LogTo.IsDebugEnabled; } public void Debug() { LogTo.Debug(); } public void DebugString() { LogTo.Debug("TheMessage"); } public void DebugStringFunc() { LogTo.Debug(()=>"TheMessage"); } public void DebugStringParams() { LogTo.Debug("TheMessage {0}", 1); } public void DebugStringException() { LogTo.DebugException("TheMessage", new Exception()); } public void DebugStringExceptionFunc() { LogTo.DebugException(()=>"TheMessage", new Exception()); } public bool IsInfoEnabled() { return LogTo.IsInfoEnabled; } public void Info() { LogTo.Info(); } public void InfoString() { LogTo.Info("TheMessage"); } public void InfoStringFunc() { LogTo.Info(()=>"TheMessage"); } public void InfoStringParams() { LogTo.Info("TheMessage {0}", 1); } public void InfoStringException() { LogTo.InfoException("TheMessage", new Exception()); } public void InfoStringExceptionFunc() { LogTo.InfoException(()=>"TheMessage", new Exception()); } public bool IsWarnEnabled() { return LogTo.IsWarnEnabled; } public void Warn() { LogTo.Warn(); } public void WarnString() { LogTo.Warn("TheMessage"); } public void WarnStringFunc() { LogTo.Warn(()=>"TheMessage"); } public void WarnStringParams() { LogTo.Warn("TheMessage {0}", 1); } public void WarnStringException() { LogTo.WarnException("TheMessage", new Exception()); } public void WarnStringExceptionFunc() { LogTo.WarnException(()=>"TheMessage", new Exception()); } public bool IsErrorEnabled() { return LogTo.IsErrorEnabled; } public void Error() { LogTo.Error(); } public void ErrorString() { LogTo.Error("TheMessage"); } public void ErrorStringFunc() { LogTo.Error(()=>"TheMessage"); } public void ErrorStringParams() { LogTo.Error("TheMessage {0}", 1); } public void ErrorStringException() { LogTo.ErrorException("TheMessage", new Exception()); } public void ErrorStringExceptionFunc() { LogTo.ErrorException(()=>"TheMessage", new Exception()); } public bool IsFatalEnabled() { return LogTo.IsFatalEnabled; } public void Fatal() { LogTo.Fatal(); } public void FatalString() { LogTo.Fatal("TheMessage"); } public void FatalStringFunc() { LogTo.Fatal(()=>"TheMessage"); } public void FatalStringParams() { LogTo.Fatal("TheMessage {0}", 1); } public void FatalStringException() { LogTo.FatalException("TheMessage", new Exception()); } public void FatalStringExceptionFunc() { LogTo.FatalException(()=>"TheMessage", new Exception()); } }
// 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.Text; using System.Runtime.InteropServices; using System.Globalization; namespace System.DirectoryServices.Interop { [StructLayout(LayoutKind.Sequential)] internal struct SystemTime { public ushort wYear; public ushort wMonth; public ushort wDayOfWeek; public ushort wDay; public ushort wHour; public ushort wMinute; public ushort wSecond; public ushort wMilliseconds; } [StructLayout(LayoutKind.Sequential)] internal class DnWithBinary { public int dwLength; public IntPtr lpBinaryValue; // GUID of directory object public IntPtr pszDNString; // Distinguished Name } [StructLayout(LayoutKind.Sequential)] internal class DnWithString { public IntPtr pszStringValue; // associated value public IntPtr pszDNString; // Distinguished Name } /// <summary> /// Helper class for dealing with struct AdsValue. /// </summary> internal class AdsValueHelper { public AdsValue adsvalue; private GCHandle _pinnedHandle; public AdsValueHelper(AdsValue adsvalue) { this.adsvalue = adsvalue; } public AdsValueHelper(object managedValue) { AdsType adsType = GetAdsTypeForManagedType(managedValue.GetType()); SetValue(managedValue, adsType); } public AdsValueHelper(object managedValue, AdsType adsType) { SetValue(managedValue, adsType); } public long LowInt64 { get => (uint)adsvalue.generic.a + (((long)adsvalue.generic.b) << 32); set { adsvalue.generic.a = (int)(value & 0xFFFFFFFF); adsvalue.generic.b = (int)(value >> 32); } } ~AdsValueHelper() { if (_pinnedHandle.IsAllocated) { _pinnedHandle.Free(); } } private AdsType GetAdsTypeForManagedType(Type type) { // Consider this code is only excercised by DirectorySearcher // it just translates the types needed by such a component, if more managed // types are to be used in the future, this function needs to be expanded. if (type == typeof(int)) { return AdsType.ADSTYPE_INTEGER; } if (type == typeof(long)) { return AdsType.ADSTYPE_LARGE_INTEGER; } if (type == typeof(bool)) { return AdsType.ADSTYPE_BOOLEAN; } return AdsType.ADSTYPE_UNKNOWN; } public AdsValue GetStruct() => adsvalue; private static ushort LowOfInt(int i) => unchecked((ushort)(i & 0xFFFF)); private static ushort HighOfInt(int i) => unchecked((ushort)((i >> 16) & 0xFFFF)); public object GetValue() { switch ((AdsType)adsvalue.dwType) { // Common for DNS and LDAP. case AdsType.ADSTYPE_UTC_TIME: { var st = new SystemTime() { wYear = LowOfInt(adsvalue.generic.a), wMonth = HighOfInt(adsvalue.generic.a), wDayOfWeek = LowOfInt(adsvalue.generic.b), wDay = HighOfInt(adsvalue.generic.b), wHour = LowOfInt(adsvalue.generic.c), wMinute = HighOfInt(adsvalue.generic.c), wSecond = LowOfInt(adsvalue.generic.d), wMilliseconds = HighOfInt(adsvalue.generic.d) }; return new DateTime(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); } case AdsType.ADSTYPE_DN_WITH_BINARY: { var dnb = new DnWithBinary(); Marshal.PtrToStructure(adsvalue.pointer.value, dnb); byte[] bytes = new byte[dnb.dwLength]; Marshal.Copy(dnb.lpBinaryValue, bytes, 0, dnb.dwLength); var strb = new StringBuilder(); var binaryPart = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { string s = bytes[i].ToString("X", CultureInfo.InvariantCulture); if (s.Length == 1) { binaryPart.Append("0"); } binaryPart.Append(s); } strb.Append("B:"); strb.Append(binaryPart.Length); strb.Append(":"); strb.Append(binaryPart.ToString()); strb.Append(":"); strb.Append(Marshal.PtrToStringUni(dnb.pszDNString)); return strb.ToString(); } case AdsType.ADSTYPE_DN_WITH_STRING: { var dns = new DnWithString(); Marshal.PtrToStructure(adsvalue.pointer.value, dns); string strValue = Marshal.PtrToStringUni(dns.pszStringValue) ?? string.Empty; var strb = new StringBuilder(); strb.Append("S:"); strb.Append(strValue.Length); strb.Append(":"); strb.Append(strValue); strb.Append(":"); strb.Append(Marshal.PtrToStringUni(dns.pszDNString)); return strb.ToString(); } case AdsType.ADSTYPE_DN_STRING: case AdsType.ADSTYPE_CASE_EXACT_STRING: case AdsType.ADSTYPE_CASE_IGNORE_STRING: case AdsType.ADSTYPE_PRINTABLE_STRING: case AdsType.ADSTYPE_NUMERIC_STRING: case AdsType.ADSTYPE_OBJECT_CLASS: // The value is a String. return Marshal.PtrToStringUni(adsvalue.pointer.value); case AdsType.ADSTYPE_BOOLEAN: // The value is a bool. return adsvalue.generic.a != 0; case AdsType.ADSTYPE_INTEGER: // The value is an int. return adsvalue.generic.a; case AdsType.ADSTYPE_NT_SECURITY_DESCRIPTOR: case AdsType.ADSTYPE_OCTET_STRING: case AdsType.ADSTYPE_PROV_SPECIFIC: // The value is a byte[]. int len = adsvalue.octetString.length; byte[] value = new byte[len]; Marshal.Copy(adsvalue.octetString.value, value, 0, len); return value; case AdsType.ADSTYPE_INVALID: throw new InvalidOperationException(SR.DSConvertTypeInvalid); case AdsType.ADSTYPE_LARGE_INTEGER: return LowInt64; // Not used in LDAP case AdsType.ADSTYPE_CASEIGNORE_LIST: case AdsType.ADSTYPE_OCTET_LIST: case AdsType.ADSTYPE_PATH: case AdsType.ADSTYPE_POSTALADDRESS: case AdsType.ADSTYPE_TIMESTAMP: case AdsType.ADSTYPE_NETADDRESS: case AdsType.ADSTYPE_FAXNUMBER: case AdsType.ADSTYPE_EMAIL: case AdsType.ADSTYPE_BACKLINK: case AdsType.ADSTYPE_HOLD: case AdsType.ADSTYPE_TYPEDNAME: case AdsType.ADSTYPE_REPLICAPOINTER: case AdsType.ADSTYPE_UNKNOWN: return new NotImplementedException(SR.Format(SR.DSAdsvalueTypeNYI, "0x" + Convert.ToString(adsvalue.dwType, 16))); default: return new ArgumentException(SR.Format(SR.DSConvertFailed, "0x" + Convert.ToString(LowInt64, 16), "0x" + Convert.ToString(adsvalue.dwType, 16))); } } public object GetVlvValue() { var vlv = new AdsVLV(); Marshal.PtrToStructure(adsvalue.octetString.value, vlv); byte[] bytes = null; if (vlv.contextID != (IntPtr)0 && vlv.contextIDlength != 0) { bytes = new byte[vlv.contextIDlength]; Marshal.Copy(vlv.contextID, bytes, 0, vlv.contextIDlength); } return new DirectoryVirtualListView { Offset = vlv.offset, ApproximateTotal = vlv.contentCount, DirectoryVirtualListViewContext = new DirectoryVirtualListViewContext(bytes) }; } private unsafe void SetValue(object managedValue, AdsType adsType) { adsvalue = new AdsValue() { dwType = (int)adsType }; switch (adsType) { case AdsType.ADSTYPE_INTEGER: adsvalue.generic.a = (int)managedValue; adsvalue.generic.b = 0; break; case AdsType.ADSTYPE_LARGE_INTEGER: LowInt64 = (long)managedValue; break; case AdsType.ADSTYPE_BOOLEAN: LowInt64 = (bool)managedValue ? -1 : 0; break; case AdsType.ADSTYPE_CASE_IGNORE_STRING: _pinnedHandle = GCHandle.Alloc(managedValue, GCHandleType.Pinned); adsvalue.pointer.value = _pinnedHandle.AddrOfPinnedObject(); break; case AdsType.ADSTYPE_PROV_SPECIFIC: byte[] bytes = (byte[])managedValue; // Filling in an ADS_PROV_SPECIFIC struct. // 1st dword (our member a) is DWORD dwLength. // 2nd dword (our member b) is byte *lpValue. adsvalue.octetString.length = bytes.Length; _pinnedHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned); adsvalue.octetString.value = _pinnedHandle.AddrOfPinnedObject(); break; default: throw new NotImplementedException(SR.Format(SR.DSAdsvalueTypeNYI, "0x" + Convert.ToString((int)adsType, 16))); } } } }
/* ==================================================================== */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Text; using System.Xml; using System.IO; using System.Threading; using System.Reflection; using System.CodeDom; using System.CodeDom.Compiler; using Microsoft.VisualBasic; namespace Oranikle.ReportDesigner { /// <summary> /// Summary description for CodeCtl. /// </summary> internal class CodeCtl : Oranikle.ReportDesigner.Base.BaseControl, IProperty { static internal long Counter; // counter used for unique expression count private DesignXmlDraw _Draw; private System.Windows.Forms.Label label1; private Oranikle.Studio.Controls.StyledButton bCheckSyntax; private System.Windows.Forms.Panel panel1; private Oranikle.Studio.Controls.CustomTextControl tbCode; private System.Windows.Forms.ListBox lbErrors; private System.Windows.Forms.Splitter splitter1; private System.Windows.Forms.Label label2; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal CodeCtl(DesignXmlDraw dxDraw) { _Draw = dxDraw; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitValues(); } private void InitValues() { XmlNode rNode = _Draw.GetReportNode(); XmlNode cNode = _Draw.GetNamedChildNode(rNode, "Code"); tbCode.Text = ""; if (cNode == null) return; StringReader tr = new StringReader(cNode.InnerText); List<string> ar = new List<string>(); while (tr.Peek() >= 0) { string line = tr.ReadLine(); ar.Add(line); } tr.Close(); // tbCode.Lines = ar.ToArray("".GetType()) as string[]; tbCode.Lines = ar.ToArray(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.bCheckSyntax = new Oranikle.Studio.Controls.StyledButton(); this.panel1 = new System.Windows.Forms.Panel(); this.tbCode = new Oranikle.Studio.Controls.CustomTextControl(); this.splitter1 = new System.Windows.Forms.Splitter(); this.lbErrors = new System.Windows.Forms.ListBox(); this.label2 = new System.Windows.Forms.Label(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(98, 6); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(144, 16); this.label1.TabIndex = 0; this.label1.Text = "Visual Basic Function Code"; // // bCheckSyntax // this.bCheckSyntax.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.bCheckSyntax.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245))))); this.bCheckSyntax.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225))))); this.bCheckSyntax.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.bCheckSyntax.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200))))); this.bCheckSyntax.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.bCheckSyntax.Font = new System.Drawing.Font("Arial", 9F); this.bCheckSyntax.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90))))); this.bCheckSyntax.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bCheckSyntax.Location = new System.Drawing.Point(365, 4); this.bCheckSyntax.Name = "bCheckSyntax"; this.bCheckSyntax.OverriddenSize = null; this.bCheckSyntax.Size = new System.Drawing.Size(82, 21); this.bCheckSyntax.TabIndex = 2; this.bCheckSyntax.Text = "Check Syntax"; this.bCheckSyntax.UseVisualStyleBackColor = true; this.bCheckSyntax.Click += new System.EventHandler(this.bCheckSyntax_Click); // // panel1 // this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panel1.Controls.Add(this.tbCode); this.panel1.Controls.Add(this.splitter1); this.panel1.Controls.Add(this.lbErrors); this.panel1.Location = new System.Drawing.Point(13, 31); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(439, 252); this.panel1.TabIndex = 4; // // tbCode // this.tbCode.AcceptsReturn = true; this.tbCode.AcceptsTab = true; this.tbCode.AddX = 0; this.tbCode.AddY = 0; this.tbCode.AllowSpace = false; this.tbCode.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbCode.BorderColor = System.Drawing.Color.LightGray; this.tbCode.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.tbCode.ChangeVisibility = false; this.tbCode.ChildControl = null; this.tbCode.ConvertEnterToTab = true; this.tbCode.ConvertEnterToTabForDialogs = false; this.tbCode.Decimals = 0; this.tbCode.DisplayList = new object[0]; this.tbCode.HideSelection = false; this.tbCode.HitText = Oranikle.Studio.Controls.HitText.String; this.tbCode.Location = new System.Drawing.Point(87, 0); this.tbCode.Multiline = true; this.tbCode.Name = "tbCode"; this.tbCode.OnDropDownCloseFocus = true; this.tbCode.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.tbCode.SelectType = 0; this.tbCode.Size = new System.Drawing.Size(352, 252); this.tbCode.TabIndex = 2; this.tbCode.UseValueForChildsVisibilty = false; this.tbCode.Value = true; this.tbCode.WordWrap = false; // // splitter1 // this.splitter1.Location = new System.Drawing.Point(0, 0); this.splitter1.Name = "splitter1"; this.splitter1.Size = new System.Drawing.Size(5, 252); this.splitter1.TabIndex = 1; this.splitter1.TabStop = false; // // lbErrors // this.lbErrors.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.lbErrors.HorizontalScrollbar = true; this.lbErrors.IntegralHeight = false; this.lbErrors.Location = new System.Drawing.Point(0, 0); this.lbErrors.Name = "lbErrors"; this.lbErrors.Size = new System.Drawing.Size(82, 252); this.lbErrors.TabIndex = 0; this.lbErrors.SelectedIndexChanged += new System.EventHandler(this.lbErrors_SelectedIndexChanged); // // label2 // this.label2.Location = new System.Drawing.Point(15, 7); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(69, 15); this.label2.TabIndex = 5; this.label2.Text = "Msgs"; // // CodeCtl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.Controls.Add(this.label2); this.Controls.Add(this.panel1); this.Controls.Add(this.bCheckSyntax); this.Controls.Add(this.label1); this.Name = "CodeCtl"; this.Size = new System.Drawing.Size(472, 288); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); } #endregion public bool IsValid() { return true; } public void Apply() { XmlNode rNode = _Draw.GetReportNode(); if (tbCode.Text.Trim().Length > 0) _Draw.SetElement(rNode, "Code", tbCode.Text); else _Draw.RemoveElement(rNode, "Code"); } private void bCheckSyntax_Click(object sender, System.EventArgs e) { CheckAssembly(); } private void CheckAssembly() { lbErrors.Items.Clear(); // clear out existing items // Generate the proxy source code List<string> lines = new List<string>(); // hold lines in array in case of error VBCodeProvider vbcp = new VBCodeProvider(); StringBuilder sb = new StringBuilder(); // Generate code with the following general form //Imports System //Imports Microsoft.VisualBasic //Imports System.Convert //Imports System.Math //Namespace Oranikle Reporting.vbgen //Public Class MyClassn // where n is a uniquely generated integer //Sub New() //End Sub // ' this is the code in the <Code> tag //End Class //End Namespace string unique = Interlocked.Increment(ref CodeCtl.Counter).ToString(); lines.Add("Imports System"); lines.Add("Imports Microsoft.VisualBasic"); lines.Add("Imports System.Convert"); lines.Add("Imports System.Math"); lines.Add("Imports Oranikle.Report.Engine"); lines.Add("Namespace Oranikle Reporting.vbgen"); string classname = "MyClass" + unique; lines.Add("Public Class " + classname); lines.Add("Private Shared _report As CodeReport"); lines.Add("Sub New()"); lines.Add("End Sub"); lines.Add("Sub New(byVal def As Report)"); lines.Add(classname + "._report = New CodeReport(def)"); lines.Add("End Sub"); lines.Add("Public Shared ReadOnly Property Report As CodeReport"); lines.Add("Get"); lines.Add("Return " + classname + "._report"); lines.Add("End Get"); lines.Add("End Property"); int pre_lines = lines.Count; // number of lines prior to user VB code // Read and write code as lines StringReader tr = new StringReader(this.tbCode.Text); while (tr.Peek() >= 0) { string line = tr.ReadLine(); lines.Add(line); } tr.Close(); lines.Add("End Class"); lines.Add("End Namespace"); foreach (string l in lines) { sb.Append(l); sb.Append(Environment.NewLine); } string vbcode = sb.ToString(); // Create Assembly CompilerParameters cp = new CompilerParameters(); cp.ReferencedAssemblies.Add("System.dll"); string re = AppDomain.CurrentDomain.BaseDirectory + "RdlEngine.dll"; cp.ReferencedAssemblies.Add(re); // also allow access to classes that have been added to report XmlNode rNode = _Draw.GetReportNode(); XmlNode cNode = _Draw.GetNamedChildNode(rNode, "CodeModules"); if (cNode != null) { foreach (XmlNode xn in cNode.ChildNodes) { if (xn.Name != "CodeModule") continue; cp.ReferencedAssemblies.Add(xn.InnerText); } } cp.GenerateExecutable = false; cp.GenerateInMemory = true; cp.IncludeDebugInformation = false; CompilerResults cr = vbcp.CompileAssemblyFromSource(cp, vbcode); if(cr.Errors.Count > 0) { StringBuilder err = new StringBuilder(string.Format("Code has {0} error(s).", cr.Errors.Count)); foreach (CompilerError ce in cr.Errors) { lbErrors.Items.Add(string.Format("Ln {0}- {1}", ce.Line - pre_lines, ce.ErrorText)); } } else MessageBox.Show("No errors", "Code Verification"); return ; } private void lbErrors_SelectedIndexChanged(object sender, System.EventArgs e) { if (lbErrors.Items.Count == 0) return; string line = lbErrors.Items[lbErrors.SelectedIndex] as string; if (!line.StartsWith("Ln")) return; int l = line.IndexOf('-'); if (l < 0) return; line = line.Substring(3, l-3); try { int i = Convert.ToInt32(line); Goto(i); } catch {} // we don't care about the error return; } public void Goto(int nLine) { int offset = 0; nLine = Math.Min(nLine, tbCode.Lines.Length); // don't go off the end for ( int i = 0; i < nLine - 1 && i < tbCode.Lines.Length; ++i ) offset += (this.tbCode.Lines[i].Length + 2); Control savectl = this.ActiveControl; tbCode.Focus(); tbCode.Select( offset, this.tbCode.Lines[nLine > 0? nLine-1: 0].Length); this.ActiveControl = savectl; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace Serialize.LiquidNET { [Serializable()] public class PropertyMap : IEnumerable { private ArrayList _List; internal PropertyMap() { _List = new ArrayList(); } public PropertyMap PrimaryKeyProperties { get { PropertyMap map = new PropertyMap(); foreach (PropertyDef def in this) { if (def.KeyType == KeyType.PrimaryKey) { map.AddPropertyDef(def.PropertyName, def.ColumnIndex, def.ColumnName, def.DBType, def.SystemType, def.KeyType); } } return map; } } internal void AddPropertyDef( string aPropertyName, int aColumnIndex, string aColumnName) { PropertyDef def = new PropertyDef( aPropertyName, aColumnIndex, aColumnName); _List.Add(def); } internal void AddPropertyDef( string aPropertyName, int aColumnIndex, string aColumnName, KeyType aKeyType) { PropertyDef def = new PropertyDef( aPropertyName, aColumnIndex, aColumnName, aKeyType); _List.Add(def); } internal void AddPropertyDef( string aPropertyName, int aColumnIndex, string aColumnName, string aDBType, string aSystemType, KeyType aKeyType) { PropertyDef def = new PropertyDef( aPropertyName, aColumnIndex, aColumnName, aDBType, aSystemType, aKeyType); _List.Add(def); } internal void AddPropertyDef( int aColumnIndex, string aPropertyName, string aColumnName, string aDBType, string aSystemType, KeyType aKeyType) { PropertyDef def = new PropertyDef( aPropertyName, aColumnIndex, aColumnName, aDBType, aSystemType, aKeyType); _List.Add(def); } internal void AddPropertyDef( string aPropertyName, int aColumnIndex, string aColumnName, string aDBType, string aSystemType, KeyType aKeyType, string aFKField, string aFKObject, string aFKRelation) { PropertyDef def = new PropertyDef( aPropertyName, aColumnIndex, aColumnName, aDBType, aSystemType, aKeyType); def.FKField = aFKField; def.FKObject = aFKObject; def.FKRelation = aFKRelation; _List.Add(def); } internal void AddPropertyDef( int aColumnIndex, string aPropertyName, string aColumnName, string aDBType, string aSystemType, KeyType aKeyType, string aFKField, string aFKObject, string aFKRelation) { PropertyDef def = new PropertyDef( aPropertyName, aColumnIndex, aColumnName, aDBType, aSystemType, aKeyType); def.FKField = aFKField; def.FKObject = aFKObject; def.FKRelation = aFKRelation; _List.Add(def); } public string ColumnName(string aPropertyName) { string ret = String.Empty; foreach (PropertyDef def in this) { if (def.PropertyName.Equals(aPropertyName)) { ret = def.ColumnName; break; } } return ret; } public PropertyDef GetWithColumnName(string aColumnName) { PropertyDef ret = null; foreach (PropertyDef def in this) { if (def.ColumnName.Equals(aColumnName)) { ret = def; break; } } return ret; } public PropertyDef GetWithPropertyName(string aPropertyName) { PropertyDef ret = null; foreach (PropertyDef def in this) { //if (def.PropertyName.Equals(aPropertyName)) if (def.ColumnName.Equals(aPropertyName)) { ret = def; break; } } return ret; } internal PropertyDef GetRelationProperty(string aRelation) { PropertyDef ret = null; foreach (PropertyDef def in this) { if (def.FKRelation.Equals(aRelation)) { ret = def; break; } } return ret; } public PropertyDef this[int aIndex] { get { return (PropertyDef)_List[aIndex]; } } public int Count { get { return _List.Count; } } public IEnumerator GetEnumerator() { return _List.GetEnumerator(); } } }
using System; using System.Diagnostics; using NBitcoin.BouncyCastle.Crypto.Utilities; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Crypto.Digests { /// <summary> /// Implementation of Keccak based on following KeccakNISTInterface.c from http://keccak.noekeon.org/ /// </summary> /// <remarks> /// Following the naming conventions used in the C source code to enable easy review of the implementation. /// </remarks> internal class KeccakDigest #if !NO_BC : IDigest, IMemoable #endif { private static readonly ulong[] KeccakRoundConstants = new ulong[]{ 0x0000000000000001UL, 0x0000000000008082UL, 0x800000000000808aUL, 0x8000000080008000UL, 0x000000000000808bUL, 0x0000000080000001UL, 0x8000000080008081UL, 0x8000000000008009UL, 0x000000000000008aUL, 0x0000000000000088UL, 0x0000000080008009UL, 0x000000008000000aUL, 0x000000008000808bUL, 0x800000000000008bUL, 0x8000000000008089UL, 0x8000000000008003UL, 0x8000000000008002UL, 0x8000000000000080UL, 0x000000000000800aUL, 0x800000008000000aUL, 0x8000000080008081UL, 0x8000000000008080UL, 0x0000000080000001UL, 0x8000000080008008UL }; private ulong[] state = new ulong[25]; protected byte[] dataQueue = new byte[192]; protected int rate; protected int bitsInQueue; protected int fixedOutputLength; protected bool squeezing; public KeccakDigest() : this(288) { } public KeccakDigest(int bitLength) { Init(bitLength); } public KeccakDigest(KeccakDigest source) { CopyIn(source); } private void CopyIn(KeccakDigest source) { Array.Copy(source.state, 0, this.state, 0, source.state.Length); Array.Copy(source.dataQueue, 0, this.dataQueue, 0, source.dataQueue.Length); this.rate = source.rate; this.bitsInQueue = source.bitsInQueue; this.fixedOutputLength = source.fixedOutputLength; this.squeezing = source.squeezing; } public virtual string AlgorithmName { get { return "Keccak-" + fixedOutputLength; } } public virtual int GetDigestSize() { return fixedOutputLength >> 3; } public virtual void Update(byte input) { Absorb(input); } public virtual void BlockUpdate(byte[] input, int inOff, int len) { Absorb(input, inOff, len); } public virtual int DoFinal(byte[] output, int outOff) { Squeeze(output, outOff, fixedOutputLength); Reset(); return GetDigestSize(); } /* * TODO Possible API change to support partial-byte suffixes. */ protected virtual int DoFinal(byte[] output, int outOff, byte partialByte, int partialBits) { if (partialBits > 0) { AbsorbBits(partialByte, partialBits); } Squeeze(output, outOff, fixedOutputLength); Reset(); return GetDigestSize(); } public virtual void Reset() { Init(fixedOutputLength); } /** * Return the size of block that the compression function is applied to in bytes. * * @return internal byte length of a block. */ public virtual int GetByteLength() { return rate >> 3; } private void Init(int bitLength) { switch (bitLength) { case 128: case 224: case 256: case 288: case 384: case 512: InitSponge(1600 - (bitLength << 1)); break; default: throw new ArgumentException("must be one of 128, 224, 256, 288, 384, or 512.", "bitLength"); } } private void InitSponge(int rate) { if (rate <= 0 || rate >= 1600 || (rate & 63) != 0) throw new InvalidOperationException("invalid rate value"); this.rate = rate; Array.Clear(state, 0, state.Length); Arrays.Fill(this.dataQueue, (byte)0); this.bitsInQueue = 0; this.squeezing = false; this.fixedOutputLength = (1600 - rate) >> 1; } protected void Absorb(byte data) { if ((bitsInQueue & 7) != 0) throw new InvalidOperationException("attempt to absorb with odd length queue"); if (squeezing) throw new InvalidOperationException("attempt to absorb while squeezing"); dataQueue[bitsInQueue >> 3] = data; if ((bitsInQueue += 8) == rate) { KeccakAbsorb(dataQueue, 0); bitsInQueue = 0; } } protected void Absorb(byte[] data, int off, int len) { if ((bitsInQueue & 7) != 0) throw new InvalidOperationException("attempt to absorb with odd length queue"); if (squeezing) throw new InvalidOperationException("attempt to absorb while squeezing"); int bytesInQueue = bitsInQueue >> 3; int rateBytes = rate >> 3; int available = rateBytes - bytesInQueue; if (len < available) { Array.Copy(data, off, dataQueue, bytesInQueue, len); this.bitsInQueue += len << 3; return; } int count = 0; if (bytesInQueue > 0) { Array.Copy(data, off, dataQueue, bytesInQueue, available); count += available; KeccakAbsorb(dataQueue, 0); } int remaining; while ((remaining = (len - count)) >= rateBytes) { KeccakAbsorb(data, off + count); count += rateBytes; } Array.Copy(data, off + count, dataQueue, 0, remaining); this.bitsInQueue = remaining << 3; } protected void AbsorbBits(int data, int bits) { if (bits < 1 || bits > 7) throw new ArgumentException("must be in the range 1 to 7", "bits"); if ((bitsInQueue & 7) != 0) throw new InvalidOperationException("attempt to absorb with odd length queue"); if (squeezing) throw new InvalidOperationException("attempt to absorb while squeezing"); int mask = (1 << bits) - 1; dataQueue[bitsInQueue >> 3] = (byte)(data & mask); // NOTE: After this, bitsInQueue is no longer a multiple of 8, so no more absorbs will work bitsInQueue += bits; } private void PadAndSwitchToSqueezingPhase() { Debug.Assert(bitsInQueue < rate); dataQueue[bitsInQueue >> 3] |= (byte)(1 << (bitsInQueue & 7)); if (++bitsInQueue == rate) { KeccakAbsorb(dataQueue, 0); } else { int full = bitsInQueue >> 6, partial = bitsInQueue & 63; int off = 0; for (int i = 0; i < full; ++i) { state[i] ^= Pack.LE_To_UInt64(dataQueue, off); off += 8; } if (partial > 0) { ulong mask = (1UL << partial) - 1UL; state[full] ^= Pack.LE_To_UInt64(dataQueue, off) & mask; } } state[(rate - 1) >> 6] ^= (1UL << 63); bitsInQueue = 0; squeezing = true; } protected void Squeeze(byte[] output, int offset, long outputLength) { if (!squeezing) { PadAndSwitchToSqueezingPhase(); } if ((outputLength & 7L) != 0L) throw new InvalidOperationException("outputLength not a multiple of 8"); long i = 0; while (i < outputLength) { if (bitsInQueue == 0) { KeccakExtract(); } int partialBlock = (int)System.Math.Min((long)bitsInQueue, outputLength - i); Array.Copy(dataQueue, (rate - bitsInQueue) >> 3, output, offset + (int)(i >> 3), partialBlock >> 3); bitsInQueue -= partialBlock; i += partialBlock; } } private void KeccakAbsorb(byte[] data, int off) { int count = rate >> 6; for (int i = 0; i < count; ++i) { state[i] ^= Pack.LE_To_UInt64(data, off); off += 8; } KeccakPermutation(); } private void KeccakExtract() { KeccakPermutation(); Pack.UInt64_To_LE(state, 0, rate >> 6, dataQueue, 0); this.bitsInQueue = rate; } private void KeccakPermutation() { ulong[] A = state; ulong a00 = A[ 0], a01 = A[ 1], a02 = A[ 2], a03 = A[ 3], a04 = A[ 4]; ulong a05 = A[ 5], a06 = A[ 6], a07 = A[ 7], a08 = A[ 8], a09 = A[ 9]; ulong a10 = A[10], a11 = A[11], a12 = A[12], a13 = A[13], a14 = A[14]; ulong a15 = A[15], a16 = A[16], a17 = A[17], a18 = A[18], a19 = A[19]; ulong a20 = A[20], a21 = A[21], a22 = A[22], a23 = A[23], a24 = A[24]; for (int i = 0; i < 24; i++) { // theta ulong c0 = a00 ^ a05 ^ a10 ^ a15 ^ a20; ulong c1 = a01 ^ a06 ^ a11 ^ a16 ^ a21; ulong c2 = a02 ^ a07 ^ a12 ^ a17 ^ a22; ulong c3 = a03 ^ a08 ^ a13 ^ a18 ^ a23; ulong c4 = a04 ^ a09 ^ a14 ^ a19 ^ a24; ulong d1 = (c1 << 1 | c1 >> -1) ^ c4; ulong d2 = (c2 << 1 | c2 >> -1) ^ c0; ulong d3 = (c3 << 1 | c3 >> -1) ^ c1; ulong d4 = (c4 << 1 | c4 >> -1) ^ c2; ulong d0 = (c0 << 1 | c0 >> -1) ^ c3; a00 ^= d1; a05 ^= d1; a10 ^= d1; a15 ^= d1; a20 ^= d1; a01 ^= d2; a06 ^= d2; a11 ^= d2; a16 ^= d2; a21 ^= d2; a02 ^= d3; a07 ^= d3; a12 ^= d3; a17 ^= d3; a22 ^= d3; a03 ^= d4; a08 ^= d4; a13 ^= d4; a18 ^= d4; a23 ^= d4; a04 ^= d0; a09 ^= d0; a14 ^= d0; a19 ^= d0; a24 ^= d0; // rho/pi c1 = a01 << 1 | a01 >> 63; a01 = a06 << 44 | a06 >> 20; a06 = a09 << 20 | a09 >> 44; a09 = a22 << 61 | a22 >> 3; a22 = a14 << 39 | a14 >> 25; a14 = a20 << 18 | a20 >> 46; a20 = a02 << 62 | a02 >> 2; a02 = a12 << 43 | a12 >> 21; a12 = a13 << 25 | a13 >> 39; a13 = a19 << 8 | a19 >> 56; a19 = a23 << 56 | a23 >> 8; a23 = a15 << 41 | a15 >> 23; a15 = a04 << 27 | a04 >> 37; a04 = a24 << 14 | a24 >> 50; a24 = a21 << 2 | a21 >> 62; a21 = a08 << 55 | a08 >> 9; a08 = a16 << 45 | a16 >> 19; a16 = a05 << 36 | a05 >> 28; a05 = a03 << 28 | a03 >> 36; a03 = a18 << 21 | a18 >> 43; a18 = a17 << 15 | a17 >> 49; a17 = a11 << 10 | a11 >> 54; a11 = a07 << 6 | a07 >> 58; a07 = a10 << 3 | a10 >> 61; a10 = c1; // chi c0 = a00 ^ (~a01 & a02); c1 = a01 ^ (~a02 & a03); a02 ^= ~a03 & a04; a03 ^= ~a04 & a00; a04 ^= ~a00 & a01; a00 = c0; a01 = c1; c0 = a05 ^ (~a06 & a07); c1 = a06 ^ (~a07 & a08); a07 ^= ~a08 & a09; a08 ^= ~a09 & a05; a09 ^= ~a05 & a06; a05 = c0; a06 = c1; c0 = a10 ^ (~a11 & a12); c1 = a11 ^ (~a12 & a13); a12 ^= ~a13 & a14; a13 ^= ~a14 & a10; a14 ^= ~a10 & a11; a10 = c0; a11 = c1; c0 = a15 ^ (~a16 & a17); c1 = a16 ^ (~a17 & a18); a17 ^= ~a18 & a19; a18 ^= ~a19 & a15; a19 ^= ~a15 & a16; a15 = c0; a16 = c1; c0 = a20 ^ (~a21 & a22); c1 = a21 ^ (~a22 & a23); a22 ^= ~a23 & a24; a23 ^= ~a24 & a20; a24 ^= ~a20 & a21; a20 = c0; a21 = c1; // iota a00 ^= KeccakRoundConstants[i]; } A[ 0] = a00; A[ 1] = a01; A[ 2] = a02; A[ 3] = a03; A[ 4] = a04; A[ 5] = a05; A[ 6] = a06; A[ 7] = a07; A[ 8] = a08; A[ 9] = a09; A[10] = a10; A[11] = a11; A[12] = a12; A[13] = a13; A[14] = a14; A[15] = a15; A[16] = a16; A[17] = a17; A[18] = a18; A[19] = a19; A[20] = a20; A[21] = a21; A[22] = a22; A[23] = a23; A[24] = a24; } #if !NO_BC public virtual IMemoable Copy() { return new KeccakDigest(this); } public virtual void Reset(IMemoable other) { CopyIn((KeccakDigest)other); } #endif } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace WebSharp { public class PassonStylesheet { protected Dictionary<Styleset, string> setDict; protected Dictionary<AttributeStyleset, string> aDict; public PassonStylesheet () { setDict = new Dictionary<Styleset, string> (); aDict = new Dictionary<AttributeStyleset, string> (); } public string this[Styleset sset] { get { if (!setDict.ContainsKey(sset)) { setDict [sset] = sset.Name == null ? "C" + setDict.Count : sset.Name; } return setDict [sset]; } } public string this[Styleset link, Styleset visited, Styleset hover, Styleset active] { get { return this[new AttributeStyleset(link, visited, hover, active)]; } } public string this[AttributeStyleset aset] { get { if (!aDict.ContainsKey(aset)) { aDict [aset] = "A" + aDict.Count.ToString("X"); } return aDict [aset]; } } public void ManualAdd(Styleset sset) { setDict [sset] = sset.Name == null ? "C" + setDict.Count : sset.Name; } public void ManualAdd(AttributeStyleset aset) { aDict [aset] = "A" + aDict.Count.ToString("X"); } public List<string> GetFormattedSheet () { List<string> sheet = new List<string> (); foreach(KeyValuePair<AttributeStyleset, string> KVP in aDict) { if (KVP.Key.Link != null) sheet.Add (String.Format("a.{0}:link {{{1}}}", KVP.Value, KVP.Key.Link.ToString())); if (KVP.Key.Visited != null) sheet.Add (String.Format("a.{0}:visited {{{1}}}", KVP.Value, KVP.Key.Visited.ToString())); if (KVP.Key.Hover != null) sheet.Add (String.Format("a.{0}:hover {{{1}}}", KVP.Value, KVP.Key.Hover.ToString())); if (KVP.Key.Active != null) sheet.Add (String.Format("a.{0}:active {{{1}}}", KVP.Value, KVP.Key.Active.ToString())); } foreach (KeyValuePair<Styleset, string> KVP in setDict) { sheet.Add (String.Format(".{0} {{{1}}}", KVP.Value, KVP.Key.ToString())); } return sheet; } } public class AttributeStyleset { public Styleset Link; public Styleset Visited; public Styleset Hover; public Styleset Active; public AttributeStyleset(Styleset link, Styleset visited, Styleset hover, Styleset active) { this.Link = link; this.Visited = visited; this.Hover = hover; this.Active = active; } public override int GetHashCode () { int hc = 0; if (Link != null) hc += Link.GetHashCode (); if (Visited != null) hc += Visited.GetHashCode (); if (Hover != null) hc += Hover.GetHashCode (); if (Active != null) hc += Active.GetHashCode (); return hc; } public override bool Equals (object obj) { if (obj == null) return false; AttributeStyleset aset = obj as AttributeStyleset; if (aset == null) return false; return (this.Link == aset.Link && this.Visited == aset.Visited && this.Hover == aset.Hover && this.Active == aset.Active); } } public class Styleset : Dictionary<string, string> { public string Name = null; public Styleset(params Style[] styles) : base() { foreach(Style S in styles) { this [S.property] = S.value; } } public void AddRange(IEnumerable<Style> i) { foreach(Style S in i) { this [S.property] = S.value; } } public override int GetHashCode () { string t = String.Empty; foreach(Style S in this) { t += S.property; } return t.GetHashCode (); } public override bool Equals (object obj) { if (obj == null) return false; Styleset S = obj as Styleset; if (S == null) return false; if (S.Count != this.Count) return false; foreach(bool r in S.Zip(this, (a, b) => (a.Key == b.Key && a.Value == b.Value))) { if (!r) return false; } return true; } public override string ToString () { return String.Join ("",this.Select((k) => String.Format("{0}:{1};", k.Key, k.Value))); } public static Styleset operator +(Styleset A, Styleset B) { Styleset C = new Styleset (); C.AddRange (A.Select(x => new Style(x.Key, x.Value))); C.AddRange (B.Select(x => new Style(x.Key, x.Value))); return C; } } public class Style : IComparable { public string property; public string value; public Style (string property, string value) { this.property = property; this.value = value; } public override int GetHashCode () { return (property).GetHashCode (); } public override bool Equals (object obj) { if (obj == null) return false; Style S = obj as Style; if (S == null) return false; if (this.property == S.property && this.value == S.value) return true; return false; } public int CompareTo(object obj) { if (obj == null) return 1; Style S = obj as Style; if (S == null) return 1; int ps = this.property.CompareTo (S.property); if (ps == 0){ return this.value.CompareTo (S.value); } else { return ps; } } public override string ToString () { return String.Format ("{0}:{1};", this.property, this.value); } public static implicit operator Style(KeyValuePair<string, string> KVP) { return new Style (KVP.Key, KVP.Value); } //BEGIN STANDARD STYLES //BACKGROUND public static Style BackgroundColor(byte r, byte g, byte b) {return new Style ("background-color", new Hexcolor(r, g, b).ToString());} public static Style BackgroundColor(Hexcolor color) {return new Style ("background-color", color.ToString());} public static Style BackgroundColor(string hex) {return new Style ("background-color", hex.StartsWith("#") ? hex : "#" + hex);} public static Style BackgroundImage(string urlpath) {return new Style ("background-image", String.Format("url({0})", urlpath));} public static Style BackgroundPosition(string value) {return new Style ("background-position", value);} public static Style BackgroundRepeat(Repeat value) {return new Style ("background-repeat", RepeatDict[value]);} public static Style BackgroundRepeat() {return new Style ("background-repeat", "inherit");} //BORDER AND OUTLINE public static Style Border(int widthpx, Border s, Hexcolor c) {return new Style ("border", String.Format("{0}px {1} {2}", widthpx, s.ToString().ToLower(), c.ToString()));} public static Style BorderRadius(int pxrad) {return new Style ("border-radius", pxrad+"px");} public static Style BorderTopLeftRadius(int pxrad) {return new Style ("border-top-left-radius", pxrad+"px");} public static Style BorderTopRightRadius(int pxrad) {return new Style ("border-top-right-radius", pxrad+"px");} public static Style BorderBottomLeftRadius(int pxrad) {return new Style ("border-bottom-left-radius", pxrad+"px");} public static Style BorderBottomRightRadius(int pxrad) {return new Style ("border-bottom-right-radius", pxrad+"px");} public static Style BoxShadow(int xpx, int ypx, Hexcolor color, int blur = 0, int spread = 0, bool inset = false) {return new Style ("box-shadow", String.Format("{0}px {1}px{3}{4} {2}{5}", xpx, ypx, color.ToString(), blur!=0?" "+blur+"px":String.Empty, spread!=0?" "+spread+"px":String.Empty, inset?" inset":String.Empty));} //DIMENSION public static Style Width(int px) {return new Style ("width", px+"px");} public static Style Height(int px) {return new Style ("height", px+"px");} public static Style MinWidth(int px) {return new Style ("min-width", px+"px");} public static Style MinHeight(int px) {return new Style ("min-height", px+"px");} public static Style MaxWidth(int px) {return new Style ("max-width", px+"px");} public static Style MaxHeight(int px) {return new Style ("max-height", px+"px");} public static Style Width(string value) {return new Style ("width", value);} public static Style Height(string value) {return new Style ("height", value);} public static Style MinWidth(string value) {return new Style ("min-width", value);} public static Style MinHeight(string value) {return new Style ("min-height", value);} public static Style MaxWidth(string value) {return new Style ("max-width", value);} public static Style MaxHeight(string value) {return new Style ("max-height", value);} public static Style Width() {return new Style ("width", "inherit");} public static Style Height() {return new Style ("height", "inherit");} public static Style MinWidth() {return new Style ("min-width", "inherit");} public static Style MinHeight() {return new Style ("min-height", "inherit");} public static Style MaxWidth() {return new Style ("max-width", "inherit");} public static Style MaxHeight() {return new Style ("max-height", "inherit");} //FONT public static Style FontFamily(params string[] names) {return new Style ("font-family", String.Join(",", names));} public static Style FontSize(int size) {return new Style ("font-size", size+"px");} public static Style FontSize(string size) {return new Style ("font-size", size);} public static Style FontWeight(Weight weight) {return new Style ("font-weight", weight.ToString().ToLower());} //MARGIN public static Style Margin(int size) {return new Style ("margin", String.Format("{0}px", size));} public static Style Margin(int topbottom, int rightleft) {return new Style ("margin", String.Format("{0}px {1}px", topbottom, rightleft));} public static Style Margin(int top, int rightleft, int bottom) {return new Style ("margin", String.Format("{0}px {1}px {2}px", top, rightleft, bottom));} public static Style Margin(int top, int right, int bottom, int left) {return new Style ("margin", String.Format("{0}px {1}px {2}px {3}px", top, right, bottom, left));} public static Style Margin(string value) {return new Style ("margin", value);} public static Style MarginBottom(int px) {return new Style ("margin-bottom", px+"px");} public static Style MarginLeft(int px) {return new Style ("margin-left", px+"px");} public static Style MarginRight(int px) {return new Style ("margin-right", px+"px");} public static Style MarginTop(int px) {return new Style ("margin-top", px+"px");} public static Style MarginBottom(string value) {return new Style ("margin-bottom", value);} public static Style MarginLeft(string value) {return new Style ("margin-left", value);} public static Style MarginRight(string value) {return new Style ("margin-right", value);} public static Style MarginTop(string value) {return new Style ("margin-top", value);} //PADDING public static Style Padding(int size) {return new Style ("padding", String.Format("{0}px", size));} public static Style Padding(int topbottom, int rightleft) {return new Style ("padding", String.Format("{0}px {1}px", topbottom, rightleft));} public static Style Padding(int top, int rightleft, int bottom) {return new Style ("padding", String.Format("{0}px {1}px {2}px", top, rightleft, bottom));} public static Style Padding(int top, int right, int bottom, int left) {return new Style ("padding", String.Format("{0}px {1}px {2}px {3}px", top, right, bottom, left));} public static Style Padding(string value) {return new Style ("padding", value);} public static Style PaddingBottom(int px) {return new Style ("padding-bottom", px+"px");} public static Style PaddingLeft(int px) {return new Style ("padding-left", px+"px");} public static Style PaddingRight(int px) {return new Style ("padding-right", px+"px");} public static Style PaddingTop(int px) {return new Style ("padding-top", px+"px");} public static Style PaddingBottom(string value) {return new Style ("padding-bottom", value);} public static Style PaddingLeft(string value) {return new Style ("padding-left", value);} public static Style PaddingRight(string value) {return new Style ("padding-right", value);} public static Style PaddingTop(string value) {return new Style ("padding-top", value);} //POSITIONING public static Style Bottom(int px) {return new Style ("bottom", px+"px");} public static Style Left(int px) {return new Style ("left", px+"px");} public static Style Right(int px) {return new Style ("right", px+"px");} public static Style Top(int px) {return new Style ("top", px+"px");} public static Style Bottom(string value) {return new Style ("bottom", value);} public static Style Left(string value) {return new Style ("left", value);} public static Style Right(string value) {return new Style ("right", value);} public static Style Top(string value) {return new Style ("top", value);} public static Style Float(Float OS) {return new Style ("float", OS.ToString().ToLower());} public static Style Overflow(Overflow OS) {return new Style ("overflow", OS.ToString().ToLower());} public static Style Position(Position PS) {return new Style ("position", PS.ToString().ToLower());} public static Style Display(Display value) {return new Style ("display", DisplayDict[value]);} public static Style VerticalAlign(string value) {return new Style ("vertical-align", value);} public static Style ZIndex(int i) {return new Style ("z-index", i.ToString());} //TEXT public static Style Color(byte r, byte g, byte b) {return new Style ("color", new Hexcolor(r, g, b).ToString());} public static Style Color(Hexcolor color) {return new Style ("color", color.ToString());} public static Style Color(string hex) {return new Style ("color", hex.StartsWith("#") ? hex : "#" + hex);} public static Style TextAlign(TextAlignment TA) {return new Style ("text-align", TA.ToString().ToLower());} public static Style TextDecoration(string value) {return new Style ("text-decoration", value);} public static Style TextShadow(int xpx, int ypx, int blur, Hexcolor color) {return new Style ("text-shadow", String.Format("{0}px {1}px {2}px {3}", xpx, ypx, blur, color.ToString()));} //BEGIN STATIC STYLE HELPERS internal static Dictionary<Repeat, string> RepeatDict = new Dictionary<Repeat, string>() {{Repeat.XY, "repeat"}, {Repeat.X, "repeat-x"}, {Repeat.Y, "repeat-y"}, {Repeat.None, "no-repeat"}}; internal static Dictionary<Display, string> DisplayDict = new Dictionary<Display, string>() { {WebSharp.Display.Inline, "inline"}, {WebSharp.Display.Block, "block"}, {WebSharp.Display.InlineBlock, "inline-block"}, {WebSharp.Display.InlineTable, "inline-table"}, {WebSharp.Display.ListItem, "list-item"}, {WebSharp.Display.RunIn, "run-in"}, {WebSharp.Display.Table, "table"}, {WebSharp.Display.TableCaption, "table-caption"}, {WebSharp.Display.TableColumnGroup, "table-column-group"}, {WebSharp.Display.TableHeaderGroup, "table-header-group"}, {WebSharp.Display.TableFooterGroup, "table-footer-group"}, {WebSharp.Display.TableRowGroup, "table-row-group"}, {WebSharp.Display.TableCell, "table-cell"}, {WebSharp.Display.TableColumn, "table-column"}, {WebSharp.Display.TableRow, "table-row"}, {WebSharp.Display.None, "none"}, {WebSharp.Display.Inherit, "inherit"}, }; } public enum Repeat { XY, X, Y, None } public enum Border {None, Hidden, Dotted, Dashed, Solid, Double, Groove, Ridge, Inset, Outset, Inherit} public enum Overflow {Visible, Hidden, Scroll, Auto, Inherit} public enum Position {Static, Absolute, Fixed, Relative, Inherit} public enum Weight {Lighter, Normal, Bold, Bolder, Inherit} public enum Float {Left, Right, None, Inherit} public enum TextAlignment {Left, Center, Right, Justify, Inherit} public enum Display {Inline, Block, InlineBlock, InlineTable, ListItem, RunIn, Table, TableCaption, TableColumnGroup, TableHeaderGroup, TableFooterGroup, TableRowGroup, TableCell, TableColumn, TableRow, None, Inherit} public struct Hexcolor { public byte R; public byte G; public byte B; public Hexcolor(byte r, byte g, byte b) { R = r; G = g; B = b; } public override int GetHashCode () { return R + G + B; } public override bool Equals (object obj) { if (obj == null || obj.GetType() != typeof(Hexcolor)) return false; Hexcolor H = (Hexcolor)obj; return (this.R == H.R && this.G == H.G && this.B == H.B); } public override string ToString () { return String.Format ("#{0:X2}{1:X2}{2:X2}", R, G, B); } public static Hexcolor Black = new Hexcolor(0, 0, 0); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using System.Threading; using Microsoft.Build.BackEnd; using Microsoft.Build.Collections; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Microsoft.Build.Exceptions; using Microsoft.Build.Execution; using Microsoft.Build.Shared; namespace Microsoft.Build.Graph { internal class GraphBuilder { internal static readonly string SolutionItemReference = "_SolutionReference"; /// <summary> /// The thread calling BuildGraph() will act as an implicit worker /// </summary> private const int ImplicitWorkerCount = 1; public IReadOnlyCollection<ProjectGraphNode> ProjectNodes { get; private set; } public IReadOnlyCollection<ProjectGraphNode> RootNodes { get; private set; } public IReadOnlyCollection<ProjectGraphNode> EntryPointNodes { get; private set; } public GraphEdges Edges { get; private set; } private readonly List<ConfigurationMetadata> _entryPointConfigurationMetadata; private readonly ParallelWorkSet<ConfigurationMetadata, ParsedProject> _graphWorkSet; private readonly ProjectCollection _projectCollection; private readonly ProjectInterpretation _projectInterpretation; private readonly ProjectGraph.ProjectInstanceFactoryFunc _projectInstanceFactory; private IReadOnlyDictionary<string, IReadOnlyCollection<string>> _solutionDependencies; public GraphBuilder( IEnumerable<ProjectGraphEntryPoint> entryPoints, ProjectCollection projectCollection, ProjectGraph.ProjectInstanceFactoryFunc projectInstanceFactory, ProjectInterpretation projectInterpretation, int degreeOfParallelism, CancellationToken cancellationToken) { var (actualEntryPoints, solutionDependencies) = ExpandSolutionIfPresent(entryPoints.ToImmutableArray()); _solutionDependencies = solutionDependencies; _entryPointConfigurationMetadata = AddGraphBuildPropertyToEntryPoints(actualEntryPoints); IEqualityComparer<ConfigurationMetadata> configComparer = EqualityComparer<ConfigurationMetadata>.Default; _graphWorkSet = new ParallelWorkSet<ConfigurationMetadata, ParsedProject>( degreeOfParallelism - ImplicitWorkerCount, configComparer, cancellationToken); _projectCollection = projectCollection; _projectInstanceFactory = projectInstanceFactory; _projectInterpretation = projectInterpretation; } public void BuildGraph() { if (_graphWorkSet.IsCompleted) { return; } var allParsedProjects = FindGraphNodes(); AddEdges(allParsedProjects); EntryPointNodes = _entryPointConfigurationMetadata.Select(e => allParsedProjects[e].GraphNode).ToList(); DetectCycles(EntryPointNodes, _projectInterpretation, allParsedProjects); RootNodes = GetGraphRoots(EntryPointNodes); ProjectNodes = allParsedProjects.Values.Select(p => p.GraphNode).ToList(); } private static IReadOnlyCollection<ProjectGraphNode> GetGraphRoots(IReadOnlyCollection<ProjectGraphNode> entryPointNodes) { var graphRoots = new List<ProjectGraphNode>(entryPointNodes.Count); foreach (var entryPointNode in entryPointNodes) { if (entryPointNode.ReferencingProjects.Count == 0) { graphRoots.Add(entryPointNode); } } graphRoots.TrimExcess(); return graphRoots; } private void AddEdges(Dictionary<ConfigurationMetadata, ParsedProject> allParsedProjects) { Edges = new GraphEdges(); AddEdgesFromProjectReferenceItems(allParsedProjects, Edges); _projectInterpretation.ReparentInnerBuilds(allParsedProjects, this); if (_solutionDependencies != null && _solutionDependencies.Count != 0) { AddEdgesFromSolution(allParsedProjects, _solutionDependencies, Edges); } } private void AddEdgesFromProjectReferenceItems(Dictionary<ConfigurationMetadata, ParsedProject> allParsedProjects, GraphEdges edges) { var transitiveReferenceCache = new Dictionary<ProjectGraphNode, HashSet<ProjectGraphNode>>(allParsedProjects.Count); foreach (var parsedProject in allParsedProjects) { var currentNode = parsedProject.Value.GraphNode; var requiresTransitiveProjectReferences = _projectInterpretation.RequiresTransitiveProjectReferences(currentNode.ProjectInstance); foreach (var referenceInfo in parsedProject.Value.ReferenceInfos) { // Always add direct references. currentNode.AddProjectReference( allParsedProjects[referenceInfo.ReferenceConfiguration].GraphNode, referenceInfo.ProjectReferenceItem, edges); // Add transitive references only if the project requires it. if (requiresTransitiveProjectReferences) { foreach (var transitiveProjectReference in GetTransitiveProjectReferencesExcludingSelf(allParsedProjects[referenceInfo.ReferenceConfiguration])) { currentNode.AddProjectReference( transitiveProjectReference, new ProjectItemInstance( project: currentNode.ProjectInstance, itemType: ProjectInterpretation.TransitiveReferenceItemName, includeEscaped: referenceInfo.ReferenceConfiguration.ProjectFullPath, directMetadata: null, definingFileEscaped: currentNode.ProjectInstance.FullPath ), edges); } } } } HashSet<ProjectGraphNode> GetTransitiveProjectReferencesExcludingSelf(ParsedProject parsedProject) { if (transitiveReferenceCache.TryGetValue(parsedProject.GraphNode, out HashSet<ProjectGraphNode> cachedTransitiveReferences)) { return cachedTransitiveReferences; } else { var transitiveReferences = new HashSet<ProjectGraphNode>(); foreach (var referenceInfo in parsedProject.ReferenceInfos) { transitiveReferences.Add(allParsedProjects[referenceInfo.ReferenceConfiguration].GraphNode); foreach (var transitiveReference in GetTransitiveProjectReferencesExcludingSelf(allParsedProjects[referenceInfo.ReferenceConfiguration])) { transitiveReferences.Add(transitiveReference); } } transitiveReferenceCache.Add(parsedProject.GraphNode, transitiveReferences); return transitiveReferences; } } } private static void AddEdgesFromSolution(IReadOnlyDictionary<ConfigurationMetadata, ParsedProject> allParsedProjects, IReadOnlyDictionary<string, IReadOnlyCollection<string>> solutionDependencies, GraphEdges edges) { var projectsByPath = new Dictionary<string, List<ProjectGraphNode>>(); foreach (var project in allParsedProjects) { var projectPath = project.Value.GraphNode.ProjectInstance.FullPath; if (projectsByPath.ContainsKey(projectPath)) { projectsByPath[projectPath].Add(project.Value.GraphNode); } else { projectsByPath[projectPath] = new List<ProjectGraphNode> {project.Value.GraphNode}; } } foreach (var solutionDependency in solutionDependencies) { var referencingProjectPath = solutionDependency.Key; ErrorUtilities.VerifyThrow(projectsByPath.ContainsKey(referencingProjectPath), "nodes should include solution projects"); var referencedNodes = solutionDependency.Value.SelectMany( referencedProjectPath => { ErrorUtilities.VerifyThrow(projectsByPath.ContainsKey(referencedProjectPath), "nodes should include solution projects"); return projectsByPath[referencedProjectPath]; }).ToArray(); var referencingNodes = projectsByPath[referencingProjectPath]; foreach (var referencingNode in referencingNodes) { foreach (var referencedNode in referencedNodes) { var stubItem = new ProjectItemInstance( referencingNode.ProjectInstance, SolutionItemReference, referencedNode.ProjectInstance.FullPath, referencingNode.ProjectInstance.FullPath); referencingNode.AddProjectReference(referencedNode, stubItem, edges); } } } } private (IReadOnlyCollection<ProjectGraphEntryPoint> NewEntryPoints, IReadOnlyDictionary<string, IReadOnlyCollection<string>> SolutionDependencies) ExpandSolutionIfPresent(IReadOnlyCollection<ProjectGraphEntryPoint> entryPoints) { if (entryPoints.Count == 0 || !entryPoints.Any(e => FileUtilities.IsSolutionFilename(e.ProjectFile))) { return (entryPoints, null); } if (entryPoints.Count != 1) { throw new ArgumentException( ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword( "StaticGraphAcceptsSingleSolutionEntryPoint", string.Join(";", entryPoints.Select(e => e.ProjectFile)))); } ErrorUtilities.VerifyThrowArgument(entryPoints.Count == 1, "StaticGraphAcceptsSingleSolutionEntryPoint"); var solutionEntryPoint = entryPoints.Single(); var solutionGlobalProperties = ImmutableDictionary.CreateRange( keyComparer: StringComparer.OrdinalIgnoreCase, valueComparer: StringComparer.OrdinalIgnoreCase, items: solutionEntryPoint.GlobalProperties ?? ImmutableDictionary<string, string>.Empty); var solution = SolutionFile.Parse(FileUtilities.NormalizePath(solutionEntryPoint.ProjectFile)); if (solution.SolutionParserWarnings.Count != 0 || solution.SolutionParserErrorCodes.Count != 0) { throw new InvalidProjectFileException( ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword( "StaticGraphSolutionLoaderEncounteredSolutionWarningsAndErrors", solutionEntryPoint.ProjectFile, string.Join(";", solution.SolutionParserWarnings), string.Join(";", solution.SolutionParserErrorCodes))); } var projectsInSolution = GetBuildableProjects(solution); var currentSolutionConfiguration = SelectSolutionConfiguration(solution, solutionGlobalProperties); var newEntryPoints = new List<ProjectGraphEntryPoint>(projectsInSolution.Count); foreach (var project in projectsInSolution) { if (project.ProjectConfigurations.Count == 0) { continue; } var projectConfiguration = SelectProjectConfiguration(currentSolutionConfiguration, project.ProjectConfigurations); if (projectConfiguration.IncludeInBuild) { newEntryPoints.Add( new ProjectGraphEntryPoint( FileUtilities.NormalizePath(project.AbsolutePath), solutionGlobalProperties .SetItem("Configuration", projectConfiguration.ConfigurationName) .SetItem("Platform", projectConfiguration.PlatformName) )); } } newEntryPoints.TrimExcess(); return (newEntryPoints, GetSolutionDependencies(solution)); IReadOnlyCollection<ProjectInSolution> GetBuildableProjects(SolutionFile solutionFile) { return solutionFile.ProjectsInOrder.Where(p => p.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat).ToImmutableArray(); } SolutionConfigurationInSolution SelectSolutionConfiguration(SolutionFile solutionFile, ImmutableDictionary<string, string> globalProperties) { var solutionConfiguration = globalProperties.ContainsKey("Configuration") ? globalProperties["Configuration"] : solutionFile.GetDefaultConfigurationName(); var solutionPlatform = globalProperties.ContainsKey("Platform") ? globalProperties["Platform"] : solutionFile.GetDefaultPlatformName(); return new SolutionConfigurationInSolution(solutionConfiguration, solutionPlatform); } ProjectConfigurationInSolution SelectProjectConfiguration( SolutionConfigurationInSolution solutionConfig, IReadOnlyDictionary<string, ProjectConfigurationInSolution> projectConfigs) { // implements the matching described in https://docs.microsoft.com/en-us/visualstudio/ide/understanding-build-configurations?view=vs-2019#how-visual-studio-assigns-project-configuration var solutionConfigFullName = solutionConfig.FullName; if (projectConfigs.ContainsKey(solutionConfigFullName)) { return projectConfigs[solutionConfigFullName]; } var partiallyMarchedConfig = projectConfigs.FirstOrDefault(pc => pc.Value.ConfigurationName.Equals(solutionConfig.ConfigurationName, StringComparison.OrdinalIgnoreCase)).Value; return partiallyMarchedConfig ?? projectConfigs.First().Value; } IReadOnlyDictionary<string, IReadOnlyCollection<string>> GetSolutionDependencies(SolutionFile solutionFile) { var solutionDependencies = new Dictionary<string, IReadOnlyCollection<string>>(); foreach (var projectWithDependencies in solutionFile.ProjectsInOrder.Where(p => p.Dependencies.Count != 0)) { solutionDependencies[FileUtilities.NormalizePath(projectWithDependencies.AbsolutePath)] = projectWithDependencies.Dependencies.Select( dependencyGuid => { // code snippet cloned from SolutionProjectGenerator.AddPropertyGroupForSolutionConfiguration if (!solutionFile.ProjectsByGuid.TryGetValue(dependencyGuid, out var dependencyProject)) { // If it's not itself part of the solution, that's an invalid solution ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile( dependencyProject != null, "SubCategoryForSolutionParsingErrors", new BuildEventFileInfo(solutionFile.FullPath), "SolutionParseProjectDepNotFoundError", projectWithDependencies.ProjectGuid, dependencyGuid); } // Add it to the list of dependencies, but only if it should build in this solution configuration // (If a project is not selected for build in the solution configuration, it won't build even if it's depended on by something that IS selected for build) // .. and only if it's known to be MSBuild format, as projects can't use the information otherwise return dependencyProject?.ProjectType == SolutionProjectType.KnownToBeMSBuildFormat ? FileUtilities.NormalizePath(dependencyProject.AbsolutePath) : null; }) .Where(p => p != null) .ToArray(); } return solutionDependencies; } } private static List<ConfigurationMetadata> AddGraphBuildPropertyToEntryPoints(IEnumerable<ProjectGraphEntryPoint> entryPoints) { { var entryPointConfigurationMetadata = new List<ConfigurationMetadata>(); foreach (var entryPoint in entryPoints) { var globalPropertyDictionary = CreatePropertyDictionary(entryPoint.GlobalProperties); AddGraphBuildGlobalVariable(globalPropertyDictionary); var configurationMetadata = new ConfigurationMetadata(FileUtilities.NormalizePath(entryPoint.ProjectFile), globalPropertyDictionary); entryPointConfigurationMetadata.Add(configurationMetadata); } return entryPointConfigurationMetadata; } void AddGraphBuildGlobalVariable(PropertyDictionary<ProjectPropertyInstance> globalPropertyDictionary) { if (globalPropertyDictionary.GetProperty(PropertyNames.IsGraphBuild) == null) { globalPropertyDictionary[PropertyNames.IsGraphBuild] = ProjectPropertyInstance.Create(PropertyNames.IsGraphBuild, "true"); } } } /// <remarks> /// Maintain the state of each node (InProcess and Processed) to detect cycles. /// Assumes edges have been added between nodes. /// Returns false if cycles were detected. /// </remarks> private void DetectCycles( IReadOnlyCollection<ProjectGraphNode> entryPointNodes, ProjectInterpretation projectInterpretation, Dictionary<ConfigurationMetadata, ParsedProject> allParsedProjects) { var nodeStates = new Dictionary<ProjectGraphNode, NodeVisitationState>(); foreach (var entryPointNode in entryPointNodes) { if (!nodeStates.ContainsKey(entryPointNode)) { VisitNode(entryPointNode, nodeStates); } else { ErrorUtilities.VerifyThrow( nodeStates[entryPointNode] == NodeVisitationState.Processed, "entrypoints should get processed after a call to detect cycles"); } } return; (bool success, List<string> projectsInCycle) VisitNode( ProjectGraphNode node, IDictionary<ProjectGraphNode, NodeVisitationState> nodeState) { nodeState[node] = NodeVisitationState.InProcess; foreach (var referenceNode in node.ProjectReferences) { if (nodeState.TryGetValue(referenceNode, out var projectReferenceNodeState)) { // Because this is a depth-first search, we should only encounter new nodes or nodes whose subgraph has been completely processed. // If we encounter a node that is currently being processed(InProcess state), it must be one of the ancestors in a circular dependency. if (projectReferenceNodeState == NodeVisitationState.InProcess) { if (node.Equals(referenceNode)) { // the project being evaluated has a reference to itself var selfReferencingProjectString = FormatCircularDependencyError(new List<string> {node.ProjectInstance.FullPath, node.ProjectInstance.FullPath}); throw new CircularDependencyException( string.Format( ResourceUtilities.GetResourceString("CircularDependencyInProjectGraph"), selfReferencingProjectString)); } // the project being evaluated has a circular dependency involving multiple projects // add this project to the list of projects involved in cycle var projectsInCycle = new List<string> {referenceNode.ProjectInstance.FullPath}; return (false, projectsInCycle); } } else { // recursively process newly discovered references var loadReference = VisitNode(referenceNode, nodeState); if (!loadReference.success) { if (loadReference.projectsInCycle[0].Equals(node.ProjectInstance.FullPath)) { // we have reached the nth project in the cycle, form error message and throw loadReference.projectsInCycle.Add(referenceNode.ProjectInstance.FullPath); loadReference.projectsInCycle.Add(node.ProjectInstance.FullPath); var errorMessage = FormatCircularDependencyError(loadReference.projectsInCycle); throw new CircularDependencyException( string.Format( ResourceUtilities.GetResourceString("CircularDependencyInProjectGraph"), errorMessage)); } // this is one of the projects in the circular dependency // update the list of projects in cycle and return the list to the caller loadReference.projectsInCycle.Add(referenceNode.ProjectInstance.FullPath); return (false, loadReference.projectsInCycle); } } } nodeState[node] = NodeVisitationState.Processed; return (true, null); } } private ParsedProject ParseProject(ConfigurationMetadata configurationMetadata) { // TODO: ProjectInstance just converts the dictionary back to a PropertyDictionary, so find a way to directly provide it. var globalProperties = configurationMetadata.GlobalProperties.ToDictionary(); var projectInstance = _projectInstanceFactory( configurationMetadata.ProjectFullPath, globalProperties, _projectCollection); if (projectInstance == null) { throw new InvalidOperationException(ResourceUtilities.GetResourceString("NullReferenceFromProjectInstanceFactory")); } var graphNode = new ProjectGraphNode(projectInstance); var referenceInfos = ParseReferences(graphNode); return new ParsedProject(configurationMetadata, graphNode, referenceInfos); } /// <summary> /// Load a graph with root node at entryProjectFile /// Maintain a queue of projects to be processed and evaluate projects in parallel /// Returns false if loading the graph is not successful /// </summary> private Dictionary<ConfigurationMetadata, ParsedProject> FindGraphNodes() { foreach (ConfigurationMetadata projectToEvaluate in _entryPointConfigurationMetadata) { SubmitProjectForParsing(projectToEvaluate); /*todo: fix the following double check-then-act concurrency bug: one thread can pass the two checks, loose context, meanwhile another thread passes the same checks with the same data and inserts its reference. The initial thread regains context and duplicates the information, leading to wasted work */ } _graphWorkSet.WaitForAllWorkAndComplete(); return _graphWorkSet.CompletedWork; } private void SubmitProjectForParsing(ConfigurationMetadata projectToEvaluate) { _graphWorkSet.AddWork(projectToEvaluate, () => ParseProject(projectToEvaluate)); } private List<ProjectInterpretation.ReferenceInfo> ParseReferences(ProjectGraphNode parsedProject) { var referenceInfos = new List<ProjectInterpretation.ReferenceInfo>(); foreach (var referenceInfo in _projectInterpretation.GetReferences(parsedProject.ProjectInstance)) { if (FileUtilities.IsSolutionFilename(referenceInfo.ReferenceConfiguration.ProjectFullPath)) { throw new InvalidOperationException(ResourceUtilities.FormatResourceStringIgnoreCodeAndKeyword( "StaticGraphDoesNotSupportSlnReferences", referenceInfo.ReferenceConfiguration.ProjectFullPath, referenceInfo.ReferenceConfiguration.ProjectFullPath )); } SubmitProjectForParsing(referenceInfo.ReferenceConfiguration); referenceInfos.Add(referenceInfo); } return referenceInfos; } internal static string FormatCircularDependencyError(List<string> projectsInCycle) { var errorMessage = new StringBuilder(projectsInCycle.Select(p => p.Length).Sum()); errorMessage.AppendLine(); for (var i = projectsInCycle.Count - 1; i >= 0; i--) { if (i != 0) { errorMessage.Append(projectsInCycle[i]) .AppendLine(" ->"); } else { errorMessage.Append(projectsInCycle[i]); } } return errorMessage.ToString(); } private static PropertyDictionary<ProjectPropertyInstance> CreatePropertyDictionary(IDictionary<string, string> properties) { PropertyDictionary<ProjectPropertyInstance> propertyDictionary; if (properties == null) { propertyDictionary = new PropertyDictionary<ProjectPropertyInstance>(0); } else { propertyDictionary = new PropertyDictionary<ProjectPropertyInstance>(properties.Count); foreach (var entry in properties) { propertyDictionary[entry.Key] = ProjectPropertyInstance.Create(entry.Key, entry.Value); } } return propertyDictionary; } internal class GraphEdges { private ConcurrentDictionary<(ProjectGraphNode, ProjectGraphNode), ProjectItemInstance> ReferenceItems = new ConcurrentDictionary<(ProjectGraphNode, ProjectGraphNode), ProjectItemInstance>(); internal int Count => ReferenceItems.Count; public ProjectItemInstance this[(ProjectGraphNode node, ProjectGraphNode reference) key] { get { ErrorUtilities.VerifyThrow(ReferenceItems.ContainsKey(key), "All requested keys should exist"); return ReferenceItems[key]; } // First edge wins, in accordance with vanilla msbuild behaviour when multiple msbuild tasks call into the same logical project set => ReferenceItems.TryAdd(key, value); } public void RemoveEdge((ProjectGraphNode node, ProjectGraphNode reference) key) { ErrorUtilities.VerifyThrow(ReferenceItems.ContainsKey(key), "All requested keys should exist"); ReferenceItems.TryRemove(key, out _); } internal bool HasEdge((ProjectGraphNode node, ProjectGraphNode reference) key) => ReferenceItems.ContainsKey(key); internal bool TryGetEdge((ProjectGraphNode node, ProjectGraphNode reference) key, out ProjectItemInstance edge) => ReferenceItems.TryGetValue(key, out edge); internal IReadOnlyDictionary<(ConfigurationMetadata, ConfigurationMetadata), ProjectItemInstance> TestOnly_AsConfigurationMetadata() { return ReferenceItems.ToImmutableDictionary( kvp => (kvp.Key.Item1.ToConfigurationMetadata(), kvp.Key.Item2.ToConfigurationMetadata()), kvp => kvp.Value ); } } private enum NodeVisitationState { // the project has been evaluated and its project references are being processed InProcess, // all project references of this project have been processed Processed } } internal readonly struct ParsedProject { public ConfigurationMetadata ConfigurationMetadata { get; } public ProjectGraphNode GraphNode { get; } public List<ProjectInterpretation.ReferenceInfo> ReferenceInfos { get; } public ParsedProject(ConfigurationMetadata configurationMetadata, ProjectGraphNode graphNode, List<ProjectInterpretation.ReferenceInfo> referenceInfos) { ConfigurationMetadata = configurationMetadata; GraphNode = graphNode; ReferenceInfos = referenceInfos; } } }