Ejemplo n.º 1
0
 static public void Assert(bool condition)
 {
     BCLDebug.Assert(condition);
 }
Ejemplo n.º 2
0
 static public void Assert(bool condition, string message)
 {
     BCLDebug.Assert(condition, message);
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Try to get the value of the switch.
        /// </summary>
        /// <param name="switchName">The name of the switch</param>
        /// <param name="isEnabled">A variable where to place the value of the switch</param>
        /// <returns>A return value of true represents that the switch was set and <paramref name="isEnabled"/> contains the value of the switch</returns>
        public static bool TryGetSwitch(string switchName, out bool isEnabled)
        {
            if (switchName == null)
            {
                throw new ArgumentNullException("switchName");
            }
            if (switchName.Length == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "switchName");
            }

            if (s_defaultsInitialized == false)
            {
                InitializeDefaultSwitchValues();
            }
#if DEBUG
            BCLDebug.Assert(s_defaultsInitialized == true, "AppContext defaults should have been initialized.");
#endif

            // By default, the switch is not enabled.
            isEnabled = false;

            SwitchValueState switchValue;
            lock (s_switchMap)
            {
                if (s_switchMap.TryGetValue(switchName, out switchValue))
                {
                    // The value is in the dictionary.
                    // There are 3 cases here:
                    // 1. The value of the switch is 'unknown'. This means that the switch name is not known to the system (either via defaults or checking overrides).
                    //    Example: This is the case when, during a servicing event, a switch is added to System.Xml which ships before mscorlib. The value of the switch
                    //             Will be unknown to mscorlib.dll and we want to prevent checking the overrides every time we check this switch
                    // 2. The switch has a valid value AND we have read the overrides for it
                    //    Example: TryGetSwitch is called for a switch set via SetSwitch
                    // 3. The switch has the default value and we need to check for overrides
                    //    Example: TryGetSwitch is called for the first time for a switch that has a default value

                    // 1. The value is unknown
                    if (switchValue == SwitchValueState.UnknownValue)
                    {
                        isEnabled = false;
                        return(false);
                    }

                    // We get the value of isEnabled from the value that we stored in the dictionary
                    isEnabled = (switchValue & SwitchValueState.HasTrueValue) == SwitchValueState.HasTrueValue;

                    // 2. The switch has a valid value AND we have checked for overrides
                    if ((switchValue & SwitchValueState.HasLookedForOverride) == SwitchValueState.HasLookedForOverride)
                    {
                        return(true);
                    }

                    // 3. The switch has a valid value, but we need to check for overrides.
                    // Regardless of whether or not the switch has an override, we need to update the value to reflect
                    // the fact that we checked for overrides.
                    bool overrideValue;
                    if (AppContextDefaultValues.TryGetSwitchOverride(switchName, out overrideValue))
                    {
                        // we found an override!
                        isEnabled = overrideValue;
                    }

                    // Update the switch in the dictionary to mark it as 'checked for override'
                    s_switchMap[switchName] = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue)
                                              | SwitchValueState.HasLookedForOverride;

                    return(true);
                }
                else
                {
                    // The value is NOT in the dictionary
                    // In this case we need to see if we have an override defined for the value.
                    // There are 2 cases:
                    // 1. The value has an override specified. In this case we need to add the value to the dictionary
                    //    and mark it as checked for overrides
                    //    Example: In a servicing event, System.Xml introduces a switch and an override is specified.
                    //             The value is not found in mscorlib (as System.Xml ships independent of mscorlib)
                    // 2. The value does not have an override specified
                    //    In this case, we want to capture the fact that we looked for a value and found nothing by adding
                    //    an entry in the dictionary with the 'sentinel' value of 'SwitchValueState.UnknownValue'.
                    //    Example: This will prevent us from trying to find overrides for values that we don't have in the dictionary

                    // 1. The value has an override specified.
                    bool overrideValue;
                    if (AppContextDefaultValues.TryGetSwitchOverride(switchName, out overrideValue))
                    {
                        isEnabled = overrideValue;

                        // Update the switch in the dictionary to mark it as 'checked for override'
                        s_switchMap[switchName] = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue)
                                                  | SwitchValueState.HasLookedForOverride;

                        return(true);
                    }

                    // 2. The value does not have an override.
                    s_switchMap[switchName] = SwitchValueState.UnknownValue;
                }
            }
            return(false); // we did not find a value for the switch
        }
Ejemplo n.º 4
0
 // Note: Do not add any code in this ctor because it is not called
 // when we set up _sharedStatics via AppDomain::SetupSharedStatics
 private SharedStatics()
 {
     BCLDebug.Assert(false, "SharedStatics..ctor() is never called.");
 }
Ejemplo n.º 5
0
        // This method should never be called.  Its sole purpose is to shut up the compiler
        //	because it warns about private fields that are never used.  Most of these fields
        //	are used in unmanaged code.
#if _DEBUG
        internal IntPtr  NeverCallThis()
        {
            m_ptr = (IntPtr)0;
            BCLDebug.Assert(false, "NeverCallThis");
            return(m_ptr);
        }
Ejemplo n.º 6
0
 // Return the Unicode category for Unicode character <= 0x00ff.
 private static UnicodeCategory GetLatin1UnicodeCategory(char ch)
 {
     BCLDebug.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f");
     return((UnicodeCategory)(categoryForLatin1[(int)ch]));
 }
Ejemplo n.º 7
0
        private static HashEntry GetHashEntry(Type enumType)
        {
            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();
                }

                ulong[]  values = null;
                String[] names  = null;

                BCLDebug.Assert(enumType.BaseType == typeof(Enum), "Base type must of type Enum");
                if (enumType.BaseType == typeof(Enum))
                {
                    InternalGetEnumValues(enumType, ref values, ref names);
                }
                // If we switch over to EnumBuilder, this code path will be required.
                else
                {
                    // fall back on reflection for odd cases
                    FieldInfo[] flds = enumType.GetFields(BindingFlags.Static | BindingFlags.Public);

                    values = new ulong[flds.Length];
                    names  = new String[flds.Length];
                    for (int i = 0; i < flds.Length; i++)
                    {
                        names[i]  = flds[i].Name;
                        values[i] = ToUInt64(flds[i].GetValue(null));
                    }

                    // Insertion Sort these values in ascending order.
                    // We use this O(n^2) algorithm, but it turns out that most of the time the elements are already in sorted order and
                    // the common case performance will be faster than quick sorting this.
                    for (int i = 1; i < values.Length; i++)
                    {
                        int    j         = i;
                        String tempStr   = names[i];
                        ulong  val       = values[i];
                        bool   exchanged = false;

                        // Since the elements are sorted we only need to do one comparision, we keep the check for j inside the loop.
                        while (values[j - 1] > val)
                        {
                            names[j]  = names[j - 1];
                            values[j] = values[j - 1];
                            j--;
                            exchanged = true;
                            if (j == 0)
                            {
                                break;
                            }
                        }

                        if (exchanged)
                        {
                            names[j]  = tempStr;
                            values[j] = val;
                        }
                    }
                }

                hashEntry = new HashEntry(names, values);
                fieldInfoHash[enumType] = hashEntry;
            }

            return(hashEntry);
        }
Ejemplo n.º 8
0
 public void NotifyEvent(ConfigEvents nEvent)
 {
     BCLDebug.Trace("REMOTE", "NotifyEvent " + ((Enum)nEvent).ToString() + "\n");
 }
Ejemplo n.º 9
0
        // GetRealObject uses the data we have in m_data and m_unityType to do a lookup on the correct
        // object to return.  We have specific code here to handle the different types which we support.
        // The reflection types (Assembly, Module, and Type) have to be looked up through their static
        // accessors by name.
        public virtual Object GetRealObject(StreamingContext context)
        {
            Assembly assem;

            BCLDebug.Trace("SER", "[GetRealObject] UnityType:", m_unityType);

            switch (m_unityType)
            {
            case EmptyUnity:
                BCLDebug.Trace("SER", "[GetRealObject]Returning Empty.Value");
                BCLDebug.Trace("SER", "[GetRealObject]Empty's value is: ", Empty.Value, "||");
                return(Empty.Value);

            case NullUnity:
                return(DBNull.Value);

            case MissingUnity:
                return(Missing.Value);

            case RuntimeTypeUnity:
                if (m_data == null || m_data.Length == 0 || m_assemName == null)
                {
                    BCLDebug.Trace("SER", "UnitySerializationHolder.GetRealObject Type. Data is: ", m_data);
                    throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
                }
                if (m_assemName.Length == 0)
                {
                    return(RuntimeType.GetTypeInternal(m_data, false, false, false));
                }

                assem = FormatterServices.LoadAssemblyFromString(m_assemName);
                if (assem == null)
                {
                    BCLDebug.Trace("SER", "UnitySerializationHolder.GetRealObject Type. AssemblyName is: ", m_assemName, " but we can't load it.");
                    throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
                }

                Type t = assem.GetTypeInternal(m_data, false, false, false);

                return(t);

            case ModuleUnity:
                if (m_data == null || m_data.Length == 0 || m_assemName == null)
                {
                    BCLDebug.Trace("SER", "UnitySerializationHolder.GetRealObject Module. Data is: ", m_data);
                    throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
                }
                assem = FormatterServices.LoadAssemblyFromString(m_assemName);
                if (assem == null)
                {
                    BCLDebug.Trace("SER", "UnitySerializationHolder.GetRealObject Module. AssemblyName is: ", m_assemName, " but we can't load it.");
                    throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
                }

                Module namedModule = assem.GetModule(m_data);
                if (namedModule == null)
                {
                    throw new SerializationException(Environment.GetResourceString("Serialization_UnableToFindModule"));
                }
                return(namedModule);

            case AssemblyUnity:
                if (m_data == null || m_data.Length == 0 || m_assemName == null)
                {
                    BCLDebug.Log("UnitySerializationHolder.GetRealObject.  Assembly. Data is: " + ((m_data == null)?"<null>":m_data));
                    throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
                }
                assem = FormatterServices.LoadAssemblyFromString(m_assemName);
                if (assem == null)
                {
                    BCLDebug.Trace("SER", "UnitySerializationHolder.GetRealObject Module. AssemblyName is: ", m_assemName, " but we can't load it.");
                    throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
                }

                return(assem);

            default:
                //This should never happen because we only use the class internally.
                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidUnity"));
            }
        }
Ejemplo n.º 10
0
        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.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.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:
                BCLDebug.Assert(false, "Invalid Object type in Format");
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
            }
        }
Ejemplo n.º 11
0
        // Compares this enum and the object. The have to be of the same type or a ArgumentException is thrown
        // Returns 0 if equal, -1 if less than, or 1 greater then the target
        /// <include file='doc\Enum.uex' path='docs/doc[@for="Enum.CompareTo"]/*' />
        public int CompareTo(Object target)
        {
            // Validate the parameters
            if (target == null)
            {
                return(1);
            }
            // Check if both of them are of the same type
            Type thisType   = this.GetType();
            Type targetType = target.GetType();

            if (thisType != targetType)
            {
                throw new ArgumentException(String.Format(Environment.GetResourceString("Arg_EnumAndObjectMustBeSameType"),
                                                          targetType.ToString(), thisType.ToString()));
            }

            FieldInfo thisField   = GetValueField(thisType);
            FieldInfo targetField = GetValueField(targetType);

            // Retrieve the value from the field.
            Object thisResult   = ((RuntimeFieldInfo)thisField).InternalGetValue(this, false);
            Object targetResult = ((RuntimeFieldInfo)targetField).InternalGetValue(target, false);

            TypeCode typeCode = this.GetTypeCode();

            switch (typeCode)
            {
            case TypeCode.Int32:
            case TypeCode.SByte:
            case TypeCode.Int16:
            case TypeCode.Int64:
            {
                Int64 result    = Convert.ToInt64(thisResult);
                Int64 compareTo = Convert.ToInt64(targetResult);
                if (result == compareTo)
                {
                    return(0);
                }
                if (result < compareTo)
                {
                    return(-1);
                }
                else
                {
                    return(1);
                }
            }

            case TypeCode.UInt32:
            case TypeCode.Byte:
            case TypeCode.UInt16:
            case TypeCode.UInt64:
            {
                UInt64 result    = Convert.ToUInt64(thisResult);
                UInt64 compareTo = Convert.ToUInt64(targetResult);
                if (result == compareTo)
                {
                    return(0);
                }
                if (result < compareTo)
                {
                    return(-1);
                }
                else
                {
                    return(1);
                }
            }

            default:
                BCLDebug.Assert(false, "Invalid switch case for CompareTo function");
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
            }
        }
        //
        // This function will convert an ExceptionResource enum value to the resource string.
        //
        internal static string GetResourceName(ExceptionResource resource)
        {
            string resourceName = null;

            switch (resource)
            {
            case ExceptionResource.Argument_ImplementIComparable:
                resourceName = "Argument_ImplementIComparable";
                break;

            case ExceptionResource.Argument_AddingDuplicate:
                resourceName = "Argument_AddingDuplicate";
                break;

            case ExceptionResource.ArgumentOutOfRange_BiggerThanCollection:
                resourceName = "ArgumentOutOfRange_BiggerThanCollection";
                break;

            case ExceptionResource.ArgumentOutOfRange_Count:
                resourceName = "ArgumentOutOfRange_Count";
                break;

            case ExceptionResource.ArgumentOutOfRange_Index:
                resourceName = "ArgumentOutOfRange_Index";
                break;

            case ExceptionResource.ArgumentOutOfRange_InvalidThreshold:
                resourceName = "ArgumentOutOfRange_InvalidThreshold";
                break;

            case ExceptionResource.ArgumentOutOfRange_ListInsert:
                resourceName = "ArgumentOutOfRange_ListInsert";
                break;

            case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum:
                resourceName = "ArgumentOutOfRange_NeedNonNegNum";
                break;

            case ExceptionResource.ArgumentOutOfRange_SmallCapacity:
                resourceName = "ArgumentOutOfRange_SmallCapacity";
                break;

            case ExceptionResource.Arg_ArrayPlusOffTooSmall:
                resourceName = "Arg_ArrayPlusOffTooSmall";
                break;

            case ExceptionResource.Arg_RankMultiDimNotSupported:
                resourceName = "Arg_RankMultiDimNotSupported";
                break;

            case ExceptionResource.Arg_NonZeroLowerBound:
                resourceName = "Arg_NonZeroLowerBound";
                break;

            case ExceptionResource.Argument_InvalidArrayType:
                resourceName = "Argument_InvalidArrayType";
                break;

            case ExceptionResource.Argument_InvalidOffLen:
                resourceName = "Argument_InvalidOffLen";
                break;

            case ExceptionResource.Argument_ItemNotExist:
                resourceName = "Argument_ItemNotExist";
                break;

            case ExceptionResource.InvalidOperation_CannotRemoveFromStackOrQueue:
                resourceName = "InvalidOperation_CannotRemoveFromStackOrQueue";
                break;

            case ExceptionResource.InvalidOperation_EmptyQueue:
                resourceName = "InvalidOperation_EmptyQueue";
                break;

            case ExceptionResource.InvalidOperation_EnumOpCantHappen:
                resourceName = "InvalidOperation_EnumOpCantHappen";
                break;

            case ExceptionResource.InvalidOperation_EnumFailedVersion:
                resourceName = "InvalidOperation_EnumFailedVersion";
                break;

            case ExceptionResource.InvalidOperation_EmptyStack:
                resourceName = "InvalidOperation_EmptyStack";
                break;

            case ExceptionResource.InvalidOperation_EnumNotStarted:
                resourceName = "InvalidOperation_EnumNotStarted";
                break;

            case ExceptionResource.InvalidOperation_EnumEnded:
                resourceName = "InvalidOperation_EnumEnded";
                break;

            case ExceptionResource.NotSupported_KeyCollectionSet:
                resourceName = "NotSupported_KeyCollectionSet";
                break;

            case ExceptionResource.NotSupported_ReadOnlyCollection:
                resourceName = "NotSupported_ReadOnlyCollection";
                break;

            case ExceptionResource.NotSupported_ValueCollectionSet:
                resourceName = "NotSupported_ValueCollectionSet";
                break;


            case ExceptionResource.NotSupported_SortedListNestedWrite:
                resourceName = "NotSupported_SortedListNestedWrite";
                break;


            case ExceptionResource.Serialization_InvalidOnDeser:
                resourceName = "Serialization_InvalidOnDeser";
                break;

            case ExceptionResource.Serialization_MissingKeyValuePairs:
                resourceName = "Serialization_MissingKeyValuePairs";
                break;

            case ExceptionResource.Serialization_NullKey:
                resourceName = "Serialization_NullKey";
                break;

            case ExceptionResource.Argument_InvalidType:
                resourceName = "Argument_InvalidType";
                break;

            case ExceptionResource.Argument_InvalidArgumentForComparison:
                resourceName = "Argument_InvalidArgumentForComparison";
                break;

            case ExceptionResource.InvalidOperation_NoValue:
                resourceName = "InvalidOperation_NoValue";
                break;

            case ExceptionResource.InvalidOperation_RegRemoveSubKey:
                resourceName = "InvalidOperation_RegRemoveSubKey";
                break;

            case ExceptionResource.Arg_RegSubKeyAbsent:
                resourceName = "Arg_RegSubKeyAbsent";
                break;

            case ExceptionResource.Arg_RegSubKeyValueAbsent:
                resourceName = "Arg_RegSubKeyValueAbsent";
                break;

            case ExceptionResource.Arg_RegKeyDelHive:
                resourceName = "Arg_RegKeyDelHive";
                break;

            case ExceptionResource.Security_RegistryPermission:
                resourceName = "Security_RegistryPermission";
                break;

            case ExceptionResource.Arg_RegSetStrArrNull:
                resourceName = "Arg_RegSetStrArrNull";
                break;

            case ExceptionResource.Arg_RegSetMismatchedKind:
                resourceName = "Arg_RegSetMismatchedKind";
                break;

            case ExceptionResource.UnauthorizedAccess_RegistryNoWrite:
                resourceName = "UnauthorizedAccess_RegistryNoWrite";
                break;

            case ExceptionResource.ObjectDisposed_RegKeyClosed:
                resourceName = "ObjectDisposed_RegKeyClosed";
                break;

            case ExceptionResource.Arg_RegKeyStrLenBug:
                resourceName = "Arg_RegKeyStrLenBug";
                break;

            case ExceptionResource.Argument_InvalidRegistryKeyPermissionCheck:
                resourceName = "Argument_InvalidRegistryKeyPermissionCheck";
                break;

            case ExceptionResource.NotSupported_InComparableType:
                resourceName = "NotSupported_InComparableType";
                break;

            default:
                BCLDebug.Assert(false, "The enum value is not defined, please checked ExceptionArgumentName Enum.");
                return(string.Empty);
            }

            return(resourceName);
        }
        //
        // This function will convert an ExceptionArgument enum value to the argument name string.
        //
        internal static string GetArgumentName(ExceptionArgument argument)
        {
            string argumentName = null;

            switch (argument)
            {
            case ExceptionArgument.array:
                argumentName = "array";
                break;

            case ExceptionArgument.arrayIndex:
                argumentName = "arrayIndex";
                break;

            case ExceptionArgument.capacity:
                argumentName = "capacity";
                break;

            case ExceptionArgument.collection:
                argumentName = "collection";
                break;

            case ExceptionArgument.list:
                argumentName = "list";
                break;

            case ExceptionArgument.converter:
                argumentName = "converter";
                break;

            case ExceptionArgument.count:
                argumentName = "count";
                break;

            case ExceptionArgument.dictionary:
                argumentName = "dictionary";
                break;

            case ExceptionArgument.dictionaryCreationThreshold:
                argumentName = "dictionaryCreationThreshold";
                break;

            case ExceptionArgument.index:
                argumentName = "index";
                break;

            case ExceptionArgument.info:
                argumentName = "info";
                break;

            case ExceptionArgument.key:
                argumentName = "key";
                break;

            case ExceptionArgument.match:
                argumentName = "match";
                break;

            case ExceptionArgument.obj:
                argumentName = "obj";
                break;

            case ExceptionArgument.queue:
                argumentName = "queue";
                break;

            case ExceptionArgument.stack:
                argumentName = "stack";
                break;

            case ExceptionArgument.startIndex:
                argumentName = "startIndex";
                break;

            case ExceptionArgument.value:
                argumentName = "value";
                break;

            case ExceptionArgument.name:
                argumentName = "name";
                break;

            case ExceptionArgument.mode:
                argumentName = "mode";
                break;

            default:
                BCLDebug.Assert(false, "The enum value is not defined, please checked ExceptionArgumentName Enum.");
                return(string.Empty);
            }

            return(argumentName);
        }
Ejemplo n.º 14
0
 static public void Fail(string message)
 {
     BCLDebug.Assert(false, message);
 }
Ejemplo n.º 15
0
        public static bool IsDefined(Type enumType, Object value)
        {
            if (enumType == null)
            {
                throw new ArgumentNullException("enumType");
            }

            if (!(enumType is RuntimeType))
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType");
            }

            if (!enumType.IsEnum)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
            }

            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            // Check if both of them are of the same type
            Type valueType = value.GetType();

            if (!(valueType is RuntimeType))
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "valueType");
            }

            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 != enumType)
                {
                    throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Arg_EnumAndObjectMustBeSameType"), valueType.ToString(), enumType.ToString()));
                }

                valueType = valueUnderlyingType;
            }
            else
            // The value must be of the same type as the Underlying type of the Enum
            if ((valueType != underlyingType) && (valueType != stringType))
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Arg_EnumUnderlyingTypeAndObjectMustBeSameType"), valueType.ToString(), underlyingType.ToString()));
            }

            // If String is passed in
            if (valueType == stringType)
            {
                // Get all of the Fields
                String[] names = GetHashEntry(enumType).names;

                for (int i = 0; i < names.Length; i++)
                {
                    if (names[i].Equals((string)value))
                    {
                        return(true);
                    }
                }

                return(false);
            }

            ulong[] values = GetHashEntry(enumType).values;

            // Look at the 8 possible enum base classes
            if (valueType == intType || valueType == typeof(short) || valueType == typeof(ushort) || valueType == typeof(byte) || valueType == typeof(sbyte) || valueType == typeof(uint) || valueType == typeof(long) || valueType == typeof(ulong))
            {
                ulong val = ToUInt64(value);

                return(BinarySearch(values, val) >= 0);
            }

            BCLDebug.Assert(false, "Unknown enum type");
            throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
        }
        // equals returns true IIF the delegate is not null and has the
        //    same target, method and invocation list as this object
        public override sealed bool Equals(Object obj)
        {
            if (obj == null || !InternalEqualTypes(this, obj))
            {
                return(false);
            }
            MulticastDelegate d = obj as MulticastDelegate;

            if (d == null)
            {
                return(false);
            }

            if (_invocationCount != (IntPtr)0)
            {
                // there are 4 kind of delegate kinds that fall into this bucket
                // 1- Multicast (_invocationList is Object[])
                // 2- Secure (_invocationList is Delegate)
                // 3- Unmanaged FntPtr (_invocationList == null)
                // 4- Open virtual (_invocationCount == MethodDesc of target)

                if (_invocationList == null)
                {
                    if (IsUnmanagedFunctionPtr())
                    {
                        if (!d.IsUnmanagedFunctionPtr())
                        {
                            return(false);
                        }


                        if (_methodPtr != d._methodPtr)
                        {
                            return(false);
                        }

                        if (GetUnmanagedCallSite() != d.GetUnmanagedCallSite())
                        {
                            return(false);
                        }

                        return(true);
                    }
                    return(base.Equals(obj));
                }
                else
                {
                    if ((_invocationList as Delegate) != null)
                    {
                        // this is a secure delegate so we need to unwrap and check the inner one
                        return(_invocationList.Equals(obj));
                    }
                    else
                    {
                        BCLDebug.Assert((_invocationList as Object[]) != null, "empty invocation list on multicast delegate");
                        return(InvocationListEquals(d));
                    }
                }
            }
            else
            {
                // among the several kind of delegates falling into this bucket one has got a non
                // empty _invocationList (open static with special sig)
                // to be equals we need to check that _invocationList matches (both null is fine)
                // and call the base.Equals()
                if (_invocationList != null)
                {
                    if (!_invocationList.Equals(d._invocationList))
                    {
                        return(false);
                    }
                    return(base.Equals(d));
                }

                // now we know 'this' is not a special one, so we can work out what the other is
                if (d._invocationList != null || d._invocationCount != (IntPtr)0)
                {
                    if ((d._invocationList as Delegate) != null)
                    {
                        // this is a secure delegate so we need to unwrap and check the inner one
                        return((d._invocationList as Delegate).Equals(this));
                    }
                    return(false);
                }

                // now we can call on the base
                return(base.Equals(d));
            }
        }
Ejemplo n.º 17
0
        private Delegate GetDelegate(DelegateEntry de)
        {
            Delegate d;

            if (de.methodName == null || de.methodName.Length == 0)
            {
                throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
            }

            Assembly assem = FormatterServices.LoadAssemblyFromStringNoThrow(de.assembly);

            if (assem == null)
            {
                BCLDebug.Trace("SER", "[DelegateSerializationHolder.ctor]: Unable to find assembly for TargetType: ", de.assembly);
                throw new SerializationException(String.Format(Environment.GetResourceString("Serialization_AssemblyNotFound"), de.assembly));
            }

            Type type = assem.GetTypeInternal(de.type, false, false, false);

            assem = FormatterServices.LoadAssemblyFromStringNoThrow(de.targetTypeAssembly);
            if (assem == null)
            {
                BCLDebug.Trace("SER", "[DelegateSerializationHolder.ctor]: Unable to find assembly for TargetType: ", de.targetTypeAssembly);
                throw new SerializationException(String.Format(Environment.GetResourceString("Serialization_AssemblyNotFound"), de.targetTypeAssembly));
            }

            Type targetType = assem.GetTypeInternal(de.targetTypeName, false, false, false);

            if (de.target == null && targetType == null)
            {
                throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
            }

            if (type == null)
            {
                BCLDebug.Trace("SER", "[DelegateSerializationHolder.GetRealObject]Missing Type");
                throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
            }

            if (targetType == null)
            {
                throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientDeserializationState"));
            }

            Object target = null;

            if (de.target != null) //We have a delegate to a non-static object
            {
                target = RemotingServices.CheckCast(de.target, targetType);
                d      = Delegate.CreateDelegate(type, target, de.methodName);
            }
            else
            {
                //For a static delegate
                d = Delegate.CreateDelegate(type, targetType, de.methodName);
            }

            // We will refuse to create delegates to methods that are non-public.
            MethodInfo mi = d.Method;

            if (mi != null)
            {
                if (!mi.IsPublic)
                {
                    throw new SerializationException(
                              Environment.GetResourceString("Serialization_RefuseNonPublicDelegateCreation"));
                }
            }

            return(d);
        }