private static ArgumentException CreateChangeTypeArgumentException(EETypePtr srcEEType, EETypePtr dstEEType)
 {
     return(new ArgumentException(SR.Format(SR.Arg_ObjObjEx, Type.GetTypeFromHandle(new RuntimeTypeHandle(srcEEType)), Type.GetTypeFromHandle(new RuntimeTypeHandle(dstEEType)))));
 }
Example #2
0
 private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object key)
 {
     return(new ArgumentException(SR.Format(SR.Argument_AddingDuplicateWithKey, key)));
 }
Example #3
0
        public static TypedReference MakeTypedReference(object target, FieldInfo[] flds)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (flds == null)
            {
                throw new ArgumentNullException(nameof(flds));
            }
            if (flds.Length == 0)
            {
                throw new ArgumentException(SR.Arg_ArrayZeroError, nameof(flds));
            }

            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(SR.Argument_MustBeRuntimeFieldInfo);
                }

                if (field.IsStatic)
                {
                    throw new ArgumentException(SR.Format(SR.Argument_TypedReferenceInvalidField, field.Name));
                }

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

                RuntimeType fieldType = (RuntimeType)field.FieldType;
                if (fieldType.IsPrimitive)
                {
                    throw new ArgumentException(SR.Format(SR.Arg_TypeRefPrimitve, field.Name));
                }

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

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

            TypedReference result = new TypedReference();

            // reference to TypedReference is banned, so have to pass result as pointer
            unsafe
            {
                InternalMakeTypedReference(&result, target, fields, targetType);
            }
            return(result);
        }
Example #4
0
        public static object CreateInstance(
            [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)]
            Type type, BindingFlags bindingAttr, Binder binder, object?[]?args, CultureInfo?culture, object?[]?activationAttributes)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            // If they didn't specify a lookup, then we will provide the default lookup.
            const BindingFlags LookupMask = (BindingFlags)0x000000FF;

            if ((bindingAttr & LookupMask) == 0)
            {
                bindingAttr |= BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;
            }

            if (activationAttributes != null && activationAttributes.Length > 0)
            {
                throw new PlatformNotSupportedException(SR.NotSupported_ActivAttr);
            }

            type = type.UnderlyingSystemType;
            CreateInstanceCheckType(type);

            args ??= Array.Empty <object>();
            int numArgs = args.Length;

            Type?[] argTypes = new Type[numArgs];
            for (int i = 0; i < numArgs; i++)
            {
                argTypes[i] = args[i]?.GetType();
            }

            ConstructorInfo[]        candidates = type.GetConstructors(bindingAttr);
            ListBuilder <MethodBase> matches    = new ListBuilder <MethodBase>(candidates.Length);

            for (int i = 0; i < candidates.Length; i++)
            {
                if (candidates[i].QualifiesBasedOnParameterCount(bindingAttr, CallingConventions.Any, argTypes))
                {
                    matches.Add(candidates[i]);
                }
            }
            if (matches.Count == 0)
            {
                if (numArgs == 0 && type.IsValueType)
                {
                    return(RuntimeAugments.NewObject(type.TypeHandle));
                }

                throw new MissingMethodException(SR.Format(SR.Arg_NoDefCTor, type));
            }

            binder ??= Type.DefaultBinder;

            MethodBase invokeMethod = binder.BindToMethod(bindingAttr, matches.ToArray(), ref args, null, culture, null, out object?state);

            if (invokeMethod.GetParametersNoCopy().Length == 0)
            {
                if (args.Length != 0)
                {
                    Debug.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs);
                    throw new NotSupportedException(SR.NotSupported_CallToVarArg);
                }

                // Desktop compat: CoreClr invokes a "fast-path" here (call Activator.CreateInstance(type, true)) that also
                // bypasses the binder.ReorderArgumentArray() call. That "fast-path" isn't a fast-path for us so we won't do that
                // but we'll still null out the "state" variable to bypass the Reorder call.
                //
                // The only time this matters at all is if (1) a third party binder is being used and (2) it actually reordered the array
                // which it shouldn't have done because (a) we didn't request it to bind arguments by name, and (b) it's kinda hard to
                // reorder a zero-length args array. But who knows what a third party binder will do if we make a call to it that we didn't
                // used to do, so we'll preserve the CoreClr order of calls just to be safe.
                state = null;
            }

            object result = ((ConstructorInfo)invokeMethod).Invoke(bindingAttr, binder, args, culture);

            System.Diagnostics.DebugAnnotations.PreviousCallContainsDebuggerStepInCode();
            if (state != null)
            {
                binder.ReorderArgumentArray(ref args, state);
            }
            return(result);
        }
 public TypeInitializationException(String fullTypeName, Exception innerException)
     : this(fullTypeName, SR.Format(SR.TypeInitialization_Type, fullTypeName), innerException)
 {
 }
Example #6
0
        private static Type?ResolveType(Assembly assembly, List <string> names, Func <Assembly, string, bool, Type?>?typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark)
        {
            Type?type = null;

            string name = EscapeTypeName(names[0]);

            // Resolve the top level type.
            if (typeResolver != null)
            {
                type = typeResolver(assembly, name, ignoreCase);
                if (type == null && throwOnError)
                {
                    if (assembly == null)
                    {
                        throw new TypeLoadException(SR.Format(SR.TypeLoad_ResolveType, name));
                    }
                    else
                    {
                        throw new TypeLoadException(SR.Format(SR.TypeLoad_ResolveTypeFromAssembly, name, assembly.FullName));
                    }
                }
            }
            else
            {
                if (assembly == null)
                {
                    type = RuntimeType.GetType(name, throwOnError, ignoreCase, false, ref stackMark);
                }
                else
                {
                    type = assembly.GetType(name, throwOnError, ignoreCase);
                }
            }

            if (type == null)
            {
                return(null);
            }

            // Resolve nested types.
            BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Public;

            if (ignoreCase)
            {
                bindingFlags |= BindingFlags.IgnoreCase;
            }

            for (int i = 1; i < names.Count; ++i)
            {
                type = type.GetNestedType(names[i], bindingFlags);
                if (type == null)
                {
                    if (throwOnError)
                    {
                        throw new TypeLoadException(SR.Format(SR.TypeLoad_ResolveNestedType, names[i], names[i - 1]));
                    }
                    else
                    {
                        break;
                    }
                }
            }
            return(type);
        }
Example #7
0
        //
        // Internal stuff
        //

        // Returns false if OriginalString value
        // (1) is not correctly escaped as per URI spec excluding intl UNC name case
        // (2) or is an absolute Uri that represents implicit file Uri "c:\dir\file"
        // (3) or is an absolute Uri that misses a slash before path "file://c:/dir/file"
        // (4) or contains unescaped backslashes even if they will be treated
        //     as forward slashes like http:\\host/path\file or file:\\\c:\path
        //
        internal unsafe bool InternalIsWellFormedOriginalString()
        {
            if (UserDrivenParsing)
            {
                throw new InvalidOperationException(SR.GetString(SR.net_uri_UserDrivenParsing, this.GetType().FullName));

                fixed(char *str = m_String)
                {
                    ushort idx = 0;

                    //
                    // For a relative Uri we only care about escaping and backslashes
                    //
                    if (!IsAbsoluteUri)
                    {
                        // my:scheme/path?query is not well formed because the colon is ambiguous
                        if (!UriParser.ShouldUseLegacyV2Quirks && CheckForColonInFirstPathSegment(m_String))
                        {
                            return(false);
                        }
                        return((CheckCanonical(str, ref idx, (ushort)m_String.Length, c_EOL)
                                & (Check.BackslashInPath | Check.EscapedCanonical)) == Check.EscapedCanonical);
                    }

                    //
                    // (2) or is an absolute Uri that represents implicit file Uri "c:\dir\file"
                    //
                    if (IsImplicitFile)
                    {
                        return(false);
                    }

                    //This will get all the offsets, a Host name will be checked separatelly below
                    EnsureParseRemaining();

                    Flags nonCanonical = (m_Flags & (Flags.E_CannotDisplayCanonical | Flags.IriCanonical));

                    // User, Path, Query or Fragment may have some non escaped characters
                    if (((nonCanonical & Flags.E_CannotDisplayCanonical & (Flags.E_UserNotCanonical | Flags.E_PathNotCanonical |
                                                                           Flags.E_QueryNotCanonical | Flags.E_FragmentNotCanonical)) != Flags.Zero) &&
                        (!m_iriParsing || (m_iriParsing &&
                                           (((nonCanonical & Flags.E_UserNotCanonical) == 0) || ((nonCanonical & Flags.UserIriCanonical) == 0)) &&
                                           (((nonCanonical & Flags.E_PathNotCanonical) == 0) || ((nonCanonical & Flags.PathIriCanonical) == 0)) &&
                                           (((nonCanonical & Flags.E_QueryNotCanonical) == 0) || ((nonCanonical & Flags.QueryIriCanonical) == 0)) &&
                                           (((nonCanonical & Flags.E_FragmentNotCanonical) == 0) || ((nonCanonical & Flags.FragmentIriCanonical) == 0)))))
                    {
                        return(false);
                    }

                    // checking on scheme:\\ or file:////
                    if (InFact(Flags.AuthorityFound))
                    {
                        idx = (ushort)(m_Info.Offset.Scheme + m_Syntax.SchemeName.Length + 2);
                        if (idx >= m_Info.Offset.User || m_String[idx - 1] == '\\' || m_String[idx] == '\\')
                        {
                            return(false);
                        }

#if !PLATFORM_UNIX
                        if (InFact(Flags.UncPath | Flags.DosPath))
                        {
                            while (++idx < m_Info.Offset.User && (m_String[idx] == '/' || m_String[idx] == '\\'))
                            {
                                return(false);
                            }
                        }
#endif // !PLATFORM_UNIX
                    }


                    // (3) or is an absolute Uri that misses a slash before path "file://c:/dir/file"
                    // Note that for this check to be more general we assert that if Path is non empty and if it requires a first slash
                    // (which looks absent) then the method has to fail.
                    // Today it's only possible for a Dos like path, i.e. file://c:/bla would fail below check.
                    if (InFact(Flags.FirstSlashAbsent) && m_Info.Offset.Query > m_Info.Offset.Path)
                    {
                        return(false);
                    }

                    // (4) or contains unescaped backslashes even if they will be treated
                    //     as forward slashes like http:\\host/path\file or file:\\\c:\path
                    // Note we do not check for Flags.ShouldBeCompressed i.e. allow // /./ and alike as valid
                    if (InFact(Flags.BackslashInPath))
                    {
                        return(false);
                    }

                    // Capturing a rare case like file:///c|/dir
                    if (IsDosPath && m_String[m_Info.Offset.Path + SecuredPathIndex - 1] == '|')
                    {
                        return(false);
                    }

                    //
                    // May need some real CPU processing to anwser the request
                    //
                    //
                    // Check escaping for authority
                    //
                    // IPv6 hosts cannot be properly validated by CheckCannonical
                    if ((m_Flags & Flags.CanonicalDnsHost) == 0 && HostType != Flags.IPv6HostType)
                    {
                        idx = m_Info.Offset.User;
                        Check result = CheckCanonical(str, ref idx, (ushort)m_Info.Offset.Path, '/');
                        if (((result & (Check.ReservedFound | Check.BackslashInPath | Check.EscapedCanonical))
                             != Check.EscapedCanonical) &&
                            (!m_iriParsing || (m_iriParsing &&
                                               ((result & (Check.DisplayCanonical | Check.FoundNonAscii | Check.NotIriCanonical))
                                                != (Check.DisplayCanonical | Check.FoundNonAscii)))))
                        {
                            return(false);
                        }
                    }

                    // Want to ensure there are slashes after the scheme
                    if ((m_Flags & (Flags.SchemeNotCanonical | Flags.AuthorityFound))
                        == (Flags.SchemeNotCanonical | Flags.AuthorityFound))
                    {
                        idx = (ushort)m_Syntax.SchemeName.Length;
                        while (str[idx++] != ':')
                        {
                            ;
                        }
                        if (idx + 1 >= m_String.Length || str[idx] != '/' || str[idx + 1] != '/')
                        {
                            return(false);
                        }
                    }
                }

                //
                // May be scheme, host, port or path need some canonicalization but still the uri string is found to be a
                // "well formed" one
                //
                return(true);
        }
Example #8
0
 internal static void ThrowInvalidTypeWithPointersNotSupported(Type targetType)
 {
     throw new ArgumentException(SR.Format(SR.Argument_InvalidTypeWithPointersNotSupported, targetType));
 }
Example #9
0
 // Looks up the resource string value for key.
 //
 // if you change this method's signature then you must change the code that calls it
 // in excep.cpp and probably you will have to visit mscorlib.h to add the new signature
 // as well as metasig.h to create the new signature type
 internal static String GetResourceStringLocal(String key)
 {
     return(SR.GetResourceString(key));
 }
Example #10
0
        private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target)
        {
            if (target == EnvironmentVariableTarget.Process)
            {
                SetEnvironmentVariableCore(variable, value);
                return;
            }

#if !FEATURE_WIN32_REGISTRY
            // other targets ignored
            return;
#else
            // explicitly null out value if is the empty string.
            if (string.IsNullOrEmpty(value) || value[0] == '\0')
            {
                value = null;
            }

            RegistryKey baseKey;
            string      keyName;

            if (target == EnvironmentVariableTarget.Machine)
            {
                baseKey = Registry.LocalMachine;
                keyName = @"System\CurrentControlSet\Control\Session Manager\Environment";
            }
            else if (target == EnvironmentVariableTarget.User)
            {
                Debug.Assert(target == EnvironmentVariableTarget.User);

                // User-wide environment variables stored in the registry are limited to 255 chars for the environment variable name.
                const int MaxUserEnvVariableLength = 255;
                if (variable.Length >= MaxUserEnvVariableLength)
                {
                    throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(variable));
                }

                baseKey = Registry.CurrentUser;
                keyName = "Environment";
            }
            else
            {
                throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)target));
            }

            using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: true))
            {
                if (environmentKey != null)
                {
                    if (value == null)
                    {
                        environmentKey.DeleteValue(variable, throwOnMissingValue: false);
                    }
                    else
                    {
                        environmentKey.SetValue(variable, value);
                    }
                }
            }

            // send a WM_SETTINGCHANGE message to all windows
            IntPtr r = Win32Native.SendMessageTimeout(new IntPtr(Win32Native.HWND_BROADCAST),
                                                      Win32Native.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero);

            if (r == IntPtr.Zero)
            {
                Debug.Assert(false, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error());
            }
#endif // FEATURE_WIN32_REGISTRY
        }
Example #11
0
 private static KeyNotFoundException GetKeyNotFoundException(object key)
 {
     return(new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())));
 }
        public static string Normalize(this string strInput, NormalizationForm normalizationForm)
        {
            if (strInput == null)
            {
                throw new ArgumentNullException(nameof(strInput));
            }
            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, strInput, strInput.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, nameof(strInput));
                }

                // 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, strInput, strInput.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, nameof(strInput));

                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));
        }
Example #13
0
 // Used by VM
 internal static string?GetResourceStringLocal(string key) => SR.GetResourceString(key);
Example #14
0
 private static ArgumentException GetWrongKeyTypeArgumentException(object key, Type targetType)
 {
     return(new ArgumentException(SR.Format(SR.Arg_WrongType, key, targetType), nameof(key)));
 }
Example #15
0
 public static bool Parse(ReadOnlySpan <char> value) =>
 TryParse(value, out bool result) ? result : throw new FormatException(SR.Format(SR.Format_BadBoolean, new string(value)));
Example #16
0
 private static ArgumentException GetWrongValueTypeArgumentException(object value, Type targetType)
 {
     return(new ArgumentException(SR.Format(SR.Arg_WrongType, value, targetType), nameof(value)));
 }
Example #17
0
        public static unsafe void SetWindowSize(int width, int height)
        {
            if (width <= 0)
            {
                throw new ArgumentOutOfRangeException("width", width, SR.ArgumentOutOfRange_NeedPosNum);
            }
            if (height <= 0)
            {
                throw new ArgumentOutOfRangeException("height", height, SR.ArgumentOutOfRange_NeedPosNum);
            }

            // Get the position of the current console window
            Interop.mincore.CONSOLE_SCREEN_BUFFER_INFO csbi = GetBufferInfo();

            // If the buffer is smaller than this new window size, resize the
            // buffer to be large enough.  Include window position.
            bool resizeBuffer = false;

            Interop.mincore.COORD size = new Interop.mincore.COORD();
            size.X = csbi.dwSize.X;
            size.Y = csbi.dwSize.Y;
            if (csbi.dwSize.X < csbi.srWindow.Left + width)
            {
                if (csbi.srWindow.Left >= Int16.MaxValue - width)
                {
                    throw new ArgumentOutOfRangeException("width", SR.ArgumentOutOfRange_ConsoleWindowBufferSize);
                }
                size.X       = (short)(csbi.srWindow.Left + width);
                resizeBuffer = true;
            }
            if (csbi.dwSize.Y < csbi.srWindow.Top + height)
            {
                if (csbi.srWindow.Top >= Int16.MaxValue - height)
                {
                    throw new ArgumentOutOfRangeException("height", SR.ArgumentOutOfRange_ConsoleWindowBufferSize);
                }
                size.Y       = (short)(csbi.srWindow.Top + height);
                resizeBuffer = true;
            }
            if (resizeBuffer)
            {
                if (!Interop.mincore.SetConsoleScreenBufferSize(OutputHandle, size))
                {
                    throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error());
                }
            }

            Interop.mincore.SMALL_RECT srWindow = csbi.srWindow;
            // Preserve the position, but change the size.
            srWindow.Bottom = (short)(srWindow.Top + height - 1);
            srWindow.Right  = (short)(srWindow.Left + width - 1);

            if (!Interop.mincore.SetConsoleWindowInfo(OutputHandle, true, &srWindow))
            {
                int errorCode = Marshal.GetLastWin32Error();

                // If we resized the buffer, un-resize it.
                if (resizeBuffer)
                {
                    Interop.mincore.SetConsoleScreenBufferSize(OutputHandle, csbi.dwSize);
                }

                // Try to give a better error message here
                Interop.mincore.COORD bounds = Interop.mincore.GetLargestConsoleWindowSize(OutputHandle);
                if (width > bounds.X)
                {
                    throw new ArgumentOutOfRangeException("width", width, SR.Format(SR.ArgumentOutOfRange_ConsoleWindowSize_Size, bounds.X));
                }
                if (height > bounds.Y)
                {
                    throw new ArgumentOutOfRangeException("height", height, SR.Format(SR.ArgumentOutOfRange_ConsoleWindowSize_Size, bounds.Y));
                }

                throw Win32Marshal.GetExceptionForWin32Error(errorCode);
            }
        }
Example #18
0
 char IConvertible.ToChar(IFormatProvider provider)
 {
     throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "Char"));
 }
Example #19
0
 private void ThrowInsufficientInformation(string field)
 {
     throw new SerializationException(
               SR.Format(SR.Serialization_InsufficientDeserializationState, field));
 }
Example #20
0
 DateTime IConvertible.ToDateTime(IFormatProvider provider)
 {
     throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Byte", "DateTime"));
 }
Example #21
0
        public virtual Object GetRealObject(StreamingContext context)
        {
            // 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.

            Assembly assembly;

            switch (m_unityType)
            {
            case EmptyUnity:
            {
                return(Empty.Value);
            }

            case NullUnity:
            {
                return(DBNull.Value);
            }

            case MissingUnity:
            {
                return(Missing.Value);
            }

            case PartialInstantiationTypeUnity:
            {
                m_unityType = RuntimeTypeUnity;
                Type definition = GetRealObject(context) as Type;
                m_unityType = PartialInstantiationTypeUnity;

                if (m_instantiation[0] == null)
                {
                    return(null);
                }

                return(MakeElementTypes(definition.MakeGenericType(m_instantiation)));
            }

            case GenericParameterTypeUnity:
            {
                if (m_declaringMethod == null && m_declaringType == null)
                {
                    ThrowInsufficientInformation("DeclaringMember");
                }

                if (m_declaringMethod != null)
                {
                    return(m_declaringMethod.GetGenericArguments()[m_genericParameterPosition]);
                }

                return(MakeElementTypes(m_declaringType.GetGenericArguments()[m_genericParameterPosition]));
            }

            case RuntimeTypeUnity:
            {
                if (m_data == null || m_data.Length == 0)
                {
                    ThrowInsufficientInformation("Data");
                }

                if (m_assemblyName == null)
                {
                    ThrowInsufficientInformation("AssemblyName");
                }

                if (m_assemblyName.Length == 0)
                {
                    return(Type.GetType(m_data, true, false));
                }

                assembly = Assembly.Load(m_assemblyName);

                Type t = assembly.GetType(m_data, true, false);

                return(t);
            }

            case ModuleUnity:
            {
                if (m_data == null || m_data.Length == 0)
                {
                    ThrowInsufficientInformation("Data");
                }

                if (m_assemblyName == null)
                {
                    ThrowInsufficientInformation("AssemblyName");
                }

                assembly = Assembly.Load(m_assemblyName);

                Module namedModule = assembly.GetModule(m_data);

                if (namedModule == null)
                {
                    throw new SerializationException(
                              SR.Format(SR.Serialization_UnableToFindModule, m_data, m_assemblyName));
                }

                return(namedModule);
            }

            case AssemblyUnity:
            {
                if (m_data == null || m_data.Length == 0)
                {
                    ThrowInsufficientInformation("Data");
                }

                if (m_assemblyName == null)
                {
                    ThrowInsufficientInformation("AssemblyName");
                }

                assembly = Assembly.Load(m_assemblyName);

                return(assembly);
            }

            default:
                throw new ArgumentException(SR.Argument_InvalidUnity);
            }
        }
Example #22
0
        private static Type?ResolveType(Assembly?assembly, string[] names, Func <Assembly?, string, bool, Type?>?typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark)
        {
            Debug.Assert(names != null && names.Length > 0);

            Type?type = null;

            // both the customer provided and the default type resolvers accept escaped type names
            string OuterMostTypeName = EscapeTypeName(names[0]);

            // Resolve the top level type.
            if (typeResolver != null)
            {
                type = typeResolver(assembly, OuterMostTypeName, ignoreCase);

                if (type == null && throwOnError)
                {
                    string errorString = assembly == null?
                                         SR.Format(SR.TypeLoad_ResolveType, OuterMostTypeName) :
                                             SR.Format(SR.TypeLoad_ResolveTypeFromAssembly, OuterMostTypeName, assembly.FullName);

                    throw new TypeLoadException(errorString);
                }
            }
            else
            {
                if (assembly == null)
                {
                    type = RuntimeType.GetType(OuterMostTypeName, throwOnError, ignoreCase, ref stackMark);
                }
                else
                {
                    type = assembly.GetType(OuterMostTypeName, throwOnError, ignoreCase);
                }
            }

            // Resolve nested types.
            if (type != null)
            {
                BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Public;
                if (ignoreCase)
                {
                    bindingFlags |= BindingFlags.IgnoreCase;
                }

                for (int i = 1; i < names.Length; i++)
                {
                    type = type.GetNestedType(names[i], bindingFlags);

                    if (type == null)
                    {
                        if (throwOnError)
                        {
                            throw new TypeLoadException(SR.Format(SR.TypeLoad_ResolveNestedType, names[i], names[i - 1]));
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

            return(type);
        }
Example #23
0
 internal static void ThrowArgumentOutOfRangeException_PrecisionTooLarge()
 {
     throw new ArgumentOutOfRangeException("precision", SR.Format(SR.Argument_PrecisionTooLarge, StandardFormat.MaxPrecision));
 }