Esempio n. 1
0
        public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            if (element.Member == null)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), "element");
            }

            Contract.EndContractBlock();

            MemberInfo member = element.Member;

            if (member.MemberType == MemberTypes.Method && inherit)
            {
                return(InternalParamGetCustomAttributes(element, null, inherit) as Attribute[]);
            }

            return(element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[]);
        }
Esempio n. 2
0
        public Version(int major, int minor, int build)
        {
            if (major < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(major), Environment.GetResourceString("ArgumentOutOfRange_Version"));
            }

            if (minor < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(minor), Environment.GetResourceString("ArgumentOutOfRange_Version"));
            }

            if (build < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(build), Environment.GetResourceString("ArgumentOutOfRange_Version"));
            }

            Contract.EndContractBlock();

            _Major = major;
            _Minor = minor;
            _Build = build;
        }
Esempio n. 3
0
        public static int Compare(String strA, int indexA, String strB, int indexB, int length, CultureInfo culture, CompareOptions options)
        {
            if (culture == null)
            {
                throw new ArgumentNullException(nameof(culture));
            }
            Contract.EndContractBlock();

            int lengthA = length;
            int lengthB = length;

            if (strA != null)
            {
                lengthA = Math.Min(lengthA, strA.Length - indexA);
            }

            if (strB != null)
            {
                lengthB = Math.Min(lengthB, strB.Length - indexB);
            }

            return(culture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options));
        }
Esempio n. 4
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        public static unsafe long ToInt64(byte[] value, int startIndex)
        {
            if (value == null)
            {
                ThrowValueArgumentNull();
            }
            if ((uint)startIndex >= value.Length)
            {
                ThrowStartIndexArgumentOutOfRange();
            }
            if (startIndex > value.Length - 8)
            {
                ThrowValueArgumentTooSmall();
            }
            Contract.EndContractBlock();

            fixed(byte *pbyte = &value[startIndex])
            {
                if (startIndex % 8 == 0)
                {
                    // data is aligned
                    return(*((long *)pbyte));
                }
                else if (IsLittleEndian)
                {
                    int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
                    int i2 = (*(pbyte + 4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24);
                    return((uint)i1 | ((long)i2 << 32));
                }
                else
                {
                    int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
                    int i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7));
                    return((uint)i2 | ((long)i1 << 32));
                }
            }
        }
Esempio n. 5
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        protected unsafe Delegate(Type target, String method)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            if (target.IsGenericType && target.ContainsGenericParameters)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_UnboundGenParam"), nameof(target));
            }

            if (method == null)
            {
                throw new ArgumentNullException(nameof(method));
            }
            Contract.EndContractBlock();

            RuntimeType rtTarget = target as RuntimeType;

            if (rtTarget == null)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(target));
            }

            // This API existed in v1/v1.1 and only expected to create open
            // static delegates. Constrain the call to BindToMethodName to such
            // and don't allow relaxed signature matching (which could make the
            // choice of target method ambiguous) for backwards compatibility.
            // The name matching was case insensitive (no idea why this is
            // different from the constructor above) and we preserve that as
            // well.
            BindToMethodName(null, rtTarget, method,
                             DelegateBindingFlags.StaticMethodOnly |
                             DelegateBindingFlags.OpenDelegateOnly |
                             DelegateBindingFlags.CaselessMatching);
        }
Esempio n. 6
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        public static unsafe int ToInt32(byte[] value, int startIndex)
        {
            if (value == null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
            }

            if ((uint)startIndex >= value.Length)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
            }

            if (startIndex > value.Length - 4)
            {
                ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
            }
            Contract.EndContractBlock();

            fixed(byte *pbyte = &value[startIndex])
            {
                if (startIndex % 4 == 0)   // data is aligned
                {
                    return(*((int *)pbyte));
                }
                else
                {
                    if (IsLittleEndian)
                    {
                        return((*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24));
                    }
                    else
                    {
                        return((*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)));
                    }
                }
            }
        }
        public static void SetCursorPosition(int left, int top)
        {
            // Note on argument checking - the upper bounds are NOT correct
            // here!  But it looks slightly expensive to compute them.  Let
            // Windows calculate them, then we'll give a nice error message.
            if (left < 0 || left >= short.MaxValue)
            {
                throw new ArgumentOutOfRangeException("left", left, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
            }
            if (top < 0 || top >= short.MaxValue)
            {
                throw new ArgumentOutOfRangeException("top", top, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
            }
            Contract.EndContractBlock();

            IntPtr hConsole = OutputHandle;

            Interop.mincore.COORD coords = new Interop.mincore.COORD();
            coords.X = (short)left;
            coords.Y = (short)top;
            if (!Interop.mincore.SetConsoleCursorPosition(hConsole, coords))
            {
                // Give a nice error message for out of range sizes
                int errorCode = Marshal.GetLastWin32Error();
                Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();
                if (left < 0 || left >= csbi.dwSize.X)
                {
                    throw new ArgumentOutOfRangeException("left", left, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
                }
                if (top < 0 || top >= csbi.dwSize.Y)
                {
                    throw new ArgumentOutOfRangeException("top", top, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
                }

                throw Win32Marshal.GetExceptionForWin32Error(errorCode);
            }
        }
Esempio n. 8
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        public static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting)
        {
            if (generation < 0)
            {
                throw new ArgumentOutOfRangeException("generation", Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
            }

            if ((mode < GCCollectionMode.Default) || (mode > GCCollectionMode.Optimized))
            {
                throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_Enum"));
            }

            Contract.EndContractBlock();

            int iInternalModes = 0;

            if (mode == GCCollectionMode.Optimized)
            {
                iInternalModes |= (int)InternalGCCollectionMode.Optimized;
            }

            if (compacting)
            {
                iInternalModes |= (int)InternalGCCollectionMode.Compacting;
            }

            if (blocking)
            {
                iInternalModes |= (int)InternalGCCollectionMode.Blocking;
            }
            else if (!compacting)
            {
                iInternalModes |= (int)InternalGCCollectionMode.NonBlocking;
            }

            _Collect(generation, iInternalModes);
        }
Esempio n. 9
0
        public static bool IsDefined(ParameterInfo element, Type attributeType, bool inherit)
        {
            // Returns true is a custom attribute subclass of attributeType class/interface with inheritance walk
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

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

            if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
            }
            Contract.EndContractBlock();

            MemberInfo member = element.Member;

            switch (member.MemberType)
            {
            case MemberTypes.Method:     // We need to climb up the member hierarchy
                return(InternalParamIsDefined(element, attributeType, inherit));

            case MemberTypes.Constructor:
                return(element.IsDefined(attributeType, false));

            case MemberTypes.Property:
                return(element.IsDefined(attributeType, false));

            default:
                Contract.Assert(false, "Invalid type for ParameterInfo member in Attribute class");
                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParamInfo"));
            }
        }
Esempio n. 10
0
        public static Decimal Round(Decimal d, int decimals, MidpointRounding mode)
        {
            if (decimals < 0 || decimals > 28)
            {
                throw new ArgumentOutOfRangeException(nameof(decimals), SR.ArgumentOutOfRange_DecimalRound);
            }
            if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero)
            {
                throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, "MidpointRounding"), nameof(mode));
            }
            Contract.EndContractBlock();

            if (mode == MidpointRounding.ToEven)
            {
                Decimal result = new Decimal();
                DecCalc.VarDecRound(ref d, decimals, ref result);
                d = result;
            }
            else
            {
                DecCalc.InternalRoundFromZero(ref d, decimals);
            }
            return(d);
        }
Esempio n. 11
0
        public ArraySegment(T[] array, int offset, int count)
        {
            if (array == null)
            {
                throw new ArgumentNullException(nameof(array));
            }
            if (offset < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
            }
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
            }
            if (array.Length - offset < count)
            {
                throw new ArgumentException(SR.Argument_InvalidOffLen);
            }
            Contract.EndContractBlock();

            _array  = array;
            _offset = offset;
            _count  = count;
        }
Esempio n. 12
0
        private static DateTimeStyles ValidateStyles(DateTimeStyles style, String parameterName)
        {
            if ((style & DateTimeFormatInfo.InvalidDateTimeStyles) != 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeStyles"), parameterName);
            }
            if (((style & (DateTimeStyles.AssumeLocal)) != 0) && ((style & (DateTimeStyles.AssumeUniversal)) != 0))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_ConflictingDateTimeStyles"), parameterName);
            }
            if ((style & DateTimeStyles.NoCurrentDateDefault) != 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetInvalidDateTimeStyles"), parameterName);
            }

            Contract.EndContractBlock();
            // RoundtripKind does not make sense for DateTimeOffset; ignore this flag for backward compatibility with DateTime
            style &= ~DateTimeStyles.RoundtripKind;

            // AssumeLocal is also ignored as that is what we do by default with DateTimeOffset.Parse
            style &= ~DateTimeStyles.AssumeLocal;

            return(style);
        }
Esempio n. 13
0
        public static ObjectHandle CreateInstanceFrom(AppDomain domain,
                                                      string assemblyFile,
                                                      string typeName,
                                                      bool ignoreCase,
                                                      BindingFlags bindingAttr,
                                                      Binder binder,
                                                      object[] args,
                                                      CultureInfo culture,
                                                      object[] activationAttributes)
        {
            if (domain == null)
                throw new ArgumentNullException("domain");
            Contract.EndContractBlock();

            return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile,
                                                                   typeName,
                                                                   ignoreCase,
                                                                   bindingAttr,
                                                                   binder,
                                                                   args,
                                                                   culture,
                                                                   activationAttributes,
                                                                   null);
        }
Esempio n. 14
0
        public static String ExpandEnvironmentVariables(String name)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            Contract.EndContractBlock();

            if (name.Length == 0)
            {
                return(name);
            }

            if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
            {
                // Environment variable accessors are not approved modern API.
                // Behave as if no variables are defined in this case.
                return(name);
            }

            int           currentSize = 100;
            StringBuilder blob        = new StringBuilder(currentSize); // A somewhat reasonable default size

#if PLATFORM_UNIX                                                       // Win32Native.ExpandEnvironmentStrings isn't available
            int lastPos = 0, pos;
            while (lastPos < name.Length && (pos = name.IndexOf('%', lastPos + 1)) >= 0)
            {
                if (name[lastPos] == '%')
                {
                    string key   = name.Substring(lastPos + 1, pos - lastPos - 1);
                    string value = Environment.GetEnvironmentVariable(key);
                    if (value != null)
                    {
                        blob.Append(value);
                        lastPos = pos + 1;
                        continue;
                    }
                }
                blob.Append(name.Substring(lastPos, pos - lastPos));
                lastPos = pos;
            }
            blob.Append(name.Substring(lastPos));
#else
            int size;

            blob.Length = 0;
            size        = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize);
            if (size == 0)
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            while (size > currentSize)
            {
                currentSize   = size;
                blob.Capacity = currentSize;
                blob.Length   = 0;

                size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize);
                if (size == 0)
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
            }
#endif // PLATFORM_UNIX

            return(blob.ToString());
        }
Esempio n. 15
0
        public static bool Equals(String a, String b, StringComparison comparisonType)
        {
            if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
            {
                throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
            }
            Contract.EndContractBlock();

            if ((Object)a == (Object)b)
            {
                return(true);
            }

            if ((Object)a == null || (Object)b == null)
            {
                return(false);
            }

            switch (comparisonType)
            {
            case StringComparison.CurrentCulture:
                return(CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, CompareOptions.None) == 0);

            case StringComparison.CurrentCultureIgnoreCase:
                return(CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, CompareOptions.IgnoreCase) == 0);

            case StringComparison.InvariantCulture:
                return(CultureInfo.InvariantCulture.CompareInfo.Compare(a, b, CompareOptions.None) == 0);

            case StringComparison.InvariantCultureIgnoreCase:
                return(CultureInfo.InvariantCulture.CompareInfo.Compare(a, b, CompareOptions.IgnoreCase) == 0);

            case StringComparison.Ordinal:
                if (a.Length != b.Length)
                {
                    return(false);
                }

                return(EqualsHelper(a, b));

            case StringComparison.OrdinalIgnoreCase:
                if (a.Length != b.Length)
                {
                    return(false);
                }
                else
                {
                    // If both strings are ASCII strings, we can take the fast path.
                    if (a.IsAscii() && b.IsAscii())
                    {
                        return(CompareOrdinalIgnoreCaseHelper(a, b) == 0);
                    }
                    // Take the slow path.

#if FEATURE_COREFX_GLOBALIZATION
                    return(CompareInfo.CompareOrdinalIgnoreCase(a, 0, a.Length, b, 0, b.Length) == 0);
#else
                    return(TextInfo.CompareOrdinalIgnoreCase(a, b) == 0);
#endif
                }

            default:
                throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
            }
        }
Esempio n. 16
0
        public static TypedReference MakeTypedReference(Object target, FieldInfo[] flds)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }
            if (flds == null)
            {
                throw new ArgumentNullException("flds");
            }
            Contract.EndContractBlock();
            if (flds.Length == 0)
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_ArrayZeroError"));
            }

            IntPtr[] fields = new IntPtr[flds.Length];
            // For proper handling of Nullable<T> don't change GetType() to something like 'IsAssignableFrom'
            // Currently we can't make a TypedReference to fields of Nullable<T>, which is fine.
            RuntimeType targetType = (RuntimeType)target.GetType();

            for (int i = 0; i < flds.Length; i++)
            {
                RuntimeFieldInfo field = flds[i] as RuntimeFieldInfo;
                if (field == null)
                {
                    throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"));
                }

                if (field.IsInitOnly || field.IsStatic)
                {
                    throw new ArgumentException(Environment.GetResourceString("Argument_TypedReferenceInvalidField"));
                }

                if (targetType != field.GetDeclaringTypeInternal() && !targetType.IsSubclassOf(field.GetDeclaringTypeInternal()))
                {
                    throw new MissingMemberException(Environment.GetResourceString("MissingMemberTypeRef"));
                }

                RuntimeType fieldType = (RuntimeType)field.FieldType;
                if (fieldType.IsPrimitive)
                {
                    throw new ArgumentException(Environment.GetResourceString("Arg_TypeRefPrimitve"));
                }

                if (i < (flds.Length - 1) && !fieldType.IsValueType)
                {
                    throw new MissingMemberException(Environment.GetResourceString("MissingMemberNestErr"));
                }

                fields[i]  = field.FieldHandle.Value;
                targetType = fieldType;
            }

#if MONO
            return(MakeTypedReferenceInternal(target, flds));
#else
            TypedReference result = new TypedReference();

            // reference to TypedReference is banned, so have to pass result as pointer
            unsafe
            {
                InternalMakeTypedReference(&result, target, fields, targetType);
            }
            return(result);
#endif
        }
Esempio n. 17
0
        public Boolean StartsWith(String value, StringComparison comparisonType)
        {
            if ((Object)value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
            {
                throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
            }
            Contract.EndContractBlock();

            if ((Object)this == (Object)value)
            {
                return(true);
            }

            if (value.Length == 0)
            {
                return(true);
            }

            switch (comparisonType)
            {
            case StringComparison.CurrentCulture:
                return(CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, CompareOptions.None));

            case StringComparison.CurrentCultureIgnoreCase:
                return(CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, CompareOptions.IgnoreCase));

            case StringComparison.InvariantCulture:
                return(CultureInfo.InvariantCulture.CompareInfo.IsPrefix(this, value, CompareOptions.None));

            case StringComparison.InvariantCultureIgnoreCase:
                return(CultureInfo.InvariantCulture.CompareInfo.IsPrefix(this, value, CompareOptions.IgnoreCase));

            case StringComparison.Ordinal:
                if (this.Length < value.Length || m_firstChar != value.m_firstChar)
                {
                    return(false);
                }
                return((value.Length == 1) ?
                       true :                      // First char is the same and thats all there is to compare
                       StartsWithOrdinalHelper(this, value));

            case StringComparison.OrdinalIgnoreCase:
                if (this.Length < value.Length)
                {
                    return(false);
                }

#if FEATURE_COREFX_GLOBALIZATION
                return(CompareInfo.CompareOrdinalIgnoreCase(this, 0, value.Length, value, 0, value.Length) == 0);
#else
                return(TextInfo.CompareOrdinalIgnoreCaseEx(this, 0, value, 0, value.Length, value.Length) == 0);
#endif

            default:
                throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
            }
        }
Esempio n. 18
0
        /// <summary>Gets a Task to represent the asynchronous operation.</summary>
        /// <param name="source">The asynchronous operation.</param>
        /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param>
        /// <param name="progress">The progress object used to receive progress updates.</param>
        /// <returns>The Task representing the asynchronous operation.</returns>
        public static Task <TResult> AsTask <TResult, TProgress>(this IAsyncOperationWithProgress <TResult, TProgress> source,
                                                                 CancellationToken cancellationToken, IProgress <TProgress> progress)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }

            Contract.EndContractBlock();

            // If source is actually a NetFx-to-WinRT adapter, unwrap it instead of creating a new Task:
            var wrapper = source as TaskToAsyncOperationWithProgressAdapter <TResult, TProgress>;

            if (wrapper != null && !wrapper.CompletedSynchronously)
            {
                Task <TResult> innerTask = wrapper.Task as Task <TResult>;
                Debug.Assert(innerTask != null);
                Debug.Assert(innerTask.Status != TaskStatus.Created);  // Is WaitingForActivation a legal state at this moment?

                if (!innerTask.IsCompleted)
                {
                    // The race here is benign: If the task completes here, the concatinations are useless, but not damaging.

                    if (cancellationToken.CanBeCanceled && wrapper.CancelTokenSource != null)
                    {
                        ConcatenateCancelTokens(cancellationToken, wrapper.CancelTokenSource, innerTask);
                    }

                    if (progress != null)
                    {
                        ConcatenateProgress(source, progress);
                    }
                }

                return(innerTask);
            }

            // Fast path to return a completed Task if the operation has already completed
            switch (source.Status)
            {
            case AsyncStatus.Completed:
                return(Task.FromResult(source.GetResults()));

            case AsyncStatus.Error:
                return(Task.FromException <TResult>(source.ErrorCode.AttachRestrictedErrorInfo()));

            case AsyncStatus.Canceled:
                return(Task.FromCanceled <TResult>(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)));
            }

            // Benign race: source may complete here. Things still work, just not taking the fast path.

            // Forward progress reports:
            if (progress != null)
            {
                ConcatenateProgress(source, progress);
            }

            // Source is not a NetFx-to-WinRT adapter, but a native future. Hook up the task:
            var bridge = new AsyncInfoToTaskBridge <TResult>(cancellationToken);

            try
            {
                source.Completed = new AsyncOperationWithProgressCompletedHandler <TResult, TProgress>(bridge.CompleteFromAsyncOperationWithProgress);
                bridge.RegisterForCancellation(source);
            }
            catch
            {
                AsyncCausalitySupport.RemoveFromActiveTasks(bridge.Task);
            }
            return(bridge.Task);
        }
Esempio n. 19
0
        internal static DelegateEntry GetDelegateSerializationInfo(
            SerializationInfo info, Type delegateType, Object target, MethodInfo method, int targetIndex)
        {
            // Used for MulticastDelegate

            if (method == null)
            {
                throw new ArgumentNullException(nameof(method));
            }
            Contract.EndContractBlock();

            if (!method.IsPublic || (method.DeclaringType != null && !method.DeclaringType.IsVisible))
            {
                new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
            }

            Type c = delegateType.BaseType;

            if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), "type");
            }

            if (method.DeclaringType == null)
            {
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization"));
            }

            DelegateEntry de = new DelegateEntry(delegateType.FullName, delegateType.Module.Assembly.FullName, target,
                                                 method.ReflectedType.Module.Assembly.FullName, method.ReflectedType.FullName, method.Name);

            if (info.MemberCount == 0)
            {
                info.SetType(typeof(DelegateSerializationHolder));
                info.AddValue("Delegate", de, typeof(DelegateEntry));
            }

            // target can be an object so it needs to be added to the info, or else a fixup is needed
            // when deserializing, and the fixup will occur too late. If it is added directly to the
            // info then the rules of deserialization will guarantee that it will be available when
            // needed

            if (target != null)
            {
                String targetName = "target" + targetIndex;
                info.AddValue(targetName, de.target);
                de.target = targetName;
            }

            // Due to a number of additions (delegate signature binding relaxation, delegates with open this or closed over the
            // first parameter and delegates over generic methods) we need to send a deal more information than previously. We can
            // get this by serializing the target MethodInfo. We still need to send the same information as before though (the
            // DelegateEntry above) for backwards compatibility. And we want to send the MethodInfo (which is serialized via an
            // ISerializable holder) as a top-level child of the info for the same reason as the target above -- we wouldn't have an
            // order of deserialization guarantee otherwise.
            String methodInfoName = "method" + targetIndex;

            info.AddValue(methodInfoName, method);

            return(de);
        }
Esempio n. 20
0
        public bool Equals(String value, StringComparison comparisonType)
        {
            if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
            {
                throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
            }
            Contract.EndContractBlock();

            if ((Object)this == (Object)value)
            {
                return(true);
            }

            if ((Object)value == null)
            {
                return(false);
            }

            switch (comparisonType)
            {
            case StringComparison.CurrentCulture:
                return(CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, CompareOptions.None) == 0);

            case StringComparison.CurrentCultureIgnoreCase:
                return(CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, CompareOptions.IgnoreCase) == 0);

            case StringComparison.InvariantCulture:
                return(CultureInfo.InvariantCulture.CompareInfo.Compare(this, value, CompareOptions.None) == 0);

            case StringComparison.InvariantCultureIgnoreCase:
                return(CultureInfo.InvariantCulture.CompareInfo.Compare(this, value, CompareOptions.IgnoreCase) == 0);

            case StringComparison.Ordinal:
                if (this.Length != value.Length)
                {
                    return(false);
                }
                return(EqualsHelper(this, value));

            case StringComparison.OrdinalIgnoreCase:
                if (this.Length != value.Length)
                {
                    return(false);
                }

                // If both strings are ASCII strings, we can take the fast path.
                if (this.IsAscii() && value.IsAscii())
                {
                    return(CompareOrdinalIgnoreCaseHelper(this, value) == 0);
                }

#if FEATURE_COREFX_GLOBALIZATION
                return(CompareInfo.CompareOrdinalIgnoreCase(this, 0, this.Length, value, 0, value.Length) == 0);
#else
                // Take the slow path.
                return(TextInfo.CompareOrdinalIgnoreCase(this, value) == 0);
#endif

            default:
                throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
            }
        }
Esempio n. 21
0
        public static string Normalize(this string value, NormalizationForm normalizationForm)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            Contract.EndContractBlock();

            // we depend on Win32 last error when calling NormalizeString
            Interop.mincore.SetLastError(Interop.ERROR_SUCCESS);

            // Guess our buffer size first
            int iLength = Interop.mincore.NormalizeString((int)normalizationForm, value, value.Length, null, 0);

            int lastError = Marshal.GetLastWin32Error();

            // Could have an error (actually it'd be quite hard to have an error here)
            if ((lastError != Interop.ERROR_SUCCESS && lastError != Interop.LAST_ERROR_TRASH_VALUE) ||
                iLength < 0)
            {
                if (lastError == Interop.ERROR_INVALID_PARAMETER)
                {
                    throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, "value");
                }

                // We shouldn't really be able to get here..., guessing length is
                // a trivial math function...
                // Can't really be Out of Memory, but just in case:
                if (lastError == Interop.ERROR_NOT_ENOUGH_MEMORY)
                {
                    throw new OutOfMemoryException(SR.Arg_OutOfMemoryException);
                }

                // Who knows what happened?  Not us!
                throw new InvalidOperationException(SR.Format(SR.UnknownError_Num, lastError));
            }

            // Don't break for empty strings (only possible for D & KD and not really possible at that)
            if (iLength == 0)
            {
                return(string.Empty);
            }

            // Someplace to stick our buffer
            char[] cBuffer = null;

            for (; ;)
            {
                // (re)allocation buffer and normalize string
                cBuffer = new char[iLength];

                // Reset last error
                Interop.mincore.SetLastError(Interop.ERROR_SUCCESS);
                iLength   = Interop.mincore.NormalizeString((int)normalizationForm, value, value.Length, cBuffer, cBuffer.Length);
                lastError = Marshal.GetLastWin32Error();

                if (lastError == Interop.ERROR_SUCCESS || lastError == Interop.LAST_ERROR_TRASH_VALUE)
                {
                    break;
                }

                // Could have an error (actually it'd be quite hard to have an error here)
                switch (lastError)
                {
                // Do appropriate stuff for the individual errors:
                case Interop.ERROR_INSUFFICIENT_BUFFER:
                    iLength = Math.Abs(iLength);
                    Debug.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length");
                    continue;

                case Interop.ERROR_INVALID_PARAMETER:
                case Interop.ERROR_NO_UNICODE_TRANSLATION:
                    // Illegal code point or order found.  Ie: FFFE or D800 D800, etc.
                    throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, "value");

                case Interop.ERROR_NOT_ENOUGH_MEMORY:
                    throw new OutOfMemoryException(SR.Arg_OutOfMemoryException);

                default:
                    // We shouldn't get here...
                    throw new InvalidOperationException(SR.Format(SR.UnknownError_Num, lastError));
                }
            }

            // Copy our buffer into our new string, which will be the appropriate size
            return(new string(cBuffer, 0, iLength));
        }
Esempio n. 22
0
        public static int Compare(String strA, String strB, StringComparison comparisonType)
        {
            // Single comparison to check if comparisonType is within [CurrentCulture .. OrdinalIgnoreCase]
            if ((uint)(comparisonType - StringComparison.CurrentCulture) > (uint)(StringComparison.OrdinalIgnoreCase - StringComparison.CurrentCulture))
            {
                throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
            }
            Contract.EndContractBlock();

            if (object.ReferenceEquals(strA, strB))
            {
                return(0);
            }

            // They can't both be null at this point.
            if (strA == null)
            {
                return(-1);
            }
            if (strB == null)
            {
                return(1);
            }

            switch (comparisonType)
            {
            case StringComparison.CurrentCulture:
                return(CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.None));

            case StringComparison.CurrentCultureIgnoreCase:
                return(CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase));

            case StringComparison.InvariantCulture:
                return(CultureInfo.InvariantCulture.CompareInfo.Compare(strA, strB, CompareOptions.None));

            case StringComparison.InvariantCultureIgnoreCase:
                return(CultureInfo.InvariantCulture.CompareInfo.Compare(strA, strB, CompareOptions.IgnoreCase));

            case StringComparison.Ordinal:
                // Most common case: first character is different.
                // Returns false for empty strings.
                if (strA.m_firstChar != strB.m_firstChar)
                {
                    return(strA.m_firstChar - strB.m_firstChar);
                }

                return(CompareOrdinalHelper(strA, strB));

            case StringComparison.OrdinalIgnoreCase:
                // If both strings are ASCII strings, we can take the fast path.
                if (strA.IsAscii() && strB.IsAscii())
                {
                    return(CompareOrdinalIgnoreCaseHelper(strA, strB));
                }

#if FEATURE_COREFX_GLOBALIZATION
                return(CompareInfo.CompareOrdinalIgnoreCase(strA, 0, strA.Length, strB, 0, strB.Length));
#else
                // Take the slow path.
                return(TextInfo.CompareOrdinalIgnoreCase(strA, strB));
#endif

            default:
                throw new NotSupportedException(Environment.GetResourceString("NotSupported_StringComparison"));
            }
        }
Esempio n. 23
0
 public String ToString(IFormatProvider provider)
 {
     Contract.Ensures(Contract.Result <String>() != null);
     Contract.EndContractBlock();
     return(this);
 }
Esempio n. 24
0
 // Returns this string.
 public override String ToString()
 {
     Contract.Ensures(Contract.Result <String>() != null);
     Contract.EndContractBlock();
     return(this);
 }
 /*==================================NextBytes===================================
 **Action:  Fills the byte array with random bytes [0..0x7f].  The entire array is filled.
 **Returns:Void
 **Arugments:  buffer -- the array to be filled. 
 **Exceptions: None
 ==============================================================================*/
 public virtual void NextBytes(byte [] buffer){ 
   if (buffer==null) throw new ArgumentNullException("buffer");
   Contract.EndContractBlock(); 
   for (int i=0; i<buffer.length; i++)="" {="" buffer[i]="(byte)(InternalSample()%(Byte.MaxValue+1));" }="" file="" provided="" for="" reference="" use="" only="" by="" microsoft="" corporation="" (c)="" 2007.="" =="++==" copyright="" corporation.="" all="" rights="" reserved.="" *="===========================================================" **="" class:="" random="" purpose:="" a="" number="" generator.="" namespace="" system="" using="" system;="" system.runtime;="" system.runtime.compilerservices;="" system.globalization;="" system.diagnostics.contracts;="" [system.runtime.interopservices.comvisible(true)]="" [serializable]="" public="" class="" private="" constants="" const="" int="" mbig="Int32.MaxValue;" mseed="161803398;" mz="0;" member="" variables="" inext;="" inextp;="" int[]="" seedarray="new" int[56];="" native="" declarations="" constructors="" random()="" :="" this(environment.tickcount)="" random(int="" seed)="" ii;="" mj,="" mk;="" initialize="" our="" seed="" array.="" this="" algorithm="" comes="" from="" numerical="" recipes="" in="" c="" (2nd="" ed.)="" subtraction="(Seed" ?="" int32.maxvalue="" math.abs(seed);="" mj="MSEED" -="" subtraction;="" seedarray[55]="mj;" mk="1;" (int="" i="1;" i<55;="" apparently="" the="" range="" [1..55]="" is="" special="" (knuth)="" and="" so="" we're="" wasting="" 0'th="" position.="" ii="(21*i)%55;" seedarray[ii]="mk;" if="" (mk<0)="" mk+="MBIG;" k="1;" k<5;="" k++)="" i<56;="" seedarray[i]="" (seedarray[i]<0)="" seedarray[i]+="MBIG;" inext="0;" inextp="21;" package="" methods="" **action:="" return="" new="" [0..1)="" reseed="" **returns:="" double="" **arguments:="" none="" **exceptions:="" #if="" !feature_coreclr="" [targetedpatchingoptout("performance="" critical="" to="" inline="" across="" ngen="" image="" boundaries")]="" #endif="" protected="" virtual="" sample()="" including="" division="" at="" end="" gives="" us="" significantly="" improved="" distribution.="" (internalsample()*(1.0="" mbig));="" internalsample()="" retval;="" locinext="inext;" locinextp="inextp;" (++locinext="">=56) locINext=1;
Esempio n. 26
0
        private DelegateSerializationHolder(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
            {
                throw new ArgumentNullException(nameof(info));
            }
            Contract.EndContractBlock();

            bool bNewWire = true;

            try
            {
                m_delegateEntry = (DelegateEntry)info.GetValue("Delegate", typeof(DelegateEntry));
            }
            catch
            {
                // Old wire format
                m_delegateEntry = OldDelegateWireFormat(info, context);
                bNewWire        = false;
            }

            if (bNewWire)
            {
                // retrieve the targets
                DelegateEntry deiter = m_delegateEntry;
                int           count  = 0;
                while (deiter != null)
                {
                    if (deiter.target != null)
                    {
                        string stringTarget = deiter.target as string; //need test to pass older wire format
                        if (stringTarget != null)
                        {
                            deiter.target = info.GetValue(stringTarget, typeof(Object));
                        }
                    }
                    count++;
                    deiter = deiter.delegateEntry;
                }

                // If the sender is as recent as us they'll have provided MethodInfos for each delegate. Look for these and pack
                // them into an ordered array if present.
                MethodInfo[] methods = new MethodInfo[count];
                int          i;
                for (i = 0; i < count; i++)
                {
                    String methodInfoName = "method" + i;
                    methods[i] = (MethodInfo)info.GetValueNoThrow(methodInfoName, typeof(MethodInfo));
                    if (methods[i] == null)
                    {
                        break;
                    }
                }

                // If we got the info then make the array available for deserialization.
                if (i == count)
                {
                    m_methods = methods;
                }
            }
        }
Esempio n. 27
0
 // Method required for the ICloneable interface.
 // There's no point in cloning a string since they're immutable, so we simply return this.
 public Object Clone()
 {
     Contract.Ensures(Contract.Result <Object>() != null);
     Contract.EndContractBlock();
     return(this);
 }
Esempio n. 28
0
        public static int Compare(String strA, int indexA, String strB, int indexB, int length, StringComparison comparisonType)
        {
            if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
            {
                throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
            }
            Contract.EndContractBlock();

            if (strA == null || strB == null)
            {
                if (object.ReferenceEquals(strA, strB))
                {
                    // They're both null
                    return(0);
                }

                return(strA == null ? -1 : 1);
            }

            if (length < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
            }

            if (indexA < 0 || indexB < 0)
            {
                string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
                throw new ArgumentOutOfRangeException(paramName, Environment.GetResourceString("ArgumentOutOfRange_Index"));
            }

            if (strA.Length - indexA < 0 || strB.Length - indexB < 0)
            {
                string paramName = strA.Length - indexA < 0 ? nameof(indexA) : nameof(indexB);
                throw new ArgumentOutOfRangeException(paramName, Environment.GetResourceString("ArgumentOutOfRange_Index"));
            }

            if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
            {
                return(0);
            }

            int lengthA = Math.Min(length, strA.Length - indexA);
            int lengthB = Math.Min(length, strB.Length - indexB);

            switch (comparisonType)
            {
            case StringComparison.CurrentCulture:
                return(CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None));

            case StringComparison.CurrentCultureIgnoreCase:
                return(CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase));

            case StringComparison.InvariantCulture:
                return(CultureInfo.InvariantCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None));

            case StringComparison.InvariantCultureIgnoreCase:
                return(CultureInfo.InvariantCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.IgnoreCase));

            case StringComparison.Ordinal:
                return(CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB));

            case StringComparison.OrdinalIgnoreCase:
#if FEATURE_COREFX_GLOBALIZATION
                return(CompareInfo.CompareOrdinalIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB));
#else
                return(TextInfo.CompareOrdinalIgnoreCaseEx(strA, indexA, strB, indexB, lengthA, lengthB));
#endif

            default:
                throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"));
            }
        }
Esempio n. 29
0
 [System.Security.SecurityCritical]  // auto-generated_required
 public static ObjectHandle CreateInstanceFrom (AppDomain domain, string assemblyFile, string typeName) {
     if (domain == null)
         throw new ArgumentNullException("domain");
     Contract.EndContractBlock();
     return domain.InternalCreateInstanceFromWithNoSecurity(assemblyFile, typeName);
 }
Esempio n. 30
0
        private void CreateFromNameAndManifests(ApplicationIdentity applicationIdentity, string[] manifestPaths)
        {
            if (applicationIdentity == null)
            {
                throw new ArgumentNullException("applicationIdentity");
            }
            if (manifestPaths == null)
            {
                throw new ArgumentNullException("manifestPaths");
            }
            Contract.EndContractBlock();

            _applicationIdentity = applicationIdentity;

            // ISSUE - need validation on manifestPaths

            IEnumDefinitionIdentity idenum = _applicationIdentity.Identity.EnumAppPath();

            _manifests     = new ArrayList(DefaultComponentCount);
            _manifestPaths = new String[manifestPaths.Length];

            IDefinitionIdentity[] asbId = new IDefinitionIdentity[1];
            int i = 0;

            while (idenum.Next(1, asbId) == 1)
            {
                ICMS cms = (ICMS)IsolationInterop.ParseManifest(manifestPaths[i], null, ref IsolationInterop.IID_ICMS);

                if (IsolationInterop.IdentityAuthority.AreDefinitionsEqual(0, cms.Identity, asbId[0]))
                {
                    _manifests.Add(cms);
                    _manifestPaths[i] = manifestPaths[i];
                }
                else
                {
#if ISOLATION_IN_MSCORLIB
                    throw new ArgumentException(Environment.GetResourceString("Argument_IllegalAppIdMismatch"));
#else
                    throw new ArgumentException("Application Identity does not match identity in manifests");
#endif
                }
                i++;
            }
            if (i != manifestPaths.Length)
            {
#if ISOLATION_IN_MSCORLIB
                throw new ArgumentException(Environment.GetResourceString("Argument_IllegalAppId"));
#else
                throw new ArgumentException("Application Identity does not have same number of components as manifest paths");
#endif
            }
            _manifests.TrimToSize();
            if (_manifests.Count <= 1)
            {
#if ISOLATION_IN_MSCORLIB
                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidAppId"));
#else
                throw new ArgumentException("Invalid identity: no deployment/app identity specified");
#endif
            }

            _definitionIdentities = null;
            _actContext           = null;
            _form        = ContextForm.Loose;
            _appRunState = ApplicationStateDisposition.Undefined;

#if ISOLATION_IN_MSCORLIB
            Contract.Assert(_manifests.Count == 2, "An application must have exactly 1 deployment component and 1 application component in Whidbey");
#endif
        }