// which should only happen if the buffer we supply isn't big
// enough, and we're using a buffer size that the man page
// says is the max for POSIX (and larger than the max for Linux).
- Debug.Fail("getdomainname failed");
- throw new InvalidOperationException(string.Format("getdomainname returned {0}", err));
+ Debug.Fail($"{nameof(GetDomainName)} failed with error {err}");
+ throw new InvalidOperationException($"{nameof(GetDomainName)}: {err}");
}
// Marshal.PtrToStringAnsi uses UTF8 on Unix.
if (err != 0)
{
// max domain name can be 255 chars.
- Debug.Fail("getnodename failed");
- throw new InvalidOperationException(string.Format("getnodename returned {0}", err));
+ Debug.Fail($"{nameof(GetNodeName)} failed with error {err}");
+ throw new InvalidOperationException($"{nameof(GetNodeName)}: {err}");
}
// Marshal.PtrToStringAnsi uses UTF8 on Unix.
key?.Dispose();
Interop.Crypto.ErrClearError();
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, oid));
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, oid));
}
return key;
}
}
else
{
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
}
SafeEcKeyHandle key = Interop.Crypto.EcKeyCreateByExplicitParameters(
{
if (nidCurveName == Interop.Crypto.NID_undef)
{
- Debug.Assert(false); // Key is invalid or doesn't have a curve
+ Debug.Fail("Key is invalid or doesn't have a curve");
return string.Empty;
}
}
else
{
- Debug.Assert(false, "ParseInternal code vs regex throw mismatch " + f.Message);
+ Debug.Fail("ParseInternal code vs regex throw mismatch " + f.Message);
}
e = null;
}
if (null != e)
{
- Debug.Assert(false, "ParseInternal code threw exception vs regex mismatch");
+ Debug.Fail("ParseInternal code threw exception vs regex mismatch");
}
}
#endif
// could compile each module with a different setting for this. We want to make sure there's a consistent behavior
// that doesn't depend on which native module this method got inlined into.
[MethodImpl(MethodImplOptions.NoInlining)]
- private static bool UsingResourceKeys()
- {
- return false;
- }
+ private static bool UsingResourceKeys() => false;
internal static string GetResourceString(string resourceKey, string defaultString = null)
{
if (UsingResourceKeys())
+ {
return defaultString ?? resourceKey;
+ }
string resourceString = null;
- try { resourceString = ResourceManager.GetString(resourceKey); }
+ try
+ {
+ resourceString = ResourceManager.GetString(resourceKey);
+ }
catch (MissingManifestResourceException) { }
- if (defaultString != null && resourceKey.Equals(resourceString, StringComparison.Ordinal))
+ if (defaultString != null && resourceKey.Equals(resourceString))
{
return defaultString;
}
return resourceString;
}
+ internal static string Format(string resourceFormat, object p1)
+ {
+ if (UsingResourceKeys())
+ {
+ return string.Join(", ", resourceFormat, p1);
+ }
+
+ return string.Format(resourceFormat, p1);
+ }
+
+ internal static string Format(string resourceFormat, object p1, object p2)
+ {
+ if (UsingResourceKeys())
+ {
+ return string.Join(", ", resourceFormat, p1, p2);
+ }
+
+ return string.Format(resourceFormat, p1, p2);
+ }
+
+ internal static string Format(string resourceFormat, object p1, object p2, object p3)
+ {
+ if (UsingResourceKeys())
+ {
+ return string.Join(", ", resourceFormat, p1, p2, p3);
+ }
+
+ return string.Format(resourceFormat, p1, p2, p3);
+ }
+
internal static string Format(string resourceFormat, params object[] args)
{
if (args != null)
{
if (UsingResourceKeys())
{
- return resourceFormat + string.Join(", ", args);
+ return resourceFormat + ", " + string.Join(", ", args);
}
return string.Format(resourceFormat, args);
return resourceFormat;
}
- internal static string Format(string resourceFormat, object p1)
+ internal static string Format(IFormatProvider provider, string resourceFormat, object p1)
{
if (UsingResourceKeys())
{
return string.Join(", ", resourceFormat, p1);
}
- return string.Format(resourceFormat, p1);
+ return string.Format(provider, resourceFormat, p1);
}
- internal static string Format(string resourceFormat, object p1, object p2)
+ internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2)
{
if (UsingResourceKeys())
{
return string.Join(", ", resourceFormat, p1, p2);
}
- return string.Format(resourceFormat, p1, p2);
+ return string.Format(provider, resourceFormat, p1, p2);
}
- internal static string Format(string resourceFormat, object p1, object p2, object p3)
+ internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3)
{
if (UsingResourceKeys())
{
return string.Join(", ", resourceFormat, p1, p2, p3);
}
- return string.Format(resourceFormat, p1, p2, p3);
+ return string.Format(provider, resourceFormat, p1, p2, p3);
+ }
+
+ internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
+ {
+ if (args != null)
+ {
+ if (UsingResourceKeys())
+ {
+ return resourceFormat + ", " + string.Join(", ", args);
+ }
+
+ return string.Format(provider, resourceFormat, args);
+ }
+
+ return resourceFormat;
}
}
}
{
throw new AsnSerializationConstraintException(
SR.Format(
+ SR.Cryptography_AsnSerializer_MultipleAsnTypeAttributes,
fieldInfo.Name,
fieldInfo.DeclaringType.FullName,
typeof(AsnTypeAttribute).FullName));
}
Debug.Fail($"Unknown curve {algorithm}");
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, algorithm));
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, algorithm));
}
}
}
Exception e = errorCode.ToCryptographicException();
if (errorCode == ErrorCode.NTE_INVALID_PARAMETER)
{
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, curveName), e);
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, curveName), e);
}
throw e;
}
if (string.IsNullOrEmpty(curve.Oid.FriendlyName))
{
throw new PlatformNotSupportedException(
- string.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value));
+ SR.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value));
}
byte[] ecNamedCurveBlob = ECCng.GetNamedCurveBlob(ref parameters, ecdh: true);
else
{
throw new PlatformNotSupportedException(
- string.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
+ SR.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
}
}
{
// FriendlyName is required; an attempt was already made to default it in ECCurve
if (string.IsNullOrEmpty(curve.Oid.FriendlyName))
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value.ToString()));
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value.ToString()));
byte[] ecNamedCurveBlob = ECCng.GetNamedCurveBlob(ref parameters, ecdh: false);
ImportKeyBlob(ecNamedCurveBlob, curve.Oid.FriendlyName, includePrivateParameters);
}
else
{
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
}
}
else
{
throw new PlatformNotSupportedException(
- string.Format(SR.Cryptography_CurveNotSupported, parameters.Curve.CurveType.ToString()));
+ SR.Format(SR.Cryptography_CurveNotSupported, parameters.Curve.CurveType.ToString()));
}
if (key == null || key.IsInvalid)
SafeEcKeyHandle key = Interop.Crypto.EcKeyCreateByOid(oid);
if (key == null || key.IsInvalid)
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, oid));
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, oid));
if (!Interop.Crypto.EcKeyGenerateKey(key))
throw Interop.Crypto.CreateOpenSslCryptographicException();
if (key == null || key.IsInvalid)
{
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, oid));
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, oid));
}
if (!Interop.Crypto.EcKeyGenerateKey(key))
else
{
throw new PlatformNotSupportedException(
- string.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
+ SR.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
}
return KeySize;
default:
// means missing resources match the code entry
- Debug.Assert(false, "Missing resources for the error " + code.ToString());
+ Debug.Fail("Missing resources for the error " + code.ToString());
codeStr = null;
break;
}
sym = arg.mpwiMemo.sym;
break;
default:
- Debug.Assert(false, "Shouldn't be here!");
+ Debug.Fail("Shouldn't be here!");
continue;
}
sym2 = arg2.mpwiMemo.sym;
break;
default:
- Debug.Assert(false, "Shouldn't be here!");
+ Debug.Fail("Shouldn't be here!");
continue;
}
id = MessageID.SK_TYVAR;
break;
default:
- Debug.Assert(false, "impossible sk");
+ Debug.Fail("impossible sk");
id = MessageID.SK_UNKNOWN;
break;
}
default:
// Shouldn't happen.
- Debug.Assert(false, $"Bad symbol kind: {sym.getKind()}");
+ Debug.Fail($"Bad symbol kind: {sym.getKind()}");
break;
}
}
default:
// Shouldn't happen.
- Debug.Assert(false, "Bad type kind");
+ Debug.Fail("Bad type kind");
break;
}
}
break;
default:
- Debug.Assert(false, "Invalid Predefined Method in VisitCALL");
+ Debug.Fail("Invalid Predefined Method in VisitCALL");
throw Error.InternalCompilerError();
}
if (m == null)
{
- Debug.Assert(false, "How did we get a call that doesn't have a methodinfo?");
+ Debug.Fail("How did we get a call that doesn't have a methodinfo?");
throw Error.InternalCompilerError();
}
if (p == null)
{
- Debug.Assert(false, "How did we get a prop that doesn't have a propinfo?");
+ Debug.Fail("How did we get a prop that doesn't have a propinfo?");
throw Error.InternalCompilerError();
}
return Expression.SubtractChecked(arg1, arg2);
default:
- Debug.Assert(false, "Invalid Predefined Method in GenerateBinaryOperator");
+ Debug.Fail("Invalid Predefined Method in GenerateBinaryOperator");
throw Error.InternalCompilerError();
}
}
return Expression.SubtractChecked(arg1, arg2, methodInfo);
default:
- Debug.Assert(false, "Invalid Predefined Method in GenerateUserDefinedBinaryOperator");
+ Debug.Fail("Invalid Predefined Method in GenerateUserDefinedBinaryOperator");
throw Error.InternalCompilerError();
}
}
return Expression.NegateChecked(arg);
default:
- Debug.Assert(false, "Invalid Predefined Method in GenerateUnaryOperator");
+ Debug.Fail("Invalid Predefined Method in GenerateUnaryOperator");
throw Error.InternalCompilerError();
}
}
return Expression.NegateChecked(arg, methodInfo);
default:
- Debug.Assert(false, "Invalid Predefined Method in GenerateUserDefinedUnaryOperator");
+ Debug.Fail("Invalid Predefined Method in GenerateUserDefinedUnaryOperator");
throw Error.InternalCompilerError();
}
}
return GenerateUserDefinedUnaryOperator(call);
default:
- Debug.Assert(false, "Invalid Predefined Method in GetExpression");
+ Debug.Fail("Invalid Predefined Method in GetExpression");
throw Error.InternalCompilerError();
}
}
mask = symbmask_t.MASK_MethodSymbol;
break;
default:
- Debug.Assert(false, "Unhandled kind");
+ Debug.Fail("Unhandled kind");
break;
}
if (swt.Sym.getKind() != SYMKIND.SK_MethodSymbol)
{
- Debug.Assert(false, "Unexpected type returned from lookup");
+ Debug.Fail("Unexpected type returned from lookup");
throw Error.InternalCompilerError();
}
switch (p)
{
default:
- Debug.Assert(false, "Unknown operator: " + p);
+ Debug.Fail("Unknown operator: " + p);
throw Error.InternalCompilerError();
// Binary Operators
throw Error.BindPropertyFailedEvent(name);
default:
- Debug.Assert(false, "Unexpected type returned from lookup");
+ Debug.Fail("Unexpected type returned from lookup");
throw Error.InternalCompilerError();
}
}
switch (type1.TypeKind)
{
default:
- Debug.Assert(false, "Bad kind in CompareTypes");
+ Debug.Fail("Bad kind in CompareTypes");
break;
case TypeKind.TK_TypeParameterType:
break;
if (property == null)
{
- Debug.Assert(false, "cannot find property for accessor");
+ Debug.Fail("cannot find property for accessor");
return false;
}
default:
// Should never call this with any other kind.
- Debug.Assert(false, "GetAssemblyID called on bad sym kind");
+ Debug.Fail("GetAssemblyID called on bad sym kind");
return null;
}
}
return ((AggregateSymbol)this).InternalsVisibleTo(assembly);
default:
// Should never call this with any other kind.
- Debug.Assert(false, "InternalsVisibleTo called on bad sym kind");
+ Debug.Fail("InternalsVisibleTo called on bad sym kind");
return false;
}
}
switch (typeBnd.TypeKind)
{
default:
- Debug.Assert(false, "Unexpected type.");
+ Debug.Fail("Unexpected type.");
return false;
case TypeKind.TK_VoidType:
switch (type.TypeKind)
{
default:
- Debug.Assert(false);
+ Debug.Fail("Unknown type kind");
return type;
case TypeKind.TK_NullType:
switch (typeSrc.TypeKind)
{
default:
- Debug.Assert(false, "Bad Symbol kind in SubstEqualTypesCore");
+ Debug.Fail("Bad Symbol kind in SubstEqualTypesCore");
return false;
case TypeKind.TK_NullType:
switch (type.TypeKind)
{
default:
- Debug.Assert(false, "Bad Symbol kind in TypeContainsType");
+ Debug.Fail("Bad Symbol kind in TypeContainsType");
return false;
case TypeKind.TK_NullType:
switch (type.TypeKind)
{
default:
- Debug.Assert(false, "Bad Symbol kind in TypeContainsTyVars");
+ Debug.Fail("Bad Symbol kind in TypeContainsTyVars");
return false;
case TypeKind.TK_NullType:
{
if (s_staticwndclass == null)
{
- const string classNameFormat = ".NET-BroadcastEventWindow.{0}.{1}";
-
IntPtr hInstance = Interop.Kernel32.GetModuleHandle(null);
- s_className = string.Format(System.Globalization.CultureInfo.InvariantCulture,
- classNameFormat,
- Convert.ToString(AppDomain.CurrentDomain.GetHashCode(), 16),
+ s_className = string.Format(
+ System.Globalization.CultureInfo.InvariantCulture,
+ ".NET-BroadcastEventWindow.{0:x}.{1}",
+ AppDomain.CurrentDomain.GetHashCode(),
s_domainQualifier);
Interop.User32.WNDCLASS tempwndclass = new Interop.User32.WNDCLASS();
}
catch (Exception e)
{
- Debug.Assert(false, "Exception occurred while freeing memory: " + e.ToString());
+ Debug.Fail("Exception occurred while freeing memory: " + e.ToString());
}
}
break;
private void WriteHelp()
{
- Console.Out.WriteLine(SR.Format(SR.HelpDescription));
+ Console.Out.WriteLine(SR.HelpDescription);
Console.Out.WriteLine(SR.Format(SR.HelpUsage, this.GetType().Assembly.GetName().Name.Substring("dotnet-".Length)));
- Console.Out.WriteLine(SR.Format(SR.HelpDevOptions));
+ Console.Out.WriteLine(SR.HelpDevOptions);
Console.Out.WriteLine(SR.Format(SR.HelpAssembly, "-a", "--assembly"));
Console.Out.WriteLine(SR.Format(SR.HelpType, "--type"));
Console.Out.WriteLine(SR.Format(SR.HelpProxy, "--proxytypes"));
Console.Out.WriteLine(SR.Format(SR.HelpForce, "--force"));
Console.Out.WriteLine(SR.Format(SR.HelpOut, "-o", "--out"));
- Console.Out.WriteLine(SR.Format(SR.HelpMiscOptions));
+ Console.Out.WriteLine(SR.HelpMiscOptions);
Console.Out.WriteLine(SR.Format(SR.HelpHelp, "-h", "--help"));
}
}
else
{
- throw new ArgumentException(SR.Format(SR.InvalidPrimitiveType, e.Value.GetType().ToString()));
+ throw new ArgumentException(SR.Format(SR.InvalidPrimitiveType, e.Value.GetType()));
}
}
}
else
{
- throw new ArgumentException(SR.Format(SR.InvalidPrimitiveType, e.Value.GetType().ToString()));
+ throw new ArgumentException(SR.Format(SR.InvalidPrimitiveType, e.Value.GetType()));
}
}
}
else
{
- throw new InvalidOperationException(SR.Format(SR.Provider_does_not_support_options, CodeDomProviderType.ToString()));
+ throw new InvalidOperationException(SR.Format(SR.Provider_does_not_support_options, CodeDomProviderType));
}
}
if ((totalMilliseconds < 0 || totalMilliseconds > int.MaxValue) && (totalMilliseconds != Timeout.Infinite))
{
throw new ArgumentOutOfRangeException(nameof(timeout), timeout,
- string.Format(CultureInfo.InvariantCulture, SR.BlockingCollection_TimeoutInvalid, int.MaxValue));
+ SR.Format(CultureInfo.InvariantCulture, SR.BlockingCollection_TimeoutInvalid, int.MaxValue));
}
}
if ((millisecondsTimeout < 0) && (millisecondsTimeout != Timeout.Infinite))
{
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), millisecondsTimeout,
- string.Format(CultureInfo.InvariantCulture, SR.BlockingCollection_TimeoutInvalid, int.MaxValue));
+ SR.Format(CultureInfo.InvariantCulture, SR.BlockingCollection_TimeoutInvalid, int.MaxValue));
}
}
case KeyCollisionBehavior.ThrowIfValueDifferent:
if (!valueComparer.Equals(_firstValue.Value, value))
{
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key));
+ throw new ArgumentException(SR.Format(SR.DuplicateKey, key));
}
result = OperationResult.NoChangeRequired;
return this;
case KeyCollisionBehavior.ThrowAlways:
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key));
+ throw new ArgumentException(SR.Format(SR.DuplicateKey, key));
default:
throw new InvalidOperationException(); // unreachable
}
#endif
if (!valueComparer.Equals(existingEntry.Value, value))
{
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key));
+ throw new ArgumentException(SR.Format(SR.DuplicateKey, key));
}
result = OperationResult.NoChangeRequired;
return this;
case KeyCollisionBehavior.ThrowAlways:
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key));
+ throw new ArgumentException(SR.Format(SR.DuplicateKey, key));
default:
throw new InvalidOperationException(); // unreachable
}
}
else
{
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key));
+ throw new ArgumentException(SR.Format(SR.DuplicateKey, key));
}
}
{
if (!_valueComparer.Equals(value, item.Value))
{
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, item.Key));
+ throw new ArgumentException(SR.Format(SR.DuplicateKey, item.Key));
}
}
else
}
else
{
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.DuplicateKey, key));
+ throw new ArgumentException(SR.Format(SR.DuplicateKey, key));
}
}
else
{
throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture, SR.InvalidMetadataValue, value.GetType().FullName));
+ SR.Format(SR.InvalidMetadataValue, value.GetType().FullName));
}
}
T value = lazy.Value;
if (value == null)
{
- throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture, SR.LazyServices_LazyResolvesToNull, typeof(T), argument));
+ throw new InvalidOperationException(SR.Format(SR.LazyServices_LazyResolvesToNull, typeof(T), argument));
}
return value;
if ((value & enumFlagSet) != value || // Ensure the member is in the set
(value & (value - 1)) != 0) // Ensure that there is only one flag in the value (i.e. value is a power of 2).
{
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_InvalidEnumInSet, parameterName, value, enumFlagSet.ToString()), parameterName);
+ throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_InvalidEnumInSet, parameterName, value, enumFlagSet.ToString()), parameterName);
}
Contract.EndContractBlock();
}
if (value.Length == 0)
{
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.ArgumentException_EmptyString, parameterName), parameterName);
+ throw new ArgumentException(SR.Format(SR.ArgumentException_EmptyString, parameterName), parameterName);
}
}
var mappedType = reflectionContext.MapType(IntrospectionExtensions.GetTypeInfo(attributedPart.GetType()));
if (mappedType.Assembly.ReflectionOnly)
{
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Argument_ReflectionContextReturnsReflectionOnlyType, nameof(reflectionContext)), nameof(reflectionContext));
+ throw new ArgumentException(SR.Format(SR.Argument_ReflectionContextReturnsReflectionOnlyType, nameof(reflectionContext)), nameof(reflectionContext));
}
ReflectionComposablePartDefinition definition = AttributedModelDiscovery.CreatePartDefinition(mappedType, PartCreationPolicyAttribute.Shared, true, (ICompositionElement)null);
{
get
{
- return string.Format(CultureInfo.CurrentCulture,
+ return SR.Format(
SR.CompositionException_ChangesRejected,
base.Message);
}
throw new ArgumentNullException(nameof(partDefinitionType));
}
- return new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidPartDefinition, partDefinitionType), parameterName);
+ return new ArgumentException(SR.Format(SR.ReflectionModel_InvalidPartDefinition, partDefinitionType), parameterName);
}
public static ArgumentException ExportFactory_TooManyGenericParameters(string typeName)
bool succeeded = ContractServices.TryCast(typeof(T), exportedValue, out typedExportedValue);
if (!succeeded)
{
- throw new CompositionContractMismatchException(string.Format(CultureInfo.CurrentCulture,
+ throw new CompositionContractMismatchException(SR.Format(
SR.ContractMismatch_ExportedValueCannotBeCastToT,
element.DisplayName,
typeof(T)));
{
if (assembly.ReflectionOnly)
{
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Argument_AssemblyReflectionOnly, nameof(assembly)), nameof(assembly));
+ throw new ArgumentException(SR.Format(SR.Argument_AssemblyReflectionOnly, nameof(assembly)), nameof(assembly));
}
_assembly = assembly;
}
{
if ((_sourceProvider == null) || (_importEngine == null))
{
- throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.ObjectMustBeInitialized, "SourceProvider")); // NOLOC
+ throw new InvalidOperationException(SR.Format(SR.ObjectMustBeInitialized, "SourceProvider")); // NOLOC
}
}
{
if ((_isRunning) || (currentValue != null))
{
- throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.ObjectAlreadyInitialized));
+ throw new InvalidOperationException(SR.ObjectAlreadyInitialized);
}
}
{
if (_sourceProvider == null)
{
- throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.ObjectMustBeInitialized, "SourceProvider")); // NOLOC
+ throw new InvalidOperationException(SR.Format(SR.ObjectMustBeInitialized, "SourceProvider")); // NOLOC
}
}
{
if ((_isRunning) || (currentValue != null))
{
- throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.ObjectAlreadyInitialized));
+ throw new InvalidOperationException(SR.ObjectAlreadyInitialized);
}
}
}
if (!MetadataViewProvider.IsViewTypeValid(metadataViewType))
{
- throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.InvalidMetadataView, metadataViewType.Name));
+ throw new InvalidOperationException(SR.Format(SR.InvalidMetadataView, metadataViewType.Name));
}
ImportDefinition importDefinition = BuildImportDefinition(type, metadataViewType, contractName, cardinality);
case ExportCardinalityCheckResult.Match:
return exports;
case ExportCardinalityCheckResult.NoExports:
- throw new ImportCardinalityMismatchException(string.Format(CultureInfo.CurrentCulture, SR.CardinalityMismatch_NoExports, definition.ToString()));
+ throw new ImportCardinalityMismatchException(SR.Format(SR.CardinalityMismatch_NoExports, definition));
default:
if (result != ExportCardinalityCheckResult.TooManyExports)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
- throw new ImportCardinalityMismatchException(string.Format(CultureInfo.CurrentCulture, SR.CardinalityMismatch_TooManyExports_Constraint, definition.ToString()));
+ throw new ImportCardinalityMismatchException(SR.Format(SR.CardinalityMismatch_TooManyExports_Constraint, definition));
}
}
}
if (type.Assembly.ReflectionOnly)
{
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Argument_ElementReflectionOnlyType, nameof(types)), nameof(types));
+ throw new ArgumentException(SR.Format(SR.Argument_ElementReflectionOnlyType, nameof(types)), nameof(types));
}
var typeInfo = type.GetTypeInfo();
var lclType = (reflectionContext != null) ? reflectionContext.MapType(typeInfo) : typeInfo;
// The final mapped type may be activated so we check to see if it is in a reflect only assembly
if (lclType.Assembly.ReflectionOnly)
{
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Argument_ReflectionContextReturnsReflectionOnlyType, nameof(reflectionContext)), nameof(reflectionContext));
+ throw new ArgumentException(SR.Format(SR.Argument_ReflectionContextReturnsReflectionOnlyType, nameof(reflectionContext)), nameof(reflectionContext));
}
typesList.Add(lclType);
}
}
else if (type.Assembly.ReflectionOnly)
{
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Argument_ElementReflectionOnlyType, nameof(types)), nameof(types));
+ throw new ArgumentException(SR.Format(SR.Argument_ElementReflectionOnlyType, nameof(types)), nameof(types));
}
}
_types = types.ToArray();
private string GetDisplayName()
{
- return string.Format(CultureInfo.CurrentCulture,
+ return SR.Format(
SR.TypeCatalog_DisplayNameFormat,
GetType().Name,
GetTypesDisplay());
string fieldName = string.Format(CultureInfo.InvariantCulture, "_{0}_{1}", propertyInfo.Name, Guid.NewGuid());
// Cache names and type for exception
- string propertyName = string.Format(CultureInfo.InvariantCulture, "{0}", propertyInfo.Name);
+ string propertyName = propertyInfo.Name;
Type[] propertyTypeArguments = new Type[] { propertyInfo.PropertyType };
Type[] optionalModifiers = null;
if (propertyInfo.CanWrite)
{
// The MetadataView '{0}' is invalid because property '{1}' has a property set method.
- throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture,
+ throw new NotSupportedException(SR.Format(
SR.InvalidSetterOnMetadataField,
viewType,
propertyName));
{
// Generate "get" method implementation.
MethodBuilder getMethodBuilder = proxyTypeBuilder.DefineMethod(
- string.Format(CultureInfo.InvariantCulture, "get_{0}", propertyName),
+ "get_" + propertyName,
MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.NewSlot | MethodAttributes.Virtual | MethodAttributes.Final,
CallingConventions.HasThis,
propertyInfo.PropertyType,
}
catch (TypeLoadException ex)
{
- throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, SR.NotSupportedInterfaceMetadataView, metadataViewType.FullName), ex);
+ throw new NotSupportedException(SR.Format(SR.NotSupportedInterfaceMetadataView, metadataViewType.FullName), ex);
}
}
else
proxyType = implementationAttribute.ImplementationType;
if(proxyType == null)
{
- throw new CompositionContractMismatchException(string.Format(CultureInfo.CurrentCulture,
+ throw new CompositionContractMismatchException(SR.Format(
SR.ContractMismatch_MetadataViewImplementationCanNotBeNull,
metadataViewType.FullName,
proxyType.FullName));
{
if(!metadataViewType.IsAssignableFrom(proxyType))
{
- throw new CompositionContractMismatchException(string.Format(CultureInfo.CurrentCulture,
+ throw new CompositionContractMismatchException(SR.Format(
SR.ContractMismatch_MetadataViewImplementationDoesNotImplementViewInterface,
metadataViewType.FullName,
proxyType.FullName));
catch (MissingMethodException ex)
{
// Unable to create an Instance of the Metadata view '{0}' because a constructor could not be selected. Ensure that the type implements a constructor which takes an argument of type IDictionary<string, object>.
- throw new CompositionContractMismatchException(string.Format(CultureInfo.CurrentCulture,
+ throw new CompositionContractMismatchException(SR.Format(
SR.CompositionException_MetadataViewInvalidConstructor,
proxyType.AssemblyQualifiedName), ex);
}
if(ex.InnerException.GetType() == typeof(InvalidCastException))
{
// Unable to create an Instance of the Metadata view {0} because the exporter exported the metadata for the item {1} with the value {2} as type {3} but the view imports it as type {4}.
- throw new CompositionContractMismatchException(string.Format(CultureInfo.CurrentCulture,
+ throw new CompositionContractMismatchException(SR.Format(
SR.ContractMismatch_InvalidCastOnMetadataField,
ex.InnerException.Data[MetadataViewGenerator.MetadataViewType],
ex.InnerException.Data[MetadataViewGenerator.MetadataItemKey],
else if (ex.InnerException.GetType() == typeof(NullReferenceException))
{
// Unable to create an Instance of the Metadata view {0} because the exporter exported the metadata for the item {1} with a null value and null is not a valid value for type {2}.
- throw new CompositionContractMismatchException(string.Format(CultureInfo.CurrentCulture,
+ throw new CompositionContractMismatchException(SR.Format(
SR.ContractMismatch_NullReferenceOnMetadataField,
ex.InnerException.Data[MetadataViewGenerator.MetadataViewType],
ex.InnerException.Data[MetadataViewGenerator.MetadataItemKey],
if ((metadataItem.Key == null) || (metadataItem.Value == null))
{
throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture, SR.Argument_NullElement, "requiredMetadata"));
+ SR.Format(SR.Argument_NullElement, "requiredMetadata"));
}
}
_isRequiredMetadataValidated = true;
if(_requiredMetadata.Count() > 0)
{
- sb.Append(string.Format("\n\tRequiredMetadata"));
+ sb.Append("\n\tRequiredMetadata");
foreach (KeyValuePair<string, Type> metadataItem in _requiredMetadata)
{
sb.Append(string.Format("\n\t\t{0}\t({1})", metadataItem.Key, metadataItem.Value));
(cardinality != ImportCardinality.ZeroOrOne)
)
{
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_InvalidEnum, nameof(cardinality), cardinality, typeof(ImportCardinality).Name), nameof(cardinality));
+ throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_InvalidEnum, nameof(cardinality), cardinality, typeof(ImportCardinality).Name), nameof(cardinality));
}
_contractName = contractName ?? EmptyContractName;
// we'll add some context and rethrow.
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ReflectionModel_ExportThrewException,
_member.GetDisplayName()),
Definition.ToElement(),
// this is not supported in MEF currently. Ideally we would validate against it, however, we already shipped
// so we will turn it into a ComposablePartException instead, that they should already be prepared for
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ExportNotValidOnIndexers,
_member.GetDisplayName()),
Definition.ToElement(),
{ // Property does not have a getter
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ReflectionModel_ExportNotReadable,
_member.GetDisplayName()),
Definition.ToElement());
if (!ContractServices.TryCast(type, value, out result))
{
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ReflectionModel_ImportNotAssignableFromExport,
export.ToElement().DisplayName,
type.FullName),
// leak out as a 'raw' unhandled exception, instead,
// we'll add some context and rethrow.
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ReflectionModel_ImportThrewException,
_member.GetDisplayName()),
Definition.ToElement(),
// this is not supported in MEF currently. Ideally we would validate against it, however, we already shipped
// so we will turn it into a ComposablePartException instead, that they should already be prepared for
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ImportNotValidOnIndexers,
_member.GetDisplayName()),
Definition.ToElement(),
// field is marked as read-only.
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ReflectionModel_ImportNotWritable,
_member.GetDisplayName()),
Definition.ToElement());
catch (TargetInvocationException exception)
{
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ReflectionModel_ImportCollectionGetThrewException,
_member.GetDisplayName()),
Definition.ToElement(),
catch (TargetInvocationException exception)
{
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ReflectionModel_ImportCollectionConstructionThrewException,
_member.GetDisplayName(),
ImportType.ActualType.FullName),
if (collectionObject == null)
{
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ReflectionModel_ImportCollectionNull,
_member.GetDisplayName()),
Definition.ToElement());
catch (Exception exception)
{
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ReflectionModel_ImportCollectionIsReadOnlyThrewException,
_member.GetDisplayName(),
collection.GetType().FullName),
if (isReadOnly)
{
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ReflectionModel_ImportCollectionNotWritable,
_member.GetDisplayName()),
Definition.ToElement());
catch (Exception exception)
{
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ReflectionModel_ImportCollectionClearThrewException,
_member.GetDisplayName(),
collection.GetType().FullName),
catch (Exception exception)
{
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ReflectionModel_ImportCollectionAddThrewException,
_member.GetDisplayName(),
collection.GetType().FullName),
(accessors.Length != 1) ||
((accessors.Length == 1) && (accessors[0].MemberType != memberType)))
{
- errorMessage = string.Format(CultureInfo.CurrentCulture, SR.LazyMemberInfo_InvalidAccessorOnSimpleMember, memberType);
+ errorMessage = SR.Format(SR.LazyMemberInfo_InvalidAccessorOnSimpleMember, memberType);
return false;
}
public override string ToString()
{
- StringBuilder sb = new StringBuilder();
-
- sb.Append(string.Format("\n\tExportFactory of: {0}", ProductImportDefinition.ToString()));
-
- return sb.ToString();
+ return "\n\tExportFactory of: " + ProductImportDefinition.ToString();
}
}
}
public override string ToString()
{
- StringBuilder sb = new StringBuilder();
-
- sb.Append(string.Format("\n\tExportFactory of: {0}", ProductImportDefinition.ToString()));
-
- return sb.ToString();
+ return "\n\tExportFactory of: " + ProductImportDefinition.ToString();
}
}
if (constructor == null)
{
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ReflectionModel_PartConstructorMissing,
Definition.GetPartType().FullName),
Definition.ToElement());
if (definition.Cardinality == ImportCardinality.ZeroOrMore && !import.ImportType.IsAssignableCollectionType)
{
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ReflectionModel_ImportManyOnParameterCanOnlyBeAssigned,
Definition.GetPartType().FullName,
definition.ImportingLazyParameter.Value.Name),
{
if (_importValues == null || !ImportValues.ContainsKey(definition))
{
- throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
+ throw new InvalidOperationException(SR.Format(
SR.InvalidOperation_GetExportedValueBeforePrereqImportSet,
definition.ToElement().DisplayName));
}
if (exception != null)
{
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ReflectionModel_PartConstructorThrewException,
Definition.GetPartType().FullName),
Definition.ToElement(),
catch (Exception exception)
{
throw new ComposablePartException(
- string.Format(CultureInfo.CurrentCulture,
+ SR.Format(
SR.ReflectionModel_PartOnImportsSatisfiedThrewException,
Definition.GetPartType().FullName),
Definition.ToElement(),
if (reflectionExportDefinition == null)
{
throw new ArgumentException(
- string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidExportDefinition, exportDefinition.GetType()),
+ SR.Format(SR.ReflectionModel_InvalidExportDefinition, exportDefinition.GetType()),
nameof(exportDefinition));
}
if (reflectionMemberImportDefinition == null)
{
throw new ArgumentException(
- string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidMemberImportDefinition, importDefinition.GetType()),
+ SR.Format(SR.ReflectionModel_InvalidMemberImportDefinition, importDefinition.GetType()),
nameof(importDefinition));
}
if (reflectionParameterImportDefinition == null)
{
throw new ArgumentException(
- string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidParameterImportDefinition, importDefinition.GetType()),
+ SR.Format(SR.ReflectionModel_InvalidParameterImportDefinition, importDefinition.GetType()),
nameof(importDefinition));
}
if (reflectionImportDefinition == null)
{
throw new ArgumentException(
- string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidImportDefinition, importDefinition.GetType()),
+ SR.Format(SR.ReflectionModel_InvalidImportDefinition, importDefinition.GetType()),
nameof(importDefinition));
}
if (partCreatorImportDefinition == null)
{
throw new ArgumentException(
- string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidImportDefinition, importDefinition.GetType()),
+ SR.Format(SR.ReflectionModel_InvalidImportDefinition, importDefinition.GetType()),
nameof(importDefinition));
}
if (reflectionExport == null)
{
throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidExportDefinition, export.GetType()));
+ SR.Format(SR.ReflectionModel_InvalidExportDefinition, export.GetType()));
}
yield return reflectionExport;
}
if (reflectionImport == null)
{
throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture, SR.ReflectionModel_InvalidMemberImportDefinition, import.GetType()));
+ SR.Format(SR.ReflectionModel_InvalidMemberImportDefinition, import.GetType()));
}
yield return reflectionImport;
}
if (name.Length == 0)
{
- throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, name.Length.ToString(CultureInfo.CurrentCulture), (0).ToString(CultureInfo.CurrentCulture)), "name.Length");
+ throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, name.Length.ToString(), "0"), "name.Length");
}
return new DesignerOptionCollection(this, parent, name, value);
_tabClasses = new Type[] { tabClass };
if (tabScope < PropertyTabScope.Document)
{
- throw new ArgumentException(SR.Format(SR.PropertyTabAttributeBadPropertyTabScope), nameof(tabScope));
+ throw new ArgumentException(SR.PropertyTabAttributeBadPropertyTabScope, nameof(tabScope));
}
TabScopes = new PropertyTabScope[] { tabScope };
}
_tabClassNames = new string[] { tabClassName };
if (tabScope < PropertyTabScope.Document)
{
- throw new ArgumentException(SR.Format(SR.PropertyTabAttributeBadPropertyTabScope), nameof(tabScope));
+ throw new ArgumentException(SR.PropertyTabAttributeBadPropertyTabScope, nameof(tabScope));
}
TabScopes = new PropertyTabScope[] { tabScope };
}
// the enum isn't a flags style.
if (!EnumType.IsDefined(typeof(FlagsAttribute), false) && !Enum.IsDefined(EnumType, value))
{
- throw new ArgumentException(SR.Format(SR.EnumConverterInvalidValue, value.ToString(), EnumType.Name));
+ throw new ArgumentException(SR.Format(SR.EnumConverterInvalidValue, value, EnumType.Name));
}
return Enum.Format(EnumType, value, "G");
string providerName = site?.Name;
if (providerName != null && providerName.Length > 0)
{
- name = string.Format(SR.MetaExtenderName, name, providerName);
+ name = SR.Format(SR.MetaExtenderName, name, providerName);
}
}
return name;
protected virtual string GetKey(Type type)
{
// This string should not be localized.
- return string.Format(CultureInfo.InvariantCulture, "{0} is a licensed component.", type.FullName);
+ return type.FullName + " is a licensed component.";
}
/// <summary>
{
if (string.IsNullOrEmpty(mask))
{
- throw new ArgumentException(SR.Format(SR.MaskedTextProviderMaskNullOrEmpty), nameof(mask));
+ throw new ArgumentException(SR.MaskedTextProviderMaskNullOrEmpty, nameof(mask));
}
foreach (char c in mask)
string childName = _name;
if (ownerName != null)
{
- childName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", ownerName, childName);
+ childName = ownerName + "." + childName;
}
return childName;
if (type == null)
{
Debug.WriteLine($"type == null, name == {name}");
- throw new ArgumentException(string.Format(SR.ErrorInvalidPropertyType, name));
+ throw new ArgumentException(SR.Format(SR.ErrorInvalidPropertyType, name));
}
if (componentClass == null)
{
Debug.WriteLine($"componentClass == null, name == {name}");
- throw new ArgumentException(string.Format(SR.InvalidNullArgument, nameof(componentClass)));
+ throw new ArgumentException(SR.Format(SR.InvalidNullArgument, nameof(componentClass)));
}
_type = type;
_componentClass = componentClass;
if (componentClass == null)
{
- throw new ArgumentException(string.Format(SR.InvalidNullArgument, nameof(componentClass)));
+ throw new ArgumentException(SR.Format(SR.InvalidNullArgument, nameof(componentClass)));
}
// If the classes are the same, we can potentially optimize the method fetch because
{
if (!_state[s_bitChangedQueried])
{
- _realChangedEvent = TypeDescriptor.GetEvents(ComponentType)[string.Format(CultureInfo.InvariantCulture, "{0}Changed", Name)];
+ _realChangedEvent = TypeDescriptor.GetEvents(ComponentType)[Name + "Changed"];
_state[s_bitChangedQueried] = true;
}
}
if (_getMethod == null)
{
- throw new InvalidOperationException(string.Format(SR.ErrorMissingPropertyAccessors, _componentClass.FullName + "." + Name));
+ throw new InvalidOperationException(SR.Format(SR.ErrorMissingPropertyAccessors, _componentClass.FullName + "." + Name));
}
}
else
_getMethod = FindMethod(_componentClass, "Get" + Name, new Type[] { _receiverType }, _type);
if (_getMethod == null)
{
- throw new ArgumentException(string.Format(SR.ErrorMissingPropertyAccessors, Name));
+ throw new ArgumentException(SR.Format(SR.ErrorMissingPropertyAccessors, Name));
}
}
_state[s_bitGetQueried] = true;
string message = t.Message ?? t.GetType().Name;
- throw new TargetInvocationException(string.Format(SR.ErrorPropertyAccessorException, Name, name, message), t);
+ throw new TargetInvocationException(SR.Format(SR.ErrorPropertyAccessorException, Name, name, message), t);
}
}
Debug.WriteLine("[" + Name + "]: ---> returning: null");
name = ci.ToString(CultureInfo.InvariantCulture);
}
- suffix = string.Format(CultureInfo.InvariantCulture, "_{0}", name);
+ suffix = "_" + name;
}
return suffix;
if (x == null || y == null || !(x is int) || !(y is int))
{
- throw new ArgumentException(SR.Format(SR.PropertyValueInvalidEntry));
+ throw new ArgumentException(SR.PropertyValueInvalidEntry);
}
return new Point((int)x, (int)y);
if (x == null || y == null || width == null || height == null ||
!(x is int) || !(y is int) || !(width is int) || !(height is int))
{
- throw new ArgumentException(SR.Format(SR.PropertyValueInvalidEntry));
+ throw new ArgumentException(SR.PropertyValueInvalidEntry);
}
return new Rectangle((int)x, (int)y, (int)width, (int)height);
if (width == null || height == null || !(width is int) || !(height is int))
{
- throw new ArgumentException(SR.Format(SR.PropertyValueInvalidEntry));
+ throw new ArgumentException(SR.PropertyValueInvalidEntry);
}
return new Size((int)width, (int)height);
if (width == null || height == null || !(width is float) || !(height is float))
{
- throw new ArgumentException(SR.Format(SR.PropertyValueInvalidEntry));
+ throw new ArgumentException(SR.PropertyValueInvalidEntry);
}
return new SizeF((float)width, (float)height);
// cardinality violations in advance of this in all but a few very rare scenarios.
if (allForExport.Length != 1)
{
- var ex = new CompositionFailedException(SR.Format(SR.CardinalityMismatch_TooManyExports, exportKey.ToString()));
+ var ex = new CompositionFailedException(SR.Format(SR.CardinalityMismatch_TooManyExports, exportKey));
Debug.WriteLine(SR.Diagnostic_ThrowingException, ex.ToString());
throw ex;
}
}
else if (!contractType.IsAssignableFrom(partType))
{
- string message = string.Format(SR.TypeInspector_ContractNotAssignable, contractType.Name, partType.Name);
+ string message = SR.Format(SR.TypeInspector_ContractNotAssignable, contractType.Name, partType.Name);
throw new CompositionFailedException(message);
}
}
string val = _map[key];
- if (val == null) throw new InvalidOperationException(string.Format(SR.AppSettingsReaderNoKey, key));
+ if (val == null) throw new InvalidOperationException(SR.Format(SR.AppSettingsReaderNoKey, key));
if (type == s_stringType)
{
catch (Exception)
{
string displayString = (val.Length == 0) ? SR.AppSettingsReaderEmptyString : val;
- throw new InvalidOperationException(string.Format(SR.AppSettingsReaderCantParse, displayString, key, type.ToString()));
+ throw new InvalidOperationException(SR.Format(SR.AppSettingsReaderCantParse, displayString, key, type));
}
}
}
{
if (xmlUtil.Reader.Name != elementName)
throw new ConfigurationErrorsException(
- string.Format(SR.Config_name_value_file_section_file_invalid_root, elementName),
+ SR.Format(SR.Config_name_value_file_section_file_invalid_root, elementName),
xmlUtil);
lineOffset = xmlUtil.Reader.LineNumber;
if (internalReader.MoveToNextAttribute())
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_unrecognized_attribute, internalReader.Name),
+ SR.Format(SR.Config_base_unrecognized_attribute, internalReader.Name),
(XmlReader)internalReader);
internalReader.MoveToElement();
base.DeserializeElement(internalReader, serializeCollectionKey);
}
}
-}
\ No newline at end of file
+}
Type providerType = Type.GetType(providerTypeName);
if (providerType == null)
{
- throw new ConfigurationErrorsException(string.Format(SR.ProviderTypeLoadFailed, providerTypeName));
+ throw new ConfigurationErrorsException(SR.Format(SR.ProviderTypeLoadFailed, providerTypeName));
}
SettingsProvider settingsProvider = TypeUtil.CreateInstance(providerType) as SettingsProvider;
if (settingsProvider == null)
{
- throw new ConfigurationErrorsException(string.Format(SR.ProviderInstantiationFailed, providerTypeName));
+ throw new ConfigurationErrorsException(SR.Format(SR.ProviderInstantiationFailed, providerTypeName));
}
settingsProvider.Initialize(null, null);
}
else
{
- throw new ConfigurationErrorsException(string.Format(SR.ProviderInstantiationFailed, providerTypeName));
+ throw new ConfigurationErrorsException(SR.Format(SR.ProviderInstantiationFailed, providerTypeName));
}
}
else
{
- throw new ConfigurationErrorsException(string.Format(SR.ProviderTypeLoadFailed, providerTypeName));
+ throw new ConfigurationErrorsException(SR.Format(SR.ProviderTypeLoadFailed, providerTypeName));
}
}
else if (attr is SettingsSerializeAsAttribute)
catch (Exception e)
{
throw ExceptionUtil.WrapAsConfigException(
- string.Format(SR.Config_exception_creating_section, factoryRecord.ConfigKey),
+ SR.Format(SR.Config_exception_creating_section, factoryRecord.ConfigKey),
e, input.SectionXmlInfo);
}
if (stream == null)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_cannot_open_config_source, sectionXmlInfo.ConfigSource),
+ SR.Format(SR.Config_cannot_open_config_source, sectionXmlInfo.ConfigSource),
sectionXmlInfo);
}
if (!throwIfNotFound) return null;
- throw new ConfigurationErrorsException(string.Format(SR.ProtectedConfigurationProvider_not_found,
+ throw new ConfigurationErrorsException(SR.Format(SR.ProtectedConfigurationProvider_not_found,
providerName));
}
catch (Exception e)
{
throw ExceptionUtil.WrapAsConfigException(
- string.Format(SR.Config_exception_creating_section_handler, factoryRecord.ConfigKey), e, filename,
+ SR.Format(SR.Config_exception_creating_section_handler, factoryRecord.ConfigKey), e, filename,
line);
}
catch (Exception e)
{
throw ExceptionUtil.WrapAsConfigException(
- string.Format(SR.Config_exception_creating_section_handler, factoryRecord.ConfigKey), e,
+ SR.Format(SR.Config_exception_creating_section_handler, factoryRecord.ConfigKey), e,
factoryRecord);
}
}
// Check for a root <configuration>
if ((xmlUtil.Reader.NodeType != XmlNodeType.Element) || (xmlUtil.Reader.Name != ConfigurationTag))
throw new ConfigurationErrorsException(
- string.Format(SR.Config_file_doesnt_have_root_configuration, xmlUtil.Filename), xmlUtil);
+ SR.Format(SR.Config_file_doesnt_have_root_configuration, xmlUtil.Filename), xmlUtil);
// Look at the configuration attributes
while (xmlUtil.Reader.MoveToNextAttribute())
{
// A configuration namespace was defined that we don't understand
ConfigurationErrorsException ce = new ConfigurationErrorsException(
- string.Format(SR.Config_namespace_invalid, xmlUtil.Reader.Value, ConfigurationNamespace),
+ SR.Format(SR.Config_namespace_invalid, xmlUtil.Reader.Value, ConfigurationNamespace),
xmlUtil);
xmlUtil.SchemaErrors.AddError(ce, ExceptionAction.Global);
}
{
// Error: duplicate <sectionGroup> declaration
xmlUtil.SchemaErrors.AddError(
- new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined_at_this_level, tagName), xmlUtil),
+ new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined_at_this_level, tagName), xmlUtil),
ExceptionAction.Local);
}
else
(!parentFactoryRecord.IsGroup || !parentFactoryRecord.IsEquivalentSectionGroupFactory(Host, typeName)))
{
xmlUtil.SchemaErrors.AddError(
- new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined, tagName), xmlUtil),
+ new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, tagName), xmlUtil),
ExceptionAction.Local);
parentFactoryRecord = null;
}
// Error: duplicate section declaration
xmlUtil.SchemaErrors.AddError(
new ConfigurationErrorsException(
- string.Format(SR.Config_tag_name_already_defined_at_this_level, tagName),
+ SR.Format(SR.Config_tag_name_already_defined_at_this_level, tagName),
xmlUtil),
ExceptionAction.Local);
}
// Already a <sectionGroup> with this name
xmlUtil.SchemaErrors.AddError(
new ConfigurationErrorsException(
- string.Format(SR.Config_tag_name_already_defined, tagName), xmlUtil),
+ SR.Format(SR.Config_tag_name_already_defined, tagName), xmlUtil),
ExceptionAction.Local);
parentFactoryRecord = null;
}
{
// Already a <section> with the same name
xmlUtil.SchemaErrors.AddError(
- new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined, tagName), xmlUtil),
+ new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, tagName), xmlUtil),
ExceptionAction.Local);
parentFactoryRecord = null;
}
case ConfigSectionsTag: // <configSections>
// Either a duplicate or not the first tag under <configuration>
xmlUtil.SchemaErrors.AddError(
- new ConfigurationErrorsException(string.Format(SR.Config_client_config_too_many_configsections_elements, tagName), xmlUtil),
+ new ConfigurationErrorsException(SR.Format(SR.Config_client_config_too_many_configsections_elements, tagName), xmlUtil),
ExceptionAction.NonSpecific);
xmlUtil.StrictSkipToNextElement(ExceptionAction.NonSpecific);
continue;
{
xmlUtil.SchemaErrors.AddError(
new ConfigurationErrorsException(
- string.Format(SR.Config_unrecognized_configuration_section, configKey), xmlUtil),
+ SR.Format(SR.Config_unrecognized_configuration_section, configKey), xmlUtil),
ExceptionAction.Local);
}
}
throw new ConfigurationErrorsException(
- string.Format(SR.Cannot_declare_or_remove_implicit_section, name), errorInfo);
+ SR.Format(SR.Cannot_declare_or_remove_implicit_section, name), errorInfo);
}
if (StringUtil.StartsWithOrdinal(name, "config"))
{
if (streamInfo.SectionName != configKey)
{
- throw new ConfigurationErrorsException(string.Format(SR.Config_source_cannot_be_shared,
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_source_cannot_be_shared,
streamname));
}
if ((streamInfo != null) && (streamInfo.SectionName != configKey))
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_source_cannot_be_shared, configSourceArg),
+ SR.Format(SR.Config_source_cannot_be_shared, configSourceArg),
errorInfo);
}
}
if (streamInfo != null)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_source_parent_conflict, configSourceArg),
+ SR.Format(SR.Config_source_parent_conflict, configSourceArg),
errorInfo);
}
}
catch (Exception e)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Decryption_failed, protectionProvider.Name, e.Message), e, filename, lineNumber);
+ SR.Format(SR.Decryption_failed, protectionProvider.Name, e.Message), e, filename, lineNumber);
}
// Detect if there is any XML left over after <EncryptedData>
return -1;
}
- Debug.Assert(false,
- "It's not possible for two location input to come from the same config file and point to the same target");
+ Debug.Fail("It's not possible for two location input to come from the same config file and point to the same target");
return 0;
}
}
}
if (_callbackMethod == null)
- throw new ArgumentException(string.Format(SR.Validator_method_not_found, _callbackMethodName));
+ throw new ArgumentException(SR.Format(SR.Validator_method_not_found, _callbackMethodName));
return new CallbackValidator(_callbackMethod);
}
}
}
}
-}
\ No newline at end of file
+}
catch (ConfigurationErrorsException ex)
{
// We wrap this in an exception with our error message and throw again.
- throw new ConfigurationErrorsException(string.Format(SR.SettingsSaveFailed, ex.Message), ex);
+ throw new ConfigurationErrorsException(SR.Format(SR.SettingsSaveFailed, ex.Message), ex);
}
}
else
internal void ValidateType(object value, Type expected)
{
if ((value != null) && (value.GetType() != expected))
- throw new ArgumentException(string.Format(SR.Converter_unsupported_value_type, expected.Name));
+ throw new ArgumentException(SR.Format(SR.Converter_unsupported_value_type, expected.Name));
}
}
-}
\ No newline at end of file
+}
}
else
{
- throw new ConfigurationErrorsException(string.Format(SR.Config_base_attribute_locked, LockItemKey));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_base_attribute_locked, LockItemKey));
}
}
}
{
// Don't allow the override
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_attribute_locked, propInfo.Name));
+ SR.Format(SR.Config_base_attribute_locked, propInfo.Name));
}
// They did not override so we need to make sure the value comes from the locked one
((_itemLockedFlag & ConfigurationValueFlags.Inherited) != 0)
)
{
- throw new ConfigurationErrorsException(string.Format(SR.Config_base_element_locked, elementName),
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_base_element_locked, elementName),
reader);
}
}
if (!validator.CanValidate(type))
{
throw new ConfigurationErrorsException(
- string.Format(SR.Validator_does_not_support_elem_type, type.Name));
+ SR.Format(SR.Validator_does_not_support_elem_type, type.Name));
}
s_perTypeValidators.Add(type, validator);
(_lockedAttributesList.DefinedInParent(prop.Name) || _lockedAttributesList.DefinedInParent(LockAll))) ||
(((_itemLockedFlag & ConfigurationValueFlags.Locked) != 0) &&
((_itemLockedFlag & ConfigurationValueFlags.Inherited) != 0))))
- throw new ConfigurationErrorsException(string.Format(SR.Config_base_attribute_locked, prop.Name));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_base_attribute_locked, prop.Name));
_modified = true;
{
if (prop.IsRequired)
{
- throw new ConfigurationErrorsException(string.Format(
+ throw new ConfigurationErrorsException(SR.Format(
SR.Config_base_required_attribute_locked, prop.Name));
}
value = s_nullPropertyValue;
else
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_element_cannot_have_multiple_child_elements, prop.Name));
+ SR.Format(SR.Config_base_element_cannot_have_multiple_child_elements, prop.Name));
}
}
}
if (value != null)
{
throw new ConfigurationErrorsException(
- string.Format(CultureInfo.CurrentCulture, format, attribToLockTrim, sb.ToString()),
+ SR.Format(format, attribToLockTrim, sb),
value.SourceInfo.FileName, value.SourceInfo.LineNumber);
}
- throw new ConfigurationErrorsException(string.Format(CultureInfo.CurrentCulture, format,
- attribToLockTrim, sb.ToString()));
+ throw new ConfigurationErrorsException(SR.Format(format,
+ attribToLockTrim, sb));
}
private ConfigurationLockCollection ParseLockedAttributes(ConfigurationValue value,
switch (lockType)
{
case ConfigurationLockCollectionType.LockedAttributes:
- throw new ConfigurationErrorsException(string.Format(SR.Empty_attribute, LockAttributesKey),
+ throw new ConfigurationErrorsException(SR.Format(SR.Empty_attribute, LockAttributesKey),
value.SourceInfo.FileName, value.SourceInfo.LineNumber);
case ConfigurationLockCollectionType.LockedElements:
- throw new ConfigurationErrorsException(string.Format(SR.Empty_attribute, LockElementsKey),
+ throw new ConfigurationErrorsException(SR.Format(SR.Empty_attribute, LockElementsKey),
value.SourceInfo.FileName, value.SourceInfo.LineNumber);
case ConfigurationLockCollectionType.LockedExceptionList:
throw new ConfigurationErrorsException(
- string.Format(SR.Config_empty_lock_attributes_except, LockAllAttributesExceptKey,
+ SR.Format(SR.Config_empty_lock_attributes_except, LockAllAttributesExceptKey,
LockAttributesKey), value.SourceInfo.FileName, value.SourceInfo.LineNumber);
case ConfigurationLockCollectionType.LockedElementsExceptionList:
throw new ConfigurationErrorsException(
- string.Format(SR.Config_empty_lock_element_except, LockAllElementsExceptKey, LockElementsKey),
+ SR.Format(SR.Config_empty_lock_element_except, LockAllElementsExceptKey, LockElementsKey),
value.SourceInfo.FileName, value.SourceInfo.LineNumber);
}
}
if ((propToLock != null) && propToLock.IsRequired)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_required_attribute_lock_attempt, propToLock.Name));
+ SR.Format(SR.Config_base_required_attribute_lock_attempt, propToLock.Name));
}
}
(((_itemLockedFlag & ConfigurationValueFlags.Locked) != 0) &&
((_itemLockedFlag & ConfigurationValueFlags.Inherited) != 0))
)
- throw new ConfigurationErrorsException(string.Format(SR.Config_base_element_locked, reader.Name), reader);
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_base_element_locked, reader.Name), reader);
if (reader.AttributeCount > 0)
if ((propertyName != LockAttributesKey) && (propertyName != LockAllAttributesExceptKey))
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_attribute_locked, propertyName), reader);
+ SR.Format(SR.Config_base_attribute_locked, propertyName), reader);
}
}
if (serializeCollectionKey && !prop.IsKey)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_unrecognized_attribute, propertyName), reader);
+ SR.Format(SR.Config_base_unrecognized_attribute, propertyName), reader);
}
Values.SetValue(propertyName,
catch
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_invalid_boolean_attribute, propertyName), reader);
+ SR.Format(SR.Config_invalid_boolean_attribute, propertyName), reader);
}
break;
case LockAttributesKey:
!OnDeserializeUnrecognizedAttribute(propertyName, reader.Value))
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_unrecognized_attribute, propertyName),
+ SR.Format(SR.Config_base_unrecognized_attribute, propertyName),
reader);
}
break;
if (nodeFound.Contains(propertyName))
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_element_cannot_have_multiple_child_elements,
+ SR.Format(SR.Config_base_element_cannot_have_multiple_child_elements,
propertyName), reader);
}
else
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_property_is_not_a_configuration_element,
+ SR.Format(SR.Config_base_property_is_not_a_configuration_element,
propertyName), reader);
}
}
!defaultCollection.OnDeserializeUnrecognizedElement(propertyName, reader))
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_unrecognized_element_name, propertyName), reader);
+ SR.Format(SR.Config_base_unrecognized_element_name, propertyName), reader);
}
}
}
// the validator supports the type of elem every time
if ((validator != null) && !validator.CanValidate(elem.GetType()))
{
- throw new ConfigurationErrorsException(string.Format(SR.Validator_does_not_support_elem_type,
+ throw new ConfigurationErrorsException(SR.Format(SR.Validator_does_not_support_elem_type,
elem.GetType().Name));
}
}
}
catch (Exception ex)
{
- throw new ConfigurationErrorsException(string.Format(SR.Validator_element_not_valid, elem.ElementTagName,
+ throw new ConfigurationErrorsException(SR.Format(SR.Validator_element_not_valid, elem.ElementTagName,
ex.Message));
}
// Derivied classes can override this to return a value for a required property that is missing
// Here we treat this as an error though
- throw new ConfigurationErrorsException(string.Format(SR.Config_base_required_attribute_missing, name),
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_base_required_attribute_missing, name),
PropertyFileName(name),
PropertyLineNumber(name));
}
{
_addElement = value;
if (BaseConfigurationRecord.IsReservedAttributeName(value))
- throw new ArgumentException(string.Format(SR.Item_name_reserved, DefaultAddItemName, value));
+ throw new ArgumentException(SR.Format(SR.Item_name_reserved, DefaultAddItemName, value));
}
}
set
{
if (BaseConfigurationRecord.IsReservedAttributeName(value))
- throw new ArgumentException(string.Format(SR.Item_name_reserved, DefaultRemoveItemName, value));
+ throw new ArgumentException(SR.Format(SR.Item_name_reserved, DefaultRemoveItemName, value));
_removeElement = value;
}
}
set
{
if (BaseConfigurationRecord.IsReservedAttributeName(value))
- throw new ArgumentException(string.Format(SR.Item_name_reserved, DefaultClearItemsName, value));
+ throw new ArgumentException(SR.Format(SR.Item_name_reserved, DefaultClearItemsName, value));
_clearElement = value;
}
}
if (IsReadOnly()) throw new ConfigurationErrorsException(SR.Config_base_read_only);
if (LockItem && (ignoreLocks == false))
- throw new ConfigurationErrorsException(string.Format(SR.Config_base_element_locked, _addElement));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_base_element_locked, _addElement));
object key = GetElementKeyInternal(element);
int iFoundItem = -1;
if (!element.Equals(entry.Value))
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_collection_entry_already_exists, key),
+ SR.Format(SR.Config_base_collection_entry_already_exists, key),
element.PropertyFileName(""), element.PropertyLineNumber(""));
}
(CollectionType == ConfigurationElementCollectionType.BasicMapAlternate))
{
if (BaseConfigurationRecord.IsReservedAttributeName(ElementName))
- throw new ArgumentException(string.Format(SR.Basicmap_item_name_reserved, ElementName));
+ throw new ArgumentException(SR.Format(SR.Basicmap_item_name_reserved, ElementName));
CheckLockedElement(ElementName, null);
}
if (index >= 0)
{
if (index > Items.Count)
- throw new ConfigurationErrorsException(string.Format(SR.IndexOutOfRange, index));
+ throw new ConfigurationErrorsException(SR.Format(SR.IndexOutOfRange, index));
Items.Insert(index, new Entry(entryType, key, element));
}
else
private void BaseAdd(int index, ConfigurationElement element, bool ignoreLocks)
{
if (IsReadOnly()) throw new ConfigurationErrorsException(SR.Config_base_read_only);
- if (index < -1) throw new ConfigurationErrorsException(string.Format(SR.IndexOutOfRange, index));
+ if (index < -1) throw new ConfigurationErrorsException(SR.Format(SR.IndexOutOfRange, index));
if ((index != -1) &&
((CollectionType == ConfigurationElementCollectionType.AddRemoveClearMap) ||
if (!element.Equals(entry.Value))
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_collection_entry_already_exists, key),
+ SR.Format(SR.Config_base_collection_entry_already_exists, key),
element.PropertyFileName(""), element.PropertyLineNumber(""));
}
if (throwIfMissing)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_collection_entry_not_found, key));
+ SR.Format(SR.Config_base_collection_entry_not_found, key));
}
return;
}
if (entry.Value.LockItem)
- throw new ConfigurationErrorsException(string.Format(SR.Config_base_attribute_locked, key));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_base_attribute_locked, key));
if (entry.Value.ElementPresent == false)
CheckLockedElement(_removeElement, null); // has remove been locked?
// remove the item at the parent level.
if (throwIfMissing)
- throw new ConfigurationErrorsException(string.Format(SR.Config_base_collection_entry_not_found, key));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_base_collection_entry_not_found, key));
if ((CollectionType != ConfigurationElementCollectionType.AddRemoveClearMap) &&
(CollectionType != ConfigurationElementCollectionType.AddRemoveClearMapAlternate))
protected internal ConfigurationElement BaseGet(int index)
{
- if (index < 0) throw new ConfigurationErrorsException(string.Format(SR.IndexOutOfRange, index));
+ if (index < 0) throw new ConfigurationErrorsException(SR.Format(SR.IndexOutOfRange, index));
int virtualIndex = 0;
Entry entry = null;
if (entry != null)
return entry.Value;
- throw new ConfigurationErrorsException(string.Format(SR.IndexOutOfRange, index));
+ throw new ConfigurationErrorsException(SR.Format(SR.IndexOutOfRange, index));
}
protected internal object[] BaseGetAllKeys()
{
int virtualIndex = 0;
Entry entry = null;
- if (index < 0) throw new ConfigurationErrorsException(string.Format(SR.IndexOutOfRange, index));
+ if (index < 0) throw new ConfigurationErrorsException(SR.Format(SR.IndexOutOfRange, index));
foreach (Entry entryfound in Items)
{
}
// Entry entry = (Entry)_items[index];
- if (entry == null) throw new ConfigurationErrorsException(string.Format(SR.IndexOutOfRange, index));
+ if (entry == null) throw new ConfigurationErrorsException(SR.Format(SR.IndexOutOfRange, index));
return entry.GetKey(this);
}
if (entryfound.EntryType != EntryType.Removed) virtualIndex++;
}
- if (entry == null) throw new ConfigurationErrorsException(string.Format(SR.IndexOutOfRange, index));
+ if (entry == null) throw new ConfigurationErrorsException(SR.Format(SR.IndexOutOfRange, index));
if (entry.Value.LockItem)
{
- throw new ConfigurationErrorsException(string.Format(SR.Config_base_attribute_locked,
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_base_attribute_locked,
entry.GetKey(this)));
}
{
if (BaseConfigurationRecord.IsReservedAttributeName(ElementName))
{
- throw new ArgumentException(string.Format(SR.Basicmap_item_name_reserved,
+ throw new ArgumentException(SR.Format(SR.Basicmap_item_name_reserved,
ElementName));
}
{
string propertyName = reader.Name;
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_unrecognized_attribute, propertyName), reader);
+ SR.Format(SR.Config_base_unrecognized_attribute, propertyName), reader);
}
}
if (elementName == ElementName)
{
if (BaseConfigurationRecord.IsReservedAttributeName(elementName))
- throw new ArgumentException(string.Format(SR.Basicmap_item_name_reserved, elementName));
+ throw new ArgumentException(SR.Format(SR.Basicmap_item_name_reserved, elementName));
ConfigurationElement elem = CallCreateNewElement();
elem.ResetLockLists(this);
elem.DeserializeElement(reader, false);
// this section handle the collection like the allow deny senario which
if (BaseConfigurationRecord.IsReservedAttributeName(elementName))
- throw new ArgumentException(string.Format(SR.Basicmap_item_name_reserved, elementName));
+ throw new ArgumentException(SR.Format(SR.Basicmap_item_name_reserved, elementName));
// have multiple tags for the collection
ConfigurationElement elem = CallCreateNewElement(elementName);
throw new ArgumentNullException(nameof(machineConfigFilename));
if (!File.Exists(machineConfigFilename))
- throw new ArgumentException(string.Format(SR.Machine_config_file_not_found, machineConfigFilename),
+ throw new ArgumentException(SR.Format(SR.Machine_config_file_not_found, machineConfigFilename),
nameof(machineConfigFilename));
MachineConfigFilename = machineConfigFilename;
internal bool IsMachinePathDefault => _getFilenameThunk == GetFilenameFromMachineConfigFilePath;
}
-}
\ No newline at end of file
+}
{
if (((_thisElement.ItemLocked & ConfigurationValueFlags.Locked) != 0) &&
((_thisElement.ItemLocked & ConfigurationValueFlags.Inherited) != 0))
- throw new ConfigurationErrorsException(string.Format(SR.Config_base_attribute_locked, name));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_base_attribute_locked, name));
ConfigurationValueFlags flags = ConfigurationValueFlags.Modified;
// the lock is in the property bag but is it the correct type?
if ((propToLock != null) && propToLock.IsRequired)
{
- throw new ConfigurationErrorsException(string.Format(SR.Config_base_required_attribute_lock_attempt,
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_base_required_attribute_lock_attempt,
propToLock.Name));
}
public void Remove(string name)
{
if (!_internalDictionary.Contains(name))
- throw new ConfigurationErrorsException(string.Format(SR.Config_base_collection_entry_not_found, name));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_base_collection_entry_not_found, name));
// in a locked list you cannot remove items that were locked in the parent
// in an exception list this is legal because it makes the list more restrictive
(((ConfigurationValueFlags)_internalDictionary[name] & ConfigurationValueFlags.Inherited) != 0))
{
if (((ConfigurationValueFlags)_internalDictionary[name] & ConfigurationValueFlags.Modified) == 0)
- throw new ConfigurationErrorsException(string.Format(SR.Config_base_attribute_locked, name));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_base_attribute_locked, name));
// allow the local one to be "removed" so it won't write out but throw if they try and remove
// one that is only inherited
public bool IsReadOnly(string name)
{
if (!_internalDictionary.Contains(name))
- throw new ConfigurationErrorsException(string.Format(SR.Config_base_collection_entry_not_found, name));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_base_collection_entry_not_found, name));
return
((ConfigurationValueFlags)_internalDictionary[name] & ConfigurationValueFlags.Inherited) != 0;
}
}
}
}
-}
\ No newline at end of file
+}
// list of validators and executes them all
throw new ConfigurationErrorsException(
- string.Format(SR.Validator_multiple_validator_attributes, info.Name));
+ SR.Format(SR.Validator_multiple_validator_attributes, info.Name));
}
ConfigurationValidatorAttribute validatorAttribute = (ConfigurationValidatorAttribute)attribute;
if (typeof(ConfigurationSection).IsAssignableFrom(type))
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_properties_may_not_be_derived_from_configuration_section, name));
+ SR.Format(SR.Config_properties_may_not_be_derived_from_configuration_section, name));
}
// save the provided name so we can check for default collection names
{
// Make sure the supplied validator supports the type of this property
if (!Validator.CanValidate(Type))
- throw new ConfigurationErrorsException(string.Format(SR.Validator_does_not_support_prop_type, Name));
+ throw new ConfigurationErrorsException(SR.Format(SR.Validator_does_not_support_prop_type, Name));
}
}
throw new ArgumentException(SR.String_null_or_empty, nameof(name));
if (BaseConfigurationRecord.IsReservedAttributeName(name))
- throw new ArgumentException(string.Format(SR.Property_name_reserved, name));
+ throw new ArgumentException(SR.Format(SR.Property_name_reserved, name));
}
private void SetDefaultValue(object value)
if (!Type.IsInstanceOfType(value))
{
if (!Converter.CanConvertFrom(value.GetType()))
- throw new ConfigurationErrorsException(string.Format(SR.Default_value_wrong_type, Name));
+ throw new ConfigurationErrorsException(SR.Format(SR.Default_value_wrong_type, Name));
value = Converter.ConvertFrom(value);
}
}
catch (Exception ex)
{
- throw new ConfigurationErrorsException(string.Format(SR.Default_value_conversion_error_from_string,
+ throw new ConfigurationErrorsException(SR.Format(SR.Default_value_conversion_error_from_string,
Name, ex.Message));
}
}
}
catch (Exception ex)
{
- throw new ConfigurationErrorsException(string.Format(SR.Top_level_conversion_error_from_string, Name,
+ throw new ConfigurationErrorsException(SR.Format(SR.Top_level_conversion_error_from_string, Name,
ex.Message));
}
catch (Exception ex)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Top_level_conversion_error_to_string, Name, ex.Message));
+ SR.Format(SR.Top_level_conversion_error_to_string, Name, ex.Message));
}
}
catch (Exception ex)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Top_level_validation_error, Name, ex.Message), ex);
+ SR.Format(SR.Top_level_validation_error, Name, ex.Message), ex);
}
}
!_converter.CanConvertTo(typeof(string)))
{
// Need to be able to convert to/from string
- throw new ConfigurationErrorsException(string.Format(SR.No_converter, Name, Type.Name));
+ throw new ConfigurationErrorsException(SR.Format(SR.No_converter, Name, Type.Name));
}
}
}
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && !factoryRecord.IsEquivalentType(_configRecord.Host, typeName))
{
- throw new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined,
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined,
SectionGroupName));
}
}
return true;
}
}
-}
\ No newline at end of file
+}
if (!typeof(ConfigurationValidatorBase).IsAssignableFrom(validator))
{
- throw new ArgumentException(string.Format(SR.Validator_Attribute_param_not_validator,
+ throw new ArgumentException(SR.Format(SR.Validator_Attribute_param_not_validator,
"ConfigurationValidatorBase"));
}
}
}
}
-}
\ No newline at end of file
+}
_keyEntropy = configurationValues["keyEntropy"];
configurationValues.Remove("keyEntropy");
if (configurationValues.Count > 0)
- throw new ConfigurationErrorsException(string.Format(SR.Unrecognized_initialization_value, configurationValues.GetKey(0)));
+ throw new ConfigurationErrorsException(SR.Format(SR.Unrecognized_initialization_value, configurationValues.GetKey(0)));
}
private static XmlNode TraverseToChild(XmlNode node, string name, bool onlyChild)
return true;
if (s == "false")
return false;
- throw new ConfigurationErrorsException(string.Format(SR.Config_invalid_boolean_attribute, valueName));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_invalid_boolean_attribute, valueName));
}
}
}
internal static ArgumentException ParameterInvalid(string parameter)
{
- return new ArgumentException(string.Format(SR.Parameter_Invalid, parameter), parameter);
+ return new ArgumentException(SR.Format(SR.Parameter_Invalid, parameter), parameter);
}
internal static ArgumentException ParameterNullOrEmpty(string parameter)
{
- return new ArgumentException(string.Format(SR.Parameter_NullOrEmpty, parameter), parameter);
+ return new ArgumentException(SR.Format(SR.Parameter_NullOrEmpty, parameter), parameter);
}
internal static ArgumentException PropertyInvalid(string property)
{
- return new ArgumentException(string.Format(SR.Property_Invalid, property), property);
+ return new ArgumentException(SR.Format(SR.Property_Invalid, property), property);
}
internal static ArgumentException PropertyNullOrEmpty(string property)
{
- return new ArgumentException(string.Format(SR.Property_NullOrEmpty, property), property);
+ return new ArgumentException(SR.Format(SR.Property_NullOrEmpty, property), property);
}
internal static InvalidOperationException UnexpectedError(string methodName)
{
- return new InvalidOperationException(string.Format(SR.Unexpected_Error, methodName));
+ return new InvalidOperationException(SR.Format(SR.Unexpected_Error, methodName));
}
internal static ConfigurationErrorsException WrapAsConfigException(string outerMessage, Exception e,
if (e != null)
{
return new ConfigurationErrorsException(
- string.Format(SR.Wrapped_exception_message, outerMessage, e.Message),
+ SR.Format(SR.Wrapped_exception_message, outerMessage, e.Message),
e,
filename,
line);
// If there is no exception, create a new exception with no further information.
return new ConfigurationErrorsException(
- string.Format(SR.Wrapped_exception_message, outerMessage, NoExceptionInformation),
+ SR.Format(SR.Wrapped_exception_message, outerMessage, NoExceptionInformation),
filename,
line);
}
}
-}
\ No newline at end of file
+}
}
names.Append(name);
}
- return new ArgumentException(string.Format(SR.Invalid_enum_value, names.ToString()));
+ return new ArgumentException(SR.Format(SR.Invalid_enum_value, names));
}
}
}
if (fRequired && a == null)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_missing_required_attribute, attrib, node.Name),
+ SR.Format(SR.Config_missing_required_attribute, attrib, node.Name),
node);
}
catch (Exception e)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_invalid_boolean_attribute, a.Name),
+ SR.Format(SR.Config_invalid_boolean_attribute, a.Name),
e, a);
}
}
if (a.Value.Trim() != a.Value)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_invalid_integer_attribute, a.Name), a);
+ SR.Format(SR.Config_invalid_integer_attribute, a.Name), a);
}
try
catch (Exception e)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_invalid_integer_attribute, a.Name),
+ SR.Format(SR.Config_invalid_integer_attribute, a.Name),
e, a);
}
}
if (node.Attributes.Count != 0)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_unrecognized_attribute, node.Attributes[0].Name),
+ SR.Format(SR.Config_base_unrecognized_attribute, node.Attributes[0].Name),
node);
}
}
if (attribute == null)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_required_attribute_missing, name),
+ SR.Format(SR.Config_base_required_attribute_missing, name),
node);
}
if (string.IsNullOrEmpty(attribute.Value) && allowEmpty == false)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_base_required_attribute_empty, name),
+ SR.Format(SR.Config_base_required_attribute_empty, name),
node);
}
// ensure the result is in or under the directory of the original source
string dirResult = UrlPath.GetDirectoryOrRootName(result);
if (!UrlPath.IsEqualOrSubdirectory(dirStream, dirResult))
- throw new ArgumentException(string.Format(SR.Config_source_not_under_config_dir, configSource));
+ throw new ArgumentException(SR.Format(SR.Config_source_not_under_config_dir, configSource));
return result;
}
FileAttributes attrs = fi.Attributes;
if ((attrs & InvalidAttributesForWrite) != 0)
{
- throw new IOException(string.Format(SR.Config_invalid_attributes_for_write, streamName));
+ throw new IOException(SR.Format(SR.Config_invalid_attributes_for_write, streamName));
}
}
// Wrap all exceptions so that we provide a meaningful filename - otherwise the end user
// will just see the temporary file name, which is meaningless.
- throw new ConfigurationErrorsException(string.Format(SR.Config_write_failed, streamName), e);
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_write_failed, streamName), e);
}
}
catch
if (!writeSucceeded)
{
- throw new ConfigurationErrorsException(string.Format(SR.Config_write_failed, target));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_write_failed, target));
}
}
}
}
}
-}
\ No newline at end of file
+}
if (!string.IsNullOrEmpty(key))
{
- sectionName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", sectionName, key);
+ sectionName = sectionName + "." + key;
}
return XmlConvert.EncodeLocalName(sectionName);
if (isUser && isApp)
{
- throw new ConfigurationErrorsException(string.Format(SR.BothScopeAttributes, setting.Name));
+ throw new ConfigurationErrorsException(SR.Format(SR.BothScopeAttributes, setting.Name));
}
else if (!(isUser || isApp))
{
- throw new ConfigurationErrorsException(string.Format(SR.NoScopeAttributes, setting.Name));
+ throw new ConfigurationErrorsException(SR.Format(SR.NoScopeAttributes, setting.Name));
}
return isUser;
FactoryRecord factoryRecord = FindFactoryRecord(configKey, false);
if (factoryRecord == null)
{
- throw new ConfigurationErrorsException(string.Format(SR.Config_unrecognized_configuration_section,
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_unrecognized_configuration_section,
configKey));
}
catch (Exception e)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_exception_creating_section_handler, factoryRecord.ConfigKey),
+ SR.Format(SR.Config_exception_creating_section_handler, factoryRecord.ConfigKey),
e, factoryRecord);
}
}
catch (Exception e)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_exception_in_config_section_handler,
+ SR.Format(SR.Config_exception_in_config_section_handler,
configSection.SectionInformation.SectionName),
e, ConfigStreamInfo.StreamName, 0);
}
catch (Exception e)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_exception_in_config_section_handler,
+ SR.Format(SR.Config_exception_in_config_section_handler,
configSection.SectionInformation.SectionName),
e, null, 0);
}
if (streamInfo.SectionName != sectionInformation.ConfigKey)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_source_cannot_be_shared, newConfigSource));
+ SR.Format(SR.Config_source_cannot_be_shared, newConfigSource));
}
}
else
// Verify that the it is an element
reader.Read();
if (reader.NodeType != XmlNodeType.Element)
- throw new ConfigurationErrorsException(string.Format(SR.Config_unexpected_node_type, reader.NodeType));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_unexpected_node_type, reader.NodeType));
// Verify the name of the element is a section
string group, name;
SplitConfigKey(configKey, out group, out name);
if (reader.Name != name)
- throw new ConfigurationErrorsException(string.Format(SR.Config_unexpected_element_name, reader.Name));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_unexpected_element_name, reader.Name));
for (;;)
{
// ensure there is a matching end element
if (reader.Depth != 0)
{
- throw new ConfigurationErrorsException(string.Format(SR.Config_unexpected_element_end),
+ throw new ConfigurationErrorsException(SR.Config_unexpected_element_end,
reader);
}
// are actually fullpaths on the remote machine. In this case there is no way to
// detect if we have a conflict or not.
if (!Host.IsRemote && _streamInfoUpdates.Contains(filename))
- throw new ArgumentException(string.Format(SR.Filename_in_SaveAs_is_used_already, filename));
+ throw new ArgumentException(SR.Format(SR.Filename_in_SaveAs_is_used_already, filename));
// If there was no config file for this config record,
// record the new stream name and version.
(!overrideMode.IsDefaultForLocationTag || !inheritInChildApplications))
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_inconsistent_location_attributes, configKey));
+ SR.Format(SR.Config_inconsistent_location_attributes, configKey));
}
addToConfigSourceUpdates = requireUpdates &&
catch (Exception e)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Encryption_failed,
+ SR.Format(SR.Encryption_failed,
configSection.SectionInformation.SectionName,
configSection.SectionInformation.ProtectionProvider.Name, e.Message),
e);
catch (Exception e)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_exception_in_config_section_handler,
+ SR.Format(SR.Config_exception_in_config_section_handler,
configSection.SectionInformation.SectionName), e);
}
}
catch (Exception e)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_exception_in_config_section_handler, sectionRecord.ConfigKey), e,
+ SR.Format(SR.Config_exception_in_config_section_handler, sectionRecord.ConfigKey), e,
ConfigStreamInfo.StreamName, 0);
}
}
if (section.Name != doc.DocumentElement.Name)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_name_value_file_section_file_invalid_root, section.Name),
+ SR.Format(SR.Config_name_value_file_section_file_invalid_root, section.Name),
doc.DocumentElement);
}
result = false;
break;
default:
- Debug.Assert(false, "Unrecognized OverrideMode");
+ Debug.Fail("Unrecognized OverrideMode");
break;
}
if (!(provider is ProtectedConfigurationProvider))
{
throw new ArgumentException(
- string.Format(SR.Config_provider_must_implement_type,
+ SR.Format(SR.Config_provider_must_implement_type,
typeof(ProtectedConfigurationProvider).ToString()), nameof(provider));
}
base.Add(provider);
}
}
-}
\ No newline at end of file
+}
ProviderSettings ps = Providers[providerName];
if (ps == null)
- throw new ArgumentException(string.Format(SR.ProtectedConfigurationProvider_not_found, providerName), nameof(providerName));
+ throw new ArgumentException(SR.Format(SR.ProtectedConfigurationProvider_not_found, providerName), nameof(providerName));
return InstantiateProvider(ps);
}
Match match = _regex.Match((string)value);
- if (!match.Success) throw new ArgumentException(string.Format(SR.Regex_validator_error, _expression));
+ if (!match.Success) throw new ArgumentException(SR.Format(SR.Regex_validator_error, _expression));
}
}
-}
\ No newline at end of file
+}
_useOAEP = GetBooleanValue(configurationValues, "useOAEP", false);
_useFIPS = GetBooleanValue(configurationValues, "useFIPS", false);
if (configurationValues.Count > 0)
- throw new ConfigurationErrorsException(string.Format(SR.Unrecognized_initialization_value, configurationValues.GetKey(0)));
+ throw new ConfigurationErrorsException(SR.Format(SR.Unrecognized_initialization_value, configurationValues.GetKey(0)));
}
public RSAParameters RsaPublicKey { get { return GetCryptoServiceProvider(false, false).ExportParameters(false); } }
return true;
if (s == "false")
return false;
- throw new ConfigurationErrorsException(string.Format(SR.Config_invalid_boolean_attribute, valueName));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_invalid_boolean_attribute, valueName));
}
private SymmetricAlgorithm GetSymAlgorithmProvider()
catch (Exception e)
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_exception_in_config_section_handler,
+ SR.Format(SR.Config_exception_in_config_section_handler,
section.SectionInformation.SectionName), e);
}
}
if (ConfigurationElement.IsLockAttributeName(attribute.Name))
{
throw new ConfigurationErrorsException(
- string.Format(SR.Config_element_locking_not_supported, sectionName), attribute);
+ SR.Format(SR.Config_element_locking_not_supported, sectionName), attribute);
}
}
}
}
}
-}
\ No newline at end of file
+}
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.AllowDefinition != value))
- throw new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined, ConfigKey));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey));
_allowDefinition = value;
_modifiedFlags[FlagAllowDefinitionModified] = true;
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.AllowExeDefinition != value))
- throw new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined, ConfigKey));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey));
_allowExeDefinition = value;
_modifiedFlags[FlagAllowExeDefinitionModified] = true;
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.OverrideModeDefault.OverrideMode != value))
- throw new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined, ConfigKey));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey));
// Threat "Inherit" as "Allow" as "Inherit" does not make sense as a default
if (value == OverrideMode.Inherit) value = OverrideMode.Allow;
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.AllowLocation != value))
- throw new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined, ConfigKey));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey));
_flags[FlagAllowLocation] = value;
_modifiedFlags[FlagAllowLocation] = true;
_flags[FlagChildrenLocked] = true;
break;
default:
- Debug.Assert(false, "Unexpected value for OverrideMode");
+ Debug.Fail("Unexpected value for OverrideMode");
break;
}
}
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.RestartOnExternalChanges != value))
- throw new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined, ConfigKey));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey));
_flags[FlagRestartOnExternalChanges] = value;
_modifiedFlags[FlagRestartOnExternalChanges] = true;
// so long as it doesn't conflict with a type already defined
FactoryRecord factoryRecord = FindParentFactoryRecord(false);
if ((factoryRecord != null) && (factoryRecord.RequirePermission != value))
- throw new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined, ConfigKey));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined, ConfigKey));
_flags[FlagRequirePermission] = value;
_modifiedFlags[FlagRequirePermission] = true;
if (!factoryRecord.IsEquivalentType(host, value))
{
- throw new ConfigurationErrorsException(string.Format(SR.Config_tag_name_already_defined,
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_tag_name_already_defined,
ConfigKey));
}
}
private object GetPropertyValueByName(string propertyName)
{
if (Properties == null || _propertyValues == null || Properties.Count == 0)
- throw new SettingsPropertyNotFoundException(string.Format(SR.SettingsPropertyNotFound, propertyName));
+ throw new SettingsPropertyNotFoundException(SR.Format(SR.SettingsPropertyNotFound, propertyName));
SettingsProperty pp = Properties[propertyName];
if (pp == null)
- throw new SettingsPropertyNotFoundException(string.Format(SR.SettingsPropertyNotFound, propertyName));
+ throw new SettingsPropertyNotFoundException(SR.Format(SR.SettingsPropertyNotFound, propertyName));
SettingsPropertyValue p = _propertyValues[propertyName];
if (p == null)
{
GetPropertiesFromProvider(pp.Provider);
p = _propertyValues[propertyName];
if (p == null)
- throw new SettingsPropertyNotFoundException(string.Format(SR.SettingsPropertyNotFound, propertyName));
+ throw new SettingsPropertyNotFoundException(SR.Format(SR.SettingsPropertyNotFound, propertyName));
}
return p.PropertyValue;
}
private void SetPropertyValueByName(string propertyName, object propertyValue)
{
if (Properties == null || _propertyValues == null || Properties.Count == 0)
- throw new SettingsPropertyNotFoundException(string.Format(SR.SettingsPropertyNotFound, propertyName));
+ throw new SettingsPropertyNotFoundException(SR.Format(SR.SettingsPropertyNotFound, propertyName));
SettingsProperty pp = Properties[propertyName];
if (pp == null)
- throw new SettingsPropertyNotFoundException(string.Format(SR.SettingsPropertyNotFound, propertyName));
+ throw new SettingsPropertyNotFoundException(SR.Format(SR.SettingsPropertyNotFound, propertyName));
if (pp.IsReadOnly)
- throw new SettingsPropertyIsReadOnlyException(string.Format(SR.SettingsPropertyReadOnly, propertyName));
+ throw new SettingsPropertyIsReadOnlyException(SR.Format(SR.SettingsPropertyReadOnly, propertyName));
if (propertyValue != null && !pp.PropertyType.IsInstanceOfType(propertyValue))
- throw new SettingsPropertyWrongTypeException(string.Format(SR.SettingsPropertyWrongType, propertyName));
+ throw new SettingsPropertyWrongTypeException(SR.Format(SR.SettingsPropertyWrongType, propertyName));
SettingsPropertyValue p = _propertyValues[propertyName];
if (p == null)
GetPropertiesFromProvider(pp.Provider);
p = _propertyValues[propertyName];
if (p == null)
- throw new SettingsPropertyNotFoundException(string.Format(SR.SettingsPropertyNotFound, propertyName));
+ throw new SettingsPropertyNotFoundException(SR.Format(SR.SettingsPropertyNotFound, propertyName));
}
p.PropertyValue = propertyValue;
}
catch (Exception e)
{
- throw new ArgumentException(string.Format(SR.Could_not_create_from_default_value, Property.Name, e.Message));
+ throw new ArgumentException(SR.Format(SR.Could_not_create_from_default_value, Property.Name, e.Message));
}
}
if (value != null && !Property.PropertyType.IsAssignableFrom(value.GetType())) // is it the correct type
- throw new ArgumentException(string.Format(SR.Could_not_create_from_default_value_2, Property.Name));
+ throw new ArgumentException(SR.Format(SR.Could_not_create_from_default_value_2, Property.Name));
}
// Attempt 3: Create via the parameterless constructor
TypeConverter converter = TypeDescriptor.GetConverter(type);
if (converter != null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string)))
return converter.ConvertFromInvariantString(serializedValue);
- throw new ArgumentException(string.Format(SR.Unable_to_convert_type_from_string, type.ToString()), nameof(type));
+ throw new ArgumentException(SR.Format(SR.Unable_to_convert_type_from_string, type), nameof(type));
default:
return null;
}
TypeConverter converter = TypeDescriptor.GetConverter(type);
if (converter != null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string)))
return converter.ConvertToInvariantString(propertyValue);
- throw new ArgumentException(string.Format(SR.Unable_to_convert_type_to_string, type.ToString()), nameof(type));
+ throw new ArgumentException(SR.Format(SR.Unable_to_convert_type_to_string, type), nameof(type));
case SettingsSerializeAs.Xml:
XmlSerializer xs = new XmlSerializer(type);
StringWriter sw = new StringWriter(CultureInfo.InvariantCulture);
if (!(provider is SettingsProvider))
{
- throw new ArgumentException(string.Format(SR.Config_provider_must_implement_type, typeof(SettingsProvider).ToString()), nameof(provider));
+ throw new ArgumentException(SR.Format(SR.Config_provider_must_implement_type, typeof(SettingsProvider)), nameof(provider));
}
base.Add(provider);
private static void ThrowIfContainsDelimiter(string value)
{
if (value.Contains(",")) // string.Contains(char) is .NetCore2.1+ specific
- throw new ConfigurationErrorsException(string.Format(SR.Config_base_value_cannot_contain, ","));
+ throw new ConfigurationErrorsException(SR.Format(SR.Config_base_value_cannot_contain, ","));
}
public void SetReadOnly()
int len = data?.Length ?? 0;
if (len < _minLength)
- throw new ArgumentException(string.Format(SR.Validator_string_min_length, _minLength));
+ throw new ArgumentException(SR.Format(SR.Validator_string_min_length, _minLength));
if (len > _maxLength)
- throw new ArgumentException(string.Format(SR.Validator_string_max_length, _maxLength));
+ throw new ArgumentException(SR.Format(SR.Validator_string_max_length, _maxLength));
// Check if the string contains any invalid characters
if ((len > 0) && !string.IsNullOrEmpty(_invalidChars))
_invalidChars.CopyTo(0, array, 0, _invalidChars.Length);
if (data.IndexOfAny(array) != -1)
- throw new ArgumentException(string.Format(SR.Validator_string_invalid_chars, _invalidChars));
+ throw new ArgumentException(SR.Format(SR.Validator_string_invalid_chars, _invalidChars));
}
}
}
-}
\ No newline at end of file
+}
if (!_base.IsAssignableFrom((Type)value))
{
- throw new ArgumentException(string.Format(SR.Subclass_validator_error, ((Type)value).FullName,
+ throw new ArgumentException(SR.Format(SR.Subclass_validator_error, ((Type)value).FullName,
_base.FullName));
}
}
}
-}
\ No newline at end of file
+}
{
Type result = TypeUtil.GetType((string)data, false);
- if (result == null) throw new ArgumentException(string.Format(SR.Type_cannot_be_resolved, (string)data));
+ if (result == null) throw new ArgumentException(SR.Format(SR.Type_cannot_be_resolved, (string)data));
return result;
}
}
-}
\ No newline at end of file
+}
ConstructorInfo ctor = type.GetConstructor(BindingFlags, null, CallingConventions.HasThis, Type.EmptyTypes,
null);
if ((ctor == null) && throwOnError)
- throw new TypeLoadException(string.Format(SR.TypeNotPublic, type.AssemblyQualifiedName));
+ throw new TypeLoadException(SR.Format(SR.TypeNotPublic, type.AssemblyQualifiedName));
return ctor;
}
if (throwOnError)
{
throw new TypeLoadException(
- string.Format(SR.Config_type_doesnt_inherit_from_type, type.FullName, baseType.FullName));
+ SR.Format(SR.Config_type_doesnt_inherit_from_type, type.FullName, baseType.FullName));
}
return null;
: SR.Validation_scalar_range_violation_not_in_range;
}
- throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
+ throw new ArgumentException(SR.Format(CultureInfo.InvariantCulture,
error,
min.ToString(),
max.ToString()));
Debug.Assert(resolution > 0, "resolution > 0");
if (value % resolution != 0)
- throw new ArgumentException(string.Format(SR.Validator_scalar_resolution_violation, resolutionAsString));
+ throw new ArgumentException(SR.Format(SR.Validator_scalar_resolution_violation, resolutionAsString));
}
public static void ValidateScalar(TimeSpan value, TimeSpan min, TimeSpan max, long resolutionInSeconds,
}
}
}
-}
\ No newline at end of file
+}
internal void AddErrorUnrecognizedAttribute(ExceptionAction action)
{
ConfigurationErrorsException ex = new ConfigurationErrorsException(
- string.Format(SR.Config_base_unrecognized_attribute, Reader.Name),
+ SR.Format(SR.Config_base_unrecognized_attribute, Reader.Name),
this);
SchemaErrors.AddError(ex, action);
internal void AddErrorRequiredAttribute(string attrib, ExceptionAction action)
{
ConfigurationErrorsException ex = new ConfigurationErrorsException(
- string.Format(SR.Config_missing_required_attribute, attrib, Reader.Name),
+ SR.Format(SR.Config_missing_required_attribute, attrib, Reader.Name),
this);
SchemaErrors.AddError(ex, action);
internal void AddErrorReservedAttribute(ExceptionAction action)
{
ConfigurationErrorsException ex = new ConfigurationErrorsException(
- string.Format(SR.Config_reserved_attribute, Reader.Name),
+ SR.Format(SR.Config_reserved_attribute, Reader.Name),
this);
SchemaErrors.AddError(ex, action);
newValue = null;
ConfigurationException ex = new ConfigurationErrorsException(
- string.Format(SR.Empty_attribute, Reader.Name),
+ SR.Format(SR.Empty_attribute, Reader.Name),
this);
SchemaErrors.AddError(ex, action);
default:
newValue = defaultValue;
SchemaErrors.AddError(
- new ConfigurationErrorsException(string.Format(SR.Config_invalid_boolean_attribute, Reader.Name), this),
+ new ConfigurationErrorsException(SR.Format(SR.Config_invalid_boolean_attribute, Reader.Name), this),
action);
break;
}
default:
// This can never happen.
- Debug.Assert(false, "Unexpected handleType value (" + handleType + ")");
+ Debug.Fail("Unexpected handleType value (" + handleType + ")");
return true;
}
}
{
case AcceptRejectRule.None:
case AcceptRejectRule.Cascade:
- Debug.Assert(false, "valid AcceptRejectRule " + value.ToString());
+ Debug.Fail("valid AcceptRejectRule " + value.ToString());
break;
}
#endif
{
case CatalogLocation.Start:
case CatalogLocation.End:
- Debug.Assert(false, "valid CatalogLocation " + value.ToString());
+ Debug.Fail("valid CatalogLocation " + value.ToString());
break;
}
#endif
case ConflictOption.CompareAllSearchableValues:
case ConflictOption.CompareRowVersion:
case ConflictOption.OverwriteChanges:
- Debug.Assert(false, "valid ConflictOption " + value.ToString());
+ Debug.Fail("valid ConflictOption " + value.ToString());
break;
}
#endif
case DataRowState.Added:
case DataRowState.Deleted:
case DataRowState.Modified:
- Debug.Assert(false, "valid DataRowState " + value.ToString());
+ Debug.Fail("valid DataRowState " + value.ToString());
break;
}
#endif
{
case KeyRestrictionBehavior.PreventUsage:
case KeyRestrictionBehavior.AllowOnly:
- Debug.Assert(false, "valid KeyRestrictionBehavior " + value.ToString());
+ Debug.Fail("valid KeyRestrictionBehavior " + value.ToString());
break;
}
#endif
case LoadOption.OverwriteChanges:
case LoadOption.PreserveChanges:
case LoadOption.Upsert:
- Debug.Assert(false, "valid LoadOption " + value.ToString());
+ Debug.Fail("valid LoadOption " + value.ToString());
break;
}
#endif
case MissingMappingAction.Passthrough:
case MissingMappingAction.Ignore:
case MissingMappingAction.Error:
- Debug.Assert(false, "valid MissingMappingAction " + value.ToString());
+ Debug.Fail("valid MissingMappingAction " + value.ToString());
break;
}
#endif
case MissingSchemaAction.Ignore:
case MissingSchemaAction.Error:
case MissingSchemaAction.AddWithKey:
- Debug.Assert(false, "valid MissingSchemaAction " + value.ToString());
+ Debug.Fail("valid MissingSchemaAction " + value.ToString());
break;
}
#endif
case Rule.Cascade:
case Rule.SetNull:
case Rule.SetDefault:
- Debug.Assert(false, "valid Rule " + value.ToString());
+ Debug.Fail("valid Rule " + value.ToString());
break;
}
#endif
{
case SchemaType.Source:
case SchemaType.Mapped:
- Debug.Assert(false, "valid SchemaType " + value.ToString());
+ Debug.Fail("valid SchemaType " + value.ToString());
break;
}
#endif
case StatementType.Update:
case StatementType.Delete:
case StatementType.Batch:
- Debug.Assert(false, "valid StatementType " + value.ToString());
+ Debug.Fail("valid StatementType " + value.ToString());
break;
}
#endif
case UpdateStatus.ErrorsOccurred:
case UpdateStatus.SkipAllRemainingRows:
case UpdateStatus.SkipCurrentRow:
- Debug.Assert(false, "valid UpdateStatus " + value.ToString());
+ Debug.Fail("valid UpdateStatus " + value.ToString());
break;
}
#endif
//
internal static Exception WrongType(Type got, Type expected)
{
- return Argument(SR.Format(SR.SQL_WrongType, got.ToString(), expected.ToString()));
+ return Argument(SR.Format(SR.SQL_WrongType, got, expected));
}
//
goto default;
#if DEBUG
case StatementType.Select:
- Debug.Assert(false, "shouldn't be here");
+ Debug.Fail("shouldn't be here");
goto default;
#endif
default:
break;
#if DEBUG
case StatementType.Select:
- Debug.Assert(false, "shouldn't be here");
+ Debug.Fail("shouldn't be here");
goto default;
case StatementType.Batch:
- Debug.Assert(false, "isRowUpdatingCommand should have been true");
+ Debug.Fail("isRowUpdatingCommand should have been true");
goto default;
#endif
default:
#if DEBUG
case StatementType.Select:
case StatementType.Insert:
- Debug.Assert(false, "should be here");
+ Debug.Fail("should be here");
goto default;
#endif
default:
break;
#if DEBUG
case StatementType.Batch:
- Debug.Assert(false, "isRowUpdatingCommand should have been true");
+ Debug.Fail("isRowUpdatingCommand should have been true");
goto default;
#endif
default:
internal static int SrcCompare(string strA, string strB) => strA == strB ? 0 : 1;
}
-}
\ No newline at end of file
+}
// found duplicate name
// the name unchanged name wins
int iMutatedName = _isMutatedName[j] ? j : i;
- Debug.Assert(_isMutatedName[iMutatedName], string.Format(CultureInfo.InvariantCulture, "{0} expected to be a mutated name", _baseParameterNames[iMutatedName]));
+ Debug.Assert(_isMutatedName[iMutatedName], $"{_baseParameterNames[iMutatedName]} expected to be a mutated name");
_baseParameterNames[iMutatedName] = null; // null out the culprit
}
}
}
else
{
- Debug.Assert(false, "Rowcount expected to be 1");
+ Debug.Fail("Rowcount expected to be 1");
useColumnsForParameterNames = false;
}
}
switch (stmtType)
{
case StatementType.Select:
- Debug.Assert(false, "how did we get here?");
+ Debug.Fail("how did we get here?");
return; // don't mess with it
case StatementType.Insert:
command = InsertCommand;
break;
#if DEBUG
case StatementType.Select:
- Debug.Assert(false, "how did we get here?");
+ Debug.Fail("how did we get here?");
goto default;
#endif
default:
public virtual int GetStringLength(int record)
{
- Debug.Assert(false, "not a String or SqlString column");
+ Debug.Fail("not a String or SqlString column");
return int.MaxValue;
}
case StorageType.SqlString: return new SqlStringStorage(column);
default:
- Debug.Assert(false, "shouldn't be here");
+ Debug.Fail("shouldn't be here");
goto case StorageType.Object;
}
}
dataCommand = _IDbDataAdapter.UpdateCommand;
break;
default:
- Debug.Assert(false, "InvalidDataRowState");
+ Debug.Fail("InvalidDataRowState");
throw ADP.InvalidDataRowState(dataRow.RowState); // out of Update without completing batch
}
else
{
// StatementType.Select, StatementType.Batch
- Debug.Assert(false, "unexpected StatementType");
+ Debug.Fail("unexpected StatementType");
}
// map the parameter results to the dataSet
//
// Storage
//
- public static Exception AggregateException(AggregateType aggregateType, Type type) => _Data(SR.Format(SR.DataStorage_AggregateException, aggregateType.ToString(), type.Name));
+ public static Exception AggregateException(AggregateType aggregateType, Type type) => _Data(SR.Format(SR.DataStorage_AggregateException, aggregateType, type.Name));
public static Exception InvalidStorageType(TypeCode typecode) => _Data(SR.Format(SR.DataStorage_InvalidStorageType, typecode.ToString()));
public static Exception RangeArgument(int min, int max) => _Argument(SR.Format(SR.Range_Argument, (min).ToString(CultureInfo.InvariantCulture), (max).ToString(CultureInfo.InvariantCulture)));
public static Exception NullRange() => _Data(SR.Range_NullRange);
public override int GetHashCode()
{
- Debug.Assert(false, "don't put DataKey into a Hashtable");
+ Debug.Fail("don't put DataKey into a Hashtable");
return base.GetHashCode();
}
public override bool Equals(object value)
{
- Debug.Assert(false, "need to directly call Equals(DataKey)");
+ Debug.Fail("need to directly call Equals(DataKey)");
return Equals((DataKey)value);
}
}
break;
case DataRowState.Deleted:
- Debug.Assert(false, "LoadOption.Upsert with deleted row, should not be here");
+ Debug.Fail("LoadOption.Upsert with deleted row, should not be here");
break;
default:
action = DataRowAction.Change;
}
else
{
- Debug.Assert(false, "ItemAdded DataRow already in view");
+ Debug.Fail("ItemAdded DataRow already in view");
}
break;
case ListChangedType.ItemDeleted:
}
else
{
- Debug.Assert(false, "ItemDeleted DataRow not in view tracking");
+ Debug.Fail("ItemDeleted DataRow not in view tracking");
}
}
if (!_rowViewCache.Remove(row))
{
- Debug.Assert(false, "ItemDeleted DataRow not in view");
+ Debug.Fail("ItemDeleted DataRow not in view");
}
break;
case ListChangedType.Reset:
case ListChangedType.PropertyDescriptorAdded:
case ListChangedType.PropertyDescriptorChanged:
case ListChangedType.PropertyDescriptorDeleted:
- Debug.Assert(false, "unexpected");
+ Debug.Fail("unexpected");
break;
}
}
case DataTypePrecedence.SqlBinary: return StorageType.SqlBinary;
case DataTypePrecedence.SqlMoney: return StorageType.SqlMoney;
default:
- Debug.Assert(false, "Invalid (unmapped) precedence " + code.ToString());
+ Debug.Fail("Invalid (unmapped) precedence " + code.ToString());
goto case DataTypePrecedence.Error;
}
}
string s2 = substring.TrimEnd(trimChars);
return table.IsSuffix(s1, s2);
default:
- Debug.Assert(false, "Unexpected LIKE kind");
+ Debug.Fail("Unexpected LIKE kind");
return DBNull.Value;
}
}
break;
default:
- Debug.Assert(false, "NYI");
+ Debug.Fail("NYI");
goto case ValueType.Object;
}
}
node = new ConstNode(_table, ValueType.Date, str);
break;
default:
- Debug.Assert(false, "unhandled token");
+ Debug.Fail("unhandled token");
break;
}
break;
default:
- Debug.Assert(false, "Unhandled operator type");
+ Debug.Fail("Unhandled operator type");
goto end_loop;
}
Debug.Assert(expr != null, "Failed to create expression");
public static Exception ArgumentType(string function, int arg, Type type)
{
- return _Eval(SR.Format(SR.Expr_ArgumentType, function, arg.ToString(CultureInfo.InvariantCulture), type.ToString()));
+ return _Eval(SR.Format(SR.Expr_ArgumentType, function, arg.ToString(CultureInfo.InvariantCulture), type));
}
public static Exception ArgumentTypeInteger(string function, int arg)
public static Exception TypeMismatchInBinop(int op, Type type1, Type type2)
{
- return _Eval(SR.Format(SR.Expr_TypeMismatchInBinop, Operators.ToString(op), type1.ToString(), type2.ToString()));
+ return _Eval(SR.Format(SR.Expr_TypeMismatchInBinop, Operators.ToString(op), type1, type2));
}
public static Exception AmbiguousBinop(int op, Type type1, Type type2)
{
- return _Eval(SR.Format(SR.Expr_AmbiguousBinop, Operators.ToString(op), type1.ToString(), type2.ToString()));
+ return _Eval(SR.Format(SR.Expr_AmbiguousBinop, Operators.ToString(op), type1, type2));
}
public static Exception UnsupportedOperator(int op)
value = -(SqlInt16)vl;
break;
default:
- Debug.Assert(false, "Missing a type conversion");
+ Debug.Fail("Missing a type conversion");
value = DBNull.Value;
break;
}
}
default:
{
- Debug.Assert(false, "Unknown Rule value");
+ Debug.Fail("Unknown Rule value");
break;
}
}
}
default:
{
- Debug.Assert(false, "Unknown Rule value");
+ Debug.Fail("Unknown Rule value");
break;
}
}
}
else
{
- Debug.Assert(false, "attempt to cascade unknown action: " + action.ToString());
+ Debug.Fail("attempt to cascade unknown action: " + action.ToString());
}
}
finally
dataRow = _dataTable.LoadDataRow(mapped, false);
break;
default:
- Debug.Assert(false, "unexpected LoadOption");
+ Debug.Fail("unexpected LoadOption");
throw ADP.InvalidLoadOption(_loadOption);
}
if ((null != _chapterMap) && (null != _dataSet))
byte bActualPrecision = BActualPrec();
_bPrec = bPrec; // restore current value
- Debug.Assert(precision == bActualPrecision, string.Format(null, "CalculatePrecision={0}, BActualPrec={1}. Results must be equal!", precision, bActualPrecision));
+ Debug.Assert(precision == bActualPrecision, $"CalculatePrecision={precision}, BActualPrec={bActualPrecision}. Results must be equal!");
#endif
return precision;
}
break;
default:
- Debug.Assert(false, "Invalid ecExpectedResult");
+ Debug.Fail("Invalid ecExpectedResult");
return SqlBoolean.Null;
}
{
if (CurrentNode != _rowElement)
{
- Debug.Assert(false);
+ Debug.Fail("Reading the initial text value for sub-regions.");
}
}
#endif
parent2 = curNode2.ParentNode;
}
- //logically, we shouldn't reach here
- Debug.Assert(false);
+ Debug.Fail("Logically, we shouldn't reach here.");
return XmlNodeOrder.Unknown;
}
#if DEBUG
object val = _pointers[pointer];
if (val != (object)pointer)
- Debug.Assert(false);
+ Debug.Fail("Pointer not present");
#endif
}
// This function attaches the DataSet to XmlDataDocument
return true;
case XmlNodeType.EntityReference:
- Debug.Assert(false);
+ Debug.Fail("Found entity reference");
return false;
default:
// Nothing to do (the row already has an associated element as a fragment
break;
case DataRowState.Detached:
- // We should not get rows in this state
- Debug.Assert(false);
+ Debug.Fail("We should not get rows in this state");
break;
default:
- // Unknown row state
- Debug.Assert(false);
+ Debug.Fail("Unknown row state");
break;
}
}
break;
case DataRowAction.Delete:
- // DataRow is beeing deleted
+ // DataRow is being deleted
// - state transition from New (AKA PendingInsert) to Detached (AKA Created)
// - state transition from Unchanged to Deleted (AKA PendingDelete)
// - state transition from Modified (AKA PendingChange) to Delete (AKA PendingDelete)
- Debug.Assert(false); // This should have been handled above, irrespective of ignoreDataSetEvents value (true or false)
+ Debug.Fail("This should have been handled above, irrespective of ignoreDataSetEvents value (true or false)");
break;
case DataRowAction.Rollback:
}
catch
{
- // We should not get any exceptions because we always handle data-type conversion
- Debug.Assert(false);
+ Debug.Fail("We should not get any exceptions because we always handle data-type conversion");
throw;
}
#endif
}
catch
{
- // We should not get any exceptions because DataSet.EnforceConstraints should be always off
- Debug.Assert(false);
+ Debug.Fail("We should not get any exceptions because DataSet.EnforceConstraints should be always off");
throw;
}
#endif
}
catch
{
- // We should not get any exceptions here
- Debug.Assert(false);
+ Debug.Fail("We should not get any exceptions here");
throw;
}
#endif
}
catch
{
- // We should not get any exceptions here
- Debug.Assert(false);
+ Debug.Fail("We should not get any exceptions here");
throw;
}
#endif
break;
default:
- // Handle your case above
- Debug.Assert(false);
+ Debug.Fail("Handle your case above");
break;
}
Debug.Assert(IsRowLive(rowElem.Row));
}
catch
{
- // We should not get any exceptions here
- Debug.Assert(false);
+ Debug.Fail("We should not get any exceptions here");
throw;
}
#endif
break;
default:
- // Handle your case above
- Debug.Assert(false);
+ Debug.Fail("Handle your case above");
break;
}
{
if (DBNull.Value == value)
{
- throw DataSetUtil.InvalidCast(string.Format(SR.DataSetLinq_NonNullableCast, typeof(T).ToString()));
+ throw DataSetUtil.InvalidCast(SR.Format(SR.DataSetLinq_NonNullableCast, typeof(T)));
}
return (T)value;
}
static internal ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value)
{
- return ArgumentOutOfRange(string.Format(SR.DataSetLinq_InvalidEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name);
+ return ArgumentOutOfRange(SR.Format(SR.DataSetLinq_InvalidEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name);
}
static internal ArgumentOutOfRangeException InvalidDataRowState(DataRowState value)
case DataRowState.Added:
case DataRowState.Deleted:
case DataRowState.Modified:
- Debug.Assert(false, "valid DataRowState " + value.ToString());
+ Debug.Fail("valid DataRowState " + value.ToString());
break;
}
#endif
case LoadOption.OverwriteChanges:
case LoadOption.PreserveChanges:
case LoadOption.Upsert:
- Debug.Assert(false, "valid LoadOption " + value.ToString());
+ Debug.Fail("valid LoadOption " + value.ToString());
break;
}
#endif
(type != s_accessViolationType) &&
!s_securityType.IsAssignableFrom(type));
}
-}
\ No newline at end of file
+}
case CommandType.Text:
case CommandType.StoredProcedure:
case CommandType.TableDirect:
- Debug.Assert(false, "valid CommandType " + value.ToString());
+ Debug.Fail("valid CommandType " + value.ToString());
break;
}
#endif
case DataRowVersion.Current:
case DataRowVersion.Original:
case DataRowVersion.Proposed:
- Debug.Assert(false, "valid DataRowVersion " + value.ToString());
+ Debug.Fail("valid DataRowVersion " + value.ToString());
break;
}
#endif
case IsolationLevel.RepeatableRead:
case IsolationLevel.Serializable:
case IsolationLevel.Snapshot:
- Debug.Assert(false, "valid IsolationLevel " + value.ToString());
+ Debug.Fail("valid IsolationLevel " + value.ToString());
break;
}
#endif
{
case KeyRestrictionBehavior.PreventUsage:
case KeyRestrictionBehavior.AllowOnly:
- Debug.Assert(false, "valid KeyRestrictionBehavior " + value.ToString());
+ Debug.Fail("valid KeyRestrictionBehavior " + value.ToString());
break;
}
#endif
case ParameterDirection.Output:
case ParameterDirection.InputOutput:
case ParameterDirection.ReturnValue:
- Debug.Assert(false, "valid ParameterDirection " + value.ToString());
+ Debug.Fail("valid ParameterDirection " + value.ToString());
break;
}
#endif
case UpdateRowSource.OutputParameters:
case UpdateRowSource.FirstReturnedRecord:
case UpdateRowSource.Both:
- Debug.Assert(false, "valid UpdateRowSource " + value.ToString());
+ Debug.Fail("valid UpdateRowSource " + value.ToString());
break;
}
#endif
#if DEBUG
else
{
- Debug.Assert(false, "empty restriction");
+ Debug.Fail("empty restriction");
}
#endif
}
}
else
{
- Debug.Assert(false, string.Format("Unknown behavior for combined set: {0}", combinedSet._behavior));
+ Debug.Fail($"Unknown behavior for combined set: {combinedSet._behavior}");
}
}
else if (componentSet._behavior == KeyRestrictionBehavior.PreventUsage)
}
else
{
- Debug.Assert(false, string.Format("Unknown behavior for combined set: {0}", combinedSet._behavior));
+ Debug.Fail($"Unknown behavior for combined set: {combinedSet._behavior}");
}
}
else
{
- Debug.Assert(false, string.Format("Unknown behavior for component set: {0}", componentSet._behavior));
+ Debug.Fail($"Unknown behavior for component set: {componentSet._behavior}");
}
}
}
}
break;
default:
- Debug.Assert(false, "invalid KeyRestrictionBehavior");
+ Debug.Fail("invalid KeyRestrictionBehavior");
throw ADP.InvalidKeyRestrictionBehavior(_behavior);
}
return true;
}
}
}
-}
\ No newline at end of file
+}
{
case CommandType.Text:
case CommandType.StoredProcedure:
- Debug.Assert(false, "valid CommandType " + value.ToString());
+ Debug.Fail("valid CommandType " + value.ToString());
break;
case CommandType.TableDirect:
break;
default:
- Debug.Assert(false, "invalid CommandType " + value.ToString());
+ Debug.Fail("invalid CommandType " + value.ToString());
break;
}
#endif
case IsolationLevel.RepeatableRead:
case IsolationLevel.Serializable:
case IsolationLevel.Snapshot:
- Debug.Assert(false, "valid IsolationLevel " + value.ToString());
+ Debug.Fail("valid IsolationLevel " + value.ToString());
break;
case IsolationLevel.Chaos:
break;
default:
- Debug.Assert(false, "invalid IsolationLevel " + value.ToString());
+ Debug.Fail("invalid IsolationLevel " + value.ToString());
break;
}
#endif
case RetCode.INVALID_HANDLE: return "INVALID_HANDLE";
case RetCode.NO_DATA: return "NO_DATA";
default:
- Debug.Assert(false, "Unknown enumerator passed to RetcodeToString method");
+ Debug.Fail("Unknown enumerator passed to RetcodeToString method");
goto case RetCode.ERROR;
}
}
default:
// this should NEVER happen
- Debug.Assert(false, "ExecuteReaderObjectcalled with unsupported ODBC API method.");
+ Debug.Fail("ExecuteReaderObjectcalled with unsupported ODBC API method.");
throw ADP.InvalidOperation(method.ToString());
}
parameter.Direction = ParameterDirection.ReturnValue;
break;
default:
- Debug.Assert(false, "Unexpected Parametertype while DeriveParamters");
+ Debug.Fail("Unexpected Parametertype while DeriveParamters");
break;
}
parameter.OdbcType = TypeMap.FromSqlType((ODBC32.SQL_TYPE)reader.GetInt16(ODBC32.DATA_TYPE - 1))._odbcType;
ProviderInfo.NoConnectionDead = true;
break;
default:
- Debug.Assert(false, "Can't flag unknown Attribute");
+ Debug.Fail("Can't flag unknown Attribute");
break;
}
}
ProviderInfo.NoSqlSoptSSHiddenColumns = true;
break;
default:
- Debug.Assert(false, "Can't flag unknown Attribute");
+ Debug.Fail("Can't flag unknown Attribute");
break;
}
}
break;
// SSS_WARNINGS_ON
default:
- Debug.Assert(false, "Can't flag unknown Attribute");
+ Debug.Fail("Can't flag unknown Attribute");
break;
}
}
switch (v2FieldId)
{
default:
- Debug.Assert(false, "Can't flag unknown Attribute");
+ Debug.Fail("Can't flag unknown Attribute");
break;
}
}
}
else
{
- Debug.Assert(false, "GetFunctions called and ConnectionHandle is null (connection is disposed?)");
+ Debug.Fail("GetFunctions called and ConnectionHandle is null (connection is disposed?)");
throw ODBC.ConnectionClosed();
}
break;
}
default:
- Debug.Assert(false, "Testing that sqltype is currently not supported");
+ Debug.Fail("Testing that sqltype is currently not supported");
return false;
}
// now we can check if we have already tested that type
break;
}
default:
- Debug.Assert(false, "Testing that sqltype is currently not supported");
+ Debug.Fail("Testing that sqltype is currently not supported");
return false;
}
return (0 != (ProviderInfo.RestrictedSQLBindTypes & (int)sqlcvt));
}
else
{
- Debug.Assert(false, "unexpected state switch");
+ Debug.Fail("unexpected state switch");
if (originalState != currentState)
{
OnStateChange(new StateChangeEventArgs(originalState, currentState));
case Keywords.Dsn: Dsn = ConvertToString(value); break;
// case Keywords.NamedConnection: NamedConnection = ConvertToString(value); break;
default:
- Debug.Assert(false, "unexpected keyword");
+ Debug.Fail("unexpected keyword");
throw ADP.KeywordNotSupported(keyword);
}
}
case Keywords.Dsn: return Dsn;
// case Keywords.NamedConnection: return NamedConnection;
default:
- Debug.Assert(false, "unexpected keyword");
+ Debug.Fail("unexpected keyword");
throw ADP.KeywordNotSupported(s_validKeywords[(int)index]);
}
}
// _namedConnection = DbConnectionStringDefaults.NamedConnection;
// break;
default:
- Debug.Assert(false, "unexpected keyword");
+ Debug.Fail("unexpected keyword");
throw ADP.KeywordNotSupported(s_validKeywords[(int)index]);
}
}
CNativeBuffer value = _cmdWrapper._dataReaderBuf;
if (null == value)
{
- Debug.Assert(false, "object is disposed");
+ Debug.Fail("object is disposed");
throw new ObjectDisposedException(GetType().Name);
}
return value;
// APP_PARAM_DESC is a (ODBCVER >= 0x0300) attribute
if (!Connection.IsV3Driver)
{
- Debug.Assert(false, "Non-V3 driver. Must not call GetDescFieldStr");
+ Debug.Fail("Non-V3 driver. Must not call GetDescFieldStr");
return null;
}
break;
// case ODBC32.SQL_HANDLE.DESC:
default:
- Debug.Assert(false, "unexpected handleType");
+ Debug.Fail("unexpected handleType");
break;
}
}
}
}
#if DEBUG
- else { Debug.Assert(false, "not expecting this"); }
+ else { Debug.Fail("not expecting this"); }
#endif
// Note: ColumnSize should never be 0,
// this represents the size of the column on the backend.
}
}
}
- Debug.Assert((0 <= cch) && (cch < 0x3fffffff), string.Format((IFormatProvider)null, "GetColumnSize: cch = {0} out of range, _internalShouldSerializeSize = {1}, _internalSize = {2}", cch, _internalShouldSerializeSize, _internalSize));
+ Debug.Assert((0 <= cch) && (cch < 0x3fffffff), $"GetColumnSize: cch = {cch} out of range, _internalShouldSerializeSize = {_internalShouldSerializeSize}, _internalSize = {_internalSize}");
return cch;
}
cch *= 2;
}
}
- Debug.Assert((0 <= cch) && (cch < 0x3fffffff), string.Format((IFormatProvider)null, "GetValueSize: cch = {0} out of range, _internalShouldSerializeSize = {1}, _internalSize = {2}", cch, _internalShouldSerializeSize, _internalSize));
+ Debug.Assert((0 <= cch) && (cch < 0x3fffffff), $"GetValueSize: cch = {cch} out of range, _internalShouldSerializeSize = {_internalShouldSerializeSize}, _internalSize = {_internalSize}");
return cch;
}
ccb = ((byte[])value).Length - offset;
}
#if DEBUG
- else { Debug.Assert(false, "not expecting this"); }
+ else { Debug.Fail("not expecting this"); }
#endif
if ((0 != (ParameterDirection.Output & _internalDirection)) && (0x3fffffff <= _internalSize))
{
case ParameterDirection.InputOutput:
return ODBC32.SQL_PARAM.INPUT_OUTPUT;
default:
- Debug.Assert(false, "Unexpected Direction Property on Parameter");
+ Debug.Fail("Unexpected Direction Property on Parameter");
return ODBC32.SQL_PARAM.INPUT;
}
}
}
else
{
- Debug.Assert(false, "shouldn't be here");
+ Debug.Fail("shouldn't be here");
}
break;
case Closing:
}
else
{
- Debug.Assert(false, "shouldn't be here");
+ Debug.Fail("shouldn't be here");
}
break;
default:
- Debug.Assert(false, "shouldn't be here");
+ Debug.Fail("shouldn't be here");
break;
}
}
break;
default:
- Debug.Assert(false, "UnknownSQLCType");
+ Debug.Fail("UnknownSQLCType");
value = null;
break;
};
}
default:
- Debug.Assert(false, "UnknownSQLCType");
+ Debug.Fail("UnknownSQLCType");
break;
}
}
// For SqlParameter, both userDefinedType and udtAssemblyQualifiedName can be NULL,
// so we are checking only maxLength if it will be used (i.e. userDefinedType is NULL)
Debug.Assert((null != userDefinedType) || (0 <= maxLength || UnlimitedMaxLengthIndicator == maxLength),
- string.Format(null, "SmiMetaData.ctor: Udt name={0}, maxLength={1}", udtAssemblyQualifiedName, maxLength));
+ $"SmiMetaData.ctor: Udt name={udtAssemblyQualifiedName}, maxLength={maxLength}");
// Type not validated until matched to a server. Could be null if extended metadata supplies three-part name!
_clrType = userDefinedType;
if (null != userDefinedType)
_maxLength = 10 - s_maxVarTimeLenOffsetFromScale[scale];
break;
default:
- Debug.Assert(false, "How in the world did we get here? :" + dbType);
+ Debug.Fail("How in the world did we get here? :" + dbType);
break;
}
internal SqlBoolean IsHidden => _isHidden;
}
-}
\ No newline at end of file
+}
case ExtendedClrTypeCode.TextReader: SetTextReader_Unchecked(sink, setters, ordinal, metaData, (TextDataFeed)value); break;
case ExtendedClrTypeCode.XmlReader: SetXmlReader_Unchecked(sink, setters, ordinal, ((XmlDataFeed)value)._source); break;
default:
- Debug.Assert(false, "Unvalidated extendedtypecode: " + typeCode);
+ Debug.Fail("Unvalidated extendedtypecode: " + typeCode);
break;
}
}
// invalid instance of SqlDbType, or one would have to add
// new member to SqlDbType without adding a case in this
// switch, hence the assert.
- Debug.Assert(false, "unsupported DbType:" + metaData[i].SqlDbType.ToString());
+ Debug.Fail("unsupported DbType:" + metaData[i].SqlDbType.ToString());
throw ADP.NotSupported();
}
}
// invalid instance of SqlDbType, or one would have to add
// new member to SqlDbType without adding a case in this
// switch, hence the assert.
- Debug.Assert(false, "unsupported DbType:" + metaData[i].SqlDbType.ToString());
+ Debug.Fail("unsupported DbType:" + metaData[i].SqlDbType.ToString());
throw ADP.NotSupported();
}
}
break;
default:
- Debug.Assert(false, "unsupported DbType:" + metaData[i].SqlDbType.ToString());
+ Debug.Fail("unsupported DbType:" + metaData[i].SqlDbType.ToString());
throw ADP.NotSupported();
}
}
internal static int GetBytes_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length)
{
Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
- Debug.Assert(ordinal >= 0, string.Format("Invalid ordinal: {0}", ordinal));
+ Debug.Assert(ordinal >= 0, $"Invalid ordinal: {ordinal}");
Debug.Assert(sink != null, "Null SmiEventSink");
Debug.Assert(getters != null, "Null getters");
- Debug.Assert(fieldOffset >= 0, string.Format("Invalid field offset: {0}", fieldOffset));
+ Debug.Assert(fieldOffset >= 0, $"Invalid field offset: {fieldOffset}");
Debug.Assert(buffer != null, "Null buffer");
- Debug.Assert(bufferOffset >= 0 && length >= 0 && bufferOffset + length <= buffer.Length, string.Format("Bad offset or length. bufferOffset: {0}, length: {1}, buffer.Length{2}", bufferOffset, length, buffer.Length));
+ Debug.Assert(bufferOffset >= 0 && length >= 0 && bufferOffset + length <= buffer.Length, $"Bad offset or length. bufferOffset: {bufferOffset}, length: {length}, buffer.Length{buffer.Length}");
int result = getters.GetBytes(sink, ordinal, fieldOffset, buffer, bufferOffset, length);
sink.ProcessMessagesAndThrow();
internal static int GetChars_Unchecked(SmiEventSink_Default sink, ITypedGettersV3 getters, int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length)
{
Debug.Assert(!IsDBNull_Unchecked(sink, getters, ordinal));
- Debug.Assert(ordinal >= 0, string.Format("Invalid ordinal: {0}", ordinal));
+ Debug.Assert(ordinal >= 0, $"Invalid ordinal: {ordinal}");
Debug.Assert(sink != null, "Null SmiEventSink");
Debug.Assert(getters != null, "Null getters");
- Debug.Assert(fieldOffset >= 0, string.Format("Invalid field offset: {0}", fieldOffset));
+ Debug.Assert(fieldOffset >= 0, $"Invalid field offset: {fieldOffset}");
Debug.Assert(buffer != null, "Null buffer");
- Debug.Assert(bufferOffset >= 0 && length >= 0 && bufferOffset + length <= buffer.Length, string.Format("Bad offset or length. bufferOffset: {0}, length: {1}, buffer.Length{2}", bufferOffset, length, buffer.Length));
+ Debug.Assert(bufferOffset >= 0 && length >= 0 && bufferOffset + length <= buffer.Length, $"Bad offset or length. bufferOffset: {bufferOffset}, length: {length}, buffer.Length{buffer.Length}");
int result = getters.GetChars(sink, ordinal, fieldOffset, buffer, bufferOffset, length);
sink.ProcessMessagesAndThrow();
case CommandType.Text:
case CommandType.StoredProcedure:
case CommandType.TableDirect:
- Debug.Assert(false, "valid CommandType " + value.ToString());
+ Debug.Fail("valid CommandType " + value.ToString());
break;
}
#endif
case ParameterDirection.Output:
case ParameterDirection.InputOutput:
case ParameterDirection.ReturnValue:
- Debug.Assert(false, "valid ParameterDirection " + value.ToString());
+ Debug.Fail("valid ParameterDirection " + value.ToString());
break;
}
#endif
case UpdateRowSource.OutputParameters:
case UpdateRowSource.FirstReturnedRecord:
case UpdateRowSource.Both:
- Debug.Assert(false, "valid UpdateRowSource " + value.ToString());
+ Debug.Fail("valid UpdateRowSource " + value.ToString());
break;
}
#endif
if (sniError != 0)
{
string sniErrorMessage = SQL.GetSNIErrorMessage(sniError);
- errorMessage = string.Format((IFormatProvider)null, "{0} (error: {1} - {2})",
+ errorMessage = string.Format("{0} (error: {1} - {2})",
errorMessage, sniError, sniErrorMessage);
}
string CatalogName = parts[MultipartIdentifier.CatalogIndex];
if (isTempTable && string.IsNullOrEmpty(CatalogName))
{
- TDSCommand += string.Format((IFormatProvider)null, "exec tempdb..{0} N'{1}.{2}'",
+ TDSCommand += string.Format("exec tempdb..{0} N'{1}.{2}'",
TableCollationsStoredProc,
SchemaName,
TableName
{
CatalogName = SqlServerEscapeHelper.EscapeIdentifier(CatalogName);
}
- TDSCommand += string.Format((IFormatProvider)null, "exec {0}..{1} N'{2}.{3}'",
+ TDSCommand += string.Format("exec {0}..{1} N'{2}.{3}'",
CatalogName,
TableCollationsStoredProc,
SchemaName,
Debug.Assert(_SqlDataReaderRowSource != null, "Should not be reading row as an XmlReader if bulk copy source is not a SqlDataReader");
return new XmlDataFeed(_SqlDataReaderRowSource.GetXmlReader(sourceOrdinal));
default:
- Debug.Fail(string.Format("Current column is marked as being a DataFeed, but no DataFeed compatible method was provided. Method: {0}", _currentRowMetadata[destRowIndex].Method));
+ Debug.Fail($"Current column is marked as being a DataFeed, but no DataFeed compatible method was provided. Method: {_currentRowMetadata[destRowIndex].Method}");
isDataFeed = false;
object columnValue = _DbDataReaderRowSource.GetValue(sourceOrdinal);
ADP.IsNullOrSqlType(columnValue, out isNull, out isSqlType);
value = new SqlDecimal(_SqlDataReaderRowSource.GetSqlSingle(sourceOrdinal).Value);
break;
default:
- Debug.Fail(string.Format("Current column is marked as being a SqlType, but no SqlType compatible method was provided. Method: {0}", _currentRowMetadata[destRowIndex].Method));
+ Debug.Fail($"Current column is marked as being a SqlType, but no SqlType compatible method was provided. Method: {_currentRowMetadata[destRowIndex].Method}");
value = (INullable)_SqlDataReaderRowSource.GetSqlValue(sourceOrdinal);
break;
}
}
default:
{
- Debug.Fail(string.Format("Current column is marked as being a SqlType, but no SqlType compatible method was provided. Method: {0}", _currentRowMetadata[destRowIndex].Method));
+ Debug.Fail($"Current column is marked as being a SqlType, but no SqlType compatible method was provided. Method: {_currentRowMetadata[destRowIndex].Method}");
break;
}
}
break;
default:
t = null;
- Debug.Fail(string.Format("Unknown value source: {0}", _rowSourceType));
+ Debug.Fail($"Unknown value source: {_rowSourceType}");
break;
}
}
else
{
- Debug.Assert(false, "OnReturnStatus: SqlCommand got too many DONEPROC events");
+ Debug.Fail("OnReturnStatus: SqlCommand got too many DONEPROC events");
parameters = null;
}
}
}
else
{
- Debug.Assert(false, "OnReturnValue: SqlCommand got too many DONEPROC events");
+ Debug.Fail("OnReturnValue: SqlCommand got too many DONEPROC events");
return null;
}
}
// InputOutput/Output parameters are aways sent
return true;
default:
- Debug.Assert(false, "Invalid ParameterDirection!");
+ Debug.Fail("Invalid ParameterDirection!");
return false;
}
}
_recoverySessionData = null;
_suppressStateChangeForReconnection = false;
}
- Debug.Assert(false, "Should not reach this point");
+ Debug.Fail("Should not reach this point");
}
internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout)
}
else
{
- Debug.Assert(false, "unexpected state switch");
+ Debug.Fail("unexpected state switch");
if (originalState != currentState)
{
OnStateChange(new StateChangeEventArgs(originalState, currentState));
case Keywords.ConnectRetryInterval: ConnectRetryInterval = ConvertToInt32(value); break;
default:
- Debug.Assert(false, "unexpected keyword");
+ Debug.Fail("unexpected keyword");
throw UnsupportedKeyword(keyword);
}
}
case Keywords.ConnectRetryInterval: return ConnectRetryInterval;
default:
- Debug.Assert(false, "unexpected keyword");
+ Debug.Fail("unexpected keyword");
throw UnsupportedKeyword(s_validKeywords[(int)index]);
}
}
_workstationID = DbConnectionStringDefaults.WorkstationID;
break;
default:
- Debug.Assert(false, "unexpected keyword");
+ Debug.Fail("unexpected keyword");
throw UnsupportedKeyword(s_validKeywords[(int)index]);
}
}
return false;
}
- Debug.Assert(TdsParser.IsValidTdsToken(token), string.Format("Invalid token after performing CleanPartialRead: {0,-2:X2}", token));
+ Debug.Assert(TdsParser.IsValidTdsToken(token), $"Invalid token after performing CleanPartialRead: {token,-2:X2}");
}
#endif
_sharedState._dataReady = false;
// if user called read but didn't fetch any values, skip the row
// same applies after NextResult on ALTROW because NextResult starts rowconsumption in that case ...
- Debug.Assert(SniContext.Snix_Read == stateObj.SniContext, string.Format((IFormatProvider)null, "The SniContext should be Snix_Read but it actually is {0}", stateObj.SniContext));
+ Debug.Assert(SniContext.Snix_Read == stateObj.SniContext, $"The SniContext should be Snix_Read but it actually is {stateObj.SniContext}");
if (_altRowStatus == ALTROWSTATUS.AltRow)
{
return false;
}
- Debug.Assert(TdsParser.IsValidTdsToken(token), string.Format("DataReady is false, but next token is invalid: {0,-2:X2}", token));
+ Debug.Assert(TdsParser.IsValidTdsToken(token), $"DataReady is false, but next token is invalid: {token,-2:X2}");
}
#endif
return false;
}
- Debug.Assert(TdsParser.IsValidTdsToken(token), string.Format("DataReady is false, but next token is invalid: {0,-2:X2}", token));
+ Debug.Assert(TdsParser.IsValidTdsToken(token), $"DataReady is false, but next token is invalid: {token,-2:X2}");
}
#endif
{
get
{
- return (string.Format((IFormatProvider)null, "{0:00}.{1:00}.{2:0000}", _loginAck.majorVersion,
+ return (string.Format("{0:00}.{1:00}.{2:0000}", _loginAck.majorVersion,
(short)_loginAck.minorVersion, _loginAck.buildNum));
}
}
requestType = TdsEnums.TransactionManagerRequestType.Save;
break;
default:
- Debug.Assert(false, "Unknown transaction type");
+ Debug.Fail("Unknown transaction type");
break;
}
_recoverySessionData = null;
}
- Debug.Assert(SniContext.Snix_Login == Parser._physicalStateObj.SniContext, string.Format((IFormatProvider)null, "SniContext should be Snix_Login; actual Value: {0}", Parser._physicalStateObj.SniContext));
+ Debug.Assert(SniContext.Snix_Login == Parser._physicalStateObj.SniContext, $"SniContext should be Snix_Login; actual Value: {Parser._physicalStateObj.SniContext}");
_parser._physicalStateObj.SniContext = SniContext.Snix_EnableMars;
_parser.EnableMars();
_parser.Disconnect();
_parser = new TdsParser(ConnectionOptions.MARS, ConnectionOptions.Asynchronous);
- Debug.Assert(SniContext.Undefined == Parser._physicalStateObj.SniContext, string.Format((IFormatProvider)null, "SniContext should be Undefined; actual Value: {0}", Parser._physicalStateObj.SniContext));
+ Debug.Assert(SniContext.Undefined == Parser._physicalStateObj.SniContext, $"SniContext should be Undefined; actual Value: {Parser._physicalStateObj.SniContext}");
try
{
_parser.Disconnect();
_parser = new TdsParser(ConnectionOptions.MARS, ConnectionOptions.Asynchronous);
- Debug.Assert(SniContext.Undefined == Parser._physicalStateObj.SniContext, string.Format((IFormatProvider)null, "SniContext should be Undefined; actual Value: {0}", Parser._physicalStateObj.SniContext));
+ Debug.Assert(SniContext.Undefined == Parser._physicalStateObj.SniContext, $"SniContext should be Undefined; actual Value: {Parser._physicalStateObj.SniContext}");
ServerInfo currentServerInfo;
if (useFailoverHost)
break;
default:
- Debug.Assert(false, "Missed token in EnvChange!");
+ Debug.Fail("Missed token in EnvChange!");
break;
}
}
break;
default:
- Debug.Assert(false, "Unknown _fedAuthLibrary type");
+ Debug.Fail("Unknown _fedAuthLibrary type");
throw SQL.ParsingErrorLibraryType(ParsingErrorState.FedAuthFeatureAckUnknownLibraryType, (int)_fedAuthFeatureExtensionData.Value.libraryType);
}
_federatedAuthenticationAcknowledged = true;
{
// No parent, so we better be LocalFromTSQL. Should we even return in this case -
// since it could be argued this is invalid?
- Debug.Assert(false, "Why are we calling IsOrphaned with no parent?");
+ Debug.Fail("Why are we calling IsOrphaned with no parent?");
Debug.Assert(_transactionType == TransactionType.LocalFromTSQL, "invalid state");
result = false;
}
byte[] byteArrayValue = (byte[])values[publicKeyIndex];
foreach (byte b in byteArrayValue)
{
- resultString.Append(string.Format((IFormatProvider)null, "{0,-2:x2}", b));
+ resultString.Append(string.Format("{0,-2:x2}", b));
}
nameString.Append(resultString.ToString());
}
}
-}
\ No newline at end of file
+}
_actualSize = 5 + (isSqlVariant ? 5 : MetaType.GetTimeSizeFromScale(GetActualScale()));
break;
default:
- Debug.Assert(false, "Unknown variable length type!");
+ Debug.Fail("Unknown variable length type!");
break;
}
}
}
}
-}
\ No newline at end of file
+}
_peekedChar = Read();
}
- Debug.Assert(_peekedChar == -1 || ((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue)), string.Format("Bad peeked character: {0}", _peekedChar));
+ Debug.Assert(_peekedChar == -1 || ((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue)), $"Bad peeked character: {_peekedChar}");
return _peekedChar;
}
}
}
- Debug.Assert(readChar == -1 || ((readChar >= char.MinValue) && (readChar <= char.MaxValue)), string.Format("Bad read character: {0}", readChar));
+ Debug.Assert(readChar == -1 || ((readChar >= char.MinValue) && (readChar <= char.MaxValue)), $"Bad read character: {readChar}");
return readChar;
}
// Load in peeked char
if ((charsNeeded > 0) && (HasPeekedChar))
{
- Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), string.Format("Bad peeked character: {0}", _peekedChar));
+ Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), $"Bad peeked character: {_peekedChar}");
buffer[index + charsRead] = (char)_peekedChar;
charsRead++;
charsNeeded--;
int peekedChar = _peekedChar;
if (peekedChar >= char.MinValue)
{
- Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), string.Format("Bad peeked character: {0}", _peekedChar));
+ Debug.Assert((_peekedChar >= char.MinValue) && (_peekedChar <= char.MaxValue), $"Bad peeked character: {_peekedChar}");
buffer[adjustedIndex] = (char)peekedChar;
adjustedIndex++;
charsRead++;
private int InternalRead(char[] buffer, int index, int count)
{
Debug.Assert(buffer != null, "Null output buffer");
- Debug.Assert((index >= 0) && (count >= 0) && (index + count <= buffer.Length), string.Format("Bad count: {0} or index: {1}", count, index));
+ Debug.Assert((index >= 0) && (count >= 0) && (index + count <= buffer.Length), $"Bad count: {count} or index: {index}");
Debug.Assert(!IsClosed, "Can't read while textreader is closed");
try
private int DecodeBytesToChars(byte[] inBuffer, int inBufferCount, char[] outBuffer, int outBufferOffset, int outBufferCount)
{
Debug.Assert(inBuffer != null, "Null input buffer");
- Debug.Assert((inBufferCount > 0) && (inBufferCount <= inBuffer.Length), string.Format("Bad inBufferCount: {0}", inBufferCount));
+ Debug.Assert((inBufferCount > 0) && (inBufferCount <= inBuffer.Length), $"Bad inBufferCount: {inBufferCount}");
Debug.Assert(outBuffer != null, "Null output buffer");
- Debug.Assert((outBufferOffset >= 0) && (outBufferCount > 0) && (outBufferOffset + outBufferCount <= outBuffer.Length), string.Format("Bad outBufferCount: {0} or outBufferOffset: {1}", outBufferCount, outBufferOffset));
+ Debug.Assert((outBufferOffset >= 0) && (outBufferCount > 0) && (outBufferOffset + outBufferCount <= outBuffer.Length), $"Bad outBufferCount: {outBufferCount} or outBufferOffset: {outBufferOffset}");
int charsRead;
int bytesUsed;
{
case CommandType.Text:
case CommandType.StoredProcedure:
- Debug.Assert(false, "valid CommandType " + value.ToString());
+ Debug.Fail("valid CommandType " + value.ToString());
break;
case CommandType.TableDirect:
break;
default:
- Debug.Assert(false, "invalid CommandType " + value.ToString());
+ Debug.Fail("invalid CommandType " + value.ToString());
break;
}
#endif
case IsolationLevel.RepeatableRead:
case IsolationLevel.Serializable:
case IsolationLevel.Snapshot:
- Debug.Assert(false, "valid IsolationLevel " + value.ToString());
+ Debug.Fail("valid IsolationLevel " + value.ToString());
break;
case IsolationLevel.Chaos:
break;
default:
- Debug.Assert(false, "invalid IsolationLevel " + value.ToString());
+ Debug.Fail("invalid IsolationLevel " + value.ToString());
break;
}
#endif
{
Debug.Assert(sniError > 0 && sniError <= (int)SNINativeMethodWrapper.SniSpecialErrors.MaxErrorValue, "SNI error is out of range");
- string errorMessageId = string.Format((IFormatProvider)null, "SNI_ERROR_{0}", sniError);
+ string errorMessageId = string.Format("SNI_ERROR_{0}", sniError);
return SR.GetResourceString(errorMessageId, errorMessageId);
}
{
if (_state != TdsParserState.Closed)
{
- Debug.Assert(false, "TdsParser.Connect called on non-closed connection!");
+ Debug.Fail("TdsParser.Connect called on non-closed connection!");
return;
}
_physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
_physicalStateObj.Dispose();
ThrowExceptionAndWarning(_physicalStateObj);
- Debug.Assert(false, "SNI returned status != success, but no error thrown?");
+ Debug.Fail("SNI returned status != success, but no error thrown?");
}
_sniSpnBuffer = null;
// a bad error could be returned (as it was when it was freed to early for me).
_physicalStateObj.Dispose();
ThrowExceptionAndWarning(_physicalStateObj);
- Debug.Assert(false, "SNI returned status != success, but no error thrown?");
+ Debug.Fail("SNI returned status != success, but no error thrown?");
}
_server = serverInfo.ResolvedServerName;
break;
default:
- Debug.Assert(false, "UNKNOWN option in SendPreLoginHandshake");
+ Debug.Fail("UNKNOWN option in SendPreLoginHandshake");
break;
}
break;
default:
- Debug.Assert(false, "Invalid client encryption option detected");
+ Debug.Fail("Invalid client encryption option detected");
break;
}
break;
default:
- Debug.Assert(false, "UNKNOWN option in ConsumePreLoginHandshake, option:" + option);
+ Debug.Fail("UNKNOWN option in ConsumePreLoginHandshake, option:" + option);
// DO NOTHING FOR THESE UNKNOWN OPTIONS
offset += 4;
string sniContextEnumName = TdsEnums.GetSniContextEnumName(stateObj.SniContext);
string sqlContextInfo = SR.GetResourceString(sniContextEnumName, sniContextEnumName);
- string providerRid = string.Format((IFormatProvider)null, "SNI_PN{0}", details.provider);
+ string providerRid = string.Format("SNI_PN{0}", details.provider);
string providerName = SR.GetResourceString(providerRid, providerRid);
- Debug.Assert(!string.IsNullOrEmpty(providerName), string.Format((IFormatProvider)null, "invalid providerResourceId '{0}'", providerRid));
+ Debug.Assert(!string.IsNullOrEmpty(providerName), $"invalid providerResourceId '{providerRid}'");
uint win32ErrorCode = details.nativeError;
if (details.sniErrorNumber == 0)
}
}
}
- errorMessage = string.Format((IFormatProvider)null, "{0} (provider: {1}, error: {2} - {3})",
+ errorMessage = string.Format("{0} (provider: {1}, error: {2} - {3})",
sqlContextInfo, providerName, (int)details.sniErrorNumber, errorMessage);
return new SqlError((int)details.nativeError, 0x00, TdsEnums.FATAL_ERROR_CLASS,
{
Debug.Assert((SniContext.Undefined != stateObj.SniContext) && // SniContext must not be Undefined
((stateObj._attentionSent) || ((SniContext.Snix_Execute != stateObj.SniContext) && (SniContext.Snix_SendRows != stateObj.SniContext))), // SniContext should not be Execute or SendRows unless attention was sent (and, therefore, we are looking for an ACK)
- string.Format("Unexpected SniContext on call to TryRun; SniContext={0}", stateObj.SniContext));
+ $"Unexpected SniContext on call to TryRun; SniContext={stateObj.SniContext}");
if (TdsParserState.Broken == State || TdsParserState.Closed == State)
{
if (!IsValidTdsToken(token))
{
- Debug.Assert(false, string.Format((IFormatProvider)null, "unexpected token; token = {0,-2:X2}", token));
+ Debug.Fail($"unexpected token; token = {token,-2:X2}");
_state = TdsParserState.Broken;
_connHandler.BreakConnection();
throw SQL.ParsingError();
{
return false;
}
- Debug.Assert(IsValidTdsToken(token), string.Format("DataReady is false, but next token is not valid: {0,-2:X2}", token));
+ Debug.Assert(IsValidTdsToken(token), $"DataReady is false, but next token is not valid: {token,-2:X2}");
}
#endif
break;
default:
- Debug.Assert(false, "Unknown environment change token: " + env.type);
+ Debug.Fail("Unknown environment change token: " + env.type);
break;
}
processedLength += env.length;
ThrowUnsupportedCollationEncountered(stateObj);
}
- Debug.Assert(codePage >= 0, string.Format("Invalid code page. codePage: {0}. cultureId: {1}", codePage, cultureId));
+ Debug.Assert(codePage >= 0, $"Invalid code page. codePage: {codePage}. cultureId: {cultureId}");
}
}
break;
default:
- Debug.Assert(false, "Unknown VariableTime type!");
+ Debug.Fail("Unknown VariableTime type!");
break;
}
}
break;
default:
- Debug.Assert(false, "unknown null sqlType!" + md.type.ToString());
+ Debug.Fail("unknown null sqlType!" + md.type.ToString());
break;
}
}
default:
- Debug.Assert(false, "Unknown tds type for SqlString!" + type.ToString(CultureInfo.InvariantCulture));
+ Debug.Fail("Unknown tds type for SqlString!" + type.ToString(CultureInfo.InvariantCulture));
break;
}
break;
default:
- Debug.Assert(false, "ReadSqlDateTime is called with the wrong tdsType");
+ Debug.Fail("ReadSqlDateTime is called with the wrong tdsType");
break;
}
break;
default:
- Debug.Assert(false, "Unknown SqlType!" + tdsType.ToString(CultureInfo.InvariantCulture));
+ Debug.Fail("Unknown SqlType!" + tdsType.ToString(CultureInfo.InvariantCulture));
break;
} // switch
}
default:
- Debug.Assert(false, "Unknown tds type in SqlVariant!" + type.ToString(CultureInfo.InvariantCulture));
+ Debug.Fail("Unknown tds type in SqlVariant!" + type.ToString(CultureInfo.InvariantCulture));
break;
} // switch
break;
default:
- Debug.Assert(false, "unknown tds type for sqlvariant!");
+ Debug.Fail("unknown tds type for sqlvariant!");
break;
} // switch
// return point for accumulated writes, note: non-accumulated writes returned from their case statements
break;
default:
- Debug.Assert(false, "unknown tds type for sqlvariant!");
+ Debug.Fail("unknown tds type for sqlvariant!");
break;
} // switch
// return point for accumulated writes, note: non-accumulated writes returned from their case statements
return true;
}
default:
- Debug.Assert(false, "Unknown token length!");
+ Debug.Fail("Unknown token length!");
tokenLength = 0;
return true;
}
dataLen = 1 + sizeof(int) + fedAuthFeatureData.accessToken.Length; // length of feature data = 1 byte for library and echo, security token length and sizeof(int) for token lengh itself
break;
default:
- Debug.Assert(false, "Unrecognized library type for fedauth feature extension request");
+ Debug.Fail("Unrecognized library type for fedauth feature extension request");
break;
}
options |= TdsEnums.FEDAUTHLIB_SECURITYTOKEN << 1;
break;
default:
- Debug.Assert(false, "Unrecognized FedAuthLibrary type for feature extension request");
+ Debug.Fail("Unrecognized FedAuthLibrary type for feature extension request");
break;
}
// Call helper function for SSPI data and actual length.
// Since we don't have SSPI data from the server, send null for the
// byte[] buffer and 0 for the int length.
- Debug.Assert(SniContext.Snix_Login == _physicalStateObj.SniContext, string.Format((IFormatProvider)null, "Unexpected SniContext. Expecting Snix_Login, actual value is '{0}'", _physicalStateObj.SniContext));
+ Debug.Assert(SniContext.Snix_Login == _physicalStateObj.SniContext, $"Unexpected SniContext. Expecting Snix_Login, actual value is '{_physicalStateObj.SniContext}'");
_physicalStateObj.SniContext = SniContext.Snix_LoginSspi;
SSPIData(null, 0, ref outSSPIBuff, ref outSSPILength);
timeout, null, stateObj, true))
{
- Debug.Assert(SniContext.Snix_Read == stateObj.SniContext, string.Format((IFormatProvider)null, "The SniContext should be Snix_Read but it actually is {0}", stateObj.SniContext));
+ Debug.Assert(SniContext.Snix_Read == stateObj.SniContext, $"The SniContext should be Snix_Read but it actually is {stateObj.SniContext}");
if (null != dtcReader && dtcReader.Read())
{
Debug.Assert(dtcReader.GetName(0) == "TM Address", "TdsParser: GetDTCAddress did not return 'TM Address'");
#if DEBUG
else
{
- Debug.Assert(false, "unexpected length (> Int32.MaxValue) returned from dtcReader.GetBytes");
+ Debug.Fail("unexpected length (> Int32.MaxValue) returned from dtcReader.GetBytes");
// if we hit this case we'll just return a null address so that the user
// will get a transcaction enlistment error in the upper layers
}
WriteString(transactionName, stateObj);
break;
default:
- Debug.Assert(false, "Unexpected TransactionManagerRequest");
+ Debug.Fail("Unexpected TransactionManagerRequest");
break;
}
}
else
{
- Debug.Assert(false, "SUDTs not yet supported.");
+ Debug.Fail("SUDTs not yet supported.");
}
break;
case SqlDbType.Date:
stateObj.WriteByte(metaData.Scale);
break;
default:
- Debug.Assert(false, "Unknown SqlDbType should have been caught earlier!");
+ Debug.Fail("Unknown SqlDbType should have been caught earlier!");
break;
}
}
break;
default:
- Debug.Assert(false, "Unknown token length!");
+ Debug.Fail("Unknown token length!");
break;
}
throw SQL.UDTUnexpectedResult(value.GetType().AssemblyQualifiedName);
default:
- Debug.Assert(false, "Unknown TdsType!" + type.NullableType.ToString("x2", (IFormatProvider)null));
+ Debug.Fail("Unknown TdsType!" + type.NullableType.ToString("x2", (IFormatProvider)null));
break;
} // switch
// return point for accumulated writes, note: non-accumulated writes returned from their case statements
_next.Write(value);
_written++;
}
- Debug.Assert(_size < 0 || _written <= _size, string.Format("Length of data written exceeds specified length. Written: {0}, specified: {1}", _written, _size));
+ Debug.Assert(_size < 0 || _written <= _size, $"Length of data written exceeds specified length. Written: {_written}, specified: {_size}");
}
public override void Write(char[] buffer, int index, int count)
break;
default:
- Debug.Assert(false, "Unknown TdsType!" + type.NullableType.ToString("x2", (IFormatProvider)null));
+ Debug.Fail("Unknown TdsType!" + type.NullableType.ToString("x2", (IFormatProvider)null));
break;
} // switch
// return point for accumulated writes, note: non-accumulated writes returned from their case statements
"Out of sync plp read request");
if (stateObj._longlenleft == 0)
{
- Debug.Assert(false, "Out of sync read request");
+ Debug.Fail("Out of sync read request");
charsRead = 0;
return true;
}
return altMetaDataSet;
}
}
- Debug.Assert(false, "Can't match up altMetaDataSet with given id");
+ Debug.Fail("Can't match up altMetaDataSet with given id");
return null;
}
// NOTE: TdsParserSessionPool may call DecrementPendingCallbacks on a TdsParserStateObject which is already disposed
// This is not dangerous (since the stateObj is no longer in use), but we need to add a workaround in the assert for it
- Debug.Assert((remaining == -1 && SessionHandle.IsNull) || (0 <= remaining && remaining < 3), string.Format("_pendingCallbacks values is invalid after decrementing: {0}", remaining));
+ Debug.Assert((remaining == -1 && SessionHandle.IsNull) || (0 <= remaining && remaining < 3), $"_pendingCallbacks values is invalid after decrementing: {remaining}");
return remaining;
}
internal int IncrementPendingCallbacks()
{
int remaining = Interlocked.Increment(ref _pendingCallbacks);
- Debug.Assert(0 < remaining && remaining <= 3, string.Format("_pendingCallbacks values is invalid after incrementing: {0}", remaining));
+ Debug.Assert(0 < remaining && remaining <= 3, $"_pendingCallbacks values is invalid after incrementing: {remaining}");
return remaining;
}
}
else
{
- Debug.Assert(false, "entered negative _inBytesPacket loop");
+ Debug.Fail("entered negative _inBytesPacket loop");
}
AssertValidState();
}
else
{
status = TdsEnums.ST_EOM;
- Debug.Assert(false, string.Format((IFormatProvider)null, "Unexpected argument {0,-2:x2} to WritePacket", flushMode));
+ Debug.Fail($"Unexpected argument {flushMode,-2:x2} to WritePacket");
}
_outBuff[0] = _outputMessageType; // Message Type
private void AssertValidState()
{
- string assertMessage = null;
-
if (_inBytesUsed < 0 || _inBytesRead < 0)
{
- assertMessage = string.Format(
- CultureInfo.InvariantCulture,
- "either _inBytesUsed or _inBytesRead is negative: {0}, {1}",
- _inBytesUsed, _inBytesRead);
+ Debug.Fail($"Invalid TDS Parser State: either _inBytesUsed or _inBytesRead is negative: {_inBytesUsed}, {_inBytesRead}");
}
else if (_inBytesUsed > _inBytesRead)
{
- assertMessage = string.Format(
- CultureInfo.InvariantCulture,
- "_inBytesUsed > _inBytesRead: {0} > {1}",
- _inBytesUsed, _inBytesRead);
- }
-
- if (assertMessage != null)
- {
- Debug.Assert(false, "Invalid TDS Parser State: " + assertMessage);
+ Debug.Fail($"Invalid TDS Parser State: _inBytesUsed > _inBytesRead: {_inBytesUsed} > {_inBytesRead}");
}
Debug.Assert(_inBytesPacket >= 0, "Packet must not be negative");
Debug.Assert(_asyncWriteCount == 0, "StateObj still has outstanding async writes");
Debug.Assert(_delayedWriteAsyncCallbackException == null, "StateObj has an unobserved exceptions from an async write");
// Attention\Cancellation\Timeouts
- Debug.Assert(!_attentionReceived && !_attentionSent && !_attentionSending, string.Format("StateObj is still dealing with attention: Sent: {0}, Received: {1}, Sending: {2}", _attentionSent, _attentionReceived, _attentionSending));
+ Debug.Assert(!_attentionReceived && !_attentionSent && !_attentionSending, $"StateObj is still dealing with attention: Sent: {_attentionSent}, Received: {_attentionReceived}, Sending: {_attentionSending}");
Debug.Assert(!_cancelled, "StateObj still has cancellation set");
Debug.Assert(!_internalTimeout, "StateObj still has internal timeout set");
// Errors and Warnings
#if DEBUG
else
{
- Debug.Assert(false, "Removing a packet from the pending list that was never added to it");
+ Debug.Fail("Removing a packet from the pending list that was never added to it");
}
#endif
}
break;
case SqlDbType.Udt:
case SqlDbType.Xml:
- Debug.Assert(false, "PLP-only types shouldn't get to this point. Type: " + _metaData.SqlDbType);
+ Debug.Fail("PLP-only types shouldn't get to this point. Type: " + _metaData.SqlDbType);
break;
case SqlDbType.Variant:
_stateObj.Parser.WriteInt(TdsEnums.FIXEDNULL, _stateObj);
break;
case SqlDbType.Structured:
- Debug.Assert(false, "Not yet implemented. Not needed until Structured UDTs");
+ Debug.Fail("Not yet implemented. Not needed until Structured UDTs");
break;
default:
- Debug.Assert(false, "Unexpected SqlDbType: " + _metaData.SqlDbType);
+ Debug.Fail("Unexpected SqlDbType: " + _metaData.SqlDbType);
break;
}
}
}
if (inaccessibleLogs != null)
- throw new SecurityException(SR.Format(wantToCreate ? SR.SomeLogsInaccessibleToCreate : SR.SomeLogsInaccessible, inaccessibleLogs.ToString()));
+ throw new SecurityException(SR.Format(wantToCreate ? SR.SomeLogsInaccessibleToCreate : SR.SomeLogsInaccessible, inaccessibleLogs));
}
finally
{
EventLogEntry entry = GetEntryAtNoThrow(index);
if (entry == null)
- throw new ArgumentException(SR.Format(SR.IndexOutOfBounds, index.ToString(CultureInfo.CurrentCulture)));
+ throw new ArgumentException(SR.Format(SR.IndexOutOfBounds, index.ToString()));
return entry;
}
if (!success)
{
- throw new InvalidOperationException(SR.Format(SR.CantReadLogEntryAt, index.ToString(CultureInfo.CurrentCulture)), new Win32Exception());
+ throw new InvalidOperationException(SR.Format(SR.CantReadLogEntryAt, index.ToString()), new Win32Exception());
}
}
{
e = new Win32Exception();
}
- throw new InvalidOperationException(SR.Format(SR.CantOpenLog, logname.ToString(), currentMachineName, e?.Message ?? ""));
+ throw new InvalidOperationException(SR.Format(SR.CantOpenLog, logname, currentMachineName, e?.Message ?? ""));
}
readHandle = handle;
string rightLogName = EventLog.LogNameFromSourceName(sourceName, currentMachineName);
string currentLogName = GetLogName(currentMachineName);
if (rightLogName != null && currentLogName != null && !string.Equals(rightLogName, currentLogName, StringComparison.OrdinalIgnoreCase))
- throw new ArgumentException(SR.Format(SR.LogSourceMismatch, Source.ToString(), currentLogName, rightLogName));
+ throw new ArgumentException(SR.Format(SR.LogSourceMismatch, Source, currentLogName, rightLogName));
}
}
finally
string rightLogName = EventLog._InternalLogNameFromSourceName(sourceName, currentMachineName);
string currentLogName = GetLogName(currentMachineName);
if (rightLogName != null && currentLogName != null && !string.Equals(rightLogName, currentLogName, StringComparison.OrdinalIgnoreCase))
- throw new ArgumentException(SR.Format(SR.LogSourceMismatch, Source.ToString(), currentLogName, rightLogName));
+ throw new ArgumentException(SR.Format(SR.LogSourceMismatch, Source, currentLogName, rightLogName));
}
boolFlags[Flag_sourceVerified] = true;
}
throw new ArgumentNullException(nameof(value));
if (!(value is CounterCreationData))
- throw new ArgumentException(SR.Format(SR.MustAddCounterCreationData));
+ throw new ArgumentException(SR.MustAddCounterCreationData);
}
}
}
else if (oldSample.CounterType != newSample.CounterType)
{
- throw new InvalidOperationException(SR.Format(SR.MismatchedCounterTypes));
+ throw new InvalidOperationException(SR.MismatchedCounterTypes);
}
if (newCounterType == Interop.Kernel32.PerformanceCounterOptions.PERF_ELAPSED_TIME)
throw new ArgumentOutOfRangeException(nameof(value));
if (_initialized)
- throw new InvalidOperationException(SR.Format(SR.CantSetLifetimeAfterInitialized));
+ throw new InvalidOperationException(SR.CantSetLifetimeAfterInitialized);
_instanceLifetime = value;
}
private void ThrowReadOnly()
{
- throw new InvalidOperationException(SR.Format(SR.ReadOnlyCounter));
+ throw new InvalidOperationException(SR.ReadOnlyCounter);
}
private static void VerifyWriteableCounterAllowed()
{
if (EnvironmentHelpers.IsAppContainerProcess)
{
- throw new NotSupportedException(SR.Format(SR.PCNotSupportedUnderAppContainer));
+ throw new NotSupportedException(SR.PCNotSupportedUnderAppContainer);
}
}
string currentMachineName = _machineName;
if (currentCategoryName == string.Empty)
- throw new InvalidOperationException(SR.Format(SR.CategoryNameMissing));
+ throw new InvalidOperationException(SR.CategoryNameMissing);
if (_counterName == string.Empty)
- throw new InvalidOperationException(SR.Format(SR.CounterNameMissing));
+ throw new InvalidOperationException(SR.CounterNameMissing);
if (ReadOnly)
{
}
if (_instanceLifetime != PerformanceCounterInstanceLifetime.Global)
- throw new InvalidOperationException(SR.Format(SR.InstanceLifetimeProcessonReadOnly));
+ throw new InvalidOperationException(SR.InstanceLifetimeProcessonReadOnly);
_initialized = true;
}
else
{
if (currentMachineName != "." && !string.Equals(currentMachineName, PerformanceCounterLib.ComputerName, StringComparison.OrdinalIgnoreCase))
- throw new InvalidOperationException(SR.Format(SR.RemoteWriting));
+ throw new InvalidOperationException(SR.RemoteWriting);
if (!PerformanceCounterLib.IsCustomCategory(currentMachineName, currentCategoryName))
- throw new InvalidOperationException(SR.Format(SR.NotCustomCounter));
+ throw new InvalidOperationException(SR.NotCustomCounter);
// check category type
PerformanceCounterCategoryType categoryType = PerformanceCounterLib.GetCategoryType(currentMachineName, currentCategoryName);
}
if (string.IsNullOrEmpty(_instanceName) && InstanceLifetime == PerformanceCounterInstanceLifetime.Process)
- throw new InvalidOperationException(SR.Format(SR.InstanceLifetimeProcessforSingleInstance));
+ throw new InvalidOperationException(SR.InstanceLifetimeProcessforSingleInstance);
_sharedCounter = new SharedPerformanceCounter(currentCategoryName.ToLower(CultureInfo.InvariantCulture), _counterName.ToLower(CultureInfo.InvariantCulture), _instanceName.ToLower(CultureInfo.InvariantCulture), _instanceLifetime);
_initialized = true;
else
{
if (_instanceName == null || _instanceName.Length == 0)
- throw new InvalidOperationException(SR.Format(SR.InstanceNameRequired));
+ throw new InvalidOperationException(SR.InstanceNameRequired);
return counterSample.GetInstanceValue(_instanceName);
}
public void RemoveInstance()
{
if (_isReadOnly)
- throw new InvalidOperationException(SR.Format(SR.ReadOnlyRemoveInstance));
+ throw new InvalidOperationException(SR.ReadOnlyRemoveInstance);
Initialize();
_sharedCounter.RemoveInstance(_instanceName.ToLower(CultureInfo.InvariantCulture), _instanceLifetime);
get
{
if (_categoryName == null)
- throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
+ throw new InvalidOperationException(SR.CategoryNameNotSet);
if (_categoryHelp == null)
_categoryHelp = PerformanceCounterLib.GetCategoryHelp(_machineName, _categoryName);
throw new ArgumentNullException(nameof(counterName));
if (_categoryName == null)
- throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
+ throw new InvalidOperationException(SR.CategoryNameNotSet);
return PerformanceCounterLib.CounterExists(_machineName, _categoryName, counterName);
}
// 1026 chars is the size of the buffer used in perfcounter.dll to get this name.
// If the categoryname plus prefix is too long, we won't be able to read the category properly.
if (categoryName.Length > (1024 - SharedPerformanceCounter.DefaultFileMappingName.Length))
- throw new ArgumentException(SR.Format(SR.CategoryNameTooLong));
+ throw new ArgumentException(SR.CategoryNameTooLong);
}
internal static void CheckValidCounter(string counterName)
{
if (counterData[i].CounterName == null || counterData[i].CounterName.Length == 0)
{
- throw new ArgumentException(SR.Format(SR.InvalidCounterName));
+ throw new ArgumentException(SR.InvalidCounterName);
}
int currentSampleType = (int)counterData[i].CounterType;
(currentSampleType == Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_TIMER))
{
if (counterData.Count <= (i + 1))
- throw new InvalidOperationException(SR.Format(SR.CounterLayout));
+ throw new InvalidOperationException(SR.CounterLayout);
else
{
currentSampleType = (int)counterData[i + 1].CounterType;
if (!PerformanceCounterLib.IsBaseCounter(currentSampleType))
- throw new InvalidOperationException(SR.Format(SR.CounterLayout));
+ throw new InvalidOperationException(SR.CounterLayout);
}
}
else if (PerformanceCounterLib.IsBaseCounter(currentSampleType))
{
if (i == 0)
- throw new InvalidOperationException(SR.Format(SR.CounterLayout));
+ throw new InvalidOperationException(SR.CounterLayout);
else
{
currentSampleType = (int)counterData[i - 1].CounterType;
(currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_RAW_FRACTION) &&
(currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_SAMPLE_FRACTION) &&
(currentSampleType != Interop.Kernel32.PerformanceCounterOptions.PERF_AVERAGE_TIMER))
- throw new InvalidOperationException(SR.Format(SR.CounterLayout));
+ throw new InvalidOperationException(SR.CounterLayout);
}
}
{
NetFrameworkUtils.EnterMutex(PerfMutexName, ref mutex);
if (!PerformanceCounterLib.IsCustomCategory(machineName, categoryName))
- throw new InvalidOperationException(SR.Format(SR.CantDeleteCategory));
+ throw new InvalidOperationException(SR.CantDeleteCategory);
SharedPerformanceCounter.RemoveAllInstances(categoryName);
public PerformanceCounter[] GetCounters()
{
if (GetInstanceNames().Length != 0)
- throw new ArgumentException(SR.Format(SR.InstanceNameRequired));
+ throw new ArgumentException(SR.InstanceNameRequired);
return GetCounters("");
}
throw new ArgumentNullException(nameof(instanceName));
if (_categoryName == null)
- throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
+ throw new InvalidOperationException(SR.CategoryNameNotSet);
if (instanceName.Length != 0 && !InstanceExists(instanceName))
throw new InvalidOperationException(SR.Format(SR.MissingInstance, instanceName, _categoryName));
public string[] GetInstanceNames()
{
if (_categoryName == null)
- throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
+ throw new InvalidOperationException(SR.CategoryNameNotSet);
return GetCounterInstances(_categoryName, _machineName);
}
throw new ArgumentNullException(nameof(instanceName));
if (_categoryName == null)
- throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
+ throw new InvalidOperationException(SR.CategoryNameNotSet);
using (CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName))
{
public InstanceDataCollectionCollection ReadCategory()
{
if (_categoryName == null)
- throw new InvalidOperationException(SR.Format(SR.CategoryNameNotSet));
+ throw new InvalidOperationException(SR.CategoryNameNotSet);
using (CategorySample categorySample = PerformanceCounterLib.GetCategorySample(_machineName, _categoryName))
{
if (!categoryExists)
{
// Consider adding diagnostic logic here, may be we can dump the nameTable...
- throw new InvalidOperationException(SR.Format(SR.MissingCategory));
+ throw new InvalidOperationException(SR.MissingCategory);
}
return counterExists;
iniWriter.Write(HelpSufix);
iniWriter.Write("=");
if (categoryHelp == null || categoryHelp == string.Empty)
- iniWriter.WriteLine(SR.Format(SR.HelpNotAvailable));
+ iniWriter.WriteLine(SR.HelpNotAvailable);
else
iniWriter.WriteLine(categoryHelp);
help = library.GetCategoryHelp(category);
if (help == null)
- throw new InvalidOperationException(SR.Format(SR.MissingCategory));
+ throw new InvalidOperationException(SR.MissingCategory);
return help;
}
}
}
if (sample == null)
- throw new InvalidOperationException(SR.Format(SR.MissingCategory));
+ throw new InvalidOperationException(SR.MissingCategory);
return sample;
}
}
if (!categoryExists)
- throw new InvalidOperationException(SR.Format(SR.MissingCategory));
+ throw new InvalidOperationException(SR.MissingCategory);
return counters;
}
}
if (!foundCategory)
- throw new InvalidOperationException(SR.Format(SR.CantReadCategoryIndex, categoryIndex.ToString(CultureInfo.CurrentCulture)));
+ throw new InvalidOperationException(SR.Format(SR.CantReadCategoryIndex, categoryIndex.ToString()));
ref readonly PERF_OBJECT_TYPE perfObject = ref MemoryMarshal.AsRef<PERF_OBJECT_TYPE>(data.Slice(pos));
return multiSample._baseCounterDefinitionSample;
}
- throw new InvalidOperationException(SR.Format(SR.CounterLayout));
+ throw new InvalidOperationException(SR.CounterLayout);
}
return sample;
}
}
if (instanceName.Length == 0)
{
- throw new ArgumentException(SR.Format(SR.Perflib_Argument_EmptyInstanceName), nameof(instanceName));
+ throw new ArgumentException(SR.Perflib_Argument_EmptyInstanceName, nameof(instanceName));
}
if (_provider == null)
{
if (_categoryData.UseUniqueSharedMemory)
{
if (instanceName != null && instanceName.Length > InstanceNameMaxLength)
- throw new InvalidOperationException(SR.Format(SR.InstanceNameTooLong));
+ throw new InvalidOperationException(SR.InstanceNameTooLong);
}
else
{
if (lifetime != PerformanceCounterInstanceLifetime.Global)
- throw new InvalidOperationException(SR.Format(SR.ProcessLifetimeNotValidInGlobal));
+ throw new InvalidOperationException(SR.ProcessLifetimeNotValidInGlobal);
}
if (counterName != null && instanceName != null)
{
if (!_categoryData.CounterNames.Contains(counterName))
- Debug.Assert(false, "Counter " + counterName + " does not exist in category " + catName);
+ Debug.Fail("Counter " + counterName + " does not exist in category " + catName);
else
_counterEntryPointer = GetCounter(counterName, instanceName, _categoryData.EnableReuse, lifetime);
}
if (newOffset > FileView._fileMappingSize || newOffset < 0)
{
- throw new InvalidOperationException(SR.Format(SR.CountersOOM));
+ throw new InvalidOperationException(SR.CountersOOM);
}
return newOffset;
currentChar++;
}
- throw new InvalidOperationException(SR.Format(SR.MappingCorrupted));
+ throw new InvalidOperationException(SR.MappingCorrupted);
}
// Compare a managed string to a string located at a given offset. If we walk past the end of the
for (i = 0; i < stringA.Length; i++)
{
if ((ulong)(currentChar + i) > (endAddress - 2))
- throw new InvalidOperationException(SR.Format(SR.MappingCorrupted));
+ throw new InvalidOperationException(SR.MappingCorrupted);
if (stringA[i] != currentChar[i])
return false;
// now check for the null termination.
if ((ulong)(currentChar + i) > (endAddress - 2))
- throw new InvalidOperationException(SR.Format(SR.MappingCorrupted));
+ throw new InvalidOperationException(SR.MappingCorrupted);
return (currentChar[i] == 0);
}
if (lifetimeEntry != null && lifetimeEntry->ProcessId != 0)
{
if (lifetime != PerformanceCounterInstanceLifetime.Process)
- throw new InvalidOperationException(SR.Format(SR.CantConvertProcessToGlobal));
+ throw new InvalidOperationException(SR.CantConvertProcessToGlobal);
// make sure only one process is using this instance.
if (ProcessData.ProcessId != lifetimeEntry->ProcessId)
else
{
if (lifetime == PerformanceCounterInstanceLifetime.Process)
- throw new InvalidOperationException(SR.Format(SR.CantConvertGlobalToProcess));
+ throw new InvalidOperationException(SR.CantConvertGlobalToProcess);
}
return true;
}
//It is very important to check the integrity of the shared memory
//everytime a new address is resolved.
if (offset > (FileView._fileMappingSize - sizeToRead) || offset < 0)
- throw new InvalidOperationException(SR.Format(SR.MappingCorrupted));
+ throw new InvalidOperationException(SR.MappingCorrupted);
long address = _baseAddress + offset;
//It is very important to check the integrity of the shared memory
//everytime a new address is resolved.
if (offset > (FileView._fileMappingSize - sizeToRead) || offset < 0)
- throw new InvalidOperationException(SR.Format(SR.MappingCorrupted));
+ throw new InvalidOperationException(SR.MappingCorrupted);
return offset;
}
get
{
if (_fileViewAddress.IsInvalid)
- throw new InvalidOperationException(SR.Format(SR.SharedMemoryGhosted));
+ throw new InvalidOperationException(SR.SharedMemoryGhosted);
return _fileViewAddress.DangerousGetHandle();
}
if (!Interop.Advapi32.ConvertStringSecurityDescriptorToSecurityDescriptor(sddlString, Interop.Kernel32.PerformanceCounterOptions.SDDL_REVISION_1,
out securityDescriptorPointer, IntPtr.Zero))
- throw new InvalidOperationException(SR.Format(SR.SetSecurityDescriptorFailed));
+ throw new InvalidOperationException(SR.SetSecurityDescriptorFailed);
Interop.Kernel32.SECURITY_ATTRIBUTES securityAttributes = new Interop.Kernel32.SECURITY_ATTRIBUTES();
securityAttributes.bInheritHandle = Interop.BOOL.FALSE;
}
if (_fileMappingHandle.IsInvalid)
{
- throw new InvalidOperationException(SR.Format(SR.CantCreateFileMapping));
+ throw new InvalidOperationException(SR.CantCreateFileMapping);
}
_fileViewAddress = Interop.Kernel32.MapViewOfFile(_fileMappingHandle, Interop.Kernel32.FileMapOptions.FILE_MAP_WRITE, 0, 0, UIntPtr.Zero);
if (_fileViewAddress.IsInvalid)
- throw new InvalidOperationException(SR.Format(SR.CantMapFileView));
+ throw new InvalidOperationException(SR.CantMapFileView);
// figure out what size the share memory really is.
Interop.Kernel32.MEMORY_BASIC_INFORMATION meminfo = new Interop.Kernel32.MEMORY_BASIC_INFORMATION();
if (Interop.Kernel32.VirtualQuery(_fileViewAddress, ref meminfo, (UIntPtr)sizeof(Interop.Kernel32.MEMORY_BASIC_INFORMATION)) == UIntPtr.Zero)
- throw new InvalidOperationException(SR.Format(SR.CantGetMappingSize));
+ throw new InvalidOperationException(SR.CantGetMappingSize);
_fileMappingSize = (int)meminfo.RegionSize;
}
{
if (handle.IsInvalid)
{
- throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture)));
+ throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString()));
}
ProcessThreadTimes processTimes = new ProcessThreadTimes();
if (waitHandle.WaitOne(0))
{
if (_haveProcessId)
- throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture)));
+ throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString()));
else
throw new InvalidOperationException(SR.ProcessHasExitedNoId);
}
{
if (Interop.Kernel32.GetExitCodeProcess(handle, out _exitCode) && _exitCode != Interop.Kernel32.HandleOptions.STILL_ACTIVE)
{
- throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture)));
+ throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString()));
}
}
return handle;
{
if (!ProcessManager.IsProcessRunning(processId, machineName))
{
- throw new ArgumentException(SR.Format(SR.MissingProccess, processId.ToString(CultureInfo.CurrentCulture)));
+ throw new ArgumentException(SR.Format(SR.MissingProccess, processId.ToString()));
}
return new Process(machineName, ProcessManager.IsRemoteMachine(machineName), processId, null);
{
if (throwIfExited)
{
- throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, processId.ToString(CultureInfo.CurrentCulture)));
+ throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, processId.ToString()));
}
else
{
if (threadHandle.IsInvalid)
{
if (result == Interop.Errors.ERROR_INVALID_PARAMETER)
- throw new InvalidOperationException(SR.Format(SR.ThreadExited, threadId.ToString(CultureInfo.CurrentCulture)));
+ throw new InvalidOperationException(SR.Format(SR.ThreadExited, threadId.ToString()));
throw new Win32Exception(result);
}
return threadHandle;
}
catch (Exception e)
{
- WriteLine(string.Format(SR.ExceptionOccurred, LogFileName, e.ToString()), useLogFile: false);
+ WriteLine(SR.Format(SR.ExceptionOccurred, LogFileName, e), useLogFile: false);
}
}
}
serverName);
throw new PrincipalOperationException(
- string.Format(CultureInfo.CurrentCulture,
- SR.ADStoreCtxCantResolveSidForCrossStore,
- err));
+ SR.Format(SR.ADStoreCtxCantResolveSidForCrossStore, err));
}
GlobalDebug.WriteLineIf(GlobalDebug.Info,
if ((value == null) || (value.Length > 0))
de.Properties[suggestedAdProperty].Value = value;
else
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.InvalidStringValueForStore, propertyName));
+ throw new ArgumentException(SR.Format(SR.InvalidStringValueForStore, propertyName));
}
protected static void BinaryToLdapConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedAdProperty)
(!memberType.IsSubclassOf(typeof(AuthenticablePrincipal))))
{
throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture, SR.StoreCtxUnsupportedPrincipalTypeForGroupInsert, memberType.ToString()));
+ SR.Format(SR.StoreCtxUnsupportedPrincipalTypeForGroupInsert, memberType));
}
// Can't inserted unpersisted principal
if (member.unpersisted)
{
// Must be a property we don't support
throw new InvalidOperationException(
- string.Format(
- CultureInfo.CurrentCulture,
+ SR.Format(
SR.StoreCtxUnsupportedPropertyForQuery,
PropertyNamesExternal.GetExternalForm(filter.PropertyName)));
}
string objClass = ExtensionHelper.ReadStructuralObjectClass(principalType);
if (null == objClass)
{
- Debug.Fail("ADStoreCtx.GetObjectClassPortion: fell off end looking for " + principalType.ToString());
- throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture, SR.StoreCtxUnsupportedPrincipalTypeForQuery, principalType.ToString()));
+ Debug.Fail($"ADStoreCtx.GetObjectClassPortion: fell off end looking for {principalType}");
+ throw new InvalidOperationException(SR.Format(SR.StoreCtxUnsupportedPrincipalTypeForQuery, principalType));
}
StringBuilder SB = new StringBuilder();
SB.Append("(&(objectClass=");
// This bit doesn't work correctly in AD (AD models the "user can't change password"
// setting as special ACEs in the ntSecurityDescriptor).
throw new InvalidOperationException(
- string.Format(
- CultureInfo.CurrentCulture,
+ SR.Format(
SR.StoreCtxUnsupportedPropertyForQuery,
PropertyNamesExternal.GetExternalForm(filter.PropertyName)));
// It's not a type of Principal that we support
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SDSUtils", "InsertPrincipal: Bad principal type:" + p.GetType().ToString());
- throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture, SR.StoreCtxUnsupportedPrincipalTypeForSave, p.GetType().ToString()));
+ throw new InvalidOperationException(SR.Format(SR.StoreCtxUnsupportedPrincipalTypeForSave, p.GetType()));
}
// Commit the properties
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "SidList: couldn't get policy handle, err={0}", err);
- throw new PrincipalOperationException(string.Format(CultureInfo.CurrentCulture,
+ throw new PrincipalOperationException(SR.Format(
SR.AuthZErrorEnumeratingGroups,
SafeNativeMethods.LsaNtStatusToWinError(err)));
}
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "SidList: LsaLookupSids failed, err={0}", err);
- throw new PrincipalOperationException(string.Format(CultureInfo.CurrentCulture,
+ throw new PrincipalOperationException(SR.Format(
SR.AuthZErrorEnumeratingGroups,
SafeNativeMethods.LsaNtStatusToWinError(err)));
}
break;
default:
- Debug.Fail(string.Format(CultureInfo.CurrentCulture, "AccountInfo.LoadValueIntoProperty: fell off end looking for {0}", propertyName));
+ Debug.Fail($"AccountInfo.LoadValueIntoProperty: fell off end looking for {propertyName}");
break;
}
}
return _scriptPathChanged == LoadState.Changed;
default:
- Debug.Fail(string.Format(CultureInfo.CurrentCulture, "AccountInfo.GetChangeStatusForProperty: fell off end looking for {0}", propertyName));
+ Debug.Fail($"AccountInfo.GetChangeStatusForProperty: fell off end looking for {propertyName}");
return false;
}
}
return _scriptPath;
default:
- Debug.Fail(string.Format(CultureInfo.CurrentCulture, "AccountInfo.GetValueForProperty: fell off end looking for {0}", propertyName));
+ Debug.Fail($"AccountInfo.GetValueForProperty: fell off end looking for {propertyName}");
return null;
}
}
else
{
lastError = Marshal.GetLastWin32Error();
- // With a zero-length buffer, this should have never succeeded
- Debug.Assert(false);
+ Debug.Fail("With a zero-length buffer, this should have never succeeded");
}
}
else
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "Failed to retrieve group list, {0}", lastError);
throw new PrincipalOperationException(
- string.Format(
- CultureInfo.CurrentCulture,
+ SR.Format(
SR.AuthZFailedToRetrieveGroupList,
lastError));
}
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "SidList: couldn't get policy handle, err={0}", err);
- throw new PrincipalOperationException(String.Format(CultureInfo.CurrentCulture,
+ throw new PrincipalOperationException(SR.Format(
SR.AuthZErrorEnumeratingGroups,
SafeNativeMethods.LsaNtStatusToWinError(err)));
}
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthZSet", "SidList: LsaLookupSids failed, err={0}", err);
- throw new PrincipalOperationException(String.Format(CultureInfo.CurrentCulture,
+ throw new PrincipalOperationException(SR.Format(
SR.AuthZErrorEnumeratingGroups,
SafeNativeMethods.LsaNtStatusToWinError(err)));
}
if (_serverProperties.contextType != _contextType)
{
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.PassedContextTypeDoesNotMatchDetectedType, _serverProperties.contextType.ToString()));
+ throw new ArgumentException(SR.Format(SR.PassedContextTypeDoesNotMatchDetectedType, _serverProperties.contextType.ToString()));
}
}
}
//
Debug.WriteLine(
- String.Format(
+ string.Format(
System.Globalization.CultureInfo.InvariantCulture,
"Principal API Debug Log - AppDomain {0} with ID {1} - {2} (UTC)",
System.Threading.Thread.GetDomain().FriendlyName,
break;
default:
- Debug.Fail(string.Format(CultureInfo.CurrentCulture, "PasswordInfo.LoadValueIntoProperty: fell off end looking for {0}", propertyName));
+ Debug.Fail($"PasswordInfo.LoadValueIntoProperty: fell off end looking for {propertyName}");
break;
}
}
return (_expirePasswordImmediately != false);
default:
- Debug.Fail(string.Format(CultureInfo.CurrentCulture, "PasswordInfo.GetChangeStatusForProperty: fell off end looking for {0}", propertyName));
+ Debug.Fail($"PasswordInfo.GetChangeStatusForProperty: fell off end looking for {propertyName}");
return false;
}
}
return _expirePasswordImmediately;
default:
- Debug.Fail(string.Format(CultureInfo.CurrentCulture, "PasswordInfo.GetValueForProperty: fell off end looking for {0}", propertyName));
+ Debug.Fail($"PasswordInfo.GetValueForProperty: fell off end looking for {propertyName}");
return null;
}
}
return _extensionCache;
default:
- Debug.Fail(string.Format(CultureInfo.CurrentCulture, "Principal.GetValueForProperty: Ran off end of list looking for {0}", propertyName));
+ Debug.Fail($"Principal.GetValueForProperty: Ran off end of list looking for {propertyName}");
return null;
}
}
}
}
- Debug.Fail(string.Format(CultureInfo.CurrentCulture, "PrincipalCollectionEnumerator.MoveNext: fell off end of function, mode = {0}", _currentMode.ToString()));
+ Debug.Fail($"PrincipalCollectionEnumerator.MoveNext: fell off end of function, mode = {_currentMode}");
return false;
}
err);
throw new PrincipalOperationException(
- string.Format(CultureInfo.CurrentCulture,
- SR.SAMStoreCtxErrorEnumeratingGroup,
- err));
+ SR.Format(SR.SAMStoreCtxErrorEnumeratingGroup, err));
}
if (string.Equals(_storeCtx.MachineFlatName, domainName, StringComparison.OrdinalIgnoreCase))
{
// Must be a property we don't support
throw new NotSupportedException(
- string.Format(
- CultureInfo.CurrentCulture,
+ SR.Format(
SR.StoreCtxUnsupportedPropertyForQuery,
PropertyNamesExternal.GetExternalForm(filter.PropertyName)));
}
this.MachineUserSuppliedName);
throw new PrincipalOperationException(
- string.Format(CultureInfo.CurrentCulture,
- SR.SAMStoreCtxCantResolveSidForCrossStore,
- err));
+ SR.Format(SR.SAMStoreCtxCantResolveSidForCrossStore, err));
}
GlobalDebug.WriteLineIf(GlobalDebug.Info,
else
{
throw new PrincipalOperationException(
- string.Format(
- CultureInfo.CurrentCulture,
+ SR.Format(
SR.SAMStoreCtxUnableToRetrieveFlatMachineName,
err));
}
}
else
{
- Debug.Assert(false);
+ Debug.Fail("Property not found");
return false;
}
}
else
{
throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture, SR.StoreCtxUnsupportedPrincipalTypeForSave, principalType.ToString()));
+ SR.Format(SR.StoreCtxUnsupportedPrincipalTypeForSave, principalType));
}
// Determine the SAM account name for the entry we'll be creating. Use the name from the NT4 IdentityClaim.
private static void ExceptionToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture,
- SR.PrincipalUnsupportPropertyForType,
- p.GetType().ToString(),
- PropertyNamesExternal.GetExternalForm(propertyName)));
+ SR.Format(SR.PrincipalUnsupportPropertyForType,
+ p.GetType(),
+ PropertyNamesExternal.GetExternalForm(propertyName)));
}
private static void StringToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
if (!isLSAM)
throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture,
- SR.PrincipalUnsupportPropertyForPlatform,
- PropertyNamesExternal.GetExternalForm(propertyName)));
+ SR.Format(SR.PrincipalUnsupportPropertyForPlatform, PropertyNamesExternal.GetExternalForm(propertyName)));
}
private static void GroupTypeToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
if (!isLSAM)
throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture,
- SR.PrincipalUnsupportPropertyForPlatform,
- PropertyNamesExternal.GetExternalForm(propertyName)));
+ SR.Format(SR.PrincipalUnsupportPropertyForPlatform, PropertyNamesExternal.GetExternalForm(propertyName)));
}
else
{
{
if (!isLSAM)
throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture,
- SR.PrincipalUnsupportPropertyForPlatform,
- PropertyNamesExternal.GetExternalForm(propertyName)));
+ SR.Format(SR.PrincipalUnsupportPropertyForPlatform, PropertyNamesExternal.GetExternalForm(propertyName)));
}
private static void AcctExpirDateToNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "UpdateGroupMembership: error while clearing, hr={0}", hr);
throw new PrincipalOperationException(
- string.Format(
- CultureInfo.CurrentCulture,
+ SR.Format(
SR.SAMStoreCtxFailedToClearGroup,
hr.ToString(CultureInfo.InvariantCulture)));
}
(memberType != typeof(GroupPrincipal)) && (!memberType.IsSubclassOf(typeof(GroupPrincipal))))
{
throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture, SR.StoreCtxUnsupportedPrincipalTypeForGroupInsert, memberType.ToString()));
+ SR.Format(SR.StoreCtxUnsupportedPrincipalTypeForGroupInsert, memberType));
}
// Can't inserted unpersisted principal
}
else
{
- Debug.Fail("SAMStoreCtx.GetSchemaFilter: fell off end looking for " + principalType.ToString());
+ Debug.Fail($"SAMStoreCtx.GetSchemaFilter: fell off end looking for {principalType}");
throw new InvalidOperationException(
- string.Format(CultureInfo.CurrentCulture, SR.StoreCtxUnsupportedPrincipalTypeForQuery, principalType.ToString()));
+ SR.Format(SR.StoreCtxUnsupportedPrincipalTypeForQuery, principalType));
}
return schemaTypes;
// Sanity check: there are no negetive OS versions, nor is there a version "0".
if (versionMajor <= 0 || versionMinor < 0)
{
- Debug.Fail(string.Format(
- CultureInfo.CurrentCulture,
- "SAMUtils.GetOSVersion: {0} claims to have negetive OS version, {1}",
- computerDE.Path,
- version));
-
+ Debug.Fail("SAMUtils.GetOSVersion: {computerDE.Path} claims to have negetive OS version, {version}");
return false;
}
}
catch (FormatException)
{
- Debug.Fail(string.Format(
- CultureInfo.CurrentCulture,
- "SAMUtils.GetOSVersion: FormatException on {0} for {1}",
- version,
- computerDE.Path));
-
+ Debug.Fail($"SAMUtils.GetOSVersion: FormatException on {version} for {computerDE.Path}");
return false;
}
catch (OverflowException)
{
- Debug.Fail(string.Format(
- CultureInfo.CurrentCulture,
- "SAMUtils.GetOSVersion: OverflowException on {0} for {1}",
- version,
- computerDE.Path));
+ Debug.Fail($"SAMUtils.GetOSVersion: OverflowException on {version} for {computerDE.Path}");
return false;
}
}
else
{
- Debug.Fail(string.Format(
- CultureInfo.CurrentCulture,
- "SAMUtils.DirectoryEntryAsPrincipal: fell off end, Path={0}, SchemaClassName={1}",
- de.Path,
- de.SchemaClassName));
+ Debug.Fail($"SAMUtils.DirectoryEntryAsPrincipal: fell off end, Path={de.Path}, SchemaClassName={de.SchemaClassName}");
return null;
}
}
p.GetChangeStatusForProperty(PropertyNames.AcctInfoExpiredAccount))
{
throw new InvalidOperationException(
- string.Format(
- CultureInfo.CurrentCulture,
+ SR.Format(
SR.StoreCtxMultipleFiltersForPropertyUnsupported,
PropertyNamesExternal.GetExternalForm(ExpirationDateFilter.PropertyNameStatic)));
}
else
{
// Internal error. Didn't match either the known multivalued or scalar cases.
- Debug.Fail(string.Format(
- CultureInfo.CurrentCulture,
- "StoreCtx.BuildFilterSet: fell off end looking for {0} of type {1}",
- propertyName,
- value.GetType().ToString()
- ));
+ Debug.Fail($"StoreCtx.BuildFilterSet: fell off end looking for {propertyName} of type {value.GetType()}");
}
qbeFilterDescription.FiltersToApply.Add(filter);
int lastError = Marshal.GetLastWin32Error();
GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetCurrentUserSid: OpenProcessToken failed, gle=" + lastError);
- throw new PrincipalOperationException(
- string.Format(CultureInfo.CurrentCulture,
- SR.UnableToOpenToken,
- lastError));
+ throw new PrincipalOperationException(SR.Format(SR.UnableToOpenToken, lastError));
}
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetCurrentUserSid: OpenThreadToken failed, gle=" + error);
- throw new PrincipalOperationException(
- string.Format(CultureInfo.CurrentCulture,
- SR.UnableToOpenToken,
- error));
+ throw new PrincipalOperationException(SR.Format(SR.UnableToOpenToken, error));
}
}
GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetCurrentUserSid: GetTokenInformation (1st try) failed, gle=" + getTokenInfoError);
throw new PrincipalOperationException(
- string.Format(CultureInfo.CurrentCulture, SR.UnableToRetrieveTokenInfo, getTokenInfoError));
+ SR.Format(SR.UnableToRetrieveTokenInfo, getTokenInfoError));
}
// Allocate the necessary buffer.
"GetCurrentUserSid: GetTokenInformation (2nd try) failed, neededBufferSize=" + neededBufferSize + ", gle=" + lastError);
throw new PrincipalOperationException(
- string.Format(CultureInfo.CurrentCulture, SR.UnableToRetrieveTokenInfo, lastError));
+ SR.Format(SR.UnableToRetrieveTokenInfo, lastError));
}
// Retrieve the user's SID from the user info
"GetCurrentUserSid: CopySid failed, errorcode=" + lastError);
throw new PrincipalOperationException(
- string.Format(CultureInfo.CurrentCulture, SR.UnableToRetrieveTokenInfo, lastError));
+ SR.Format(SR.UnableToRetrieveTokenInfo, lastError));
}
return pCopyOfUserSid;
{
GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetMachineDomainSid: LsaOpenPolicy failed, gle=" + SafeNativeMethods.LsaNtStatusToWinError(err));
- throw new PrincipalOperationException(string.Format(CultureInfo.CurrentCulture,
+ throw new PrincipalOperationException(SR.Format(
SR.UnableToRetrievePolicy,
SafeNativeMethods.LsaNtStatusToWinError(err)));
}
{
GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetMachineDomainSid: LsaQueryInformationPolicy failed, gle=" + SafeNativeMethods.LsaNtStatusToWinError(err));
- throw new PrincipalOperationException(string.Format(CultureInfo.CurrentCulture,
+ throw new PrincipalOperationException(SR.Format(
SR.UnableToRetrievePolicy,
SafeNativeMethods.LsaNtStatusToWinError(err)));
}
"GetMachineDomainSid: CopySid failed, errorcode=" + lastError);
throw new PrincipalOperationException(
- string.Format(CultureInfo.CurrentCulture, SR.UnableToRetrievePolicy, lastError));
+ SR.Format(SR.UnableToRetrievePolicy, lastError));
}
return pCopyOfSid;
{
GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetDcName: DsGetDcName failed, err=" + err);
throw new PrincipalOperationException(
- string.Format(
- CultureInfo.CurrentCulture,
+ SR.Format(
SR.UnableToRetrieveDomainInfo,
err));
}
GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "BeginImpersonation: LogonUser failed, gle=" + lastError);
throw new PrincipalOperationException(
- string.Format(CultureInfo.CurrentCulture,
- SR.UnableToImpersonateCredentials,
- lastError));
+ SR.Format(SR.UnableToImpersonateCredentials, lastError));
}
result = UnsafeNativeMethods.ImpersonateLoggedOnUser(hToken);
UnsafeNativeMethods.CloseHandle(hToken);
throw new PrincipalOperationException(
- string.Format(CultureInfo.CurrentCulture,
- SR.UnableToImpersonateCredentials,
- lastError));
+ SR.Format(SR.UnableToImpersonateCredentials, lastError));
}
hUserToken = hToken;
{
GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "IsMachineDC: DsRoleGetPrimaryDomainInformation failed, err=" + err);
throw new PrincipalOperationException(
- string.Format(
- CultureInfo.CurrentCulture,
+ SR.Format(
SR.UnableToRetrieveDomainInfo,
err));
}
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
+ throw new ArgumentException(SR.BerConverterNotMatch);
}
if (!(value[valueCount] is int))
{
// argument is wrong
Debug.WriteLine("type should be int\n");
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
+ throw new ArgumentException(SR.BerConverterNotMatch);
}
// one int argument
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
+ throw new ArgumentException(SR.BerConverterNotMatch);
}
if (!(value[valueCount] is bool))
{
// argument is wrong
Debug.WriteLine("type should be boolean\n");
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
+ throw new ArgumentException(SR.BerConverterNotMatch);
}
// one int argument
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
+ throw new ArgumentException(SR.BerConverterNotMatch);
}
if (value[valueCount] != null && !(value[valueCount] is string))
// argument is wrong
Debug.WriteLine("type should be string, but receiving value has type of ");
Debug.WriteLine(value[valueCount].GetType());
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
+ throw new ArgumentException(SR.BerConverterNotMatch);
}
// one string argument
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
+ throw new ArgumentException(SR.BerConverterNotMatch);
}
if (value[valueCount] != null && !(value[valueCount] is byte[]))
// argument is wrong
Debug.WriteLine("type should be byte[], but receiving value has type of ");
Debug.WriteLine(value[valueCount].GetType());
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
+ throw new ArgumentException(SR.BerConverterNotMatch);
}
byte[] tempValue = (byte[])value[valueCount];
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
+ throw new ArgumentException(SR.BerConverterNotMatch);
}
if (value[valueCount] != null && !(value[valueCount] is string[]))
// argument is wrong
Debug.WriteLine("type should be string[], but receiving value has type of ");
Debug.WriteLine(value[valueCount].GetType());
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
+ throw new ArgumentException(SR.BerConverterNotMatch);
}
string[] stringValues = (string[])value[valueCount];
{
// we don't have enough argument for the format string
Debug.WriteLine("value argument is not valid, valueCount >= value.Length\n");
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
+ throw new ArgumentException(SR.BerConverterNotMatch);
}
if (value[valueCount] != null && !(value[valueCount] is byte[][]))
// argument is wrong
Debug.WriteLine("type should be byte[][], but receiving value has type of ");
Debug.WriteLine(value[valueCount].GetType());
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.BerConverterNotMatch));
+ throw new ArgumentException(SR.BerConverterNotMatch);
}
byte[][] tempValue = (byte[][])value[valueCount];
{
Debug.WriteLine("Format string contains undefined character: ");
Debug.WriteLine(new string(fmt, 1));
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.BerConverterUndefineChar));
+ throw new ArgumentException(SR.BerConverterUndefineChar);
}
// process the return value
else
{
Debug.WriteLine("Format string contains undefined character\n");
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.BerConverterUndefineChar));
+ throw new ArgumentException(SR.BerConverterUndefineChar);
}
if (error != 0)
{
if (value < TimeSpan.Zero)
{
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.NoNegativeTimeLimit), nameof(value));
+ throw new ArgumentException(SR.NoNegativeTimeLimit, nameof(value));
}
_connectionTimeOut = value;
throw new NotSupportedException(SR.NotSupportTransportSMTP);
}
- throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.TransportNotFound , transport.ToString()), typeof(ActiveDirectoryInterSiteTransport), transport.ToString());
+ throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.TransportNotFound, transport.ToString()), typeof(ActiveDirectoryInterSiteTransport), transport.ToString());
}
else
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
default:
// should not happen since we are calling this only internally
- Debug.Assert(false, "ConfigurationSet.GetRoleOwner: Invalid role type.");
+ Debug.Fail("ConfigurationSet.GetRoleOwner: Invalid role type.");
break;
}
entry.RefreshCache();
}
default:
// should not happen since we are calling this only internally
- Debug.Assert(false, "Domain.GetRoleOwner: Invalid role type.");
+ Debug.Fail("Domain.GetRoleOwner: Invalid role type.");
break;
}
default:
// should not happen since we are calling this only internally
- Debug.Assert(false, "Forest.GetRoleOwner: Invalid role type.");
+ Debug.Fail("Forest.GetRoleOwner: Invalid role type.");
break;
}
if (hostName == null)
{
- Debug.Fail(string.Format(CultureInfo.InvariantCulture, "ConfigurationSet::GetReplicaList - no dnsHostName information for replica {0}", ntdsaName));
+ Debug.Fail($"ConfigurationSet::GetReplicaList - no dnsHostName information for replica {ntdsaName}");
if (isADAM)
{
throw new ActiveDirectoryOperationException(SR.Format(SR.NoHostNameOrPortNumber , ntdsaName));
{
if (serverPorts[ntdsaName] == null)
{
- Debug.Fail(string.Format(CultureInfo.InvariantCulture, "ConfigurationSet::GetReplicaList - no port number information for replica {0}", ntdsaName));
+ Debug.Fail($"ConfigurationSet::GetReplicaList - no port number information for replica {ntdsaName}");
throw new ActiveDirectoryOperationException(SR.Format(SR.NoHostNameOrPortNumber , ntdsaName));
}
}
if (err != 0)
{
throw new InvalidOperationException(
- string.Format(
- CultureInfo.CurrentCulture,
+ SR.Format(
SR.UnableToRetrieveDomainInfo,
err));
}
ColorTranslator.ToWin32(background));
if (status == 2 /* invalid parameter*/ && (Width >= short.MaxValue || Height >= short.MaxValue))
{
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidSize));
+ throw new ArgumentException(SR.GdiplusInvalidSize);
}
Gdip.CheckStatus(status);
{
if (RawFormat.Guid == ImageFormat.Icon.Guid)
{
- throw new InvalidOperationException(SR.Format(SR.CantMakeIconTransparent));
+ throw new InvalidOperationException(SR.CantMakeIconTransparent);
}
Size size = Size;
{
if (x < 0 || x >= Width)
{
- throw new ArgumentOutOfRangeException(nameof(x), SR.Format(SR.ValidRangeX));
+ throw new ArgumentOutOfRangeException(nameof(x), SR.ValidRangeX);
}
if (y < 0 || y >= Height)
{
- throw new ArgumentOutOfRangeException(nameof(y), SR.Format(SR.ValidRangeY));
+ throw new ArgumentOutOfRangeException(nameof(y), SR.ValidRangeY);
}
int color = 0;
{
if ((PixelFormat & PixelFormat.Indexed) != 0)
{
- throw new InvalidOperationException(SR.Format(SR.GdiplusCannotSetPixelFromIndexedPixelFormat));
+ throw new InvalidOperationException(SR.GdiplusCannotSetPixelFromIndexedPixelFormat);
}
if (x < 0 || x >= Width)
{
- throw new ArgumentOutOfRangeException(nameof(x), SR.Format(SR.ValidRangeX));
+ throw new ArgumentOutOfRangeException(nameof(x), SR.ValidRangeX);
}
if (y < 0 || y >= Height)
{
- throw new ArgumentOutOfRangeException(nameof(y), SR.Format(SR.ValidRangeY));
+ throw new ArgumentOutOfRangeException(nameof(y), SR.ValidRangeY);
}
int status = Gdip.GdipBitmapSetPixel(new HandleRef(this, nativeImage), x, y, color.ToArgb());
if (hbm == IntPtr.Zero)
{
- throw new OutOfMemoryException(SR.Format(SR.GraphicsBufferQueryFail));
+ throw new OutOfMemoryException(SR.GraphicsBufferQueryFail);
}
pbmi.bmiHeader_biSize = Marshal.SizeOf(typeof(NativeMethods.BITMAPINFOHEADER));
case NativeMethods.OBJ_ENHMETADC:
break;
default:
- throw new ArgumentException(SR.Format(SR.DCTypeInvalid));
+ throw new ArgumentException(SR.DCTypeInvalid);
}
if (FillBitmapInfo(hdc, hpal, ref pbmi))
{
if (oldBusy == BufferBusyPainting)
{
- throw new InvalidOperationException(SR.Format(SR.GraphicsBufferCurrentlyBusy));
+ throw new InvalidOperationException(SR.GraphicsBufferCurrentlyBusy);
}
if (_compatGraphics != null)
public void SetSigmaBellShape(float focus, float scale)
{
if (focus < 0 || focus > 1)
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(focus));
+ throw new ArgumentException(SR.GdiplusInvalidParameter, nameof(focus));
if (scale < 0 || scale > 1)
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(scale));
+ throw new ArgumentException(SR.GdiplusInvalidParameter, nameof(scale));
Gdip.CheckStatus(Gdip.GdipSetLineSigmaBlend(new HandleRef(this, NativeBrush), focus, scale));
}
public void SetBlendTriangularShape(float focus, float scale)
{
if (focus < 0 || focus > 1)
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(focus));
+ throw new ArgumentException(SR.GdiplusInvalidParameter, nameof(focus));
if (scale < 0 || scale > 1)
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(scale));
+ throw new ArgumentException(SR.GdiplusInvalidParameter, nameof(scale));
Gdip.CheckStatus(Gdip.GdipSetLineLinearBlend(new HandleRef(this, NativeBrush), focus, scale));
{
if (!_interpolationColorsWasSet)
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
- SR.Format(SR.InterpolationColorsColorBlendNotSet), string.Empty));
+ SR.InterpolationColorsColorBlendNotSet, string.Empty));
// Figure out the size of blend factor array.
Gdip.CheckStatus(Gdip.GdipGetLinePresetBlendCount(new HandleRef(this, NativeBrush), out int retval));
if (value == null)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
- SR.Format(SR.InterpolationColorsInvalidColorBlendObject), string.Empty));
+ SR.InterpolationColorsInvalidColorBlendObject, string.Empty));
}
else if (value.Colors.Length < 2)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
- SR.Format(SR.InterpolationColorsInvalidColorBlendObject),
- SR.Format(SR.InterpolationColorsLength)));
+ SR.InterpolationColorsInvalidColorBlendObject,
+ SR.InterpolationColorsLength));
}
else if (value.Colors.Length != value.Positions.Length)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
- SR.Format(SR.InterpolationColorsInvalidColorBlendObject),
- SR.Format(SR.InterpolationColorsLengthsDiffer)));
+ SR.InterpolationColorsInvalidColorBlendObject,
+ SR.InterpolationColorsLengthsDiffer));
}
else if (value.Positions[0] != 0.0f)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
- SR.Format(SR.InterpolationColorsInvalidColorBlendObject),
- SR.Format(SR.InterpolationColorsInvalidStartPosition)));
+ SR.InterpolationColorsInvalidColorBlendObject,
+ SR.InterpolationColorsInvalidStartPosition));
}
else if (value.Positions[value.Positions.Length - 1] != 1.0f)
{
throw new ArgumentException(SR.Format(SR.InterpolationColorsCommon,
- SR.Format(SR.InterpolationColorsInvalidColorBlendObject),
- SR.Format(SR.InterpolationColorsInvalidEndPosition)));
+ SR.InterpolationColorsInvalidColorBlendObject,
+ SR.InterpolationColorsInvalidEndPosition));
}
public void SetSigmaBellShape(float focus, float scale)
{
if (focus < 0 || focus > 1)
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(focus));
+ throw new ArgumentException(SR.GdiplusInvalidParameter, nameof(focus));
if (scale < 0 || scale > 1)
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(scale));
+ throw new ArgumentException(SR.GdiplusInvalidParameter, nameof(scale));
Gdip.CheckStatus(Gdip.GdipSetPathGradientSigmaBlend(new HandleRef(this, NativeBrush), focus, scale));
}
public void SetBlendTriangularShape(float focus, float scale)
{
if (focus < 0 || focus > 1)
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(focus));
+ throw new ArgumentException(SR.GdiplusInvalidParameter, nameof(focus));
if (scale < 0 || scale > 1)
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter), nameof(scale));
+ throw new ArgumentException(SR.GdiplusInvalidParameter, nameof(scale));
Gdip.CheckStatus(Gdip.GdipSetPathGradientLinearBlend(new HandleRef(this, NativeBrush), focus, scale));
}
// Special case this incredibly common error message to give more information
if (status == Gdip.NotTrueTypeFont)
{
- throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont_NoName));
+ throw new ArgumentException(SR.GdiplusNotTrueTypeFont_NoName);
}
else if (status != Gdip.Ok)
{
// Special case this incredibly common error message to give more information
if (status == Gdip.NotTrueTypeFont)
{
- throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont_NoName));
+ throw new ArgumentException(SR.GdiplusNotTrueTypeFont_NoName);
}
else if (status != Gdip.Ok)
{
if (image == null)
throw new ArgumentNullException(nameof(image));
if ((image.PixelFormat & PixelFormat.Indexed) != 0)
- throw new ArgumentException(SR.Format(SR.GdiplusCannotCreateGraphicsFromIndexedPixelFormat), nameof(image));
+ throw new ArgumentException(SR.GdiplusCannotCreateGraphicsFromIndexedPixelFormat, nameof(image));
Gdip.CheckStatus(Gdip.GdipGetImageGraphicsContext(
new HandleRef(image, image.nativeImage),
int count = destPoints.Length;
if (count != 3 && count != 4)
- throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidLength));
+ throw new ArgumentException(SR.GdiplusDestPointsInvalidLength);
fixed (PointF* p = destPoints)
{
int count = destPoints.Length;
if (count != 3 && count != 4)
- throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidLength));
+ throw new ArgumentException(SR.GdiplusDestPointsInvalidLength);
fixed (Point* p = destPoints)
{
int count = destPoints.Length;
if (count != 3 && count != 4)
- throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidLength));
+ throw new ArgumentException(SR.GdiplusDestPointsInvalidLength);
fixed (PointF* p = destPoints)
{
int count = destPoints.Length;
if (count != 3 && count != 4)
- throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidLength));
+ throw new ArgumentException(SR.GdiplusDestPointsInvalidLength);
fixed (PointF* p = destPoints)
{
int count = destPoints.Length;
if (count != 3 && count != 4)
- throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidLength));
+ throw new ArgumentException(SR.GdiplusDestPointsInvalidLength);
fixed (Point* p = destPoints)
{
if (destPoints == null)
throw new ArgumentNullException(nameof(destPoints));
if (destPoints.Length != 3)
- throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidParallelogram));
+ throw new ArgumentException(SR.GdiplusDestPointsInvalidParallelogram);
fixed (PointF* p = destPoints)
{
if (destPoints == null)
throw new ArgumentNullException(nameof(destPoints));
if (destPoints.Length != 3)
- throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidParallelogram));
+ throw new ArgumentException(SR.GdiplusDestPointsInvalidParallelogram);
fixed (Point* p = destPoints)
{
if (destPoints == null)
throw new ArgumentNullException(nameof(destPoints));
if (destPoints.Length != 3)
- throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidParallelogram));
+ throw new ArgumentException(SR.GdiplusDestPointsInvalidParallelogram);
fixed (PointF* p = destPoints)
{
if (destPoints == null)
throw new ArgumentNullException(nameof(destPoints));
if (destPoints.Length != 3)
- throw new ArgumentException(SR.Format(SR.GdiplusDestPointsInvalidParallelogram));
+ throw new ArgumentException(SR.GdiplusDestPointsInvalidParallelogram);
fixed (Point* p = destPoints)
{
image = Metafile.FromGDIplus(nativeImage);
break;
default:
- throw new ArgumentException(SR.Format(SR.InvalidImage));
+ throw new ArgumentException(SR.InvalidImage);
}
return image;
internal void SetNativeImage(IntPtr handle)
{
if (handle == IntPtr.Zero)
- throw new ArgumentException(SR.Format(SR.NativeHandle0), nameof(handle));
+ throw new ArgumentException(SR.NativeHandle0, nameof(handle));
nativeImage = handle;
}
{
if (value < 0 || value >= FrameCount)
{
- throw new ArgumentException(SR.Format(SR.InvalidFrame), nameof(value));
+ throw new ArgumentException(SR.InvalidFrame, nameof(value));
}
if (Animated)
Gdip.CheckStatus(status);
if (lineCap == IntPtr.Zero)
{
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter));
+ throw new ArgumentException(SR.GdiplusInvalidParameter);
}
return CustomLineCap.CreateCustomLineCapObject(lineCap);
// If the CustomEndCap has never been set, this accessor should throw.
if (_cachedEndCap == null)
{
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter));
+ throw new ArgumentException(SR.GdiplusInvalidParameter);
}
return _cachedEndCap;
if (value == null || value.Length == 0)
{
- throw new ArgumentException(SR.Format(SR.InvalidDashPattern));
+ throw new ArgumentException(SR.InvalidDashPattern);
}
foreach (float val in value)
{
if (val <= 0)
{
- throw new ArgumentException(SR.Format(SR.InvalidDashPattern));
+ throw new ArgumentException(SR.InvalidDashPattern);
}
}
if (value.Length <= 1)
{
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter));
+ throw new ArgumentException(SR.GdiplusInvalidParameter);
}
foreach (float val in value)
{
if (val < 0 || val > 1)
{
- throw new ArgumentException(SR.Format(SR.GdiplusInvalidParameter));
+ throw new ArgumentException(SR.GdiplusInvalidParameter);
}
}
if(x == null || y == null ||
!(x is int) || !(y is int)) {
- throw new ArgumentException(SR.Format(SR.PropertyValueInvalidEntry));
+ throw new ArgumentException(SR.PropertyValueInvalidEntry);
}
{
if (settings.IsDefaultPrinter)
{
- return SR.Format(SR.InvalidPrinterException_NoDefaultPrinter);
+ return SR.InvalidPrinterException_NoDefaultPrinter;
}
else
{
}
catch (SecurityException)
{
- return SR.Format(SR.InvalidPrinterException_InvalidPrinter, SR.Format(SR.CantTellPrinterName));
+ return SR.Format(SR.InvalidPrinterException_InvalidPrinter, SR.CantTellPrinterName);
}
}
}
public override string ToString()
{
- string ret = "[PageSettings: Color={0}";
- ret += ", Landscape={1}";
- ret += ", Margins={2}";
- ret += ", PaperSize={3}";
- ret += ", PaperSource={4}";
- ret += ", PrinterResolution={5}";
- ret += "]";
-
- return string.Format(ret, this.color, this.landscape, this.margins, this.paperSize, this.paperSource, this.printerResolution);
+ return $"[{nameof(PageSettings)}: {nameof(Color)}={color}, {nameof(Landscape)}={landscape}, {nameof(Margins)}={margins}, {nameof(PaperSize)}={paperSize}, {nameof(PaperSource)}={paperSource}, {nameof(PrinterResolution)}={printerResolution}]";
}
}
}
set
{
if (_kind != PaperKind.Custom && !_createdByDefaultConstructor)
- throw new ArgumentException(SR.Format(SR.PSizeNotCustom));
+ throw new ArgumentException(SR.PSizeNotCustom);
_height = value;
}
}
set
{
if (_kind != PaperKind.Custom && !_createdByDefaultConstructor)
- throw new ArgumentException(SR.Format(SR.PSizeNotCustom));
+ throw new ArgumentException(SR.PSizeNotCustom);
_name = value;
}
}
set
{
if (_kind != PaperKind.Custom && !_createdByDefaultConstructor)
- throw new ArgumentException(SR.Format(SR.PSizeNotCustom));
+ throw new ArgumentException(SR.PSizeNotCustom);
_width = value;
}
}
bool status = SafeNativeMethods.PrintDlg(data);
if (!status)
- return SR.Format(SR.NoDefaultPrinter);
+ return SR.NoDefaultPrinter;
IntPtr handle = data.hDevNames;
IntPtr names = SafeNativeMethods.GlobalLock(new HandleRef(data, handle));
bool status = SafeNativeMethods.PrintDlg(data);
if (!status)
- return SR.Format(SR.NoDefaultPrinter);
+ return SR.NoDefaultPrinter;
IntPtr handle = data.hDevNames;
IntPtr names = SafeNativeMethods.GlobalLock(new HandleRef(data, handle));
data.Flags = SafeNativeMethods.PD_RETURNDEFAULT;
bool status = SafeNativeMethods.PrintDlg(data);
if (!status)
- return SR.Format(SR.NoDefaultPrinter);
+ return SR.NoDefaultPrinter;
IntPtr handle = data.hDevNames;
IntPtr names = SafeNativeMethods.GlobalLock(new HandleRef(data, handle));
bool status = SafeNativeMethods.PrintDlg(data);
if (!status)
- return SR.Format(SR.NoDefaultPrinter);
+ return SR.NoDefaultPrinter;
IntPtr handle = data.hDevNames;
IntPtr names = SafeNativeMethods.GlobalLock(new HandleRef(data, handle));
int width = size.Width * 72 / 100;
int height = size.Height * 72 / 100;
- StringBuilder sb = new StringBuilder();
- sb.Append(
- "copies=" + printer_settings.Copies + " " +
- "Collate=" + printer_settings.Collate + " " +
- "ColorModel=" + (page_settings.Color ? "Color" : "Black") + " " +
- "PageSize=" + string.Format("Custom.{0}x{1}", width, height) + " " +
- "landscape=" + page_settings.Landscape
- );
+ var sb = new StringBuilder();
+ sb.Append("copies=").Append(printer_settings.Copies).Append(' ')
+ .Append("Collate=").Append(printer_settings.Collate).Append(' ')
+ .Append("ColorModel=").Append(page_settings.Color ? "Color" : "Black").Append(' ')
+ .Append("PageSize=Custom.").Append(width).Append('x').Append(height).Append(' ')
+ .Append("landscape=").Append(page_settings.Landscape);
if (printer_settings.CanDuplex)
{
if (printer_settings.Duplex == Duplex.Simplex)
+ {
sb.Append(" Duplex=None");
+ }
else
+ {
sb.Append(" Duplex=DuplexNoTumble");
+ }
}
return LibcupsNative.cupsParseOptions(sb.ToString(), 0, ref options);
public static explicit operator bool (TriState value)
{
if (value.IsDefault)
- throw new InvalidCastException(SR.Format(SR.TriStateCompareError));
+ throw new InvalidCastException(SR.TriStateCompareError);
else
return (value == TriState.True);
}
if(x == null || y == null || width == null || height == null ||
!(x is int) || !(y is int) || !(width is int) || !(height is int) ) {
- throw new ArgumentException(SR.Format(SR.PropertyValueInvalidEntry));
+ throw new ArgumentException(SR.PropertyValueInvalidEntry);
}
return new Rectangle((int)x,
(int)y,
if(width == null || height == null ||
!(width is int) || !(height is int)) {
- throw new ArgumentException(SR.Format(SR.PropertyValueInvalidEntry));
+ throw new ArgumentException(SR.PropertyValueInvalidEntry);
}
return new Size((int)width,
(int)height);
#if GDI_FINALIZATION_WATCH
else
{
- try { Debug.WriteLine(string.Format("Allocation stack:\r\n{0}\r\nDeallocation stack:\r\n{1}", AllocationSite, DeAllocationSite)); } catch {}
+ try { Debug.WriteLine($"Allocation stack:\r\n{AllocationSite}\r\nDeallocation stack:\r\n{DeAllocationSite}"); } catch {}
}
#endif
}
// the hDc will be created on demand.
#if TRACK_HDC
- Debug.WriteLine( DbgUtil.StackTraceToStr(String.Format( "DeviceContext( hWnd=0x{0:x8} )", unchecked((int) hWnd))));
+ Debug.WriteLine( DbgUtil.StackTraceToStr(string.Format( "DeviceContext( hWnd=0x{0:x8} )", unchecked((int) hWnd))));
#endif
}
_hWnd = IntUnsafeNativeMethods.WindowFromDC(new HandleRef(this, _hDC));
}
#if TRACK_HDC
- Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("DeviceContext( hDC=0x{0:X8}, Type={1} )", unchecked((int) hDC), dcType) ));
+ Debug.WriteLine( DbgUtil.StackTraceToStr( string.Format("DeviceContext( hDC=0x{0:X8}, Type={1} )", unchecked((int) hDC), dcType) ));
#endif
}
// CreateDC and CreateIC add an HDC handle to the HandleCollector; to remove it properly we need
// to call DeleteHDC.
#if TRACK_HDC
- Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("DC.DeleteHDC(hdc=0x{0:x8})", unchecked((int) _hDC))));
+ Debug.WriteLine( DbgUtil.StackTraceToStr( string.Format("DC.DeleteHDC(hdc=0x{0:x8})", unchecked((int) _hDC))));
#endif
IntUnsafeNativeMethods.DeleteHDC(new HandleRef(this, _hDC));
// CreatCompatibleDC adds a GDI handle to HandleCollector, to remove it properly we need to call
// DeleteDC.
#if TRACK_HDC
- Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("DC.DeleteDC(hdc=0x{0:x8})", unchecked((int) _hDC))));
+ Debug.WriteLine( DbgUtil.StackTraceToStr( string.Format("DC.DeleteDC(hdc=0x{0:x8})", unchecked((int) _hDC))));
#endif
IntUnsafeNativeMethods.DeleteDC(new HandleRef(this, _hDC));
// For example, the default font is System.
_hDC = IntUnsafeNativeMethods.GetDC(new HandleRef(this, _hWnd));
#if TRACK_HDC
- Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("hdc[0x{0:x8}]=DC.GetHdc(hWnd=0x{1:x8})", unchecked((int) _hDC), unchecked((int) _hWnd))));
+ Debug.WriteLine( DbgUtil.StackTraceToStr( string.Format("hdc[0x{0:x8}]=DC.GetHdc(hWnd=0x{1:x8})", unchecked((int) _hDC), unchecked((int) _hWnd))));
#endif
}
IntUnsafeNativeMethods.ReleaseDC(new HandleRef(this, _hWnd), new HandleRef(this, _hDC));
// Note: retVal == 0 means it was not released but doesn't necessarily means an error; class or private DCs are never released.
#if TRACK_HDC
- Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("[ret={0}]=DC.ReleaseDC(hDc=0x{1:x8}, hWnd=0x{2:x8})", retVal, unchecked((int) _hDC), unchecked((int) _hWnd))));
+ Debug.WriteLine( DbgUtil.StackTraceToStr( string.Format("[ret={0}]=DC.ReleaseDC(hDc=0x{1:x8}, hWnd=0x{2:x8})", retVal, unchecked((int) _hDC), unchecked((int) _hWnd))));
#endif
_hDC = IntPtr.Zero;
}
IntUnsafeNativeMethods.RestoreDC(new HandleRef(this, _hDC), -1);
#if TRACK_HDC
// Note: Winforms may call this method during app exit at which point the DC may have been finalized already causing this assert to popup.
- Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("ret[0]=DC.RestoreHdc(hDc=0x{1:x8}, state={2})", result, unchecked((int) _hDC), restoreState) ));
+ Debug.WriteLine( DbgUtil.StackTraceToStr( string.Format("ret[0]=DC.RestoreHdc(hDc=0x{1:x8}, state={2})", result, unchecked((int) _hDC), restoreState) ));
#endif
Debug.Assert(_contextStack != null, "Someone is calling RestoreHdc() before SaveHdc()");
_contextStack.Push(g);
#if TRACK_HDC
- Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("state[0]=DC.SaveHdc(hDc=0x{1:x8})", state, unchecked((int) _hDC)) ));
+ Debug.WriteLine( DbgUtil.StackTraceToStr( string.Format("state[0]=DC.SaveHdc(hDc=0x{1:x8})", state, unchecked((int) _hDC)) ));
#endif
return state;
{
get
{
- throw new InvalidOperationException(string.Format(SR.IsolatedStorage_CurrentSizeUndefined, nameof(CurrentSize)));
+ throw new InvalidOperationException(SR.Format(SR.IsolatedStorage_CurrentSizeUndefined, nameof(CurrentSize)));
}
}
{
get
{
- throw new InvalidOperationException(string.Format(SR.IsolatedStorage_QuotaIsUndefined, nameof(UsedSize)));
+ throw new InvalidOperationException(SR.Format(SR.IsolatedStorage_QuotaIsUndefined, nameof(UsedSize)));
}
}
{
get
{
- throw new InvalidOperationException(string.Format(SR.IsolatedStorage_QuotaIsUndefined, nameof(AvailableFreeSpace)));
+ throw new InvalidOperationException(SR.Format(SR.IsolatedStorage_QuotaIsUndefined, nameof(AvailableFreeSpace)));
}
}
if (_validQuota)
return _quota;
- throw new InvalidOperationException(string.Format(SR.IsolatedStorage_QuotaIsUndefined, nameof(MaximumSize)));
+ throw new InvalidOperationException(SR.Format(SR.IsolatedStorage_QuotaIsUndefined, nameof(MaximumSize)));
}
}
if (_validQuota)
return (long)_quota;
- throw new InvalidOperationException(string.Format(SR.IsolatedStorage_QuotaIsUndefined, nameof(Quota)));
+ throw new InvalidOperationException(SR.Format(SR.IsolatedStorage_QuotaIsUndefined, nameof(Quota)));
}
internal set
}
catch (FileNotFoundException)
{
- throw new FileNotFoundException(string.Format(SR.PathNotFound_Path, sourceFileName));
+ throw new FileNotFoundException(SR.Format(SR.PathNotFound_Path, sourceFileName));
}
catch (PathTooLongException)
{
}
catch (FileNotFoundException)
{
- throw new FileNotFoundException(string.Format(SR.PathNotFound_Path, sourceFileName));
+ throw new FileNotFoundException(SR.Format(SR.PathNotFound_Path, sourceFileName));
}
catch (PathTooLongException)
{
}
catch (DirectoryNotFoundException)
{
- throw new DirectoryNotFoundException(string.Format(SR.PathNotFound_Path, sourceDirectoryName));
+ throw new DirectoryNotFoundException(SR.Format(SR.PathNotFound_Path, sourceDirectoryName));
}
catch (PathTooLongException)
{
}
catch (XmlException exception)
{
- var r = SR.NotAValidXmlIdString;
- var s = SR.Format(r, id);
- throw new XmlException(s, exception);
+ throw new XmlException(SR.Format(SR.NotAValidXmlIdString, id), exception);
}
}
default:
//Debug.Assert is fine here since the parameters have already been validated. And all the properties are
//readonly
- Debug.Assert(false, "This option should never be called");
+ Debug.Fail("This option should never be called");
break;
}
}
else // An unexpected element is an error.
{
- Debug.Assert(false, "Unknown value type for properties");
+ Debug.Fail("Unknown value type for properties");
}
}
}
// fall-through is not allowed
default:
{
- Debug.Assert(false, "Encountered an invalid CompressionOption enum value");
+ Debug.Fail("Encountered an invalid CompressionOption enum value");
goto case CompressionOption.NotCompressed;
}
}
if (serverEUID != peerID)
{
- throw new UnauthorizedAccessException(string.Format(SR.UnauthorizedAccess_ClientIsNotCurrentUser, peerID, serverEUID));
+ throw new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_ClientIsNotCurrentUser, peerID, serverEUID));
}
}
Interop.Sys.Shutdown(handle, SocketShutdown.Both);
int result = Interop.Serial.SerialPortClose(handle);
- Debug.Assert(result == 0, string.Format(
- "Close failed with result {0} and error {1}",
- result, Interop.Sys.GetLastErrorInfo()));
+ Debug.Assert(result == 0, $"Close failed with result {result} and error {Interop.Sys.GetLastErrorInfo()}");
return result == 0;
}
set
{
if (value < MinDataBits || value > MaxDataBits)
- throw new ArgumentOutOfRangeException(nameof(DataBits), string.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, MinDataBits, MaxDataBits));
+ throw new ArgumentOutOfRangeException(nameof(DataBits), SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, MinDataBits, MaxDataBits));
if (IsOpen)
_internalSerialStream.DataBits = value;
if (!(value is ASCIIEncoding || value is UTF8Encoding || value is UnicodeEncoding || value is UTF32Encoding ||
value.CodePage < 50000 || value.CodePage == 54936))
{
- throw new ArgumentException(string.Format(SR.NotSupportedEncoding, value.WebName), nameof(Encoding));
+ throw new ArgumentException(SR.Format(SR.NotSupportedEncoding, value.WebName), nameof(Encoding));
}
_encoding = value;
if (value == null)
throw new ArgumentNullException(nameof(NewLine));
if (value.Length == 0)
- throw new ArgumentException(string.Format(SR.InvalidNullEmptyArgument, nameof(NewLine)), nameof(NewLine));
+ throw new ArgumentException(SR.Format(SR.InvalidNullEmptyArgument, nameof(NewLine)), nameof(NewLine));
_newLine = value;
}
throw new ArgumentException(SR.PortNameEmpty_String, nameof(PortName));
if (IsOpen)
- throw new InvalidOperationException(string.Format(SR.Cant_be_set_when_open, nameof(PortName)));
+ throw new InvalidOperationException(SR.Format(SR.Cant_be_set_when_open, nameof(PortName)));
_portName = value;
}
}
throw new ArgumentOutOfRangeException(nameof(ReadBufferSize));
if (IsOpen)
- throw new InvalidOperationException(string.Format(SR.Cant_be_set_when_open, nameof(ReadBufferSize)));
+ throw new InvalidOperationException(SR.Format(SR.Cant_be_set_when_open, nameof(ReadBufferSize)));
_readBufferSize = value;
}
throw new ArgumentOutOfRangeException(nameof(WriteBufferSize));
if (IsOpen)
- throw new InvalidOperationException(string.Format(SR.Cant_be_set_when_open, nameof(WriteBufferSize)));
+ throw new InvalidOperationException(SR.Format(SR.Cant_be_set_when_open, nameof(WriteBufferSize)));
_writeBufferSize = value;
}
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value.Length == 0)
- throw new ArgumentException(string.Format(SR.InvalidNullEmptyArgument, nameof(value)), nameof(value));
+ throw new ArgumentException(SR.Format(SR.InvalidNullEmptyArgument, nameof(value)), nameof(value));
int startTicks = Environment.TickCount;
int numCharsRead;
{
if (!pollReadEvents && !pollWriteEvents)
{
- // This should not happen
- Debug.Assert(false);
+ Debug.Fail("This should not happen");
throw new Exception();
}
else
{
// otherwise, we can present the bounds on the baud rate for this driver
- throw new ArgumentOutOfRangeException(nameof(BaudRate), string.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 0, _commProp.dwMaxBaud));
+ throw new ArgumentOutOfRangeException(nameof(BaudRate), SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 0, _commProp.dwMaxBaud));
}
}
// Set only if it's different. Rollback to previous values if setting fails.
}
if (_commProp.dwMaxBaud != 0 && baudRate > _commProp.dwMaxBaud)
- throw new ArgumentOutOfRangeException(nameof(baudRate), string.Format(SR.Max_Baud, _commProp.dwMaxBaud));
+ throw new ArgumentOutOfRangeException(nameof(baudRate), SR.Format(SR.Max_Baud, _commProp.dwMaxBaud));
_comStat = new Interop.Kernel32.COMSTAT();
// create internal DCB structure, initialize according to Platform SDK
else
{
// should not happen
- Debug.Fail(string.Format("Unexpected error code from EscapeCommFunction in SerialPort.Dispose(bool) Error code: 0x{0:x}", (uint)hr));
+ Debug.Fail($"Unexpected error code from EscapeCommFunction in SerialPort.Dispose(bool) Error code: 0x{(uint)hr:x}");
// Do not throw an exception from the finalizer here.
if (disposing)
_dcb.StopBits = NativeMethods.TWOSTOPBITS;
break;
default:
- Debug.Assert(false, "Invalid value for stopBits");
+ Debug.Fail("Invalid value for stopBits");
break;
}
// Ignore ERROR_IO_INCOMPLETE and ERROR_INVALID_PARAMETER, because there's a chance we'll get
// one of those while shutting down
if (!((error == Interop.Errors.ERROR_IO_INCOMPLETE || error == Interop.Errors.ERROR_INVALID_PARAMETER) && ShutdownLoop))
- Debug.Assert(false, "GetOverlappedResult returned error, we might leak intOverlapped memory" + error.ToString(CultureInfo.InvariantCulture));
+ Debug.Fail("GetOverlappedResult returned error, we might leak intOverlapped memory" + error.ToString(CultureInfo.InvariantCulture));
}
}
else if (hr != Interop.Errors.ERROR_INVALID_PARAMETER)
{
// ignore ERROR_INVALID_PARAMETER errors. WaitCommError seems to return this
// when SetCommMask is changed while it's blocking (like we do in Dispose())
- Debug.Assert(false, "WaitCommEvent returned error " + hr);
+ Debug.Fail("WaitCommEvent returned error " + hr);
}
}
}
{
get
{
- Debug.Assert(false, "Unreachable");
+ Debug.Fail("Unreachable");
return new InvalidOperationException("Code supposed to be unreachable");
}
}
private static string QuoteName(string name)
{
- return string.Format(CultureInfo.CurrentCulture, "'{0}'", name);
+ return "'" + name + "'";
}
private static string GetDisplayName(string name)
if (hModule == IntPtr.Zero)
{
// This is unlikely, so having the TypeInitializationException wrapping it is fine.
- throw new Win32Exception(Marshal.GetLastWin32Error(), string.Format(SR.LoadLibraryFailed, wminet_utilsPath));
+ throw new Win32Exception(Marshal.GetLastWin32Error(), SR.Format(SR.LoadLibraryFailed, wminet_utilsPath));
}
if (LoadDelegate(ref ResetSecurity_f, hModule, "ResetSecurity") &&
}
else
{
- LoadPlatformNotSupportedDelegates(string.Format(SR.PlatformNotSupported_FrameworkUpdatedRequired, wminet_utilsPath));
+ LoadPlatformNotSupportedDelegates(SR.Format(SR.PlatformNotSupported_FrameworkUpdatedRequired, wminet_utilsPath));
}
}
static bool LoadDelegate<TDelegate>(ref TDelegate delegate_f, IntPtr hModule, string procName) where TDelegate : class
}
catch
{
- throw new ArgumentOutOfRangeException(string.Format(SR.UnableToCreateCodeGeneratorException , strProvider ));
+ throw new ArgumentOutOfRangeException(SR.Format(SR.UnableToCreateCodeGeneratorException , strProvider ));
}
if(bSucceeded == true)
}
else
{
- throw new ArgumentOutOfRangeException(string.Format(SR.UnableToCreateCodeGeneratorException , strProvider));
+ throw new ArgumentOutOfRangeException(SR.Format(SR.UnableToCreateCodeGeneratorException , strProvider));
}
return true;
}
&& state.ExpectedBytesToRead.HasValue
&& state.CurrentBytesRead < state.ExpectedBytesToRead.Value)
{
- state.LifecycleAwaitable.SetException(new IOException(string.Format(
+ state.LifecycleAwaitable.SetException(new IOException(SR.Format(
SR.net_http_io_read_incomplete,
state.ExpectedBytesToRead.Value,
state.CurrentBytesRead)));
int dispositionTypeLength = GetDispositionTypeExpressionLength(dispositionType, 0, out tempDispositionType);
if ((dispositionTypeLength == 0) || (tempDispositionType.Length != dispositionType.Length))
{
- throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture,
+ throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_headers_invalid_value, dispositionType));
}
}
if (result.IndexOf("\"", 0, StringComparison.Ordinal) >= 0) // Only bounding quotes are allowed.
{
- throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
+ throw new ArgumentException(SR.Format(CultureInfo.InvariantCulture,
SR.net_http_headers_invalid_value, input));
}
else if (RequiresEncoding(result))
if (HttpRuleParser.GetTokenLength(value, 0) != value.Length)
{
- throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
+ throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
}
}
if ((HttpRuleParser.GetCommentLength(value, 0, out length) != HttpParseResult.Parsed) ||
(length != value.Length)) // no trailing spaces allowed
{
- throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
+ throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
}
}
if ((HttpRuleParser.GetQuotedStringLength(value, 0, out length) != HttpParseResult.Parsed) ||
(length != value.Length)) // no trailing spaces allowed
{
- throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
+ throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
}
}
object result = null;
if (!TryParseValue(value, storeValue, ref index, out result))
{
- throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value,
+ throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value,
value == null ? "<null>" : value.Substring(index)));
}
return result;
break;
default:
- Debug.Assert(false, "Unknown StoreLocation value: " + location.ToString());
+ Debug.Fail("Unknown StoreLocation value: " + location.ToString());
break;
}
}
// value already set.
if (!info.CanAddValue(descriptor.Parser))
{
- throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_single_value_header, descriptor.Name));
+ throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_single_value_header, descriptor.Name));
}
int index = 0;
int mediaTypeLength = GetMediaTypeExpressionLength(mediaType, 0, out tempMediaType);
if ((mediaTypeLength == 0) || (tempMediaType.Length != mediaType.Length))
{
- throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, mediaType));
+ throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, mediaType));
}
}
// Either value is null/empty or a valid token/quoted string
if (!(string.IsNullOrEmpty(value) || (GetValueLength(value, 0) == value.Length)))
{
- throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
+ throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value));
}
}
{
// There is some invalid leftover data. Normally BaseHeaderParser.TryParseValue would
// handle this, but ProductInfoHeaderValue does not derive from BaseHeaderParser.
- throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, input.Substring(index)));
+ throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, input.Substring(index)));
}
return (ProductInfoHeaderValue)result;
}
string host = null;
if (HttpRuleParser.GetHostLength(receivedBy, 0, true, out host) != receivedBy.Length)
{
- throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, receivedBy));
+ throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, receivedBy));
}
}
}
if (!HeaderUtilities.TryParseInt32(input, current, codeLength, out code))
{
- Debug.Assert(false, "Unable to parse value even though it was parsed as <=3 digits string. Input: '" +
+ Debug.Fail("Unable to parse value even though it was parsed as <=3 digits string. Input: '" +
input + "', Current: " + current + ", CodeLength: " + codeLength);
return false;
}
string host = null;
if (HttpRuleParser.GetHostLength(agent, 0, true, out host) != agent.Length)
{
- throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, agent));
+ throw new FormatException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, agent));
}
}
}
if (value > HttpContent.MaxBufferSize)
{
throw new ArgumentOutOfRangeException(nameof(value), value,
- string.Format(System.Globalization.CultureInfo.InvariantCulture,
+ SR.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize));
}
CheckDisposedOrStarted();
if (value > HttpContent.MaxBufferSize)
{
throw new ArgumentOutOfRangeException(nameof(value), value,
- string.Format(CultureInfo.InvariantCulture, SR.net_http_content_buffersize_limit,
+ SR.Format(CultureInfo.InvariantCulture, SR.net_http_content_buffersize_limit,
HttpContent.MaxBufferSize));
}
// This should only be hit when called directly; HttpClient/HttpClientHandler
// will not exceed this limit.
throw new ArgumentOutOfRangeException(nameof(maxBufferSize), maxBufferSize,
- string.Format(System.Globalization.CultureInfo.InvariantCulture,
+ SR.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize));
}
if (contentLength > maxBufferSize)
{
- error = new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, maxBufferSize));
+ error = new HttpRequestException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, maxBufferSize));
return null;
}
{
if (!IsSuccessStatusCode)
{
- throw new HttpRequestException(string.Format(
+ throw new HttpRequestException(SR.Format(
System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_message_not_success_statuscode,
(int)_statusCode,
break;
case HttpParseResult.NotParsed:
- Debug.Assert(false, "'NotParsed' is unexpected: We started nested expression " +
+ Debug.Fail("'NotParsed' is unexpected: We started nested expression " +
"parsing, because we found the open-char. So either it's a valid nested " +
"expression or it has invalid format.");
break;
return HttpParseResult.InvalidFormat;
default:
- Debug.Assert(false, "Unknown enum result: " + nestedResult);
+ Debug.Fail("Unknown enum result: " + nestedResult);
break;
}
}
if (boundary.Length > 70)
{
throw new ArgumentOutOfRangeException(nameof(boundary), boundary,
- string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_field_too_long, 70));
+ SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_field_too_long, 70));
}
// Cannot end with space.
if (boundary.EndsWith(" ", StringComparison.Ordinal))
{
- throw new ArgumentException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, boundary), nameof(boundary));
+ throw new ArgumentException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, boundary), nameof(boundary));
}
Contract.EndContractBlock();
}
else
{
- throw new ArgumentException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, boundary), nameof(boundary));
+ throw new ArgumentException(SR.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, boundary), nameof(boundary));
}
}
}
}
if (!UseCookies)
{
- throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
+ throw new InvalidOperationException(SR.Format(CultureInfo.InvariantCulture,
SR.net_http_invalid_enable_first, nameof(UseCookies), "true"));
}
CheckDisposedOrStarted();
CheckDisposedOrStarted();
if (value != null && value != CredentialCache.DefaultCredentials && !(value is NetworkCredential))
{
- throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture,
+ throw new PlatformNotSupportedException(SR.Format(CultureInfo.InvariantCulture,
SR.net_http_value_not_supported, value, nameof(Credentials)));
}
CheckDisposedOrStarted();
if (value != null && value != CredentialCache.DefaultCredentials && !(value is NetworkCredential))
{
- throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture,
+ throw new PlatformNotSupportedException(SR.Format(CultureInfo.InvariantCulture,
SR.net_http_value_not_supported, value, nameof(DefaultProxyCredentials)));
}
{
if (!RTServerCustomValidationRequestedSupported)
{
- throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture,
+ throw new PlatformNotSupportedException(SR.Format(CultureInfo.InvariantCulture,
SR.net_http_feature_requires_Windows10Version1607));
}
}
RTCertificate rtClientCert = await CertificateHelper.ConvertDotNetClientCertToWinRtClientCertAsync(clientCert).ConfigureAwait(false);
if (rtClientCert == null)
{
- throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture,
+ throw new PlatformNotSupportedException(SR.Format(CultureInfo.InvariantCulture,
SR.net_http_feature_UWPClientCertSupportRequiresCertInPersonalCertificateStore));
}
if (string.Equals(request.Method.Method, HttpMethod.Trace.Method, StringComparison.OrdinalIgnoreCase))
{
// https://github.com/dotnet/corefx/issues/22161
- throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture,
+ throw new PlatformNotSupportedException(SR.Format(CultureInfo.InvariantCulture,
SR.net_http_httpmethod_notsupported_error, request.Method.Method));
}
bool endOfMessage)
{
Debug.Assert(messageType == WebSocketMessageType.Binary || messageType == WebSocketMessageType.Text,
- string.Format(CultureInfo.InvariantCulture,
- "The value of 'messageType' ({0}) is invalid. Valid message types: '{1}, {2}'",
- messageType,
- WebSocketMessageType.Binary,
- WebSocketMessageType.Text));
+ $"The value of 'messageType' ({messageType}) is invalid. Valid message types: '{WebSocketMessageType.Binary}, {WebSocketMessageType.Text}'");
if (messageType == WebSocketMessageType.Text)
{
// This indicates a contract violation of the websocket protocol component,
// because we currently don't support any WebSocket extensions and would
// not accept a Websocket handshake requesting extensions
- Debug.Assert(false,
- string.Format(CultureInfo.InvariantCulture,
+ Debug.Fail(string.Format(CultureInfo.InvariantCulture,
"The value of 'bufferType' ({0}) is invalid. Valid buffer types: {1}, {2}, {3}, {4}, {5}.",
bufferType,
WebSocketProtocolComponent.BufferType.Close,
int receiveState;
if ((receiveState = Interlocked.Exchange(ref _receiveState, newReceiveState)) != expectedReceiveState)
{
- Debug.Assert(false,
- string.Format(CultureInfo.InvariantCulture,
- "'_receiveState' had an invalid value '{0}'. The expected value was '{1}'.",
- receiveState,
- expectedReceiveState));
+ Debug.Fail($"'_receiveState' had an invalid value '{receiveState}'. The expected value was '{expectedReceiveState}'.");
}
}
break;
default:
- string assertMessage = string.Format(CultureInfo.InvariantCulture,
- "Invalid action '{0}' returned from WebSocketGetAction.",
- action);
- Debug.Assert(false, assertMessage);
+ Debug.Fail($"Invalid action '{action}' returned from WebSocketGetAction.");
throw new InvalidOperationException();
}
}
_receiveState = ReceiveState.Application;
break;
case ReceiveState.Application:
- Debug.Assert(false, "'originalReceiveState' MUST NEVER be ReceiveState.Application at this point.");
+ Debug.Fail("'originalReceiveState' MUST NEVER be ReceiveState.Application at this point.");
break;
case ReceiveState.PayloadAvailable:
WebSocketReceiveResult receiveResult;
_receiveCompleted = true;
break;
default:
- Debug.Assert(false,
- string.Format(CultureInfo.InvariantCulture, "Invalid ReceiveState '{0}'.", originalReceiveState));
+ Debug.Fail($"Invalid ReceiveState '{originalReceiveState}'.");
break;
}
}
if (previousState != SendBufferState.None)
{
- Debug.Assert(false, "'m_SendBufferState' MUST BE 'None' at this point.");
+ Debug.Fail("'m_SendBufferState' MUST BE 'None' at this point.");
// Indicates a violation in the API contract that could indicate
// memory corruption because the pinned sendbuffer is shared between managed and native code
throw new AccessViolationException();
(int)bufferLength);
}
- Debug.Assert(false, "'buffer' MUST reference a memory segment within the pinned InternalBuffer.");
+ Debug.Fail("'buffer' MUST reference a memory segment within the pinned InternalBuffer.");
// Indicates a violation in the contract with native Websocket.dll and could indicate
// memory corruption because the internal buffer is shared between managed and native code
throw new AccessViolationException();
}
else
{
- Debug.Assert(false, "'buffer' MUST reference a memory segment within the pinned InternalBuffer.");
+ Debug.Fail("'buffer' MUST reference a memory segment within the pinned InternalBuffer.");
// Indicates a violation in the contract with native Websocket.dll and could indicate
// memory corruption because the internal buffer is shared between managed and native code
throw new AccessViolationException();
ThrowIfDisposed();
if (dataBufferCount > dataBuffers.Length)
{
- Debug.Assert(false, "'dataBufferCount' MUST NOT be bigger than 'dataBuffers.Length'.");
+ Debug.Fail("'dataBufferCount' MUST NOT be bigger than 'dataBuffers.Length'.");
// Indicates a violation in the contract with native Websocket.dll and could indicate
// memory corruption because the internal buffer is shared between managed and native code
throw new AccessViolationException();
{
if (!isSendActivity || !isPinnedSendPayloadBuffer)
{
- Debug.Assert(false,
- "'dataBuffer.BufferLength' MUST NOT be bigger than 'm_ReceiveBufferSize' and 'm_SendBufferSize'.");
+ Debug.Fail("'dataBuffer.BufferLength' MUST NOT be bigger than 'm_ReceiveBufferSize' and 'm_SendBufferSize'.");
// Indicates a violation in the contract with native Websocket.dll and could indicate
// memory corruption because the internal buffer is shared between managed and native code
throw new AccessViolationException();
if (!isPinnedSendPayloadBuffer && !IsNativeBuffer(bufferData, bufferLength))
{
- Debug.Assert(false,
- "WebSocketGetAction MUST return a pointer within the pinned internal buffer.");
+ Debug.Fail("WebSocketGetAction MUST return a pointer within the pinned internal buffer.");
// Indicates a violation in the contract with native Websocket.dll and could indicate
// memory corruption because the internal buffer is shared between managed and native code
throw new AccessViolationException();
action != WebSocketProtocolComponent.Action.IndicateReceiveComplete &&
action != WebSocketProtocolComponent.Action.IndicateSendComplete)
{
- Debug.Assert(false, "At least one 'dataBuffer.Buffer' MUST NOT be NULL.");
+ Debug.Fail("At least one 'dataBuffer.Buffer' MUST NOT be NULL.");
}
}
bufferLength = buffer.Data.BufferLength;
break;
default:
- Debug.Assert(false,
- string.Format(CultureInfo.InvariantCulture,
- "BufferType '{0}' is invalid/unknown.",
- bufferType));
+ Debug.Fail($"BufferType '{bufferType}' is invalid/unknown.");
break;
}
}
throw new ObjectDisposedException(GetType().FullName);
}
- Debug.Assert(false, "Only one outstanding async operation is allowed per HttpListenerAsyncEventArgs instance.");
+ Debug.Fail("Only one outstanding async operation is allowed per HttpListenerAsyncEventArgs instance.");
// Only one at a time.
throw new InvalidOperationException();
}
if ((httpHeader.Name == null && length != 0) ||
(httpHeader.Name != null && length != httpHeader.Name.Length))
{
- Debug.Assert(false, "The length of 'httpHeader.Name' MUST MATCH 'length'.");
+ Debug.Fail("The length of 'httpHeader.Name' MUST MATCH 'length'.");
throw new AccessViolationException();
}
if ((httpHeader.Value == null && length != 0) ||
(httpHeader.Value != null && length != httpHeader.Value.Length))
{
- Debug.Assert(false, "The length of 'httpHeader.Value' MUST MATCH 'length'.");
+ Debug.Fail("The length of 'httpHeader.Value' MUST MATCH 'length'.");
throw new AccessViolationException();
}
}
// Either TLS is already established or server does not support TLS
if (!(_connection._networkStream is TlsStream))
{
- throw new SmtpException(SR.Format(SR.MailServerDoesNotSupportStartTls));
+ throw new SmtpException(SR.MailServerDoesNotSupportStartTls);
}
}
Authorization auth = _connection._authenticationModules[_currentModule].Authenticate(_authResponse, null, _connection, _connection._client.TargetName, _connection._channelBindingToken);
if (auth == null)
{
- throw new SmtpException(SR.Format(SR.SmtpAuthenticationFailed));
+ throw new SmtpException(SR.SmtpAuthenticationFailed);
}
IAsyncResult result = AuthCommand.BeginSend(_connection, auth.Message, s_authenticateContinueCallback, this);
{
default:
case SmtpStatusCode.CommandUnrecognized:
- return SR.Format(SR.SmtpCommandUnrecognized);
+ return SR.SmtpCommandUnrecognized;
case SmtpStatusCode.SyntaxError:
- return SR.Format(SR.SmtpSyntaxError);
+ return SR.SmtpSyntaxError;
case SmtpStatusCode.CommandNotImplemented:
- return SR.Format(SR.SmtpCommandNotImplemented);
+ return SR.SmtpCommandNotImplemented;
case SmtpStatusCode.BadCommandSequence:
- return SR.Format(SR.SmtpBadCommandSequence);
+ return SR.SmtpBadCommandSequence;
case SmtpStatusCode.CommandParameterNotImplemented:
- return SR.Format(SR.SmtpCommandParameterNotImplemented);
+ return SR.SmtpCommandParameterNotImplemented;
case SmtpStatusCode.SystemStatus:
- return SR.Format(SR.SmtpSystemStatus);
+ return SR.SmtpSystemStatus;
case SmtpStatusCode.HelpMessage:
- return SR.Format(SR.SmtpHelpMessage);
+ return SR.SmtpHelpMessage;
case SmtpStatusCode.ServiceReady:
- return SR.Format(SR.SmtpServiceReady);
+ return SR.SmtpServiceReady;
case SmtpStatusCode.ServiceClosingTransmissionChannel:
- return SR.Format(SR.SmtpServiceClosingTransmissionChannel);
+ return SR.SmtpServiceClosingTransmissionChannel;
case SmtpStatusCode.ServiceNotAvailable:
- return SR.Format(SR.SmtpServiceNotAvailable);
+ return SR.SmtpServiceNotAvailable;
case SmtpStatusCode.Ok:
- return SR.Format(SR.SmtpOK);
+ return SR.SmtpOK;
case SmtpStatusCode.UserNotLocalWillForward:
- return SR.Format(SR.SmtpUserNotLocalWillForward);
+ return SR.SmtpUserNotLocalWillForward;
case SmtpStatusCode.MailboxBusy:
- return SR.Format(SR.SmtpMailboxBusy);
+ return SR.SmtpMailboxBusy;
case SmtpStatusCode.MailboxUnavailable:
- return SR.Format(SR.SmtpMailboxUnavailable);
+ return SR.SmtpMailboxUnavailable;
case SmtpStatusCode.LocalErrorInProcessing:
- return SR.Format(SR.SmtpLocalErrorInProcessing);
+ return SR.SmtpLocalErrorInProcessing;
case SmtpStatusCode.UserNotLocalTryAlternatePath:
- return SR.Format(SR.SmtpUserNotLocalTryAlternatePath);
+ return SR.SmtpUserNotLocalTryAlternatePath;
case SmtpStatusCode.InsufficientStorage:
- return SR.Format(SR.SmtpInsufficientStorage);
+ return SR.SmtpInsufficientStorage;
case SmtpStatusCode.ExceededStorageAllocation:
- return SR.Format(SR.SmtpExceededStorageAllocation);
+ return SR.SmtpExceededStorageAllocation;
case SmtpStatusCode.MailboxNameNotAllowed:
- return SR.Format(SR.SmtpMailboxNameNotAllowed);
+ return SR.SmtpMailboxNameNotAllowed;
case SmtpStatusCode.StartMailInput:
- return SR.Format(SR.SmtpStartMailInput);
+ return SR.SmtpStartMailInput;
case SmtpStatusCode.TransactionFailed:
- return SR.Format(SR.SmtpTransactionFailed);
+ return SR.SmtpTransactionFailed;
case SmtpStatusCode.ClientNotPermitted:
- return SR.Format(SR.SmtpClientNotPermitted);
+ return SR.SmtpClientNotPermitted;
case SmtpStatusCode.MustIssueStartTlsFirst:
- return SR.Format(SR.SmtpMustIssueStartTlsFirst);
+ return SR.SmtpMustIssueStartTlsFirst;
}
}
}
internal SmtpFailedRecipientsException(List<SmtpFailedRecipientException> innerExceptions, bool allFailed) :
- base(allFailed ? SR.Format(SR.SmtpAllRecipientsFailed) : SR.Format(SR.SmtpRecipientFailed),
+ base(allFailed ? SR.SmtpAllRecipientsFailed : SR.SmtpRecipientFailed,
innerExceptions != null && innerExceptions.Count > 0 ? innerExceptions[0].FailedRecipient : null,
innerExceptions != null && innerExceptions.Count > 0 ? innerExceptions[0] : null)
{
if (!MimeBasePart.IsAscii(name, false))
{
- throw new FormatException(SR.Format(SR.InvalidHeaderName));
+ throw new FormatException(SR.InvalidHeaderName);
}
// normalize the case of well known headers
// outputs the RFC 2822 formatted date string including time zone
public override string ToString() =>
- string.Format("{0} {1}", FormatDate(_date), _unknownTimeZone ? UnknownTimeZoneDefaultOffset : TimeSpanToOffset(_timeZone));
+ FormatDate(_date) + " " + (_unknownTimeZone ? UnknownTimeZoneDefaultOffset : TimeSpanToOffset(_timeZone));
// returns true if the offset is of the form [+|-]dddd and
// within the range 0000 to 9959
private PingReply SendPingCore(IPAddress address, byte[] buffer, int timeout, PingOptions options)
{
// Win32 Icmp* APIs fail with E_ACCESSDENIED when called from UWP due to Windows OS limitations.
- throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture,
+ throw new PlatformNotSupportedException(SR.Format(CultureInfo.InvariantCulture,
SR.net_ping_not_supported_uwp));
}
private Task<PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions options)
{
// Win32 Icmp* APIs fail with E_ACCESSDENIED when called from UWP due to Windows OS limitations.
- throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture,
+ throw new PlatformNotSupportedException(SR.Format(CultureInfo.InvariantCulture,
SR.net_ping_not_supported_uwp));
}
}
{
if (throwOnError)
{
- throw new CookieException(SR.Format(SR.net_cookie_size, cookie.ToString(), m_maxCookieSize));
+ throw new CookieException(SR.Format(SR.net_cookie_size, cookie, m_maxCookieSize));
}
return;
}
{
Exception inner = exception.InnerException;
string message = inner != null ?
- string.Format("{0} {1}", exception.Message, inner.Message) :
+ exception.Message + " " + inner.Message :
exception.Message;
return new WebException(
}
else
{
- throw new IOException(SR.Format(SR.net_io_readfailure, SR.Format(SR.net_io_connectionclosed)));
+ throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed));
}
}
bytesRead = Transport.Read(buffer, offset, buffer.Length - offset);
if (bytesRead == 0)
{
- throw new IOException(SR.Format(SR.net_io_readfailure, SR.Format(SR.net_io_connectionclosed)));
+ throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed));
}
offset += bytesRead;
if (payloadSize < 0)
{
// Let's call user callback and he call us back and we will throw
- workerResult.InvokeCallback(new System.IO.IOException(SR.Format(SR.net_frame_read_size)));
+ workerResult.InvokeCallback(new System.IO.IOException(SR.net_frame_read_size));
}
if (payloadSize == 0)
{
if (level == IPProtectionLevel.Unspecified)
{
- throw new ArgumentException(SR.Format(SR.net_sockets_invalid_optionValue_all), nameof(level));
+ throw new ArgumentException(SR.net_sockets_invalid_optionValue_all, nameof(level));
}
if (_addressFamily == AddressFamily.InterNetworkV6)
const int MaxSelect = 65536;
if (checkRead != null && checkRead.Count > MaxSelect)
{
- throw new ArgumentOutOfRangeException(nameof(checkRead), SR.Format(SR.net_sockets_toolarge_select, nameof(checkRead), MaxSelect.ToString(NumberFormatInfo.CurrentInfo)));
+ throw new ArgumentOutOfRangeException(nameof(checkRead), SR.Format(SR.net_sockets_toolarge_select, nameof(checkRead), MaxSelect.ToString()));
}
if (checkWrite != null && checkWrite.Count > MaxSelect)
{
- throw new ArgumentOutOfRangeException(nameof(checkWrite), SR.Format(SR.net_sockets_toolarge_select, nameof(checkWrite), MaxSelect.ToString(NumberFormatInfo.CurrentInfo)));
+ throw new ArgumentOutOfRangeException(nameof(checkWrite), SR.Format(SR.net_sockets_toolarge_select, nameof(checkWrite), MaxSelect.ToString()));
}
if (checkError != null && checkError.Count > MaxSelect)
{
- throw new ArgumentOutOfRangeException(nameof(checkError), SR.Format(SR.net_sockets_toolarge_select, nameof(checkError), MaxSelect.ToString(NumberFormatInfo.CurrentInfo)));
+ throw new ArgumentOutOfRangeException(nameof(checkError), SR.Format(SR.net_sockets_toolarge_select, nameof(checkError), MaxSelect.ToString()));
}
SocketError errorCode = SocketPal.Select(checkRead, checkWrite, checkError, microSeconds);
{
if (value != null && value.Length > ushort.MaxValue)
{
- throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(CultureInfo.InvariantCulture,SR.net_headers_toolong, ushort.MaxValue));
+ throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(CultureInfo.InvariantCulture,SR.net_headers_toolong, ushort.MaxValue));
}
}
InvalidateCachedArrays();
{
if (value != null && value.Length > ushort.MaxValue)
{
- throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(CultureInfo.InvariantCulture, SR.net_headers_toolong, ushort.MaxValue));
+ throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(CultureInfo.InvariantCulture, SR.net_headers_toolong, ushort.MaxValue));
}
}
this.Set(header.GetName(), value);
{
if (value != null && value.Length > ushort.MaxValue)
{
- throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(CultureInfo.InvariantCulture, SR.net_headers_toolong, ushort.MaxValue));
+ throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(CultureInfo.InvariantCulture, SR.net_headers_toolong, ushort.MaxValue));
}
}
this.Add(header.GetName(), value);
{
if (value != null && value.Length > ushort.MaxValue)
{
- throw new ArgumentOutOfRangeException(nameof(value), value, string.Format(CultureInfo.InvariantCulture, SR.net_headers_toolong, ushort.MaxValue));
+ throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(CultureInfo.InvariantCulture, SR.net_headers_toolong, ushort.MaxValue));
}
}
InvalidateCachedArrays();
{
if (value != null && value.Length > ushort.MaxValue)
{
- throw new ArgumentOutOfRangeException(nameof(value), value,string.Format(CultureInfo.InvariantCulture, SR.net_headers_toolong, ushort.MaxValue));
+ throw new ArgumentOutOfRangeException(nameof(value), value,SR.Format(CultureInfo.InvariantCulture, SR.net_headers_toolong, ushort.MaxValue));
}
}
InvalidateCachedArrays();
{
if (headerValue != null && headerValue.Length > ushort.MaxValue)
{
- throw new ArgumentOutOfRangeException(nameof(headerValue), headerValue, string.Format(CultureInfo.InvariantCulture, SR.net_headers_toolong, ushort.MaxValue));
+ throw new ArgumentOutOfRangeException(nameof(headerValue), headerValue, SR.Format(CultureInfo.InvariantCulture, SR.net_headers_toolong, ushort.MaxValue));
}
}
InvalidateCachedArrays();
{
if (HeaderInfo[headerName].IsRequestRestricted)
{
- throw new ArgumentException(string.Format(SR.net_headerrestrict, headerName), nameof(headerName));
+ throw new ArgumentException(SR.Format(SR.net_headerrestrict, headerName), nameof(headerName));
}
}
else if (_type == WebHeaderCollectionType.HttpListenerResponse)
{
if (HeaderInfo[headerName].IsResponseRestricted)
{
- throw new ArgumentException(string.Format(SR.net_headerrestrict, headerName), nameof(headerName));
+ throw new ArgumentException(SR.Format(SR.net_headerrestrict, headerName), nameof(headerName));
}
}
}
{
if (!MessageWebSocketClientCertificateSupported)
{
- throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture,
+ throw new PlatformNotSupportedException(SR.Format(CultureInfo.InvariantCulture,
SR.net_WebSockets_UWPClientCertSupportRequiresWindows10GreaterThan1703));
}
RTCertificate winRtClientCert = await CertificateHelper.ConvertDotNetClientCertToWinRtClientCertAsync(dotNetClientCert).ConfigureAwait(false);
if (winRtClientCert == null)
{
- throw new PlatformNotSupportedException(string.Format(
+ throw new PlatformNotSupportedException(SR.Format(
CultureInfo.InvariantCulture,
SR.net_WebSockets_UWPClientCertSupportRequiresCertInPersonalCertificateStore));
}
/// <returns>The string representation.</returns>
public override string ToString()
{
- CultureInfo ci = CultureInfo.CurrentCulture;
- return string.Format(ci, "{{ {{M11:{0} M12:{1}}} {{M21:{2} M22:{3}}} {{M31:{4} M32:{5}}} }}",
- M11.ToString(ci), M12.ToString(ci),
- M21.ToString(ci), M22.ToString(ci),
- M31.ToString(ci), M32.ToString(ci));
+ return string.Format(CultureInfo.CurrentCulture, "{{ {{M11:{0} M12:{1}}} {{M21:{2} M22:{3}}} {{M31:{4} M32:{5}}} }}",
+ M11, M12,
+ M21, M22,
+ M31, M32);
}
/// <summary>
/// <returns>The string representation.</returns>
public override string ToString()
{
- CultureInfo ci = CultureInfo.CurrentCulture;
-
- return string.Format(ci, "{{ {{M11:{0} M12:{1} M13:{2} M14:{3}}} {{M21:{4} M22:{5} M23:{6} M24:{7}}} {{M31:{8} M32:{9} M33:{10} M34:{11}}} {{M41:{12} M42:{13} M43:{14} M44:{15}}} }}",
- M11.ToString(ci), M12.ToString(ci), M13.ToString(ci), M14.ToString(ci),
- M21.ToString(ci), M22.ToString(ci), M23.ToString(ci), M24.ToString(ci),
- M31.ToString(ci), M32.ToString(ci), M33.ToString(ci), M34.ToString(ci),
- M41.ToString(ci), M42.ToString(ci), M43.ToString(ci), M44.ToString(ci));
+ return string.Format(CultureInfo.CurrentCulture, "{{ {{M11:{0} M12:{1} M13:{2} M14:{3}}} {{M21:{4} M22:{5} M23:{6} M24:{7}}} {{M31:{8} M32:{9} M33:{10} M34:{11}}} {{M41:{12} M42:{13} M43:{14} M44:{15}}} }}",
+ M11, M12, M13, M14,
+ M21, M22, M23, M24,
+ M31, M32, M33, M34,
+ M41, M42, M43, M44);
}
/// <summary>
/// <returns>The string representation.</returns>
public override string ToString()
{
- CultureInfo ci = CultureInfo.CurrentCulture;
-
- return string.Format(ci, "{{X:{0} Y:{1} Z:{2} W:{3}}}", X.ToString(ci), Y.ToString(ci), Z.ToString(ci), W.ToString(ci));
+ return string.Format(CultureInfo.CurrentCulture, "{{X:{0} Y:{1} Z:{2} W:{3}}}", X, Y, Z, W);
}
/// <summary>
break;
case TypeCode.Char:
DiagnosticUtility.DebugAssert("Char is not a valid schema primitive and should be treated as int in DataContract");
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.CharIsInvalidPrimitive)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.CharIsInvalidPrimitive));
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
if (type == Globals.TypeOfArray)
type = Globals.TypeOfObjectArray;
if (type.GetArrayRank() > 1)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SupportForMultidimensionalArraysNotPresent)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.SupportForMultidimensionalArraysNotPresent));
this.StableName = DataContract.GetStableName(type);
Init(CollectionKind.Array, type.GetElementType(), null);
}
#if uapaot
if (XmlFormatGetOnlyCollectionReaderDelegate == null)
{
- throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, UnderlyingType.ToString()));
+ throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, UnderlyingType));
}
#endif
XmlFormatGetOnlyCollectionReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this);
{
if (DataContractSerializer.Option == SerializationOption.CodeGenOnly)
{
- throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, type.ToString()));
+ throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, type));
}
}
}
DataContract dataContract = s_dataContractCache[id];
if (dataContract == null)
{
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.DataContractCacheOverflow)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.DataContractCacheOverflow));
}
return dataContract;
}
return i;
}
}
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.DataContractCacheOverflow)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.DataContractCacheOverflow));
}
private static bool ContractMatches(DataContract contract, DataContract cachedContract)
if (newSize <= value)
{
DiagnosticUtility.DebugAssert("DataContract cache overflow");
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.Format(SR.DataContractCacheOverflow)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SerializationException(SR.DataContractCacheOverflow));
}
Array.Resize<DataContract>(ref s_dataContractCache, newSize);
}
internal virtual bool IsISerializable
{
get { return false; }
- set { ThrowInvalidDataContractException(SR.Format(SR.RequiresClassDataContractToSetIsISerializable)); }
+ set { ThrowInvalidDataContractException(SR.RequiresClassDataContractToSetIsISerializable); }
}
internal XmlDictionaryString Name
internal static string GetClrTypeFullName(Type type)
{
- return !type.IsGenericTypeDefinition && type.ContainsGenericParameters ? string.Format(CultureInfo.InvariantCulture, "{0}.{1}", type.Namespace, type.Name) : type.FullName;
+ return !type.IsGenericTypeDefinition && type.ContainsGenericParameters ? type.Namespace + "." + type.Name : type.FullName;
}
internal static void GetClrNameAndNamespace(string fullTypeName, out string localName, out string ns)
}
if (maxItemsInObjectGraph < 0)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(maxItemsInObjectGraph), SR.Format(SR.ValueMustBeNonNegative)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(maxItemsInObjectGraph), SR.ValueMustBeNonNegative));
_maxItemsInObjectGraph = maxItemsInObjectGraph;
_ignoreExtensionDataObject = ignoreExtensionDataObject;
set
{
if (value < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.OrderCannotBeNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.OrderCannotBeNegative));
_order = value;
}
}
internal void AddQualifiedNameAttribute(ElementData element, string elementPrefix, string elementName, string elementNs, string valueName, string valueNs)
{
string prefix = ExtensionDataReader.GetPrefix(valueNs);
- element.AddAttribute(elementPrefix, elementNs, elementName, string.Format(CultureInfo.InvariantCulture, "{0}:{1}", prefix, valueName));
+ element.AddAttribute(elementPrefix, elementNs, elementName, prefix + ":" + valueName);
bool prefixDeclaredOnElement = false;
if (element.attributes != null)
tempDelegate = tempDelegate ?? CreateJsonFormatReaderDelegate();
if (tempDelegate == null)
- throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalClassDataContract.UnderlyingType.ToString()));
+ throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalClassDataContract.UnderlyingType));
}
#endif
else
tempDelegate = tempDelegate ?? CreateJsonFormatWriterDelegate();
if (tempDelegate == null)
- throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalClassDataContract.UnderlyingType.ToString()));
+ throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalClassDataContract.UnderlyingType));
}
#endif
else
tempDelegate = tempDelegate ?? CreateJsonFormatReaderDelegate();
if (tempDelegate == null)
- throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalCollectionDataContract.UnderlyingType.ToString()));
+ throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalCollectionDataContract.UnderlyingType));
}
#endif
else
tempDelegate = tempDelegate ?? CreateJsonFormatGetOnlyReaderDelegate();
if (tempDelegate == null)
- throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalCollectionDataContract.UnderlyingType.ToString()));
+ throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalCollectionDataContract.UnderlyingType));
}
#endif
else
tempDelegate = tempDelegate ?? CreateJsonFormatWriterDelegate();
if (tempDelegate == null)
- throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalCollectionDataContract.UnderlyingType.ToString()));
+ throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, TraditionalCollectionDataContract.UnderlyingType));
}
#endif
else
JsonReadWriteDelegates result = GetGeneratedReadWriteDelegates(c);
if (result == null)
{
- throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, c.UnderlyingType.ToString()));
+ throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, c.UnderlyingType));
}
else
{
}
}
}
-}
\ No newline at end of file
+}
}
// m_obj must ALWAYS have at least one slot empty (null).
DiagnosticUtility.DebugAssert("Object table overflow");
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ObjectTableOverflow)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.ObjectTableOverflow));
}
private void RemoveAt(int position)
}
// m_obj must ALWAYS have at least one slot empty (null).
DiagnosticUtility.DebugAssert("Object table overflow");
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ObjectTableOverflow)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.ObjectTableOverflow));
}
private int ComputeStartPosition(object o)
// 0X7FEFFFFF is not prime, but it is the largest possible array size. There's nowhere to go from here.
};
}
-}
\ No newline at end of file
+}
{
return ProcessClassDataContract((ClassDataContract)contract, context, memberNode);
}
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.QueryGeneratorPathToMemberNotFound)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.QueryGeneratorPathToMemberNotFound));
}
static DataContract ProcessClassDataContract(ClassDataContract contract, ExportContext context, MemberInfo memberNode)
return member.MemberTypeContract;
}
}
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.QueryGeneratorPathToMemberNotFound)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.QueryGeneratorPathToMemberNotFound));
}
static IEnumerable<DataMember> GetDataMembers(ClassDataContract contract)
}
}
}
-}
\ No newline at end of file
+}
#endif
{
if (!xmlReader.Read())
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnexpectedEndOfFile)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile));
}
internal static void ParseQualifiedName(string qname, XmlReaderDelegator xmlReader, out string name, out string ns, out string prefix)
while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement)
{
if (xmlReader.EOF)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnexpectedEndOfFile)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile));
if (xmlChildNodes == null)
xmlChildNodes = new List<XmlNode>();
}
}
else if (xmlReader.EOF)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnexpectedEndOfFile)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile));
else if (IsContentNode(xmlReader.NodeType))
couldBeClassData = couldBeISerializableData = couldBeCollectionData = false;
if (isNew)
{
xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.IdLocalName,
- DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", objectId));
+ DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "i{0}", objectId));
return false;
}
else
{
- xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "{0}{1}", "i", objectId));
+ xmlWriter.WriteAttributeString(Globals.SerPrefix, DictionaryGlobals.RefLocalName, DictionaryGlobals.SerializationNamespace, string.Format(CultureInfo.InvariantCulture, "i{0}", objectId));
return true;
}
}
internal string GetAttribute(int i)
{
if (isEndOfEmptyElement)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(i), SR.Format(SR.XmlElementAttributes)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(i), SR.XmlElementAttributes));
return reader.GetAttribute(i);
}
internal void MoveToAttribute(int i)
{
if (isEndOfEmptyElement)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(i), SR.Format(SR.XmlElementAttributes)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(i), SR.XmlElementAttributes));
reader.MoveToAttribute(i);
}
public override void Close()
{
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IXmlSerializableIllegalOperation)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.IXmlSerializableIllegalOperation));
}
public override XmlReaderSettings Settings { get { return InnerReader.Settings; } }
public override void Close()
{
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IXmlSerializableIllegalOperation)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.IXmlSerializableIllegalOperation));
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
Type type = knownTypes[i];
if (type == null)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.CannotExportNullKnownType)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.CannotExportNullKnownType));
AddType(type);
}
}
}
-}
\ No newline at end of file
+}
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.ValueMustBeNonNegative));
if ((charCount % 4) != 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString(NumberFormatInfo.CurrentInfo))));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString())));
return charCount / 4 * 3;
}
if (chars == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars)));
if (index < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.ValueMustBeNonNegative));
if (index > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > chars.Length - index)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - index)));
if (count == 0)
return 0;
if ((count % 4) != 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, count.ToString(NumberFormatInfo.CurrentInfo))));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, count.ToString())));
fixed (byte* _char2val = &s_char2val[0])
{
fixed (char* _chars = &chars[index])
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars)));
if (charIndex < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative));
if (charIndex > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (charCount < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.ValueMustBeNonNegative));
if (charCount > chars.Length - charIndex)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex)));
if (bytes == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(bytes)));
if (byteIndex < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative));
if (byteIndex > bytes.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length)));
if (charCount == 0)
return 0;
if ((charCount % 4) != 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString(NumberFormatInfo.CurrentInfo))));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString())));
fixed (byte* _char2val = &s_char2val[0])
{
fixed (char* _chars = &chars[charIndex])
int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1));
if (pb + byteCount > pbMax)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlArrayTooSmall), nameof(bytes)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlArrayTooSmall, nameof(bytes)));
pb[0] = (byte)((v1 << 2) | ((v2 >> 4) & 0x03));
if (byteCount > 1)
if (chars == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars)));
if (charIndex < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative));
if (charIndex > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (charCount < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.ValueMustBeNonNegative));
if (charCount > chars.Length - charIndex)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - charIndex)));
if (bytes == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(bytes)));
if (byteIndex < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative));
if (byteIndex > bytes.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length)));
if (charCount == 0)
return 0;
if ((charCount % 4) != 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString(NumberFormatInfo.CurrentInfo))));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidBase64Length, charCount.ToString())));
fixed (byte* _char2val = &s_char2val[0])
{
fixed (byte* _chars = &chars[charIndex])
int byteCount = (v4 != 64 ? 3 : (v3 != 64 ? 2 : 1));
if (pb + byteCount > pbMax)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlArrayTooSmall), nameof(bytes)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlArrayTooSmall, nameof(bytes)));
pb[0] = (byte)((v1 << 2) | ((v2 >> 4) & 0x03));
if (byteCount > 1)
if (bytes == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(bytes)));
if (byteIndex < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative));
if (byteIndex > bytes.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length)));
if (byteCount < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.ValueMustBeNonNegative));
if (byteCount > bytes.Length - byteIndex)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex)));
if (chars == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars)));
if (charIndex < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative));
if (charIndex > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (charCount < 0 || charCount > chars.Length - charIndex)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlArrayTooSmall), nameof(chars)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlArrayTooSmall, nameof(chars)));
// We've computed exactly how many chars there are and verified that
// there's enough space in the char buffer, so we can proceed without
if (bytes == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(bytes)));
if (byteIndex < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.ValueMustBeNonNegative));
if (byteIndex > bytes.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteIndex), SR.Format(SR.OffsetExceedsBufferSize, bytes.Length)));
if (byteCount < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.ValueMustBeNonNegative));
if (byteCount > bytes.Length - byteIndex)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(byteCount), SR.Format(SR.SizeExceedsRemainingBufferSpace, bytes.Length - byteIndex)));
if (chars == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars)));
if (charIndex < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.ValueMustBeNonNegative));
if (charIndex > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(charIndex), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (charCount < 0 || charCount > chars.Length - charIndex)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlArrayTooSmall), nameof(chars)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlArrayTooSmall, nameof(chars)));
// We've computed exactly how many chars there are and verified that
// there's enough space in the char buffer, so we can proceed without
if (charCount < 0)
throw new ArgumentOutOfRangeException(nameof(charCount), SR.ValueMustBeNonNegative);
if ((charCount % 2) != 0)
- throw new FormatException(SR.Format(SR.XmlInvalidBinHexLength, charCount.ToString(NumberFormatInfo.CurrentInfo)));
+ throw new FormatException(SR.Format(SR.XmlInvalidBinHexLength, charCount.ToString()));
return charCount / 2;
}
return charCount;
}
}
-}
\ No newline at end of file
+}
if (guid == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(guid)));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > guid.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, guid.Length)));
if (guidLength > guid.Length - offset)
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value));
if (value.Length == 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidUniqueId)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.XmlInvalidUniqueId));
fixed (char* pch = value)
{
UnsafeParse(pch, value.Length);
if (chars == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars)));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > chars.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - offset)));
if (count == 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.Format(SR.XmlInvalidUniqueId)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(SR.XmlInvalidUniqueId));
fixed (char* pch = &chars[offset])
{
UnsafeParse(pch, count);
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars)));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer)));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > buffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, buffer.Length)));
pb[3] = (byte)value;
}
}
-}
\ No newline at end of file
+}
protected XmlDeclarationNode MoveToDeclaration()
{
if (_attributeCount < 1)
- XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlDeclMissingVersion)));
+ XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlDeclMissingVersion));
if (_attributeCount > 3)
- XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlMalformedDecl)));
+ XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlMalformedDecl));
// version
if (!CheckDeclAttribute(0, "version", "1.0", false, SR.XmlInvalidVersion))
- XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlDeclMissingVersion)));
+ XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlDeclMissingVersion));
// encoding/standalone
// We only validate that they are the only attributes that exist. Encoding can have any value.
if (CheckDeclAttribute(1, "encoding", null, true, SR.XmlInvalidEncoding_UTF8))
{
if (_attributeCount == 3 && !CheckStandalone(2))
- XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlMalformedDecl)));
+ XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlMalformedDecl));
}
else if (!CheckStandalone(1) || _attributeCount > 2)
{
- XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlMalformedDecl)));
+ XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlMalformedDecl));
}
}
{
XmlAttributeNode node = _attributeNodes[attr];
if (!node.Prefix.IsEmpty)
- XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlMalformedDecl)));
+ XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlMalformedDecl));
if (node.LocalName != "standalone")
return false;
if (!node.Value.Equals2("yes", false) && !node.Value.Equals2("no", false))
- XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlInvalidStandalone)));
+ XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlInvalidStandalone));
return true;
}
{
XmlAttributeNode node = _attributeNodes[index];
if (!node.Prefix.IsEmpty)
- XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlMalformedDecl)));
+ XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlMalformedDecl));
if (node.LocalName != localName)
return false;
private XmlAttributeNode GetAttributeNode(int index)
{
if (!_node.CanGetAttribute)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.XmlElementAttributes)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.XmlElementAttributes));
if (index < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.ValueMustBeNonNegative));
if (index >= _attributeCount)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.OffsetExceedsBufferSize, _attributeCount)));
return _attributeNodes[index];
if (chars == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars)));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > chars.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - offset)));
int actual;
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer)));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > buffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, buffer.Length)));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > buffer.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
if (count == 0)
{
int nodeDepth = _node.NodeType == XmlNodeType.Element ? _depth - 1 : _depth;
if (nodeDepth == 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlEndElementNoOpenNodes)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlEndElementNoOpenNodes));
// If depth is non-zero, then the document isn't what was expected
XmlElementNode elementNode = _elementNodes[nodeDepth];
XmlExceptionHelper.ThrowEndElementExpected(this, elementNode.LocalName.GetString(), elementNode.Namespace.Uri.GetString());
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer)));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > buffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, buffer.Length)));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > buffer.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
if (count == 0)
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer)));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > buffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, buffer.Length)));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > buffer.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
if (count == 0)
public override void ResolveEntity()
{
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidOperation)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlInvalidOperation));
}
public override void Skip()
public override void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes)
{
if (_signing)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlCanonicalizationStarted)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlCanonicalizationStarted));
if (_signingWriter == null)
_signingWriter = CreateSigningNodeWriter();
public override void EndCanonicalization()
{
if (!_signing)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlCanonicalizationNotStarted)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlCanonicalizationNotStarted));
_signingWriter.Flush();
_signingWriter.Close();
protected void ThrowClosed()
{
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlWriterClosed)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlWriterClosed));
}
private static BinHexEncoding BinHexEncoding
{
// An empty namespace means no namespace; prefix must be empty
if (prefix.Length != 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlEmptyNamespaceRequiresNullPrefix), nameof(prefix)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlEmptyNamespaceRequiresNullPrefix, nameof(prefix)));
}
else if (prefix.Length == 0)
{
}
else if (text.IndexOf("--", StringComparison.Ordinal) != -1 || (text.Length > 0 && text[text.Length - 1] == '-'))
{
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlInvalidCommentChars), nameof(text)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlInvalidCommentChars, nameof(text)));
}
StartComment();
ThrowClosed();
if (_documentState == DocumentState.Epilog)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlOnlyOneRoot)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlOnlyOneRoot));
if (localName == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName)));
if (localName.Length == 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.InvalidLocalNameEmpty), nameof(localName)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.InvalidLocalNameEmpty, nameof(localName)));
if (_writeState == WriteState.Attribute)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteStartElement", WriteState.ToString())));
ThrowClosed();
if (_documentState == DocumentState.Epilog)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlOnlyOneRoot)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlOnlyOneRoot));
if (localName == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName)));
if (localName.Length == 0)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.InvalidLocalNameEmpty), nameof(localName)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.InvalidLocalNameEmpty, nameof(localName)));
if (_writeState == WriteState.Attribute)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteStartElement", WriteState.ToString())));
}
{
FlushElement();
if (_depth == 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlIllegalOutsideRoot)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlIllegalOutsideRoot));
}
protected async Task StartContentAsync()
{
await FlushElementAsync().ConfigureAwait(false);
if (_depth == 0)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlIllegalOutsideRoot)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlIllegalOutsideRoot));
}
protected void StartContent(char ch)
private void VerifyWhitespace(char ch)
{
if (!IsWhitespace(ch))
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlIllegalOutsideRoot)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlIllegalOutsideRoot));
}
private void VerifyWhitespace(string s)
{
for (int i = 0; i < s.Length; i++)
if (!IsWhitespace(s[i]))
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlIllegalOutsideRoot)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlIllegalOutsideRoot));
}
private void VerifyWhitespace(char[] chars, int offset, int count)
{
for (int i = 0; i < count; i++)
if (!IsWhitespace(chars[offset + i]))
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlIllegalOutsideRoot)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlIllegalOutsideRoot));
}
private bool IsWhitespace(char ch)
if (localName == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName)));
if (localName.Length == 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.InvalidLocalNameEmpty), nameof(localName)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.InvalidLocalNameEmpty, nameof(localName)));
if (namespaceUri == null)
namespaceUri = string.Empty;
string prefix = GetQualifiedNamePrefix(namespaceUri, null);
if (localName == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName)));
if (localName.Value.Length == 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.InvalidLocalNameEmpty), nameof(localName)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.InvalidLocalNameEmpty, nameof(localName)));
if (namespaceUri == null)
namespaceUri = XmlDictionaryString.Empty;
string prefix = GetQualifiedNamePrefix(namespaceUri.Value, namespaceUri);
ThrowClosed();
if (name != "xml")
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlProcessingInstructionNotSupported), nameof(name)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlProcessingInstructionNotSupported, nameof(name)));
if (_writeState != WriteState.Start)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidDeclaration)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlInvalidDeclaration));
// The only thing the text can legitimately contain is version, encoding, and standalone.
// We only support version 1.0, we can only write whatever encoding we were supplied,
ThrowClosed();
if (_writeState == WriteState.Start || _writeState == WriteState.Prolog)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlNoRootElement)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlNoRootElement));
FinishDocument();
_writeState = WriteState.Start;
c != '\t' &&
c != '\n' &&
c != '\r')
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlOnlyWhitespace), nameof(whitespace)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlOnlyWhitespace, nameof(whitespace)));
}
WriteString(whitespace);
// Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does.
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > chars.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - offset)));
// Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does.
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > chars.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - offset)));
ThrowClosed();
if (ch >= 0xd800 && ch <= 0xdfff)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlMissingLowSurrogate), nameof(ch)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlMissingLowSurrogate, nameof(ch)));
if (_attributeValue != null)
WriteAttributeText(ch.ToString());
}
else if (value.GetType().IsArray)
{
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlNestedArraysNotSupported), nameof(value)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlNestedArraysNotSupported, nameof(value)));
}
else
{
// Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does.
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > buffer.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
// Not checking upper bound because it will be caught by "count". This is what XmlTextWriter does.
if (offset < 0)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (count < 0)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > buffer.Length - offset)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
if (IsClosed)
ThrowClosed();
if (Signing)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlCanonicalizationStarted)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlCanonicalizationStarted));
FlushElement();
if (_signingWriter == null)
_signingWriter = CreateSigningNodeWriter();
if (IsClosed)
ThrowClosed();
if (!Signing)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlCanonicalizationNotStarted)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlCanonicalizationNotStarted));
_signingWriter.Flush();
_writer = _signingWriter.NodeWriter;
}
{
FlushBase64();
if (_documentState == DocumentState.Epilog)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlOnlyOneRoot)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlOnlyOneRoot));
if (_documentState == DocumentState.Document && count > 1 && _depth == 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlOnlyOneRoot)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlOnlyOneRoot));
if (_writeState == WriteState.Attribute)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteStartElement", WriteState.ToString())));
AutoComplete(WriteState.Content);
return;
if (prefix == "xmlns" && uri == xmlnsNamespace)
return;
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlReservedPrefix), nameof(prefix)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlReservedPrefix, nameof(prefix)));
}
}
Namespace nameSpace;
}
}
if (prefix.Length != 0 && uri.Length == 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlEmptyNamespaceRequiresNullPrefix), nameof(prefix)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.XmlEmptyNamespaceRequiresNullPrefix, nameof(prefix)));
if (uri.Length == xmlnsNamespace.Length && uri == xmlnsNamespace)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlSpecificBindingNamespace, "xmlns", uri)));
// The addressing namespace and the xmlNamespace are the same length, so add a quick check to try to disambiguate
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(buffer));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > buffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, buffer.Length)));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > buffer.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
MoveToInitial(quotas, session, null);
if (array == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(array)));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > array.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, array.Length)));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > array.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
}
return new XmlSigningNodeWriter(false);
}
}
-}
\ No newline at end of file
+}
public XmlDictionaryString Add(int id, string value)
{
if (id < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(id), SR.Format(SR.XmlInvalidID)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(id), SR.XmlInvalidID));
if (value == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value));
XmlDictionaryString xmlString;
if (TryLookup(id, out xmlString))
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlIDDefined)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlIDDefined));
xmlString = new XmlDictionaryString(this, value, id);
if (id >= MaxArrayEntries)
private void WroteAttributeValue()
{
if (_wroteAttributeValue && !_inList)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlOnlySingleValue)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlOnlySingleValue));
_wroteAttributeValue = true;
}
if (array == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(array)));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > array.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, array.Length)));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > array.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
}
}
}
}
-}
\ No newline at end of file
+}
if (key != -1)
{
// If the key is already set, then something is wrong
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlKeyAlreadyExists)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlKeyAlreadyExists));
}
key = Add(value.Value);
{
if (inclusivePrefixes[i] == null)
{
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.InvalidInclusivePrefixListCollection));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.InvalidInclusivePrefixListCollection);
}
_inclusivePrefixes[i] = inclusivePrefixes[i];
}
if (prefixBuffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(prefixBuffer)));
if (prefixOffset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixOffset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixOffset), SR.ValueMustBeNonNegative));
if (prefixOffset > prefixBuffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixOffset), SR.Format(SR.OffsetExceedsBufferSize, prefixBuffer.Length)));
if (prefixLength < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixLength), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixLength), SR.ValueMustBeNonNegative));
if (prefixLength > prefixBuffer.Length - prefixOffset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixLength), SR.Format(SR.SizeExceedsRemainingBufferSpace, prefixBuffer.Length - prefixOffset)));
if (localNameBuffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localNameBuffer)));
if (localNameOffset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(localNameOffset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(localNameOffset), SR.ValueMustBeNonNegative));
if (localNameOffset > localNameBuffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(localNameOffset), SR.Format(SR.OffsetExceedsBufferSize, localNameBuffer.Length)));
if (localNameLength < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(localNameLength), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(localNameLength), SR.ValueMustBeNonNegative));
if (localNameLength > localNameBuffer.Length - localNameOffset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(localNameLength), SR.Format(SR.SizeExceedsRemainingBufferSpace, localNameBuffer.Length - localNameOffset)));
ThrowIfClosed();
if (prefixBuffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(prefixBuffer)));
if (prefixOffset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixOffset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixOffset), SR.ValueMustBeNonNegative));
if (prefixOffset > prefixBuffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixOffset), SR.Format(SR.OffsetExceedsBufferSize, prefixBuffer.Length)));
if (prefixLength < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixLength), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixLength), SR.ValueMustBeNonNegative));
if (prefixLength > prefixBuffer.Length - prefixOffset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixLength), SR.Format(SR.SizeExceedsRemainingBufferSpace, prefixBuffer.Length - prefixOffset)));
if (nsBuffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(nsBuffer)));
if (nsOffset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(nsOffset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(nsOffset), SR.ValueMustBeNonNegative));
if (nsOffset > nsBuffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(nsOffset), SR.Format(SR.OffsetExceedsBufferSize, nsBuffer.Length)));
if (nsLength < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(nsLength), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(nsLength), SR.ValueMustBeNonNegative));
if (nsLength > nsBuffer.Length - nsOffset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(nsLength), SR.Format(SR.SizeExceedsRemainingBufferSpace, nsBuffer.Length - nsOffset)));
ThrowIfClosed();
if (prefixBuffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(prefixBuffer)));
if (prefixOffset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixOffset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixOffset), SR.ValueMustBeNonNegative));
if (prefixOffset > prefixBuffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixOffset), SR.Format(SR.OffsetExceedsBufferSize, prefixBuffer.Length)));
if (prefixLength < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixLength), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixLength), SR.ValueMustBeNonNegative));
if (prefixLength > prefixBuffer.Length - prefixOffset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(prefixLength), SR.Format(SR.SizeExceedsRemainingBufferSpace, prefixBuffer.Length - prefixOffset)));
if (localNameBuffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localNameBuffer)));
if (localNameOffset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(localNameOffset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(localNameOffset), SR.ValueMustBeNonNegative));
if (localNameOffset > localNameBuffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(localNameOffset), SR.Format(SR.OffsetExceedsBufferSize, localNameBuffer.Length)));
if (localNameLength < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(localNameLength), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(localNameLength), SR.ValueMustBeNonNegative));
if (localNameLength > localNameBuffer.Length - localNameOffset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(localNameLength), SR.Format(SR.SizeExceedsRemainingBufferSpace, localNameBuffer.Length - localNameOffset)));
ThrowIfClosed();
if (chars == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars)));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > chars.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - offset)));
ThrowIfClosed();
if (chars == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars)));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > chars.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - offset)));
if (_inStartElement)
if (chars == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(chars)));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > chars.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, chars.Length)));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > chars.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, chars.Length - offset)));
if (_inStartElement)
if (this.IsEmptyElement)
return string.Empty;
if (!Read())
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidOperation)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlInvalidOperation));
if (this.NodeType == XmlNodeType.EndElement)
return string.Empty;
}
sb.Append(value);
}
if (!Read())
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidOperation)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlInvalidOperation));
}
if (sb != null)
result = sb.ToString();
if (array == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(array)));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > array.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, array.Length)));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > array.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
}
if (quotas == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(quotas)));
if (quotas._readOnly)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.QuotaCopyReadOnly)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.QuotaCopyReadOnly));
InternalCopyTo(quotas);
}
if (_readOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.QuotaIsReadOnly, "MaxStringContentLength")));
if (value <= 0)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.QuotaMustBePositive), nameof(value)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.QuotaMustBePositive, nameof(value)));
_maxStringContentLength = value;
_modifiedQuotas |= XmlDictionaryReaderQuotaTypes.MaxStringContentLength;
}
if (_readOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.QuotaIsReadOnly, "MaxArrayLength")));
if (value <= 0)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.QuotaMustBePositive), nameof(value)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.QuotaMustBePositive, nameof(value)));
_maxArrayLength = value;
_modifiedQuotas |= XmlDictionaryReaderQuotaTypes.MaxArrayLength;
}
if (_readOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.QuotaIsReadOnly, "MaxBytesPerRead")));
if (value <= 0)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.QuotaMustBePositive), nameof(value)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.QuotaMustBePositive, nameof(value)));
_maxBytesPerRead = value;
_modifiedQuotas |= XmlDictionaryReaderQuotaTypes.MaxBytesPerRead;
if (_readOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.QuotaIsReadOnly, "MaxDepth")));
if (value <= 0)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.QuotaMustBePositive), nameof(value)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.QuotaMustBePositive, nameof(value)));
_maxDepth = value;
_modifiedQuotas |= XmlDictionaryReaderQuotaTypes.MaxDepth;
if (_readOnly)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.QuotaIsReadOnly, "MaxNameTableCharCount")));
if (value <= 0)
- throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.QuotaMustBePositive), nameof(value)));
+ throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.QuotaMustBePositive, nameof(value)));
_maxNameTableCharCount = value;
_modifiedQuotas |= XmlDictionaryReaderQuotaTypes.MaxNameTableCharCount;
Stream stream = value.GetStream();
if (stream == null)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.XmlInvalidStream)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.XmlInvalidStream));
int blockSize = 256;
int bytesRead = 0;
byte[] block = new byte[blockSize];
if (array == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(array)));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > array.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, array.Length)));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > array.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset)));
}
private static string GetWhatWasFound(XmlDictionaryReader reader)
{
if (reader.EOF)
- return SR.Format(SR.XmlFoundEndOfFile);
+ return SR.XmlFoundEndOfFile;
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (buffer == null)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer)));
if (offset < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.ValueMustBeNonNegative));
if (offset > buffer.Length)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(offset), SR.Format(SR.OffsetExceedsBufferSize, buffer.Length)));
if (count < 0)
- throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ValueMustBeNonNegative)));
+ throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.ValueMustBeNonNegative));
if (count > buffer.Length - offset)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset)));
MoveToInitial(quotas, onClose);
break;
if (!space)
- XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlSpaceBetweenAttributes)));
+ XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlSpaceBetweenAttributes));
}
if (_buffered && (BufferReader.Offset - startOffset) > _maxBytesPerRead)
byte[] buff = BufferReader.GetBuffer(3, out off);
if (buff[off + 1] == 0xBF && (buff[off + 2] == 0xBE || buff[off + 2] == 0xBF))
{
- XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlInvalidFFFE)));
+ XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlInvalidFFFE));
}
BufferReader.Advance(3);
}
{
if (buffer[offset + 2] == (byte)'>')
break;
- XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlInvalidCommentChars)));
+ XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlInvalidCommentChars));
}
BufferReader.SkipByte();
}
}
else
{
- XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlInvalidFFFE)));
+ XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlInvalidFFFE));
}
}
else
else
{
if (OutsideRootElement)
- XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlCDATAInvalidAtTopLevel)));
+ XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlCDATAInvalidAtTopLevel));
ReadCData();
}
buffer[offset + 1] == (byte)']' &&
buffer[offset + 2] == (byte)'>')
{
- XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.Format(SR.XmlCloseCData)));
+ XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlCloseCData));
}
BufferReader.SkipByte();
{
int val = portStr[idx] - '0';
if (val < 0 || val > 9 || (port = (port * 10 + val)) > 0xFFFF)
- throw new UriFormatException(SR.Format(SR.net_uri_PortOutOfRange, _syntax.GetType().ToString(), portStr));
+ throw new UriFormatException(SR.Format(SR.net_uri_PortOutOfRange, _syntax.GetType(), portStr));
}
if (port != _info.Offset.PortValue)
{
internal unsafe bool InternalIsWellFormedOriginalString()
{
if (UserDrivenParsing)
- throw new InvalidOperationException(SR.Format(SR.net_uri_UserDrivenParsing, this.GetType().ToString()));
+ throw new InvalidOperationException(SR.Format(SR.net_uri_UserDrivenParsing, this.GetType()));
fixed (char* str = _string)
{
if (otherUri._string[portIndex] != ':')
{
// Something wrong with the NotDefaultPort flag. Reset to path index
- Debug.Assert(false, "Uri failed to locate custom port at index: " + portIndex);
+ Debug.Fail("Uri failed to locate custom port at index: " + portIndex);
portIndex = otherUri._info.Offset.Path;
}
}
protected virtual string Resolve(Uri baseUri, Uri relativeUri, out UriFormatException parsingError)
{
if (baseUri.UserDrivenParsing)
- throw new InvalidOperationException(SR.Format(SR.net_uri_UserDrivenParsing, this.GetType().ToString()));
+ throw new InvalidOperationException(SR.Format(SR.net_uri_UserDrivenParsing, this.GetType()));
if (!baseUri.IsAbsoluteUri)
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
throw new ArgumentOutOfRangeException(nameof(format));
if (uri.UserDrivenParsing)
- throw new InvalidOperationException(SR.Format(SR.net_uri_UserDrivenParsing, this.GetType().ToString()));
+ throw new InvalidOperationException(SR.Format(SR.net_uri_UserDrivenParsing, this.GetType()));
if (!uri.IsAbsoluteUri)
throw new InvalidOperationException(SR.net_uri_NotAbsolute);
{
case XmlNodeType.Document:
source = ((XDocument)source).Root;
- if (source == null) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_MissingRoot));
+ if (source == null) throw new InvalidOperationException(SR.InvalidOperation_MissingRoot);
validationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints;
break;
case XmlNodeType.Element:
break;
case XmlNodeType.Attribute:
if (((XAttribute)source).IsNamespaceDeclaration) goto default;
- if (source.Parent == null) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_MissingParent));
+ if (source.Parent == null) throw new InvalidOperationException(SR.InvalidOperation_MissingParent);
break;
default:
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_BadNodeType, nt));
case State.InReadElementContent:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
case State.InReadElementContent:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
case State.InReadElementContent:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
case State.InReadElementContent:
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return false;
}
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return false;
}
int len = ValidateNames.ParseNCName(ncname, 0);
if (len != ncname.Length)
{
- throw new ArgumentException(string.Format(len == 0 ? SR.Xml_BadStartNameChar : SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(ncname, len)));
+ throw new ArgumentException(SR.Format(len == 0 ? SR.Xml_BadStartNameChar : SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(ncname, len)));
}
}
break;
default:
- Debug.Assert(false, "Unknown event: " + page[idxEvent].EventType);
+ Debug.Fail("Unknown event: " + page[idxEvent].EventType);
break;
}
}
}
- Debug.Assert(false, "Unknown event should be added to end of event sequence.");
+ Debug.Fail("Unknown event should be added to end of event sequence.");
}
/// <summary>
}
}
- Debug.Assert(false, "Unknown event should be added to end of event sequence.");
+ Debug.Fail("Unknown event should be added to end of event sequence.");
return string.Empty;
}
internal static Exception CreateReadContentAsException(string methodName, XmlNodeType nodeType, IXmlLineInfo lineInfo)
{
- return new InvalidOperationException(AddLineInfo(SR.Format(SR.Xml_InvalidReadContentAs, new string[] { methodName, nodeType.ToString() }), lineInfo));
+ return new InvalidOperationException(AddLineInfo(SR.Format(SR.Xml_InvalidReadContentAs, methodName, nodeType), lineInfo));
}
internal static Exception CreateReadElementContentAsException(string methodName, XmlNodeType nodeType, IXmlLineInfo lineInfo)
{
- return new InvalidOperationException(AddLineInfo(SR.Format(SR.Xml_InvalidReadElementContentAs, new string[] { methodName, nodeType.ToString() }), lineInfo));
+ return new InvalidOperationException(AddLineInfo(SR.Format(SR.Xml_InvalidReadElementContentAs, methodName, nodeType), lineInfo));
}
private static string AddLineInfo(string message, IXmlLineInfo lineInfo)
return Read();
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return false;
}
}
return;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return;
}
}
Debug.Assert(AttributeCount > 0);
return reader.ReadContentAsBase64(buffer, index, count);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
Debug.Assert(AttributeCount > 0);
return reader.ReadContentAsBinHex(buffer, index, count);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
throw new InvalidOperationException(SR.Xml_MixingReadValueChunkWithBinary);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
throw new InvalidOperationException(SR.Xml_MixingReadValueChunkWithBinary);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
break;
}
throw CreateReadContentAsException(methodName);
return await ReadAsync().ConfigureAwait(false);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return false;
}
}
return;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return;
}
}
Debug.Assert(AttributeCount > 0);
return await reader.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
Debug.Assert(AttributeCount > 0);
return await reader.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return 0;
}
}
throw new InvalidOperationException(SR.Xml_MixingReadValueChunkWithBinary);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_state}");
return AsyncHelper.DoneTaskZero;
}
}
_fragmentType = XmlNodeType.Document;
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected conformance level {settings.ConformanceLevel}");
goto case ConformanceLevel.Document;
}
}
case XmlNodeType.None: settings.ConformanceLevel = ConformanceLevel.Auto; break;
case XmlNodeType.Element: settings.ConformanceLevel = ConformanceLevel.Fragment; break;
case XmlNodeType.Document: settings.ConformanceLevel = ConformanceLevel.Document; break;
- default: Debug.Assert(false); goto case XmlNodeType.None;
+ default: Debug.Fail($"Unexpected fragment type {_fragmentType}"); goto case XmlNodeType.None;
}
settings.CheckCharacters = _checkCharacters;
settings.LineNumberOffset = _lineNumberOffset;
break;
default:
//should never hit here
- Debug.Assert(false, "Invalid InitInputType");
+ Debug.Fail("Invalid InitInputType");
break;
}
}
FinishReadElementContentAsBinary();
continue;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected parsing function {_parsingFunction}");
break;
}
}
switch (_parsingFunction)
{
case ParsingFunction.InReadAttributeValue:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected parsing function {_parsingFunction}");
break;
case ParsingFunction.InIncrementalRead:
FinishIncrementalRead();
_emptyEntityInAttributeResolved = true;
break;
default:
- Debug.Assert(false);
+ Debug.Fail("Unexpected entity type");
throw new XmlException(SR.Xml_InternalError, string.Empty);
}
}
_parsingFunction = ParsingFunction.AfterResolveEmptyEntityInContent;
break;
default:
- Debug.Assert(false);
+ Debug.Fail("Unexpected entity type");
throw new XmlException(SR.Xml_InternalError, string.Empty);
}
}
ParseDtdFromParserContext();
break;
default:
- Debug.Assert(false, "Unhandled DtdProcessing enumeration value.");
+ Debug.Fail("Unhandled DtdProcessing enumeration value.");
break;
}
}
charsDecoded += chDec;
bytesDecoded += bDec;
}
- Debug.Assert(false, "We should get an exception again.");
+ Debug.Fail("We should get an exception again.");
}
catch (ArgumentException)
{
xmlDeclState = 3;
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected xmlDeclState {xmlDeclState}");
break;
}
sb.Append(chars, _ps.charPos, pos - _ps.charPos);
ThrowUnexpectedToken(pos, ">");
}
- Debug.Assert(false, "We should never get to this point.");
+ Debug.Fail("We should never get to this point.");
ReadData:
if (ReadData() == 0)
{
if (_ps.chars[_ps.charPos] != (char)0xD)
{
- Debug.Assert(false, "We should never get to this point.");
+ Debug.Fail("We should never get to this point.");
Throw(SR.Xml_UnexpectedEOF1);
}
Debug.Assert(_ps.isEof);
Throw(SR.Xml_UnclosedQuote);
}
if (HandleEntityEnd(true))
- { // no EndEntity reporting while parsing attributes
- Debug.Assert(false);
+ {
+ Debug.Fail("no EndEntity reporting while parsing attributes");
Throw(SR.Xml_InternalError);
}
// update info for the next attribute value chunk
{
if (_parsingStatesStackTop == -1)
{
- Debug.Assert(false);
+ Debug.Fail($"Unexpected parsing states stack top {_parsingStatesStackTop}");
Throw(SR.Xml_InternalError);
}
{
if (_ps.chars[_ps.charPos] != (char)0xD)
{
- Debug.Assert(false, "We should never get to this point.");
+ Debug.Fail("We should never get to this point.");
Throw(SR.Xml_UnexpectedEOF1);
}
Debug.Assert(_ps.isEof);
}
if (_ps.chars[_ps.charPos] != (char)0xD)
{
- Debug.Assert(false, "We should never get to this point.");
+ Debug.Fail("We should never get to this point.");
Throw(SR.Xml_UnexpectedEOF1);
}
Debug.Assert(_ps.isEof);
pos = startPos;
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected read state {_incReadState}");
break;
}
Debug.Assert(_incReadState == IncrementalReadState.Text ||
goto ReturnText;
}
default:
- Debug.Assert(false, "We should never get to this point.");
+ Debug.Fail("We should never get to this point.");
break;
}
chars = _ps.chars;
}
else
{
- Debug.Assert(false, "We should never get to this point.");
+ Debug.Fail("We should never get to this point.");
}
}
}
return FinishInitTextReaderAsync();
default:
//should never hit here
- Debug.Assert(false, "Invalid InitInputType");
+ Debug.Fail("Invalid InitInputType");
return Task.CompletedTask;
}
}
// Needed only for XmlTextReader
//XmlTextReader can't execute Async method.
case ParsingFunction.OpenUrl:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected parsing function {_parsingFunction}");
break;
case ParsingFunction.SwitchToInteractive:
Debug.Assert(!_ps.appendMode);
case ParsingFunction.InReadElementContentAsBinary:
return FinishReadElementContentAsBinaryAsync().CallBoolTaskFuncWhenFinishAsync(thisRef => thisRef.ReadAsync(), this);
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected parsing function {_parsingFunction}");
break;
}
}
switch (_parsingFunction)
{
case ParsingFunction.InReadAttributeValue:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected parsing function {_parsingFunction}");
break;
// Needed only for XmlTextReader (ReadChars, ReadBase64, ReadBinHex)
case ParsingFunction.InIncrementalRead:
return ParseDtdFromParserContextAsync();
default:
- Debug.Assert(false, "Unhandled DtdProcessing enumeration value.");
+ Debug.Fail("Unhandled DtdProcessing enumeration value.");
break;
}
xmlDeclState = 3;
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected xmlDeclState {xmlDeclState}");
break;
}
sb.Append(chars, _ps.charPos, pos - _ps.charPos);
ThrowUnexpectedToken(pos, ">");
}
- Debug.Assert(false, "We should never get to this point.");
+ Debug.Fail("We should never get to this point.");
}
Debug.Assert(_index > 0);
{
if (_ps.chars[_ps.charPos] != (char)0xD)
{
- Debug.Assert(false, "We should never get to this point.");
+ Debug.Fail("We should never get to this point.");
Throw(SR.Xml_UnexpectedEOF1);
}
Debug.Assert(_ps.isEof);
}
if (HandleEntityEnd(true))
- { // no EndEntity reporting while parsing attributes
- Debug.Assert(false);
+ {
+ Debug.Fail("no EndEntity reporting while parsing attributes");
Throw(SR.Xml_InternalError);
}
// update info for the next attribute value chunk
{
if (_ps.chars[_ps.charPos] != (char)0xD)
{
- Debug.Assert(false, "We should never get to this point.");
+ Debug.Fail("We should never get to this point.");
Throw(SR.Xml_UnexpectedEOF1);
}
Debug.Assert(_ps.isEof);
}
if (_ps.chars[_ps.charPos] != (char)0xD)
{
- Debug.Assert(false, "We should never get to this point.");
+ Debug.Fail("We should never get to this point.");
Throw(SR.Xml_UnexpectedEOF1);
}
Debug.Assert(_ps.isEof);
}
else
{
- Debug.Assert(false, "We should never get to this point.");
+ Debug.Fail("We should never get to this point.");
// 'other' is null, 'this' is not null. Always return 1, like "".CompareTo(null).
return 1;
}
case State.Closed:
return WriteState.Closed;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected state {_currentState}");
return WriteState.Error;
}
}
_stack[_top].defaultNs = ns;
break;
default:
- Debug.Assert(false, "Should have never come here");
+ Debug.Fail("Should have never come here");
return;
}
_stack[_top].defaultNsState = (declared ? NamespaceState.DeclaredAndWrittenOut : NamespaceState.DeclaredButNotWrittenOut);
_readBinaryHelper.Finish();
goto case ParsingFunction.Read;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected parsing function {_parsingFunction}");
return false;
}
}
await _readBinaryHelper.FinishAsync().ConfigureAwait(false);
goto case ParsingFunction.Read;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected parsing function {_parsingFunction}");
return false;
}
}
}
else
{
- Debug.Assert(false, "Expected currentState <= State.Error ");
+ Debug.Fail("Expected currentState <= State.Error ");
return WriteState.Error;
}
}
else if (State.RootLevelAttr == _currentState)
_currentState = State.RootLevelSpecAttr;
else
- Debug.Assert(false, "State.Attribute == currentState || State.RootLevelAttr == currentState");
+ Debug.Fail("State.Attribute == currentState || State.RootLevelAttr == currentState");
if (_attrValueCache == null)
{
break;
default:
- Debug.Assert(false, "We should not get to this point.");
+ Debug.Fail("We should not get to this point.");
break;
}
}
{
if (state >= State.Error)
{
- Debug.Assert(false, "We should never get to this point. State = " + state);
+ Debug.Fail("We should never get to this point. State = " + state);
return "Error";
}
else
default:
- Debug.Assert(false, "We should not get to this point.");
+ Debug.Fail("We should not get to this point.");
break;
}
}
writer.WriteValue((string)item.data);
break;
default:
- Debug.Assert(false, "Unexpected ItemType value.");
+ Debug.Fail("Unexpected ItemType value.");
break;
}
}
await writer.WriteStringAsync((string)item.data).ConfigureAwait(false);
break;
default:
- Debug.Assert(false, "Unexpected ItemType value.");
+ Debug.Fail("Unexpected ItemType value.");
break;
}
}
// do nothing on root level namespace
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected node type {nodeType}");
break;
}
// do nothing on root level namespace
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected node type {nodeType}");
break;
}
writer = new XmlAutoDetectWriter(output, this);
break;
default:
- Debug.Assert(false, "Invalid XmlOutputMethod setting.");
+ Debug.Fail("Invalid XmlOutputMethod setting.");
return null;
}
}
writer = new XmlAutoDetectWriter(output, this);
break;
default:
- Debug.Assert(false, "Invalid XmlOutputMethod setting.");
+ Debug.Fail("Invalid XmlOutputMethod setting.");
return null;
}
}
writer = new XmlAutoDetectWriter(output, this);
break;
default:
- Debug.Assert(false, "Invalid XmlOutputMethod setting.");
+ Debug.Fail("Invalid XmlOutputMethod setting.");
return null;
}
switch (_coreReader.NodeType)
{
case XmlNodeType.Element:
- Debug.Assert(false); //Should not happen as the caching reader does not cache elements in simple content
+ Debug.Fail("Should not happen as the caching reader does not cache elements in simple content");
break;
case XmlNodeType.Text:
switch (_coreReader.NodeType)
{
case XmlNodeType.Element:
- Debug.Assert(false); //Should not happen as the caching reader does not cache elements in simple content
+ Debug.Fail("Should not happen as the caching reader does not cache elements in simple content");
break;
case XmlNodeType.Text:
break;
default:
- throw new InvalidOperationException(SR.Format(SR.Xml_UnexpectedNodeType, new string[] { _currentNode.NodeType.ToString() }));
+ throw new InvalidOperationException(SR.Format(SR.Xml_UnexpectedNodeType, _currentNode.NodeType));
}
}
break;
default:
- throw new InvalidOperationException(SR.Format(SR.Xml_UnexpectedNodeType, new string[] { _currentNode.NodeType.ToString() }));
+ throw new InvalidOperationException(SR.Format(SR.Xml_UnexpectedNodeType, _currentNode.NodeType));
}
}
Debug.Assert(child == childToStopAt);
_namespaceParent = element;
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected scope {scope}");
return false;
}
return true;
_attributeIndex = index;
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected scope {scope}");
return false;
}
return true;
break;
default:
- throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.Xdom_Import, node.NodeType.ToString()));
+ throw new InvalidOperationException(SR.Format(CultureInfo.InvariantCulture, SR.Xdom_Import, node.NodeType));
}
}
internal static Exception UnexpectedNodeType(XmlNodeType nodetype)
{
- return new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.Xml_UnexpectedNodeType, nodetype.ToString()));
+ return new InvalidOperationException(SR.Format(CultureInfo.InvariantCulture, SR.Xml_UnexpectedNodeType, nodetype.ToString()));
}
}
}
public virtual string Value
{
get { return null; }
- set { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.Xdom_Node_SetVal, NodeType.ToString())); }
+ set { throw new InvalidOperationException(SR.Format(CultureInfo.InvariantCulture, SR.Xdom_Node_SetVal, NodeType.ToString())); }
}
// Gets the type of the current node.
{
#if DEBUG
if (((object)strA != (object)strB) && string.Equals(strA, strB))
- Debug.Assert(false, "Ref.Equal: Object comparison used for non-atomized string '" + strA + "'");
+ Debug.Fail("Ref.Equal: Object comparison used for non-atomized string '" + strA + "'");
#endif
return (object)strA == (object)strB;
}
{
return _fallbackResolver.GetEntity(absoluteUri, role, ofObjectToReturn);
}
- throw new XmlException(SR.Format(SR.Xml_CannotResolveUrl, absoluteUri.ToString()));
+ throw new XmlException(SR.Format(SR.Xml_CannotResolveUrl, absoluteUri));
}
if (ofObjectToReturn == null || ofObjectToReturn == typeof(Stream) || ofObjectToReturn == typeof(object))
{
return _fallbackResolver.GetEntityAsync(absoluteUri, role, ofObjectToReturn);
}
- throw new XmlException(SR.Format(SR.Xml_CannotResolveUrl, absoluteUri.ToString()));
+ throw new XmlException(SR.Format(SR.Xml_CannotResolveUrl, absoluteUri));
}
if (ofObjectToReturn == null || ofObjectToReturn == typeof(Stream) || ofObjectToReturn == typeof(object))
internal override bool IsEqual(object o1, object o2)
{
- //Debug.WriteLineIf(DiagnosticsSwitches.XmlSchema.TraceVerbose, string.Format("\t\tSchemaDatatype.IsEqual({0}, {1})", o1, o2));
return Compare(o1, o2) == 0;
}
}
return;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected token {token}");
break;
}
_scanningFunction = _savedScanningFunction;
goto SwitchAgain;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected scanning function {_scanningFunction}");
return Token.None;
}
}
private void OnUnexpectedError()
{
- Debug.Assert(false, "This is an unexpected error that should have been handled in the ScanXXX methods.");
+ Debug.Fail("This is an unexpected error that should have been handled in the ScanXXX methods.");
Throw(_curPos, SR.Xml_InternalError);
}
}
return;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected token {token}");
break;
}
_scanningFunction = _savedScanningFunction;
goto SwitchAgain;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected scanning function {_scanningFunction}");
return Token.None;
}
}
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected facet type {facet.FacetType}");
break;
}
}
return ST_double;
default:
- Debug.Assert(false, "Expected type not matched");
+ Debug.Fail("Expected type not matched");
return ST_string;
}
/* if (currentType == null)
return TF_time | TF_string;
else
{
- Debug.Assert(false, "Expected date, time or dateTime");
+ Debug.Fail("Expected date, time or dateTime");
return TF_string;
}
}
case ListType.Set:
return _set[ns] != null;
}
- Debug.Assert(false);
+ Debug.Fail($"Unexpected type {_type}");
return false;
}
}
return sb.ToString();
}
- Debug.Assert(false);
+ Debug.Fail($"Unexpected type {_type}");
return string.Empty;
}
return false;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected root type {rootType}");
break;
}
return true;
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected compositor {external.Compositor}");
break;
}
}
}
else
{
- Debug.Assert(false);
+ Debug.Fail("Unexpected particle");
}
return false;
}
else
{
- Debug.Assert(false);
+ Debug.Fail("Unexpected particle");
}
if (particle.MinOccurs == decimal.One && particle.MaxOccurs == decimal.One)
{
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected match state {attributeMatchState}");
break;
}
return attDef;
}
else
{
- Debug.Assert(false);
+ Debug.Fail("Unexpected particle");
}
return false;
}
else
{
- Debug.Assert(false);
+ Debug.Fail("Unexpected particle");
}
if (particle.MinOccurs == decimal.One && particle.MaxOccurs == decimal.One)
{
case TypeCode.Int64: return valueConverter.ChangeType(_unionVal.i64Val, ValueType);
case TypeCode.Double: return valueConverter.ChangeType(_unionVal.dblVal, ValueType);
case TypeCode.DateTime: return valueConverter.ChangeType(_unionVal.dtVal, ValueType);
- default: Debug.Assert(false, "Should never get here"); break;
+ default: Debug.Fail("Should never get here"); break;
}
}
return valueConverter.ChangeType(_objVal, ValueType, _nsPrefix);
case TypeCode.Int64: return valueConverter.ToBoolean(_unionVal.i64Val);
case TypeCode.Double: return valueConverter.ToBoolean(_unionVal.dblVal);
case TypeCode.DateTime: return valueConverter.ToBoolean(_unionVal.dtVal);
- default: Debug.Assert(false, "Should never get here"); break;
+ default: Debug.Fail("Should never get here"); break;
}
}
case TypeCode.Int64: return valueConverter.ToDateTime(_unionVal.i64Val);
case TypeCode.Double: return valueConverter.ToDateTime(_unionVal.dblVal);
case TypeCode.DateTime: return _unionVal.dtVal;
- default: Debug.Assert(false, "Should never get here"); break;
+ default: Debug.Fail("Should never get here"); break;
}
}
case TypeCode.Int64: return valueConverter.ToDouble(_unionVal.i64Val);
case TypeCode.Double: return _unionVal.dblVal;
case TypeCode.DateTime: return valueConverter.ToDouble(_unionVal.dtVal);
- default: Debug.Assert(false, "Should never get here"); break;
+ default: Debug.Fail("Should never get here"); break;
}
}
case TypeCode.Int64: return valueConverter.ToInt32(_unionVal.i64Val);
case TypeCode.Double: return valueConverter.ToInt32(_unionVal.dblVal);
case TypeCode.DateTime: return valueConverter.ToInt32(_unionVal.dtVal);
- default: Debug.Assert(false, "Should never get here"); break;
+ default: Debug.Fail("Should never get here"); break;
}
}
case TypeCode.Int64: return _unionVal.i64Val;
case TypeCode.Double: return valueConverter.ToInt64(_unionVal.dblVal);
case TypeCode.DateTime: return valueConverter.ToInt64(_unionVal.dtVal);
- default: Debug.Assert(false, "Should never get here"); break;
+ default: Debug.Fail("Should never get here"); break;
}
}
case TypeCode.Int64: return valueConverter.ChangeType(_unionVal.i64Val, type);
case TypeCode.Double: return valueConverter.ChangeType(_unionVal.dblVal, type);
case TypeCode.DateTime: return valueConverter.ChangeType(_unionVal.dtVal, type);
- default: Debug.Assert(false, "Should never get here"); break;
+ default: Debug.Fail("Should never get here"); break;
}
}
case TypeCode.Int64: return valueConverter.ToString(_unionVal.i64Val);
case TypeCode.Double: return valueConverter.ToString(_unionVal.dblVal);
case TypeCode.DateTime: return valueConverter.ToString(_unionVal.dtVal);
- default: Debug.Assert(false, "Should never get here"); break;
+ default: Debug.Fail("Should never get here"); break;
}
}
return valueConverter.ToString(_objVal, _nsPrefix);
internal override XmlSchemaObject Clone()
{
- System.Diagnostics.Debug.Assert(false, "Should never call Clone() on XmlSchemaComplexType. Call Clone(XmlSchema) instead.");
+ System.Diagnostics.Debug.Fail("Should never call Clone() on XmlSchemaComplexType. Call Clone(XmlSchema) instead.");
return Clone(null);
}
internal override XmlSchemaObject Clone()
{
- System.Diagnostics.Debug.Assert(false, "Should never call Clone() on XmlSchemaElement. Call Clone(XmlSchema) instead.");
+ System.Diagnostics.Debug.Fail("Should never call Clone() on XmlSchemaElement. Call Clone(XmlSchema) instead.");
return Clone(null);
}
internal override XmlSchemaObject Clone()
{
- System.Diagnostics.Debug.Assert(false, "Should never call Clone() on XmlSchemaGroup. Call Clone(XmlSchema) instead.");
+ System.Diagnostics.Debug.Fail("Should never call Clone() on XmlSchemaGroup. Call Clone(XmlSchema) instead.");
return Clone(null);
}
[XmlIgnore]
internal virtual string IdAttribute
{
- get { Debug.Assert(false); return null; }
- set { Debug.Assert(false); }
+ get { Debug.Fail("Should not use base property"); return null; }
+ set { Debug.Fail("Should not use base property"); }
}
internal virtual void SetUnhandledAttributes(XmlAttribute[] moreAttributes) { }
[XmlIgnore]
internal virtual string NameAttribute
{
- get { Debug.Assert(false); return null; }
- set { Debug.Assert(false); }
+ get { Debug.Fail("Should not use base property"); return null; }
+ set { Debug.Fail("Should not use base property"); }
}
[XmlIgnore]
{
if (name.Namespace.Length != 0)
{
- builder.Append(SR.Format(SR.Sch_ElementNameAndNamespace, subBuilder.ToString(), name.Namespace));
+ builder.Append(SR.Format(SR.Sch_ElementNameAndNamespace, subBuilder, name.Namespace));
}
else
{
- builder.Append(SR.Format(SR.Sch_ElementName, subBuilder.ToString()));
+ builder.Append(SR.Format(SR.Sch_ElementName, subBuilder));
}
}
}
subBuilder.Append(nsList[i]);
}
}
- builder.Append(SR.Format(SR.Sch_AnyElementNS, subBuilder.ToString()));
+ builder.Append(SR.Format(SR.Sch_AnyElementNS, subBuilder));
}
internal static string QNameString(string localName, string ns)
break;
default:
- Debug.Assert(false, "Type code " + typeCode + " is not supported.");
+ Debug.Fail("Type code " + typeCode + " is not supported.");
break;
}
prefix = nsResolver.LookupPrefix(qname.Namespace);
if (prefix == null)
- throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoPrefix, qname.ToString(), qname.Namespace));
+ throw new InvalidCastException(SR.Format(SR.XmlConvert_TypeNoPrefix, qname, qname.Namespace));
return (prefix.Length != 0) ? string.Concat(prefix, ":", qname.Name) : qname.Name;
}
container = _redefine;
break;
default:
- Debug.Assert(false, "State is " + state);
+ Debug.Fail("State is " + state);
break;
}
return container;
_redefine = (XmlSchemaRedefine)container;
break;
default:
- Debug.Assert(false, "State is " + state);
+ Debug.Fail("State is " + state);
break;
}
}
builder._sequence.Items.Add(builder._element);
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected parent element {builder.ParentElement}");
break;
}
}
_attributeGroup.Attributes.Add(value);
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected parent element {this.ParentElement}");
break;
}
}
((XmlSchemaGroupBase)this.ParentContainer).Items.Add(particle);
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected parent element {this.ParentElement}");
break;
}
}
if (iFace == iType)
return;
}
- Debug.Assert(false);
+ Debug.Fail("Interface not found");
#endif
}
object var;
if (TryGetVariable(name, out var))
return var;
- System.Diagnostics.Debug.Assert(false);
+ System.Diagnostics.Debug.Fail("Variable not found");
return null;
}
Ldc((bool)o);
break;
case TypeCode.Char:
- Debug.Assert(false, "Char is not a valid schema primitive and should be treated as int in DataContract");
+ Debug.Fail("Char is not a valid schema primitive and should be treated as int in DataContract");
throw new NotSupportedException(SR.XmlInvalidCharSchemaPrimitive);
case TypeCode.SByte:
case TypeCode.Byte:
{
internal static Exception NotSupported(string msg)
{
- System.Diagnostics.Debug.Assert(false, msg);
+ System.Diagnostics.Debug.Fail(msg);
return new NotSupportedException(msg);
}
}
MethodInfo addMethod = targetCollectionType.GetMethod("Add");
if (addMethod == null)
{
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
}
object[] arguments = new object[1];
}
else
{
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
}
var typeMemberTypeTuple = Tuple.Create(o.GetType(), memberType);
return fieldInfo.GetValue(o);
}
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
}
private bool WriteMemberText(Member anyText)
}
else
{
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
}
}
else
{
if (member == null)
{
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
}
member.Source(value);
}
break;
default:
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
}
}
else
{
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
}
member?.ChoiceSource?.Invoke(element.Name);
}
else
{
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
}
return memberType;
{
if (member == null)
{
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
}
member.Source(rre);
}
else
{
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
}
AddObjectsIntoTargetCollection(collection, listOfItems, collectionType);
throw new NotImplementedException("special.TypeDesc.CanBeAttributeValue");
}
else
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
}
else
{
};
}
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
}
else
{
((XmlNode)o).WriteTo(Writer);
break;
default:
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
}
}
}
}
else
{
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
}
}
}
if (enumMapping == null)
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
WriteXsiType(enumMapping.TypeName, ns);
Writer.WriteString(WriteEnumMethod(enumMapping, o));
}
if (arrayMapping == null)
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
WriteXsiType(arrayMapping.TypeName, ns);
WriteMember(o, null, arrayMapping.ElementsSortedByDerivation, null, null, arrayMapping.TypeDesc, true);
return memberField.GetValue(o);
}
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
}
private void WriteMember(object memberValue, AttributeAccessor attribute, TypeDesc memberTypeDesc, object container)
}
else
{
- // #10593: Add More Tests for Serialization Code
- Debug.Assert(false);
+ Debug.Fail("#10593: Add More Tests for Serialization Code");
}
}
else if (o is byte[] a)
}
else
{
- // #10593: Add More Tests for Serialization Code
- Debug.Assert(false);
+ Debug.Fail("#10593: Add More Tests for Serialization Code");
}
}
else
{
- // #10593: Add More Tests for Serialization Code
- Debug.Assert(false);
+ Debug.Fail("#10593: Add More Tests for Serialization Code");
}
}
}
else
{
- throw new InvalidOperationException(SR.Format(SR.XmlInternalError));
+ throw new InvalidOperationException(SR.XmlInternalError);
}
}
if (!foundMatchedMember)
{
- throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, $"Could not find member named {memberName} of type {declaringType.ToString()}"));
+ throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, $"Could not find member named {memberName} of type {declaringType}"));
}
declaringType = currentType;
{
if (type.ContainsGenericParameters)
{
- throw new InvalidOperationException(SR.Format(SR.XmlUnsupportedOpenGenericType, type.ToString()));
+ throw new InvalidOperationException(SR.Format(SR.XmlUnsupportedOpenGenericType, type));
}
TypeDesc typeDesc = (TypeDesc)s_primitiveTypes[type];
if (typeDesc == null)
#if DEBUG
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
- if (value.GetType() != typeof(string)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, SR.Format(SR.XmlInvalidDefaultValue, value.ToString(), value.GetType().FullName)));
+ if (value.GetType() != typeof(string)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, SR.Format(SR.XmlInvalidDefaultValue, value, value.GetType().FullName)));
#endif
// check the validity of the value
{
string defaultValue = XmlCustomFormatter.FromDefaultValue(value, pm.TypeDesc.FormatterName);
if (defaultValue == null)
- throw new InvalidOperationException(SR.Format(SR.XmlInvalidDefaultValue, value.ToString(), pm.TypeDesc.Name));
+ throw new InvalidOperationException(SR.Format(SR.XmlInvalidDefaultValue, value, pm.TypeDesc.Name));
return defaultValue;
}
- throw new InvalidOperationException(SR.Format(SR.XmlInvalidDefaultValue, value.ToString(), pm.TypeDesc.Name));
+ throw new InvalidOperationException(SR.Format(SR.XmlInvalidDefaultValue, value, pm.TypeDesc.Name));
}
private void ExportRootIfNecessary(TypeScope typeScope)
{
if (name.Name == Soap.Array && name.Namespace == Soap.Encoding)
{
- throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncoding, name.ToString()));
+ throw new InvalidOperationException(SR.Format(SR.XmlInvalidEncoding, name));
}
else
{
- throw new InvalidOperationException(SR.Format(SR.XmlMissingDataType, name.ToString()));
+ throw new InvalidOperationException(SR.Format(SR.XmlMissingDataType, name));
}
}
}
{
XmlSchemaElement element = (XmlSchemaElement)Schemas.Find(name, typeof(XmlSchemaElement));
if (element == null)
- throw new InvalidOperationException(SR.Format(SR.XmlMissingElement, name.ToString()));
+ throw new InvalidOperationException(SR.Format(SR.XmlMissingElement, name));
return element;
}
return fieldVariable;
}
}
- throw new InvalidOperationException(SR.Format(SR.XmlSerializerUnsupportedType, memberInfos[0].ToString()));
+ throw new InvalidOperationException(SR.Format(SR.XmlSerializerUnsupportedType, memberInfos[0]));
}
private string WriteMethodInfo(string escapedName, string typeVariable, string memberName, bool isNonPublic, params string[] paramTypes)
if (XmlMapping.IsShallow(mappings))
{
- throw new InvalidOperationException(SR.Format(SR.XmlMelformMapping));
+ throw new InvalidOperationException(SR.XmlMelformMapping);
}
Assembly assembly = null;
case 6: opcode = OpCodes.Ldc_I4_6; break;
case 7: opcode = OpCodes.Ldc_I4_7; break;
case 8: opcode = OpCodes.Ldc_I4_8; break;
- default: Debug.Assert(false); return;
+ default: Debug.Fail($"Unexpected int val {intVal}"); return;
}
Emit(opcode);
}
Call(XmlILMethods.StrCat4);
break;
default:
- Debug.Assert(false, "Shouldn't be called");
+ Debug.Fail("Shouldn't be called");
break;
}
}
case QilNodeType.Divide: Emit(OpCodes.Div); break;
case QilNodeType.Modulo: Emit(OpCodes.Rem); break;
case QilNodeType.Negate: Emit(OpCodes.Neg); break;
- default: Debug.Assert(false, opType + " must be an arithmetic operation."); break;
+ default: Debug.Fail($"{opType} must be an arithmetic operation."); break;
}
break;
case QilNodeType.Divide: meth = XmlILMethods.DecDiv; break;
case QilNodeType.Modulo: meth = XmlILMethods.DecRem; break;
case QilNodeType.Negate: meth = XmlILMethods.DecNeg; break;
- default: Debug.Assert(false, opType + " must be an arithmetic operation."); break;
+ default: Debug.Fail($"{opType} must be an arithmetic operation."); break;
}
Call(meth);
break;
default:
- Debug.Assert(false, "The " + opType + " arithmetic operation cannot be performed on values of type " + code + ".");
+ Debug.Fail($"The {opType} arithmetic operation cannot be performed on values of type {code}.");
break;
}
}
case XmlTypeCode.QName: meth = XmlILMethods.QNameEq; break;
case XmlTypeCode.Decimal: meth = XmlILMethods.DecEq; break;
default:
- Debug.Assert(false, "Type " + code + " does not support the equals operation.");
+ Debug.Fail($"Type {code} does not support the equals operation.");
break;
}
case XmlTypeCode.String: meth = XmlILMethods.StrCmp; break;
case XmlTypeCode.Decimal: meth = XmlILMethods.DecCmp; break;
default:
- Debug.Assert(false, "Type " + code + " does not support the equals operation.");
+ Debug.Fail($"Type {code} does not support the equals operation.");
break;
}
case GenerateNameType.TagNameAndMappings: meth = XmlILMethods.StartElemMapName; break;
case GenerateNameType.TagNameAndNamespace: meth = XmlILMethods.StartElemNmspName; break;
case GenerateNameType.QName: meth = XmlILMethods.StartElemQName; break;
- default: Debug.Assert(false, nameType + " is invalid here."); break;
+ default: Debug.Fail($"{nameType} is invalid here."); break;
}
}
else
{
case GenerateNameType.LiteralLocalName: meth = XmlILMethods.StartElemLocNameUn; break;
case GenerateNameType.LiteralName: meth = XmlILMethods.StartElemLitNameUn; break;
- default: Debug.Assert(false, nameType + " is invalid here."); break;
+ default: Debug.Fail($"{nameType} is invalid here."); break;
}
}
{
case GenerateNameType.LiteralLocalName: meth = XmlILMethods.EndElemLocNameUn; break;
case GenerateNameType.LiteralName: meth = XmlILMethods.EndElemLitNameUn; break;
- default: Debug.Assert(false, nameType + " is invalid here."); break;
+ default: Debug.Fail($"{nameType} is invalid here."); break;
}
}
case GenerateNameType.TagNameAndMappings: meth = XmlILMethods.StartAttrMapName; break;
case GenerateNameType.TagNameAndNamespace: meth = XmlILMethods.StartAttrNmspName; break;
case GenerateNameType.QName: meth = XmlILMethods.StartAttrQName; break;
- default: Debug.Assert(false, nameType + " is invalid here."); break;
+ default: Debug.Fail($"{nameType} is invalid here."); break;
}
}
else
{
case GenerateNameType.LiteralLocalName: meth = XmlILMethods.StartAttrLocNameUn; break;
case GenerateNameType.LiteralName: meth = XmlILMethods.StartAttrLitNameUn; break;
- default: Debug.Assert(false, nameType + " is invalid here."); break;
+ default: Debug.Fail($"{nameType} is invalid here."); break;
}
}
break;
case XmlTypeCode.AnyAtomicType:
- Debug.Assert(false, "Heterogenous sort key is not allowed.");
+ Debug.Fail("Heterogenous sort key is not allowed.");
return;
default:
- Debug.Assert(false, "Sorting over datatype " + keyType.TypeCode + " is not allowed.");
+ Debug.Fail($"Sorting over datatype {keyType.TypeCode} is not allowed.");
break;
}
}
break;
default:
- Debug.Assert(false, "Invalid location: " + _storage.Location);
+ Debug.Fail($"Invalid location: {_storage.Location}");
break;
}
}
break;
default:
- Debug.Assert(false, "Invalid location: " + _storage.Location);
+ Debug.Fail($"Invalid location: {_storage.Location}");
break;
}
case 1: _arg1 = arg; break;
case 2: _arg2 = arg; break;
default:
- Debug.Assert(false, "Cannot handle more than 2 arguments.");
+ Debug.Fail("Cannot handle more than 2 arguments.");
break;
}
}
case QilNodeType.Function: this.xstates = this.parentInfo.InitialStates; break;
case QilNodeType.RtfCtor: this.xstates = PossibleXmlStates.WithinContent; break;
case QilNodeType.Choice: this.xstates = PossibleXmlStates.Any; break;
- default: Debug.Assert(false, ndConstr.NodeType + " is not handled by XmlILStateAnalyzer."); break;
+ default: Debug.Fail($"{ndConstr.NodeType} is not handled by XmlILStateAnalyzer."); break;
}
if (ndContent != null)
case QilNodeType.Le: return cmp <= 0 ? f.True() : f.False();
}
- Debug.Assert(false, "Cannot fold this comparison operation: " + opType);
+ Debug.Fail($"Cannot fold this comparison operation: {opType}");
return null;
}
case QilNodeType.Modulo: return f.Modulo(left, right);
}
- Debug.Assert(false, "Cannot fold this arithmetic operation: " + opType);
+ Debug.Fail($"Cannot fold this arithmetic operation: {opType}");
return null;
}
return true;
default:
- Debug.Assert(false, "Pattern " + step.NodeType + " should have been handled.");
+ Debug.Fail($"Pattern {step.NodeType} should have been handled.");
break;
}
}
return true;
default:
- Debug.Assert(false, "Pattern " + step.NodeType + " should have been handled.");
+ Debug.Fail($"Pattern {step.NodeType} should have been handled.");
break;
}
}
return true;
default:
- Debug.Assert(false, "Pattern " + step.NodeType + " should have been handled.");
+ Debug.Fail($"Pattern {step.NodeType} should have been handled.");
break;
}
}
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected node type {ndProp.NodeType}");
break;
}
case QilNodeType.Le: opcode = OpCodes.Bgt_Un; break;
case QilNodeType.Eq: opcode = OpCodes.Bne_Un; break;
case QilNodeType.Ne: opcode = OpCodes.Beq; break;
- default: Debug.Assert(false); opcode = OpCodes.Nop; break;
+ default: Debug.Fail($"Unexpected rel op {relOp}"); opcode = OpCodes.Nop; break;
}
}
else
case QilNodeType.Le: opcode = OpCodes.Bgt; break;
case QilNodeType.Eq: opcode = OpCodes.Bne_Un; break;
case QilNodeType.Ne: opcode = OpCodes.Beq; break;
- default: Debug.Assert(false); opcode = OpCodes.Nop; break;
+ default: Debug.Fail($"Unexpected rel op {relOp}"); opcode = OpCodes.Nop; break;
}
}
_helper.Emit(opcode, _iterCurr.LabelBranch);
case QilNodeType.Le: opcode = OpCodes.Ble; break;
case QilNodeType.Eq: opcode = OpCodes.Beq; break;
case QilNodeType.Ne: opcode = OpCodes.Bne_Un; break;
- default: Debug.Assert(false); opcode = OpCodes.Nop; break;
+ default: Debug.Fail($"Unexpected rel op {relOp}"); opcode = OpCodes.Nop; break;
}
_helper.Emit(opcode, _iterCurr.LabelBranch);
_iterCurr.Storage = StorageDescriptor.None();
case QilNodeType.Ge: opcode = OpCodes.Bge_S; break;
case QilNodeType.Le: opcode = OpCodes.Ble_S; break;
case QilNodeType.Ne: opcode = OpCodes.Bne_Un_S; break;
- default: Debug.Assert(false); opcode = OpCodes.Nop; break;
+ default: Debug.Fail($"Unexpected rel op {relOp}"); opcode = OpCodes.Nop; break;
}
// Push "true" if comparison succeeds, "false" otherwise
case QilNodeType.NamespaceDecl: return XPathNodeType.Namespace;
}
- Debug.Assert(false, "Cannot map QilNodeType " + typ + " to an XPathNodeType");
+ Debug.Fail($"Cannot map QilNodeType {typ} to an XPathNodeType");
return XPathNodeType.All;
}
message = s + "\n" + message;
}
n.Annotation = message;
- Debug.Assert(false, message);
+ Debug.Fail(message);
}
}
}
return DocOrderMerge();
}
- Debug.Assert(false, "Invalid IteratorState " + _state);
+ Debug.Fail($"Invalid IteratorState {_state}");
return IteratorResult.NoMoreNodes;
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
- Debug.Assert(false, "Should never be called on XmlAttributeCache.");
+ Debug.Fail("Should never be called on XmlAttributeCache.");
}
internal override void WriteEndElement(string prefix, string localName, string ns)
{
- Debug.Assert(false, "Should never be called on XmlAttributeCache.");
+ Debug.Fail("Should never be called on XmlAttributeCache.");
}
public override void WriteComment(string text)
{
- Debug.Assert(false, "Should never be called on XmlAttributeCache.");
+ Debug.Fail("Should never be called on XmlAttributeCache.");
}
public override void WriteProcessingInstruction(string name, string text)
{
- Debug.Assert(false, "Should never be called on XmlAttributeCache.");
+ Debug.Fail("Should never be called on XmlAttributeCache.");
}
public override void WriteEntityRef(string name)
{
- Debug.Assert(false, "Should never be called on XmlAttributeCache.");
+ Debug.Fail("Should never be called on XmlAttributeCache.");
}
/// <summary>
break;
default:
- Debug.Assert(false, "Text cannot be output in the " + _xstate + " state.");
+ Debug.Fail("Text cannot be output in the " + _xstate + " state.");
break;
}
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected node type {navigator.NodeType}");
break;
}
case XmlState.WithinPI: return XPathNodeType.ProcessingInstruction;
}
- Debug.Assert(false, xstate.ToString() + " is not a valid XmlState.");
+ Debug.Fail(xstate.ToString() + " is not a valid XmlState.");
return XPathNodeType.Element;
}
break;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected node type {nav.NodeType}");
break;
}
LNegative:
// bi was bigger than this.
- Debug.Assert(false, "Who's subtracting to negative?");
+ Debug.Fail("Who's subtracting to negative?");
_length = 0;
AssertValid();
}
{
case 0:
// This assert depends on the way we are going to represent None
- // Debug.Assert(false);
sb.Append("none");
break;
case 1:
return XmlQueryCardinality.ZeroOrMore;
default:
- Debug.Assert(false);
+ Debug.Fail($"Unexpected type code {typeCode}");
return XmlQueryCardinality.None;
}
}
QilNode IXPathBuilder<QilNode>.Predicate(QilNode node, QilNode condition, bool isReverseStep)
{
- Debug.Assert(false, "Should not call to this function.");
+ Debug.Fail("Should not call to this function.");
return null;
}
break;
default:
- Debug.Assert(false, "Unexpected node type.");
+ Debug.Fail("Unexpected node type.");
break;
}
}
_writer.WriteString(mainNode.Value);
break;
case XmlNodeType.CDATA:
- Debug.Assert(false, "XSLT never gives us CDATA");
+ Debug.Fail("XSLT never gives us CDATA");
_writer.WriteCData(mainNode.Value);
break;
case XmlNodeType.EntityReference:
case XPathResultType.Error:
return val;
default:
- Debug.Assert(false, "unexpected XPath type");
+ Debug.Fail("unexpected XPath type");
return val;
}
}
internal override void Execute(Processor processor, ActionFrame frame)
{
- Debug.Assert(false);
+ Debug.Fail("Override invoked");
}
private static OutputMethod ParseOutputMethod(string value, Compiler compiler)
allowMultiple = usage.AllowMultiple;
}
else
- throw new FormatException(SR.Format(SR.Format_AttributeUsage, attributeFilterType.ToString()));
+ throw new FormatException(SR.Format(SR.Format_AttributeUsage, attributeFilterType));
}
internal static IEnumerable<object> FilterCustomAttributes(IEnumerable<object> attributes, Type attributeFilterType)
foreach (object attr in attributes)
{
if (attr == null)
- throw new InvalidOperationException(SR.Format(SR.InvalidOperation_NullAttribute));
+ throw new InvalidOperationException(SR.InvalidOperation_NullAttribute);
if (attributeFilterType.IsInstanceOfType(attr))
yield return attr;
// don't expect to hit this as the parameter types we pass are
// specified to match known definitions precisely.
- Debug.Assert(false, "Current platform has ambiguous match for: " + type.FullName + "." + name);
+ Debug.Assert(false, $"Current platform has ambiguous match for: {type.FullName}.{name}");
return null;
}
}
int separator = blobReader.ReadByte();
if (separator > 0x7f)
{
- throw new BadImageFormatException(string.Format(SR.InvalidDocumentName, separator));
+ throw new BadImageFormatException(SR.Format(SR.InvalidDocumentName, separator));
}
var pooledBuilder = PooledStringBuilder.GetInstance();
int entryPointRowId = (int)(entryPointToken & TokenTypeIds.RIDMask);
if (entryPointToken != 0 && ((entryPointToken & TokenTypeIds.TypeMask) != TokenTypeIds.MethodDef || entryPointRowId == 0))
{
- throw new BadImageFormatException(string.Format(SR.InvalidEntryPointToken, entryPointToken));
+ throw new BadImageFormatException(SR.Format(SR.InvalidEntryPointToken, entryPointToken));
}
ulong externalTableMask = reader.ReadUInt64();
if ((externalTableMask & ~validTables) != 0)
{
- throw new BadImageFormatException(string.Format(SR.UnknownTables, externalTableMask));
+ throw new BadImageFormatException(SR.Format(SR.UnknownTables, externalTableMask));
}
externalTableRowCounts = ReadMetadataTableRowCounts(ref reader, externalTableMask);
break;
default:
- throw new BadImageFormatException(string.Format(SR.InvalidImportDefinitionKind, kind));
+ throw new BadImageFormatException(SR.Format(SR.InvalidImportDefinitionKind, kind));
}
return true;
break;
default:
- Debug.Assert(false);
+ Debug.Assert(false, $"Unexpected treatment {treatment}");
return default(BlobHandle);
}
[MethodImpl(MethodImplOptions.NoInlining)]
internal static Exception InvalidArgument_Handle(string parameterName)
{
- throw new ArgumentException(SR.Format(SR.InvalidHandle), parameterName);
+ throw new ArgumentException(SR.InvalidHandle, parameterName);
}
[MethodImpl(MethodImplOptions.NoInlining)]
}
}
- e = new FileNotFoundException(SR.Format(SR.UnableToDetermineCoreAssembly));
+ e = new FileNotFoundException(SR.UnableToDetermineCoreAssembly);
return null;
}
case PrimitiveTypeCode.UIntPtr: return CoreType.UIntPtr;
case PrimitiveTypeCode.Void: return CoreType.Void;
default:
- Debug.Assert(false, "Unexpected PrimitiveTypeCode: " + typeCode);
+ Debug.Fail("Unexpected PrimitiveTypeCode: " + typeCode);
return CoreType.Void;
}
}
return ((TypeSpecificationHandle)handle).ToTypeString(reader, typeContext);
default:
- Debug.Assert(false, $"Invalid handle passed to ToTypeString: 0x{handle.GetToken():x8}");
+ Debug.Fail($"Invalid handle passed to ToTypeString: 0x{handle.GetToken():x8}");
return "?";
}
}
}
default:
- Debug.Assert(typeCode >= ResourceTypeCode.StartOfUserTypes, string.Format(CultureInfo.InvariantCulture, "ResourceReader: Unsupported ResourceTypeCode in .resources file! {0}", typeCode));
+ Debug.Assert(typeCode >= ResourceTypeCode.StartOfUserTypes, $"ResourceReader: Unsupported ResourceTypeCode in .resources file! {typeCode}");
throw new PlatformNotSupportedException(SR.NotSupported_BinarySerializedResources);
}
}
}
#if PERF
- Debug.WriteLine(String.Format("CacheMemoryMonitor.GetPercentToTrim: percent={0:N}, lastTrimPercent={1:N}{Environment.NewLine}",
+ Debug.WriteLine(string.Format("CacheMemoryMonitor.GetPercentToTrim: percent={0:N}, lastTrimPercent={1:N}{Environment.NewLine}",
percent,
lastTrimPercent));
#endif
}
#if PERF
- Debug.WriteLine(String.Format("PhysicalMemoryMonitor.GetPercentToTrim: percent={0:N}, lastTrimPercent={1:N}, secondsSinceTrim={2:N}{3}",
+ Debug.WriteLine(string.Format("PhysicalMemoryMonitor.GetPercentToTrim: percent={0:N}, lastTrimPercent={1:N}, secondsSinceTrim={2:N}{3}",
percent,
lastTrimPercent,
ticksSinceTrim/TimeSpan.TicksPerSecond,
{
return base.Message;
}
- string valueMessage = SR.Format(SR.SwitchExpressionException_UnmatchedValue, UnmatchedValue.ToString());
+ string valueMessage = SR.Format(SR.SwitchExpressionException_UnmatchedValue, UnmatchedValue);
return base.Message + Environment.NewLine + valueMessage;
}
}
}
-}
\ No newline at end of file
+}
Marshal.Release(pUnknown);
}
}
- throw new InvalidOperationException(string.Format(SR.StandardOleMarshalObjectGetMarshalerFailed, riid.ToString()));
+ throw new InvalidOperationException(SR.Format(SR.StandardOleMarshalObjectGetMarshalerFailed, riid.ToString()));
}
int IMarshal.GetUnmarshalClass(ref Guid riid, IntPtr pv, int dwDestContext, IntPtr pvDestContext, int mshlflags, out Guid pCid)
{
if (!t.IsSerializable && !HasSurrogate(t))
{
- throw new SerializationException(string.Format(CultureInfo.InvariantCulture, SR.Serialization_NonSerType, t.FullName, t.Assembly.FullName));
+ throw new SerializationException(SR.Format(CultureInfo.InvariantCulture, SR.Serialization_NonSerType, t.FullName, t.Assembly.FullName));
}
}
{
if (!holder.CanSurrogatedObjectValueChange && returnValue != holder.ObjectValue)
{
- throw new SerializationException(string.Format(CultureInfo.CurrentCulture, SR.Serialization_NotCyclicallyReferenceableSurrogate, surrogate.GetType().FullName));
+ throw new SerializationException(SR.Format(SR.Serialization_NotCyclicallyReferenceableSurrogate, surrogate.GetType().FullName));
}
holder.SetObjectValue(returnValue, this);
}
}
if (!(member is FieldInfo)) // desktop checks specifically for RuntimeFieldInfo and SerializationFieldInfo, but the former is an implementation detail in corelib
{
- throw new SerializationException(SR.Format(SR.Serialization_InvalidType, member.GetType().ToString()));
+ throw new SerializationException(SR.Format(SR.Serialization_InvalidType, member.GetType()));
}
//Create a new fixup holder
// break;
default:
- Debug.Assert(false, "We should never get here. Someone forgot to handle an input stream optimisation option.");
+ Debug.Fail("We should never get here. Someone forgot to handle an input stream optimisation option.");
readAsyncOperation = null;
break;
}
return null;
Debug.Assert(wrtStr is TWinRtStream,
- string.Format("Attempted to get the underlying WinRT stream typed as \"{0}\"," +
- " but the underlying WinRT stream cannot be cast to that type. Its actual type is \"{1}\".",
- typeof(TWinRtStream).ToString(), wrtStr.GetType().ToString()));
+ $"Attempted to get the underlying WinRT stream typed as \"{typeof(TWinRtStream)}\", " +
+ $"but the underlying WinRT stream cannot be cast to that type. Its actual type is \"{wrtStr.GetType()}\".");
return wrtStr as TWinRtStream;
}
{
private NotifyCollectionChangedToManagedAdapter()
{
- Debug.Assert(false, "This class is never instantiated");
+ Debug.Fail("This class is never instantiated");
}
internal event NotifyCollectionChangedEventHandler CollectionChanged
{
private NotifyCollectionChangedToWinRTAdapter()
{
- Debug.Assert(false, "This class is never instantiated");
+ Debug.Fail("This class is never instantiated");
}
// An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj.
{
private NotifyPropertyChangedToManagedAdapter()
{
- Debug.Assert(false, "This class is never instantiated");
+ Debug.Fail("This class is never instantiated");
}
internal event PropertyChangedEventHandler PropertyChanged
{
private NotifyPropertyChangedToWinRTAdapter()
{
- Debug.Assert(false, "This class is never instantiated");
+ Debug.Fail("This class is never instantiated");
}
// An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj.
private ICommandToManagedAdapter()
{
- Debug.Assert(false, "This class is never instantiated");
+ Debug.Fail("This class is never instantiated");
}
private event EventHandler CanExecuteChanged
{
private ICommandToWinRTAdapter()
{
- Debug.Assert(false, "This class is never instantiated");
+ Debug.Fail("This class is never instantiated");
}
// An instance field typed as EventRegistrationTokenTable is injected into managed classed by the compiler when compiling for /t:winmdobj.
if (!base.Task.IsFaulted)
{
- Debug.Assert(false, string.Format("Expected base task to already be faulted but found it in state {0}", base.Task.Status));
+ Debug.Fail($"Expected base task to already be faulted but found it in state {base.Task.Status}");
base.TrySetException(ex);
}
}
// Defend against a faulty IAsyncInfo implementation:
if (error == null)
{
- Debug.Assert(false, "IAsyncInfo.Status == Error, but ErrorCode returns a null Exception (implying S_OK).");
+ Debug.Fail("IAsyncInfo.Status == Error, but ErrorCode returns a null Exception (implying S_OK).");
error = new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion);
}
else
{
// This really shouldn't happen, but could in a variety of misuse cases
// such as a faulty underlying IAsyncInfo implementation.
- Debug.Assert(false, string.Format("Unexpected exception in Complete: {0}", exc.ToString()));
+ Debug.Fail($"Unexpected exception in Complete: {exc}");
if (AsyncCausalitySupport.LoggingOn)
AsyncCausalitySupport.TraceOperationCompletedError(this.Task);
// do we allow it to be propagated out to the invoker of the Completed handler.
if (!base.TrySetException(exc))
{
- Debug.Assert(false, "The task was already completed and thus the exception couldn't be stored.");
+ Debug.Fail("The task was already completed and thus the exception couldn't be stored.");
throw;
}
}
if (!base.Task.IsFaulted)
{
- Debug.Assert(false, string.Format("Expected base task to already be faulted but found it in state {0}", base.Task.Status));
+ Debug.Fail($"Expected base task to already be faulted but found it in state {base.Task.Status}");
base.TrySetException(ex);
}
}
// Defend against a faulty IAsyncInfo implementation:
if (error == null)
{
- Debug.Assert(false, "IAsyncInfo.Status == Error, but ErrorCode returns a null Exception (implying S_OK).");
+ Debug.Fail("IAsyncInfo.Status == Error, but ErrorCode returns a null Exception (implying S_OK).");
error = new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion);
}
else
{
// This really shouldn't happen, but could in a variety of misuse cases
// such as a faulty underlying IAsyncInfo implementation.
- Debug.Assert(false, string.Format("Unexpected exception in Complete: {0}", exc.ToString()));
+ Debug.Fail($"Unexpected exception in Complete: {exc}");
if (AsyncCausalitySupport.LoggingOn)
AsyncCausalitySupport.TraceOperationCompletedError(this.Task);
// do we allow it to be propagated out to the invoker of the Completed handler.
if (!base.TrySetException(exc))
{
- Debug.Assert(false, "The task was already completed and thus the exception couldn't be stored.");
+ Debug.Fail("The task was already completed and thus the exception couldn't be stored.");
throw;
}
}
internal virtual void OnCompleted(TCompletedHandler userCompletionHandler, AsyncStatus asyncStatus)
{
- Debug.Assert(false, "This (sub-)type of IAsyncInfo does not support completion notifications "
+ Debug.Fail("This (sub-)type of IAsyncInfo does not support completion notifications "
+ " (" + this.GetType().ToString() + ")");
}
internal virtual void OnProgress(TProgressHandler userProgressHandler, TProgressInfo progressInfo)
{
- Debug.Assert(false, "This (sub-)type of IAsyncInfo does not support progress notifications "
+ Debug.Fail("This (sub-)type of IAsyncInfo does not support progress notifications "
+ " (" + this.GetType().ToString() + ")");
}
break;
default:
- Debug.Assert(false, "Unexpected task.Status: It should be terminal if TaskCompleted() is called.");
+ Debug.Fail("Unexpected task.Status: It should be terminal if TaskCompleted() is called.");
break;
}
switch (asyncState)
{
case STATE_NOT_INITIALIZED:
- Debug.Assert(false, "STATE_NOT_INITIALIZED should only occur when this object was not"
+ Debug.Fail("STATE_NOT_INITIALIZED should only occur when this object was not"
+ " fully constructed, in which case we should never get here");
return AsyncStatus.Error;
return AsyncStatus.Error;
case STATE_CLOSED:
- Debug.Assert(false, "This method should never be called is this IAsyncInfo is CLOSED");
+ Debug.Fail("This method should never be called is this IAsyncInfo is CLOSED");
return AsyncStatus.Error;
}
- Debug.Assert(false, "The switch above is missing a case");
+ Debug.Fail("The switch above is missing a case");
return AsyncStatus.Error;
}
return funcCTokIPrgrTask(_cancelTokenSource.Token, this);
}
- Debug.Assert(false, "We should never get here!"
+ Debug.Fail("We should never get here!"
+ " Public methods creating instances of this class must be typesafe to ensure that taskProvider"
+ " can always be cast to one of the above Func types."
+ " The taskProvider is " + (taskProvider == null
// Indicates a bug in the implementation, not in user's code.
//
- Debug.Assert(false, "Length > ushort.MaxValue");
+ Debug.Fail("Length > ushort.MaxValue");
// Replacing SystemException with InvalidOperationException. It's not a perfect fit,
// but it's the best exception type available to indicate a failure because
// of a bug in the ACE itself.
{
throw new ArgumentOutOfRangeException(
nameof(opaque),
- string.Format(CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_ArrayLength, 0, MaxOpaqueLength));
+ SR.Format(SR.ArgumentOutOfRange_ArrayLength, 0, MaxOpaqueLength));
}
else if (opaque.Length % 4 != 0)
{
throw new ArgumentOutOfRangeException(
nameof(opaque),
- string.Format(CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_ArrayLengthMultiple, 4));
+ SR.Format(SR.ArgumentOutOfRange_ArrayLengthMultiple, 4));
}
}
{
if (OpaqueLength > MaxOpaqueLength)
{
- Debug.Assert(false, "OpaqueLength somehow managed to exceed MaxOpaqueLength");
+ Debug.Fail("OpaqueLength somehow managed to exceed MaxOpaqueLength");
// Replacing SystemException with InvalidOperationException. It's not a perfect fit,
// but it's the best exception type available to indicate a failure because
// of a bug in the ACE itself.
// Indicates a bug in the implementation, not in user's code
//
- Debug.Assert(false, "Invalid ACE type");
+ Debug.Fail("Invalid ACE type");
// Replacing SystemException with InvalidOperationException. It's not a perfect fit,
// but it's the best exception type available to indicate a failure because
// of a bug in the ACE itself.
{
throw new ArgumentOutOfRangeException(
nameof(opaque),
- string.Format(CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_ArrayLength, 0, MaxOpaqueLengthInternal));
+ SR.Format(SR.ArgumentOutOfRange_ArrayLength, 0, MaxOpaqueLengthInternal));
}
else if (opaque.Length % 4 != 0)
{
throw new ArgumentOutOfRangeException(
nameof(opaque),
- string.Format(CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_ArrayLengthMultiple, 4));
+ SR.Format(SR.ArgumentOutOfRange_ArrayLengthMultiple, 4));
}
}
{
if (OpaqueLength > MaxOpaqueLengthInternal)
{
- Debug.Assert(false, "OpaqueLength somehow managed to exceed MaxOpaqueLength");
+ Debug.Fail("OpaqueLength somehow managed to exceed MaxOpaqueLength");
// Replacing SystemException with InvalidOperationException. It's not a perfect fit,
// but it's the best exception type available to indicate a failure because
// of a bug in the ACE itself.
{
if (OpaqueLength > MaxOpaqueLengthInternal)
{
- Debug.Assert(false, "OpaqueLength somehow managed to exceed MaxOpaqueLength");
+ Debug.Fail("OpaqueLength somehow managed to exceed MaxOpaqueLength");
// Replacing SystemException with InvalidOperationException. It's not a perfect fit,
// but it's the best exception type available to indicate a failure because
// of a bug in the ACE itself.
result = _securityDescriptor.DiscretionaryAcl.RemoveAccess(AccessControlType.Allow, sid, -1, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, 0);
if (result == false)
{
- Debug.Assert(false, "Invalid operation");
+ Debug.Fail("Invalid operation");
throw new InvalidOperationException();
}
result = _securityDescriptor.DiscretionaryAcl.RemoveAccess(AccessControlType.Deny, sid, -1, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, 0);
if (result == false)
{
- Debug.Assert(false, "Invalid operation");
+ Debug.Fail("Invalid operation");
throw new InvalidOperationException();
}
}
else
{
- Debug.Assert(false, "rule.AccessControlType unrecognized");
+ Debug.Fail("rule.AccessControlType unrecognized");
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)rule.AccessControlType), "rule.AccessControlType");
}
}
else
{
- Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32GetSecurityInfo() failed with unexpected error code {0}", error));
+ Debug.Fail($"Win32GetSecurityInfo() failed with unexpected error code {error}");
exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error));
}
}
}
else
{
- Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Unexpected error code {0}", error));
+ Debug.Fail($"Unexpected error code {error}");
exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error));
}
}
}
else
{
- System.Diagnostics.Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "LookupPrivilegeValue() failed with unrecognized error code {0}", error));
+ System.Diagnostics.Debug.Fail($"LookupPrivilegeValue() failed with unrecognized error code {error}");
throw new InvalidOperationException();
}
}
}
else if (error != 0)
{
- System.Diagnostics.Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "WindowsIdentity.GetCurrentThreadToken() failed with unrecognized error code {0}", error));
+ System.Diagnostics.Debug.Fail($"WindowsIdentity.GetCurrentThreadToken() failed with unrecognized error code {error}");
throw new InvalidOperationException();
}
}
}
else if (error != 0)
{
- System.Diagnostics.Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "AdjustTokenPrivileges() failed with unrecognized error code {0}", error));
+ System.Diagnostics.Debug.Fail($"AdjustTokenPrivileges() failed with unrecognized error code {error}");
throw new InvalidOperationException();
}
}
}
else if (error != 0)
{
- System.Diagnostics.Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "AdjustTokenPrivileges() failed with unrecognized error code {0}", error));
+ System.Diagnostics.Debug.Fail($"AdjustTokenPrivileges() failed with unrecognized error code {error}");
throw new InvalidOperationException();
}
}
}
public PrivilegeNotHeldException(string privilege)
- : base(string.Format(CultureInfo.CurrentCulture, SR.PrivilegeNotHeld_Named, privilege))
+ : base(SR.Format(SR.PrivilegeNotHeld_Named, privilege))
{
_privilegeName = privilege;
}
public PrivilegeNotHeldException(string privilege, Exception inner)
- : base(string.Format(CultureInfo.CurrentCulture, SR.PrivilegeNotHeld_Named, privilege), inner)
+ : base(SR.Format(SR.PrivilegeNotHeld_Named, privilege), inner)
{
_privilegeName = privilege;
}
// Indicates that the marshaling logic in GetBinaryForm is busted
//
- Debug.Assert(false, "binaryForm produced invalid output");
+ Debug.Fail("binaryForm produced invalid output");
throw new InvalidOperationException();
}
else if (error != Interop.Errors.ERROR_SUCCESS)
{
- Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.ConvertSdToSddl returned {0}", error));
+ Debug.Fail($"Win32.ConvertSdToSddl returned {error}");
throw new InvalidOperationException();
}
}
else if (error != Interop.Errors.ERROR_SUCCESS)
{
- Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Unexpected error out of Win32.ConvertStringSdToSd: {0}", error));
+ Debug.Fail($"Unexpected error out of Win32.ConvertStringSdToSd: {error}");
throw new Win32Exception(error, SR.Format(SR.AccessControl_UnexpectedError, error));
}
}
else
{
// both are null, shouldn't happen
- Debug.Assert(false, "Internal error: both name and handle are null");
+ Debug.Fail("Internal error: both name and handle are null");
throw new ArgumentException();
}
{
if (!TryRemoveClaim(claim))
{
- throw new InvalidOperationException(string.Format(SR.InvalidOperation_ClaimCannotBeRemoved, claim));
+ throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ClaimCannotBeRemoved, claim));
}
}
if (string.IsNullOrEmpty(curve.Oid.FriendlyName))
{
throw new PlatformNotSupportedException(
- string.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value));
+ SR.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value));
}
// Map curve name to algorithm to support pre-Win10 curves
errorCode == Interop.NCrypt.ErrorCode.NTE_NOT_SUPPORTED)
{
throw new PlatformNotSupportedException(
- string.Format(SR.Cryptography_CurveNotSupported, curve.Oid.FriendlyName), e);
+ SR.Format(SR.Cryptography_CurveNotSupported, curve.Oid.FriendlyName), e);
}
throw;
keySize = 521;
break;
default:
- Debug.Fail(string.Format("Unknown algorithm {0}", algorithm.ToString()));
+ Debug.Fail($"Unknown algorithm {algorithm}");
throw new ArgumentException(SR.Cryptography_InvalidKeySize);
}
else
{
throw new PlatformNotSupportedException(
- string.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
+ SR.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
}
_lastAlgorithm = algorithm;
throw new ArgumentNullException(nameof(Oid));
if (string.IsNullOrEmpty(value.Value) && string.IsNullOrEmpty(value.FriendlyName))
- throw new ArgumentException(string.Format(SR.Cryptography_InvalidCurveOid));
+ throw new ArgumentException(SR.Cryptography_InvalidCurveOid);
_oid = value;
}
Debug.Assert(CurveType == ECCurveType.Implicit);
if (HasAnyExplicitParameters() || Oid != null)
{
- throw new CryptographicException(string.Format(SR.Cryptography_CurveNotSupported, CurveType.ToString()));
+ throw new CryptographicException(SR.Format(SR.Cryptography_CurveNotSupported, CurveType.ToString()));
}
}
}
}
else
{
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, curve.Value.CurveType.ToString()));
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, curve.Value.CurveType.ToString()));
}
try
if (curve.Value.IsNamed &&
errorCode == ErrorCode.NTE_INVALID_PARAMETER || errorCode == ErrorCode.NTE_NOT_SUPPORTED)
{
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, curve.Value.Oid.FriendlyName), e);
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, curve.Value.Oid.FriendlyName), e);
}
throw;
}
return "nistP521";
}
- Debug.Fail(string.Format("Unknown curve {0}", algorithm));
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, algorithm));
+ Debug.Fail($"Unknown curve {algorithm}");
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, algorithm));
}
/// <summary>
if (curve.IsNamed)
{
if (string.IsNullOrEmpty(curve.Oid.FriendlyName))
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value));
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value));
// Map curve name to algorithm to support pre-Win10 curves
alg = algorithmResolver(curve.Oid.FriendlyName);
}
else
{
- Debug.Fail(string.Format("Unknown algorithm {0}", alg.ToString()));
+ Debug.Fail($"Unknown algorithm {alg}");
throw new ArgumentException(SR.Cryptography_InvalidKeySize);
}
}
}
else
{
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
}
try
errorCode == Interop.NCrypt.ErrorCode.NTE_NOT_SUPPORTED)
{
string target = curve.IsNamed ? curve.Oid.FriendlyName : curve.CurveType.ToString();
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, target), e);
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, target), e);
}
throw;
if (curve.IsNamed)
{
if (string.IsNullOrEmpty(curve.Oid.FriendlyName))
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value));
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value));
// Map curve name to algorithm to support pre-Win10 curves
CngAlgorithm alg = CngKey.EcdhCurveNameToAlgorithm(curve.Oid.FriendlyName);
keySize = 521;
else
{
- Debug.Fail(string.Format("Unknown algorithm {0}", alg.ToString()));
+ Debug.Fail($"Unknown algorithm {alg}");
throw new ArgumentException(SR.Cryptography_InvalidKeySize);
}
CngKey key = _core.GetOrGenerateKey(keySize, alg);
}
else
{
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
}
}
if (curve.IsNamed)
{
if (string.IsNullOrEmpty(curve.Oid.FriendlyName))
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value));
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value));
// Map curve name to algorithm to support pre-Win10 curves
CngAlgorithm alg = CngKey.EcdsaCurveNameToAlgorithm(curve.Oid.FriendlyName);
keySize = 521;
else
{
- Debug.Fail(string.Format("Unknown algorithm {0}", alg.ToString()));
+ Debug.Fail($"Unknown algorithm {alg}");
throw new ArgumentException(SR.Cryptography_InvalidKeySize);
}
CngKey key = _core.GetOrGenerateKey(keySize, alg);
}
else
{
- throw new PlatformNotSupportedException(string.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
+ throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString()));
}
}
}
default:
{
- Debug.Assert(false);
+ Debug.Fail($"Unexpected key param {keyParam}");
break;
}
}
}
default:
{
- Debug.Assert(false);
+ Debug.Fail($"Unexpected key param {keyParam}");
break;
}
}
if (PublicOnly)
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
if (rgbHash.Length != SHA1_HASHSIZE)
- throw new CryptographicException(string.Format(SR.Cryptography_InvalidHashSize, "SHA1", SHA1_HASHSIZE));
+ throw new CryptographicException(SR.Format(SR.Cryptography_InvalidHashSize, "SHA1", SHA1_HASHSIZE));
// Only SHA1 allowed; the default value is SHA1
if (str != null && !string.Equals(str, "SHA1", StringComparison.OrdinalIgnoreCase))
int calgHash = CapiHelper.NameOrOidToHashAlgId(str, OidGroup.HashAlgorithm);
if (rgbHash.Length != _sha1.HashSize / 8)
- throw new CryptographicException(string.Format(SR.Cryptography_InvalidHashSize, "SHA1", _sha1.HashSize / 8));
+ throw new CryptographicException(SR.Format(SR.Cryptography_InvalidHashSize, "SHA1", _sha1.HashSize / 8));
return CapiHelper.SignValue(
SafeProvHandle,
return new SubjectIdentifierOrKey(SubjectIdentifierOrKeyType.SubjectKeyIdentifier, subjectIdentifier.Value);
default:
- Debug.Assert(false); // Only the framework can construct SubjectIdentifier's so if we got a bad value here, that's our fault.
+ Debug.Fail("Only the framework can construct SubjectIdentifier's so if we got a bad value here, that's our fault.");
throw new CryptographicException(SR.Format(SR.Cryptography_Cms_Invalid_Subject_Identifier_Type, subjectIdentifierType));
}
}
break;
default:
- Debug.Fail(
- string.Format(
- "Invalid parser state. Position {0}, State {1}, Character {2}, String \"{3}\"",
- pos,
- state,
- c,
- stringForm));
-
+ Debug.Fail($"Invalid parser state. Position {pos}, State {state}, Character {c}, String \"{stringForm}\"");
throw new CryptographicException(SR.Cryptography_Invalid_X500Name);
}
uint allFlags = 0x71F1;
uint dwFlags = (uint)flags;
if ((dwFlags & ~allFlags) != 0)
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Arg_EnumIllegalVal, "flag"));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, "flag"));
}
private volatile string _lazyDistinguishedName;
set
{
if (value < X509RevocationMode.NoCheck || value > X509RevocationMode.Offline)
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Arg_EnumIllegalVal, nameof(value)));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, nameof(value)));
_revocationMode = value;
}
}
set
{
if (value < X509RevocationFlag.EndCertificateOnly || value > X509RevocationFlag.ExcludeRoot)
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Arg_EnumIllegalVal, nameof(value)));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, nameof(value)));
_revocationFlag = value;
}
}
set
{
if (value < X509VerificationFlags.NoFlag || value > X509VerificationFlags.AllFlags)
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Arg_EnumIllegalVal, nameof(value)));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, nameof(value)));
_verificationFlags = value;
}
}
public X509Store(StoreName storeName, StoreLocation storeLocation)
{
if (storeLocation != StoreLocation.CurrentUser && storeLocation != StoreLocation.LocalMachine)
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Arg_EnumIllegalVal, nameof(storeLocation)));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, nameof(storeLocation)));
switch (storeName)
{
Name = "TrustedPublisher";
break;
default:
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Arg_EnumIllegalVal, nameof(storeName)));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, nameof(storeName)));
}
Location = storeLocation;
public X509Store(string storeName, StoreLocation storeLocation)
{
if (storeLocation != StoreLocation.CurrentUser && storeLocation != StoreLocation.LocalMachine)
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Arg_EnumIllegalVal, nameof(storeLocation)));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, nameof(storeLocation)));
Location = storeLocation;
Name = storeName;
// This is the self-referential case. First, check that we have a document context.
// The Enveloped Signature does not discard comments as per spec; those will be omitted during the transform chain process
if (document == null)
- throw new CryptographicException(string.Format(CultureInfo.CurrentCulture, SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri));
+ throw new CryptographicException(SR.Format(SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri));
// Normalize the containing document
resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
{
// This is a self referencial case
if (document == null)
- throw new CryptographicException(string.Format(CultureInfo.CurrentCulture, SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri));
+ throw new CryptographicException(SR.Format(SR.Cryptography_Xml_SelfReferenceRequiresContext, _uri));
// We should not discard comments here!!!
resolver = (SignedXml.ResolverSet ? SignedXml._xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), baseUri));
{
_canonicalizationMethodTransform = CryptoHelpers.CreateFromName<Transform>(CanonicalizationMethod);
if (_canonicalizationMethodTransform == null)
- throw new CryptographicException(string.Format(CultureInfo.CurrentCulture, SR.Cryptography_Xml_CreateTransformFailed, CanonicalizationMethod));
+ throw new CryptographicException(SR.Format(SR.Cryptography_Xml_CreateTransformFailed, CanonicalizationMethod));
_canonicalizationMethodTransform.SignedXml = SignedXml;
_canonicalizationMethodTransform.Reference = null;
}
string keyName = null;
if (cspKey != null && cspKey.CspKeyContainerInfo.KeyContainerName != null)
{
- keyName = string.Format(CultureInfo.InvariantCulture,
- "\"{0}\"",
- cspKey.CspKeyContainerInfo.KeyContainerName);
+ keyName = "\"" + cspKey.CspKeyContainerInfo.KeyContainerName + "\"";
}
else if (certificate2 != null)
{
- keyName = string.Format(CultureInfo.InvariantCulture,
- "\"{0}\"",
- certificate2.GetNameInfo(X509NameType.SimpleName, false));
+ keyName = "\"" + certificate2.GetNameInfo(X509NameType.SimpleName, false) + "\"";
}
else if (certificate != null)
{
- keyName = string.Format(CultureInfo.InvariantCulture,
- "\"{0}\"",
- certificate.Subject);
+ keyName = "\"" + certificate.Subject + "\"";
}
else
{
if (InformationLoggingEnabled)
{
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_BeginCanonicalization,
canonicalizationTransform.Algorithm,
canonicalizationTransform.GetType().Name);
if (VerboseLoggingEnabled)
{
- string canonicalizationSettings = string.Format(CultureInfo.InvariantCulture,
+ string canonicalizationSettings = SR.Format(CultureInfo.InvariantCulture,
SR.Log_CanonicalizationSettings,
canonicalizationTransform.Resolver.GetType(),
canonicalizationTransform.BaseURI);
{
MethodInfo validationMethod = formatValidator.Method;
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_CheckSignatureFormat,
validationMethod.Module.Assembly.FullName,
validationMethod.DeclaringType.FullName,
if (InformationLoggingEnabled)
{
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_CheckSignedInfo,
signedInfo.Id != null ? signedInfo.Id : NullString);
WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCheckSignedInfo, logMessage);
if (VerboseLoggingEnabled)
{
- string contextData = string.Format(CultureInfo.InvariantCulture,
+ string contextData = SR.Format(CultureInfo.InvariantCulture,
SR.Log_XmlContext,
context != null ? context.OuterXml : NullString);
if (VerboseLoggingEnabled)
{
- string contextData = string.Format(CultureInfo.InvariantCulture,
+ string contextData = SR.Format(CultureInfo.InvariantCulture,
SR.Log_XmlContext,
context != null ? context.OuterXml : NullString);
{
using (StreamReader reader = new StreamReader(canonicalizationTransform.GetOutput(typeof(Stream)) as Stream))
{
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_CanonicalizedOutput,
reader.ReadToEnd());
WriteLine(signedXml,
validAlgorithmBuilder.AppendFormat("\"{0}\"", validAlgorithm);
}
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_UnsafeCanonicalizationMethod,
algorithm,
validAlgorithmBuilder.ToString());
validAlgorithmBuilder.AppendFormat("\"{0}\"", validAlgorithm);
}
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_UnsafeTransformMethod,
algorithm,
validAlgorithmBuilder.ToString());
{
foreach (XmlAttribute propagatedNamespace in namespaces)
{
- string propagationMessage = string.Format(CultureInfo.InvariantCulture,
+ string propagationMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_PropagatingNamespace,
propagatedNamespace.Name,
propagatedNamespace.Value);
} while (readBytes == buffer.Length);
// Log out information about it
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_TransformedReferenceContents,
Encoding.UTF8.GetString(ms.ToArray()));
WriteLine(reference,
if (InformationLoggingEnabled)
{
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_SigningAsymmetric,
GetKeyName(key),
signatureDescription.GetType().Name,
if (InformationLoggingEnabled)
{
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_SigningHmac,
key.GetType().Name);
{
HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName<HashAlgorithm>(reference.DigestMethod);
string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name;
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_SigningReference,
GetObjectId(reference),
reference.Uri,
{
if (InformationLoggingEnabled)
{
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_VerificationFailed,
failureLocation);
if (InformationLoggingEnabled)
{
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_KeyUsages,
keyUsages.KeyUsages,
GetOidName(keyUsages.Oid),
if (InformationLoggingEnabled)
{
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_VerifyReference,
GetObjectId(reference),
reference.Uri,
{
HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName<HashAlgorithm>(reference.DigestMethod);
string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name;
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_ReferenceHash,
GetObjectId(reference),
reference.DigestMethod,
if (InformationLoggingEnabled)
{
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_VerifySignedInfoAsymmetric,
GetKeyName(key),
signatureDescription.GetType().Name,
if (VerboseLoggingEnabled)
{
- string hashLog = string.Format(CultureInfo.InvariantCulture,
+ string hashLog = SR.Format(CultureInfo.InvariantCulture,
SR.Log_ActualHashValue,
FormatBytes(actualHashValue));
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, hashLog);
- string signatureLog = string.Format(CultureInfo.InvariantCulture,
+ string signatureLog = SR.Format(CultureInfo.InvariantCulture,
SR.Log_RawSignatureValue,
FormatBytes(signatureValue));
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, signatureLog);
if (InformationLoggingEnabled)
{
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_VerifySignedInfoHmac,
mac.GetType().Name);
WriteLine(signedXml,
if (VerboseLoggingEnabled)
{
- string hashLog = string.Format(CultureInfo.InvariantCulture,
+ string hashLog = SR.Format(CultureInfo.InvariantCulture,
SR.Log_ActualHashValue,
FormatBytes(actualHashValue));
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, hashLog);
- string signatureLog = string.Format(CultureInfo.InvariantCulture,
+ string signatureLog = SR.Format(CultureInfo.InvariantCulture,
SR.Log_RawSignatureValue,
FormatBytes(signatureValue));
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.VerifySignedInfo, signatureLog);
if (InformationLoggingEnabled)
{
- string buildMessage = string.Format(CultureInfo.InvariantCulture,
+ string buildMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_BuildX509Chain,
GetKeyName(certificate));
WriteLine(signedXml,
if (VerboseLoggingEnabled)
{
// Dump out the flags and other miscelanious information used for building
- string revocationMode = string.Format(CultureInfo.InvariantCulture,
+ string revocationMode = SR.Format(CultureInfo.InvariantCulture,
SR.Log_RevocationMode,
chain.ChainPolicy.RevocationFlag);
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, revocationMode);
- string revocationFlag = string.Format(CultureInfo.InvariantCulture,
+ string revocationFlag = SR.Format(CultureInfo.InvariantCulture,
SR.Log_RevocationFlag,
chain.ChainPolicy.RevocationFlag);
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, revocationFlag);
- string verificationFlags = string.Format(CultureInfo.InvariantCulture,
+ string verificationFlags = SR.Format(CultureInfo.InvariantCulture,
SR.Log_VerificationFlag,
chain.ChainPolicy.VerificationFlags);
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, verificationFlags);
- string verificationTime = string.Format(CultureInfo.InvariantCulture,
+ string verificationTime = SR.Format(CultureInfo.InvariantCulture,
SR.Log_VerificationTime,
chain.ChainPolicy.VerificationTime);
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, verificationTime);
- string urlTimeout = string.Format(CultureInfo.InvariantCulture,
+ string urlTimeout = SR.Format(CultureInfo.InvariantCulture,
SR.Log_UrlTimeout,
chain.ChainPolicy.UrlRetrievalTimeout);
WriteLine(signedXml, TraceEventType.Verbose, SignedXmlDebugEvent.X509Verification, urlTimeout);
{
if (status.Status != X509ChainStatusFlags.NoError)
{
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_X509ChainError,
status.Status,
status.StatusInformation);
{
HashAlgorithm hashAlgorithm = CryptoHelpers.CreateFromName<HashAlgorithm>(reference.DigestMethod);
string hashAlgorithmName = hashAlgorithm == null ? "null" : hashAlgorithm.GetType().Name;
- string logMessage = string.Format(CultureInfo.InvariantCulture,
+ string logMessage = SR.Format(CultureInfo.InvariantCulture,
SR.Log_SignedXmlRecursionLimit,
GetObjectId(reference),
reference.DigestMethod,
// Rare case that we have defined a type of identity reference and not included it in the code logic above.
// To avoid this we do not allow IdentityReference to be subclassed outside of the BCL.
//
- Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
+ Debug.Fail("Source type is an IdentityReference type which has not been included in translation logic.");
throw new NotSupportedException();
}
}
// Rare case that we have defined a type of identity reference and not included it in the code logic above.
// To avoid this we do not allow IdentityReference to be subclassed outside of the BCL.
//
- Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
+ Debug.Fail("Source type is an IdentityReference type which has not been included in translation logic.");
throw new NotSupportedException();
}
}
// Rare case that we have defined a type of identity reference and not included it in the code logic above.
// To avoid this we do not allow IdentityReference to be subclassed outside of the BCL.
//
- Debug.Assert(false, "Source type is an IdentityReference type which has not been included in translation logic.");
+ Debug.Fail("Source type is an IdentityReference type which has not been included in translation logic.");
throw new NotSupportedException();
}
}
{
// this should never happen since we are already validating account name length in constructor and
// it is less than this limit
- Debug.Assert(false, "NTAccount::TranslateToSids - source account name is too long.");
+ Debug.Fail("NTAccount::TranslateToSids - source account name is too long.");
throw new InvalidOperationException();
}
if (unchecked((int)win32ErrorCode) != Interop.Errors.ERROR_TRUSTED_RELATIONSHIP_FAILURE)
{
- Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Interop.LsaLookupNames(2) returned unrecognized error {0}", win32ErrorCode));
+ Debug.Fail($"Interop.LsaLookupNames(2) returned unrecognized error {win32ErrorCode}");
}
throw new Win32Exception(unchecked((int)win32ErrorCode));
}
else if (Error != Interop.Errors.ERROR_SUCCESS)
{
- Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.CreateSidFromString returned unrecognized error {0}", Error));
+ Debug.Fail($"Win32.CreateSidFromString returned unrecognized error {Error}");
throw new Win32Exception(Error);
}
}
else if (ErrorCode != Interop.Errors.ERROR_SUCCESS)
{
- Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.GetWindowsAccountDomainSid returned unrecognized error {0}", ErrorCode));
+ Debug.Fail($"Win32.GetWindowsAccountDomainSid returned unrecognized error {ErrorCode}");
throw new Win32Exception(ErrorCode);
}
}
else if (Error != Interop.Errors.ERROR_SUCCESS)
{
- Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.CreateWellKnownSid returned unrecognized error {0}", Error));
+ Debug.Fail($"Win32.CreateWellKnownSid returned unrecognized error {Error}");
throw new Win32Exception(Error);
}
}
else if (Error != Interop.Errors.ERROR_SUCCESS)
{
- Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32.GetWindowsAccountDomainSid returned unrecognized error {0}", Error));
+ Debug.Fail($"Win32.GetWindowsAccountDomainSid returned unrecognized error {Error}");
throw new Win32Exception(Error);
}
return ResultSid;
{
uint win32ErrorCode = Interop.Advapi32.LsaNtStatusToWinError(ReturnCode);
- Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Interop.LsaLookupSids returned {0}", win32ErrorCode));
+ Debug.Fail($"Interop.LsaLookupSids returned {win32ErrorCode}");
throw new Win32Exception(unchecked((int)win32ErrorCode));
}
if (!parsed || (hour < 0 || hour > 23))
{
- throw new FormatException(string.Format(SR.InvalidSkipHourValue, value));
+ throw new FormatException(SR.Format(SR.InvalidSkipHourValue, value));
}
skipHours.Add(hour);
catch (Exception e)
{
_status.currentState = ServiceControlStatus.STATE_PAUSED;
- WriteLogEntry(SR.Format(SR.ContinueFailed, e.ToString()), true);
+ WriteLogEntry(SR.Format(SR.ContinueFailed, e), true);
// We re-throw the exception so that the advapi32 code can report
// ERROR_EXCEPTION_IN_SERVICE as it would for native services.
}
catch (Exception e)
{
- WriteLogEntry(SR.Format(SR.CommandFailed, e.ToString()), true);
+ WriteLogEntry(SR.Format(SR.CommandFailed, e), true);
// We should re-throw the exception so that the advapi32 code can report
// ERROR_EXCEPTION_IN_SERVICE as it would for native services.
catch (Exception e)
{
_status.currentState = ServiceControlStatus.STATE_RUNNING;
- WriteLogEntry(SR.Format(SR.PauseFailed, e.ToString()), true);
+ WriteLogEntry(SR.Format(SR.PauseFailed, e), true);
// We re-throw the exception so that the advapi32 code can report
// ERROR_EXCEPTION_IN_SERVICE as it would for native services.
}
catch (Exception e)
{
- WriteLogEntry(SR.Format(SR.PowerEventFailed, e.ToString()), true);
+ WriteLogEntry(SR.Format(SR.PowerEventFailed, e), true);
// We rethrow the exception so that advapi32 code can report
// ERROR_EXCEPTION_IN_SERVICE as it would for native services.
}
catch (Exception e)
{
- WriteLogEntry(SR.Format(SR.SessionChangeFailed, e.ToString()), true);
+ WriteLogEntry(SR.Format(SR.SessionChangeFailed, e), true);
// We rethrow the exception so that advapi32 code can report
// ERROR_EXCEPTION_IN_SERVICE as it would for native services.
{
_status.currentState = previousState;
SetServiceStatus(_statusHandle, pStatus);
- WriteLogEntry(SR.Format(SR.StopFailed, e.ToString()), true);
+ WriteLogEntry(SR.Format(SR.StopFailed, e), true);
throw;
}
}
try
{
OnShutdown();
- WriteLogEntry(SR.Format(SR.ShutdownOK));
+ WriteLogEntry(SR.ShutdownOK);
if (_status.currentState == ServiceControlStatus.STATE_PAUSED || _status.currentState == ServiceControlStatus.STATE_RUNNING)
{
}
catch (Exception e)
{
- WriteLogEntry(SR.Format(SR.ShutdownFailed, e.ToString()), true);
+ WriteLogEntry(SR.Format(SR.ShutdownFailed, e), true);
throw;
}
}
}
catch (Exception e)
{
- WriteLogEntry(SR.Format(SR.StartFailed, e.ToString()), true);
+ WriteLogEntry(SR.Format(SR.StartFailed, e), true);
_status.currentState = ServiceControlStatus.STATE_STOPPED;
// We capture the exception so that it can be propagated
}
if (!ServiceBase.ValidServiceName(value))
- throw new ArgumentException(SR.Format(SR.ServiceName, value, ServiceBase.MaxNameLength.ToString(CultureInfo.CurrentCulture)));
+ throw new ArgumentException(SR.Format(SR.ServiceName, value, ServiceBase.MaxNameLength.ToString()));
Close();
_name = value;
string userGivenName = String.IsNullOrEmpty(_eitherName) ? _displayName : _eitherName;
if (String.IsNullOrEmpty(userGivenName))
- throw new InvalidOperationException(SR.Format(SR.ServiceName, userGivenName, ServiceBase.MaxNameLength.ToString(CultureInfo.CurrentCulture)));
+ throw new InvalidOperationException(SR.Format(SR.ServiceName, userGivenName, ServiceBase.MaxNameLength.ToString()));
// Try it as a display name
string result = GetServiceKeyName(_serviceManagerHandle, userGivenName);
Debug.Assert(((bLastVirama ? 1 : 0) + (bLastATR ? 1 : 0) +
(bLastDevenagariStressAbbr ? 1 : 0) +
((cLastCharForNextNukta > 0) ? 1 : 0)) == 1,
- string.Format(CultureInfo.InvariantCulture,
- "[ISCIIEncoding.GetChars]Special cases require 1 and only 1 special case flag: LastATR {0} Dev. {1} Nukta {2}",
- bLastATR, bLastDevenagariStressAbbr, cLastCharForNextNukta));
+ $"[ISCIIEncoding.GetChars]Special cases require 1 and only 1 special case flag: LastATR {bLastATR} Dev. {bLastDevenagariStressAbbr} Nukta {cLastCharForNextNukta}");
// If the last one was an ATR, then we'll have to do ATR stuff
if (bLastATR)
{
// We must be the Devenagari special case for F0, B8 & F0, BF
Debug.Assert(currentCodePage == CodeDevanagari && b == DevenagariExt,
- string.Format(CultureInfo.InvariantCulture,
- "[ISCIIEncoding.GetChars] Devenagari special case must {0} not {1} or in Devanagari code page {2} not {3}.",
- DevenagariExt, b, CodeDevanagari, currentCodePage));
+ $"[ISCIIEncoding.GetChars] Devenagari special case must {DevenagariExt} not {b} or in Devanagari code page {CodeDevanagari} not {currentCodePage}.");
bLastDevenagariStressAbbr = bLastSpecial = true;
}
ushort byteTemp;
while ((byteTemp = *((ushort*)pData)) != 0)
{
- Debug.Assert(arrayTemp[byteTemp] == UNKNOWN_CHAR, string.Format(CultureInfo.InvariantCulture,
- "[SBCSCodePageEncoding::ReadBestFitTable] Expected unallocated byte (not 0x{2:X2}) for best fit byte at 0x{0:X2} for code page {1}",
- byteTemp, CodePage, (int)arrayTemp[byteTemp]));
+ Debug.Assert(arrayTemp[byteTemp] == UNKNOWN_CHAR, $"[SBCSCodePageEncoding::ReadBestFitTable] Expected unallocated byte (not 0x{(int)arrayTemp[byteTemp]:X2}) for best fit byte at 0x{byteTemp:X2} for code page {CodePage}");
pData += 2;
arrayTemp[byteTemp] = *((char*)pData);
// This won't work if it won't round trip.
Debug.Assert(arrayTemp[iBestFitCount - 1] != (char)0,
- string.Format(CultureInfo.InvariantCulture,
- "[SBCSCodePageEncoding.ReadBestFitTable] No valid Unicode value {0:X4} for round trip bytes {1:X4}, encoding {2}",
- (int)_mapBytesToUnicode[input], (int)input, CodePage));
+ $"[SBCSCodePageEncoding.ReadBestFitTable] No valid Unicode value {(int)_mapBytesToUnicode[input]:X4} for round trip bytes {(int)input:X4}, encoding {CodePage}");
}
unicodePosition++;
}
}
else
{
- return new InvalidOperationException(SR.Format(SR.EmptyJsonIsInvalid));
+ return new InvalidOperationException(SR.EmptyJsonIsInvalid);
}
}
builder.Append("...");
}
- throw new ArgumentException(SR.Format(SR.CannotWriteInvalidUTF8, builder.ToString()));
+ throw new ArgumentException(SR.Format(SR.CannotWriteInvalidUTF8, builder));
}
public static void ThrowArgumentException_InvalidUTF16(int charAsInt)
return 3;
default:
- throw new ArgumentException(SR.Format(SR.UnexpectedOpcode, opcode.ToString(CultureInfo.CurrentCulture)));
+ throw new ArgumentException(SR.Format(SR.UnexpectedOpcode, opcode.ToString()));
}
}
if (IsCaptureSlot(capnum))
return new RegexNode(RegexNode.Testref, _options, capnum);
else
- throw MakeException(RegexParseError.UndefinedReference, SR.Format(SR.UndefinedReference, capnum.ToString(CultureInfo.CurrentCulture)));
+ throw MakeException(RegexParseError.UndefinedReference, SR.Format(SR.UndefinedReference, capnum.ToString()));
}
else
- throw MakeException(RegexParseError.MalformedReference, SR.Format(SR.MalformedReference, capnum.ToString(CultureInfo.CurrentCulture)));
+ throw MakeException(RegexParseError.MalformedReference, SR.Format(SR.MalformedReference, capnum.ToString()));
}
else if (RegexCharClass.IsWordChar(ch))
{
if (IsCaptureSlot(capnum))
return new RegexNode(RegexNode.Ref, _options, capnum);
else
- throw MakeException(RegexParseError.UndefinedBackref, SR.Format(SR.UndefinedBackref, capnum.ToString(CultureInfo.CurrentCulture)));
+ throw MakeException(RegexParseError.UndefinedBackref, SR.Format(SR.UndefinedBackref, capnum.ToString()));
}
}
if (IsCaptureSlot(capnum))
return new RegexNode(RegexNode.Ref, _options, capnum);
else if (capnum <= 9)
- throw MakeException(RegexParseError.UndefinedBackref, SR.Format(SR.UndefinedBackref, capnum.ToString(CultureInfo.CurrentCulture)));
+ throw MakeException(RegexParseError.UndefinedBackref, SR.Format(SR.UndefinedBackref, capnum.ToString()));
}
}
break;
default:
- throw new ArgumentException(SR.Format(SR.UnexpectedOpcode, nodetype.ToString(CultureInfo.CurrentCulture)));
+ throw new ArgumentException(SR.Format(SR.UnexpectedOpcode, nodetype.ToString()));
}
}
}
{
get
{
- Debug.Assert(false, "PromotableSinglePhaseNotification called for a non promotable enlistment.");
+ Debug.Fail("PromotableSinglePhaseNotification called for a non promotable enlistment.");
throw new NotImplementedException();
}
}
{
get
{
- Debug.Assert(false, "ResourceManagerIdentifier called for non durable enlistment");
+ Debug.Fail("ResourceManagerIdentifier called for non durable enlistment");
throw new NotImplementedException();
}
}
internal virtual void InternalAborted(InternalEnlistment enlistment)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for InternalEnlistment State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for InternalEnlistment State; Current State: {GetType()}");
throw TransactionException.CreateEnlistmentStateException(null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void InternalCommitted(InternalEnlistment enlistment)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for InternalEnlistment State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for InternalEnlistment State; Current State: {GetType()}");
throw TransactionException.CreateEnlistmentStateException(null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void InternalIndoubt(InternalEnlistment enlistment)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for InternalEnlistment State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for InternalEnlistment State; Current State: {GetType()}");
throw TransactionException.CreateEnlistmentStateException(null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void ChangeStateCommitting(InternalEnlistment enlistment)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for InternalEnlistment State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for InternalEnlistment State; Current State: {GetType()}");
throw TransactionException.CreateEnlistmentStateException(null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void ChangeStatePromoted(InternalEnlistment enlistment, IPromotedEnlistment promotedEnlistment)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for InternalEnlistment State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for InternalEnlistment State; Current State: {GetType()}");
throw TransactionException.CreateEnlistmentStateException(null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void ChangeStateDelegated(InternalEnlistment enlistment)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for InternalEnlistment State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for InternalEnlistment State; Current State: {GetType()}");
throw TransactionException.CreateEnlistmentStateException(null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void ChangeStatePreparing(InternalEnlistment enlistment)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for InternalEnlistment State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for InternalEnlistment State; Current State: {GetType()}");
throw TransactionException.CreateEnlistmentStateException(null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
internal virtual void ChangeStateSinglePhaseCommit(InternalEnlistment enlistment)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for InternalEnlistment State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for InternalEnlistment State; Current State: {GetType()}");
throw TransactionException.CreateEnlistmentStateException(null, enlistment == null ? Guid.Empty : enlistment.DistributedTxId);
}
}
default:
{
- Debug.Assert(false, "InternalTransaction.DistributedTransactionOutcome - Unexpected TransactionStatus");
+ Debug.Fail("InternalTransaction.DistributedTransactionOutcome - Unexpected TransactionStatus");
TransactionException.CreateInvalidOperationException(TraceSourceType.TraceSourceLtm,
"",
null,
{
string messagewithTxId = SR.EnlistmentStateException;
if (IncludeDistributedTxId(distributedTxId))
- messagewithTxId = string.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
+ messagewithTxId = SR.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
if (IncludeDistributedTxId(distributedTxId))
{
- return new TransactionException(string.Format(SR.DistributedTxIDInTransactionException, message, distributedTxId));
+ return new TransactionException(SR.Format(SR.DistributedTxIDInTransactionException, message, distributedTxId));
}
return new TransactionException(message);
}
{
string messagewithTxId = message;
if (IncludeDistributedTxId(distributedTxId))
- messagewithTxId = string.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
+ messagewithTxId = SR.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
return Create(messagewithTxId, innerException);
}
{
string messagewithTxId = message;
if (IncludeDistributedTxId(distributedTxId))
- messagewithTxId = string.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
+ messagewithTxId = SR.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
return Create(traceSource, messagewithTxId, innerException);
}
{
if (IncludeDistributedTxId(distributedTxId))
{
- return new TransactionException(string.Format(SR.DistributedTxIDInTransactionException, message, distributedTxId));
+ return new TransactionException(SR.Format(SR.DistributedTxIDInTransactionException, message, distributedTxId));
}
return new TransactionException(message);
}
{
string messagewithTxId = SR.TransactionAlreadyCompleted;
if (IncludeDistributedTxId(distributedTxId))
- messagewithTxId = string.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
+ messagewithTxId = SR.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
string messagewithTxId = message;
if (IncludeDistributedTxId(distributedTxId))
- messagewithTxId = string.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
+ messagewithTxId = SR.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
return CreateInvalidOperationException(traceSource, messagewithTxId, innerException);
}
{
string messagewithTxId = message;
if (IncludeDistributedTxId(distributedTxId))
- messagewithTxId = string.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
+ messagewithTxId = SR.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
return TransactionAbortedException.Create(messagewithTxId, innerException);
}
internal TransactionAbortedException(Exception innerException, Guid distributedTxId) :
base(IncludeDistributedTxId(distributedTxId) ?
- string.Format(SR.DistributedTxIDInTransactionException, SR.TransactionAborted, distributedTxId)
+ SR.Format(SR.DistributedTxIDInTransactionException, SR.TransactionAborted, distributedTxId)
: SR.TransactionAborted, innerException)
{
}
{
string messagewithTxId = message;
if (IncludeDistributedTxId(distributedTxId))
- messagewithTxId = string.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
+ messagewithTxId = SR.Format(SR.DistributedTxIDInTransactionException, messagewithTxId, distributedTxId);
return TransactionInDoubtException.Create(traceSource, messagewithTxId, innerException);
}
internal virtual void EndCommit(InternalTransaction tx)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for State; Current State: {GetType()}");
throw TransactionException.CreateTransactionStateException(tx._innerException, tx.DistributedTxId);
}
internal virtual void ChangeStateTransactionAborted(InternalTransaction tx, Exception e)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for State; Current State: {GetType()}");
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
internal virtual void ChangeStateTransactionCommitted(InternalTransaction tx)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for State; Current State: {GetType()}");
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
internal virtual void InDoubtFromEnlistment(InternalTransaction tx)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for State; Current State: {GetType()}");
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
internal virtual void ChangeStatePromotedAborted(InternalTransaction tx)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for State; Current State: {GetType()}");
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
internal virtual void ChangeStatePromotedCommitted(InternalTransaction tx)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for State; Current State: {GetType()}");
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
internal virtual void InDoubtFromDtc(InternalTransaction tx)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for State; Current State: {GetType()}");
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
internal virtual void ChangeStatePromotedPhase0(InternalTransaction tx)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for State; Current State: {GetType()}");
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
internal virtual void ChangeStatePromotedPhase1(InternalTransaction tx)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for State; Current State: {GetType()}");
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
internal virtual void ChangeStateAbortedDuringPromotion(InternalTransaction tx)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for State; Current State: {GetType()}");
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
internal virtual void Phase0VolatilePrepareDone(InternalTransaction tx)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for State; Current State: {GetType()}");
throw TransactionException.CreateTransactionStateException(tx._innerException, tx.DistributedTxId);
}
internal virtual void Phase1VolatilePrepareDone(InternalTransaction tx)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for State; Current State: {GetType()}");
throw TransactionException.CreateTransactionStateException(tx._innerException, tx.DistributedTxId);
}
internal virtual void RestartCommitIfNeeded(InternalTransaction tx)
{
- Debug.Assert(false, string.Format(null, "Invalid Event for State; Current State: {0}", GetType()));
+ Debug.Fail($"Invalid Event for State; Current State: {GetType()}");
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
distributedTx = TransactionStatePSPEOperation.PSPEPromote(tx);
- Debug.Assert((distributedTx == null), string.Format(null, "PSPEPromote for non-MSDTC promotion returned a distributed transaction."));
- Debug.Assert((tx.promotedToken != null), string.Format(null, "PSPEPromote for non-MSDTC promotion did not set InternalTransaction.PromotedToken."));
+ Debug.Assert((distributedTx == null), "PSPEPromote for non-MSDTC promotion returned a distributed transaction.");
+ Debug.Assert((tx.promotedToken != null), "PSPEPromote for non-MSDTC promotion did not set InternalTransaction.PromotedToken.");
}
catch (TransactionPromotionException e)
{
if (left == null || right == null || bottom == null || top == null ||
!(left is int) || !(right is int) || !(bottom is int) || !(top is int))
{
- throw new ArgumentException(SR.Format(SR.PropertyValueInvalidEntry));
+ throw new ArgumentException(SR.PropertyValueInvalidEntry);
}
return new Margins((int)left,