private static Exception CreateArgumentOutOfRangeException_PrecisionTooLarge() { return(new ArgumentOutOfRangeException("precision", SR.Format(SR.Argument_PrecisionTooLarge, StandardFormat.MaxPrecision))); }
decimal IConvertible.ToDecimal(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Decimal")); }
// Load the specified assembly, and call the specified type's // "static void Initialize()" method. private static void CallStartupHook(StartupHookNameOrPath startupHook) { Assembly assembly; try { if (startupHook.Path != null) { Debug.Assert(Path.IsPathFullyQualified(startupHook.Path)); assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(startupHook.Path); } else if (startupHook.AssemblyName != null) { Debug.Assert(startupHook.AssemblyName != null); assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(startupHook.AssemblyName); } else { // Empty slot - skip it return; } } catch (Exception assemblyLoadException) { throw new ArgumentException( SR.Format(SR.Argument_StartupHookAssemblyLoadFailed, startupHook.Path ?? startupHook.AssemblyName !.ToString()), assemblyLoadException); } Debug.Assert(assembly != null); Type type = assembly.GetType(StartupHookTypeName, throwOnError: true) !; // Look for a static method without any parameters MethodInfo?initializeMethod = type.GetMethod(InitializeMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static, null, // use default binder Type.EmptyTypes, // parameters null); // no parameter modifiers bool wrongSignature = false; if (initializeMethod == null) { // There weren't any static methods without // parameters. Look for any methods with the correct // name, to provide precise error handling. try { // This could find zero, one, or multiple methods // with the correct name. initializeMethod = type.GetMethod(InitializeMethodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); } catch (AmbiguousMatchException) { // Found multiple. Will throw below due to initializeMethod being null. Debug.Assert(initializeMethod == null); } if (initializeMethod != null) { // Found one wrongSignature = true; } else { // Didn't find any throw new MissingMethodException(StartupHookTypeName, InitializeMethodName); } } else if (initializeMethod.ReturnType != typeof(void)) { wrongSignature = true; } if (wrongSignature) { throw new ArgumentException(SR.Format(SR.Argument_InvalidStartupHookSignature, StartupHookTypeName + Type.Delimiter + InitializeMethodName, startupHook.Path ?? startupHook.AssemblyName.ToString())); } Debug.Assert(initializeMethod != null && initializeMethod.IsStatic && initializeMethod.ReturnType == typeof(void) && initializeMethod.GetParameters().Length == 0); initializeMethod.Invoke(null, null); }
public static unsafe float Round(float x, int digits, MidpointRounding mode) { if ((digits < 0) || (digits > maxRoundingDigits)) { throw new ArgumentOutOfRangeException(nameof(digits), SR.ArgumentOutOfRange_RoundingDigits); } if (mode < MidpointRounding.ToEven || mode > MidpointRounding.ToPositiveInfinity) { throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode)); } if (Abs(x) < singleRoundLimit) { var power10 = roundPower10Single[digits]; x *= power10; switch (mode) { // Rounds to the nearest value; if the number falls midway, // it is rounded to the nearest value with an even least significant digit case MidpointRounding.ToEven: { x = Round(x); break; } // Rounds to the nearest value; if the number falls midway, // it is rounded to the nearest value above (for positive numbers) or below (for negative numbers) case MidpointRounding.AwayFromZero: { float fraction = ModF(x, &x); if (Abs(fraction) >= 0.5) { x += Sign(fraction); } break; } // Directed rounding: Round to the nearest value, toward to zero case MidpointRounding.ToZero: { x = Truncate(x); break; } // Directed Rounding: Round down to the next value, toward negative infinity case MidpointRounding.ToNegativeInfinity: { x = Floor(x); break; } // Directed rounding: Round up to the next value, toward positive infinity case MidpointRounding.ToPositiveInfinity: { x = Ceiling(x); break; } default: { throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode)); } } x /= power10; } return(x); }
bool IConvertible.ToBoolean(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Boolean")); }
private static KeyNotFoundException GetKeyNotFoundException(object key) { throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); }
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); }
private void ThrowInsufficientInformation(string field) { throw new SerializationException( SR.Format(SR.Serialization_InsufficientDeserializationState, field)); }
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); } }
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); } }
char IConvertible.ToChar(IFormatProvider?provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "Char")); }
public static bool Parse(ReadOnlySpan <char> value) => TryParse(value, out bool result) ? result : throw new FormatException(SR.Format(SR.Format_BadBoolean, new string(value)));
public static T CreateInstance <T>() { T t = default(T); bool missingDefaultConstructor = false; EETypePtr eetype = EETypePtr.EETypePtrOf <T>(); if (!RuntimeHelpers.IsReference <T>()) { // Early out for valuetypes since we don't support default constructors anyway. // This lets codegens that expand IsReference<T> optimize away the rest of this code. } else if (eetype.ComponentSize != 0) { // ComponentSize > 0 indicates an array-like type (e.g. string, array, etc). // Allocating this using the normal allocator would result in silent heap corruption. missingDefaultConstructor = true; } else if (eetype.IsInterface) { // Do not attempt to allocate interface types either missingDefaultConstructor = true; } else { bool oldValueOfMissingDefaultCtorMarkerBool = s_createInstanceMissingDefaultConstructor; try { #if PROJECTN t = CreateInstanceIntrinsic <T>(); DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); #else t = (T)(RuntimeImports.RhNewObject(eetype)); // Run the default constructor. If the default constructor was missing, codegen // will expand DefaultConstructorOf to ClassWithMissingConstructor::.ctor // and we detect that later. IntPtr defaultConstructor = DefaultConstructorOf <T>(); RawCalliHelper.Call(defaultConstructor, t); DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); #endif } catch (Exception e) { throw new TargetInvocationException(e); } if (s_createInstanceMissingDefaultConstructor != oldValueOfMissingDefaultCtorMarkerBool) { missingDefaultConstructor = true; // We didn't call the real .ctor (because there wasn't one), but we still allocated // an uninitialized object. If it has a finalizer, it would run - prevent that. GC.SuppressFinalize(t); } } if (missingDefaultConstructor) { throw new MissingMethodException(SR.Format(SR.MissingConstructor_Name, typeof(T))); } return(t); }
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)); }
private static ArgumentException GetWrongValueTypeArgumentException(object value, Type targetType) { return(new ArgumentException(SR.Format(SR.Arg_WrongType, value, targetType), nameof(value))); }
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); }
private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object key) { return(new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key))); }
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))))); }
internal static void ThrowInvalidTypeWithPointersNotSupported(Type targetType) { throw new ArgumentException(SR.Format(SR.Argument_InvalidTypeWithPointersNotSupported, targetType)); }
// // 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.Format(SR.net_uri_UserDrivenParsing, this.GetType())); fixed(char *str = _string) { int 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 (CheckForColonInFirstPathSegment(_string)) { return(false); } return((CheckCanonical(str, ref idx, _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 separately below EnsureParseRemaining(); Flags nonCanonical = (_flags & (Flags.E_CannotDisplayCanonical | Flags.IriCanonical)); // Cleanup canonical IRI from nonCanonical if ((nonCanonical & (Flags.UserIriCanonical | Flags.PathIriCanonical | Flags.QueryIriCanonical | Flags.FragmentIriCanonical)) != 0) { if ((nonCanonical & (Flags.E_UserNotCanonical | Flags.UserIriCanonical)) == (Flags.E_UserNotCanonical | Flags.UserIriCanonical)) { nonCanonical = nonCanonical & ~(Flags.E_UserNotCanonical | Flags.UserIriCanonical); } if ((nonCanonical & (Flags.E_PathNotCanonical | Flags.PathIriCanonical)) == (Flags.E_PathNotCanonical | Flags.PathIriCanonical)) { nonCanonical = nonCanonical & ~(Flags.E_PathNotCanonical | Flags.PathIriCanonical); } if ((nonCanonical & (Flags.E_QueryNotCanonical | Flags.QueryIriCanonical)) == (Flags.E_QueryNotCanonical | Flags.QueryIriCanonical)) { nonCanonical = nonCanonical & ~(Flags.E_QueryNotCanonical | Flags.QueryIriCanonical); } if ((nonCanonical & (Flags.E_FragmentNotCanonical | Flags.FragmentIriCanonical)) == (Flags.E_FragmentNotCanonical | Flags.FragmentIriCanonical)) { nonCanonical = nonCanonical & ~(Flags.E_FragmentNotCanonical | Flags.FragmentIriCanonical); } } // 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)) { return(false); } // checking on scheme:\\ or file://// if (InFact(Flags.AuthorityFound)) { idx = _info.Offset.Scheme + _syntax.SchemeName.Length + 2; if (idx >= _info.Offset.User || _string[idx - 1] == '\\' || _string[idx] == '\\') { return(false); } if (InFact(Flags.UncPath | Flags.DosPath)) { while (++idx < _info.Offset.User && (_string[idx] == '/' || _string[idx] == '\\')) { return(false); } } } // (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) && _info.Offset.Query > _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 && _string[_info.Offset.Path + SecuredPathIndex - 1] == '|') { return(false); } // // May need some real CPU processing to answer the request // // // Check escaping for authority // // IPv6 hosts cannot be properly validated by CheckCannonical if ((_flags & Flags.CanonicalDnsHost) == 0 && HostType != Flags.IPv6HostType) { idx = _info.Offset.User; Check result = CheckCanonical(str, ref idx, _info.Offset.Path, '/'); if (((result & (Check.ReservedFound | Check.BackslashInPath | Check.EscapedCanonical)) != Check.EscapedCanonical) && (!_iriParsing || (_iriParsing && ((result & (Check.DisplayCanonical | Check.FoundNonAscii | Check.NotIriCanonical)) != (Check.DisplayCanonical | Check.FoundNonAscii))))) { return(false); } } // Want to ensure there are slashes after the scheme if ((_flags & (Flags.SchemeNotCanonical | Flags.AuthorityFound)) == (Flags.SchemeNotCanonical | Flags.AuthorityFound)) { idx = _syntax.SchemeName.Length; while (str[idx++] != ':') { ; } if (idx + 1 >= _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); }
private static void ThrowMinMaxException <T>(T min, T max) { throw new ArgumentException(SR.Format(SR.Argument_MinMaxValue, min, max)); }
public TypeInitializationException(String fullTypeName, Exception innerException) : this(fullTypeName, SR.Format(SR.TypeInitialization_Type, fullTypeName), innerException) { }
internal static string GetString(string format, params object[] args) { return(SR.Format(format, args)); }
private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) { SetEnvironmentVariableCore(variable, value); return; } #if FEATURE_WIN32_REGISTRY if (AppDomain.IsAppXModel()) #endif { // other targets ignored return; } #if FEATURE_WIN32_REGISTRY // 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) { // 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 = Interop.User32.SendMessageTimeout(new IntPtr(Interop.User32.HWND_BROADCAST), Interop.User32.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero); Debug.Assert(r != IntPtr.Zero, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error()); #endif // FEATURE_WIN32_REGISTRY }
float IConvertible.ToSingle(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Single")); }
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); }
DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "DateTime")); }
private static ArgumentException GetWrongKeyTypeArgumentException(object key, Type targetType) { return(new ArgumentException(SR.Format(SR.Arg_WrongType, key, targetType), nameof(key))); }
// Parse a string specifying a list of assemblies and types // containing a startup hook, and call each hook in turn. private static void ProcessStartupHooks() { // Initialize tracing before any user code can be called. System.Diagnostics.Tracing.RuntimeEventSource.Initialize(); string?startupHooksVariable = AppContext.GetData("STARTUP_HOOKS") as string; if (startupHooksVariable == null) { return; } ReadOnlySpan <char> disallowedSimpleAssemblyNameChars = stackalloc char[4] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar, ' ', ',' }; // Parse startup hooks variable string[] startupHookParts = startupHooksVariable.Split(Path.PathSeparator); StartupHookNameOrPath[] startupHooks = new StartupHookNameOrPath[startupHookParts.Length]; for (int i = 0; i < startupHookParts.Length; i++) { string startupHookPart = startupHookParts[i]; if (string.IsNullOrEmpty(startupHookPart)) { // Leave the slot in startupHooks empty (nulls for everything). This is simpler than shifting and resizing the array. continue; } if (Path.IsPathFullyQualified(startupHookPart)) { startupHooks[i].Path = startupHookPart; } else { // The intent here is to only support simple assembly names, but AssemblyName .ctor accepts // lot of other forms (fully qualified assembly name, strings which look like relative paths and so on). // So add a check on top which will disallow any directory separator, space or comma in the assembly name. for (int j = 0; j < disallowedSimpleAssemblyNameChars.Length; j++) { if (startupHookPart.Contains(disallowedSimpleAssemblyNameChars[j])) { throw new ArgumentException(SR.Format(SR.Argument_InvalidStartupHookSimpleAssemblyName, startupHookPart)); } } if (startupHookPart.EndsWith(DisallowedSimpleAssemblyNameSuffix, StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(SR.Format(SR.Argument_InvalidStartupHookSimpleAssemblyName, startupHookPart)); } try { // This will throw if the string is not a valid assembly name. startupHooks[i].AssemblyName = new AssemblyName(startupHookPart); } catch (Exception assemblyNameException) { throw new ArgumentException(SR.Format(SR.Argument_InvalidStartupHookSimpleAssemblyName, startupHookPart), assemblyNameException); } } } // Call each hook in turn foreach (StartupHookNameOrPath startupHook in startupHooks) { CallStartupHook(startupHook); } }
private static Exception CreateArgumentException_InvalidTypeWithPointersNotSupported(Type type) { return(new ArgumentException(SR.Format(SR.Argument_InvalidTypeWithPointersNotSupported, type))); }