1
0
Fork 0
mirror of https://github.com/VSadov/Satori.git synced 2025-06-09 09:34:49 +09:00

Fix argument exception warnings on runtime (#35717)

* Fix argument exception warnings on runtime

* Apply feedback

* Addressing feedback and test fix

* Fix test failures

* Fix tests for NetFx run

* Fix suppressed warning for socket.SendAsyn(e) and fix corresponding tests

* Applied feedback
This commit is contained in:
buyaa-n 2020-05-15 13:55:30 -07:00 committed by GitHub
parent ca0fd167d5
commit ee0aadc3da
Signed by: github
GPG key ID: 4AEE18F83AFDEB23
99 changed files with 257 additions and 236 deletions

View file

@ -155,6 +155,7 @@ csharp_space_between_square_brackets = false
# Analyzers
dotnet_code_quality.ca1802.api_surface = private, internal
dotnet_code_quality.CA2208.api_surface = public
# C++ Files
[*.{cpp,h,in}]

View file

@ -106,7 +106,7 @@
<Rule Id="CA2200" Action="Warning" /> <!-- Rethrow to preserve stack details. -->
<Rule Id="CA2201" Action="None" /> <!-- Do not raise reserved exception types -->
<Rule Id="CA2207" Action="Warning" /> <!-- Initialize value type static fields inline -->
<Rule Id="CA2208" Action="None" /> <!-- Instantiate argument exceptions correctly -->
<Rule Id="CA2208" Action="Info" /> <!-- Instantiate argument exceptions correctly -->
<Rule Id="CA2211" Action="None" /> <!-- Non-constant fields should not be visible -->
<Rule Id="CA2213" Action="None" /> <!-- Disposable fields should be disposed -->
<Rule Id="CA2214" Action="None" /> <!-- Do not call overridable methods in constructors -->

View file

@ -124,7 +124,7 @@ namespace Internal.Runtime.InteropServices
if (!Path.IsPathRooted(cxt.AssemblyPath))
{
throw new ArgumentException();
throw new ArgumentException(null, nameof(cxt));
}
Type classType = FindClassType(cxt.ClassId, cxt.AssemblyPath, cxt.AssemblyName, cxt.TypeName);
@ -156,7 +156,7 @@ namespace Internal.Runtime.InteropServices
if (!Path.IsPathRooted(cxt.AssemblyPath))
{
throw new ArgumentException();
throw new ArgumentException(null, nameof(cxt));
}
Type classType = FindClassType(cxt.ClassId, cxt.AssemblyPath, cxt.AssemblyName, cxt.TypeName);
@ -288,7 +288,7 @@ $@"{nameof(RegisterClassForTypeInternal)} arguments:
if (cxtInt.InterfaceId != Guid.Empty
|| cxtInt.ClassFactoryDest != IntPtr.Zero)
{
throw new ArgumentException();
throw new ArgumentException(null, nameof(pCxtInt));
}
try
@ -328,7 +328,7 @@ $@"{nameof(UnregisterClassForTypeInternal)} arguments:
if (cxtInt.InterfaceId != Guid.Empty
|| cxtInt.ClassFactoryDest != IntPtr.Zero)
{
throw new ArgumentException();
throw new ArgumentException(null, nameof(pCxtInt));
}
try

View file

@ -85,7 +85,9 @@ namespace System
// malicious caller to increment the pointer to an arbitrary
// location in memory and read the contents.
if (ArgPtr == IntPtr.Zero)
#pragma warning disable CA2208 // Instantiate argument exceptions correctly, the argument not applicable
throw new ArgumentNullException();
#pragma warning restore CA2208
TypedReference result = default;
// reference to TypedReference is banned, so have to pass result as pointer

View file

@ -135,7 +135,7 @@ namespace System
if ((4 == IntPtr.Size) && (bytesAllocated > int.MaxValue))
{
throw new ArgumentOutOfRangeException("pressure",
throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
SR.ArgumentOutOfRange_MustBeNonNegInt32);
}

View file

@ -136,7 +136,7 @@ namespace System.Runtime.InteropServices
{
IntPtr ptr;
if (!TryGetOrCreateComInterfaceForObjectInternal(this, instance, flags, out ptr))
throw new ArgumentException();
throw new ArgumentException(null, nameof(instance));
return ptr;
}
@ -215,7 +215,7 @@ namespace System.Runtime.InteropServices
{
object? obj;
if (!TryGetOrCreateObjectForComInstanceInternal(this, externalComObject, flags, null, out obj))
throw new ArgumentNullException();
throw new ArgumentNullException(nameof(externalComObject));
return obj!;
}
@ -271,7 +271,7 @@ namespace System.Runtime.InteropServices
object? obj;
if (!TryGetOrCreateObjectForComInstanceInternal(this, externalComObject, flags, wrapper, out obj))
throw new ArgumentNullException();
throw new ArgumentNullException(nameof(externalComObject));
return obj!;
}

View file

@ -2755,7 +2755,7 @@ namespace System
protected override PropertyInfo? GetPropertyImpl(
string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers)
{
if (name == null) throw new ArgumentNullException();
if (name == null) throw new ArgumentNullException(nameof(name));
ListBuilder<PropertyInfo> candidates = GetPropertyCandidates(name, bindingAttr, types, false);
@ -2791,7 +2791,7 @@ namespace System
public override EventInfo? GetEvent(string name, BindingFlags bindingAttr)
{
if (name is null) throw new ArgumentNullException();
if (name is null) throw new ArgumentNullException(nameof(name));
FilterHelper(bindingAttr, ref name, out _, out MemberListType listType);
@ -2854,7 +2854,7 @@ namespace System
public override Type? GetInterface(string fullname, bool ignoreCase)
{
if (fullname is null) throw new ArgumentNullException();
if (fullname is null) throw new ArgumentNullException(nameof(fullname));
BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic;
@ -2888,7 +2888,7 @@ namespace System
public override Type? GetNestedType(string fullname, BindingFlags bindingAttr)
{
if (fullname is null) throw new ArgumentNullException();
if (fullname is null) throw new ArgumentNullException(nameof(fullname));
bindingAttr &= ~BindingFlags.Static;
string name, ns;
@ -2916,7 +2916,7 @@ namespace System
public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr)
{
if (name is null) throw new ArgumentNullException();
if (name is null) throw new ArgumentNullException(nameof(name));
ListBuilder<MethodInfo> methods = default;
ListBuilder<ConstructorInfo> constructors = default;

View file

@ -260,7 +260,7 @@ namespace System.Threading
get;
}
private static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException
private static RegisteredWaitHandle RegisterWaitForSingleObject(
WaitHandle waitObject,
WaitOrTimerCallback callBack,
object? state,

View file

@ -42,7 +42,7 @@ namespace System.Buffers
public ArrayBufferWriter(int initialCapacity)
{
if (initialCapacity <= 0)
throw new ArgumentException(nameof(initialCapacity));
throw new ArgumentException(null, nameof(initialCapacity));
_buffer = new T[initialCapacity];
_index = 0;
@ -101,7 +101,7 @@ namespace System.Buffers
public void Advance(int count)
{
if (count < 0)
throw new ArgumentException(nameof(count));
throw new ArgumentException(null, nameof(count));
if (_index > _buffer.Length - count)
ThrowInvalidOperationException_AdvancedTooFar(_buffer.Length);

View file

@ -43,7 +43,7 @@ namespace System.Threading.Tasks
return;
}
throw new ArgumentNullException();
throw new ArgumentNullException(nameof(asyncResult));
}
/// <summary>Processes an IAsyncResult returned by Begin.</summary>
@ -55,7 +55,7 @@ namespace System.Threading.Tasks
return task.GetAwaiter().GetResult();
}
throw new ArgumentNullException();
throw new ArgumentNullException(nameof(asyncResult));
}
/// <summary>Provides a simple IAsyncResult that wraps a Task.</summary>

View file

@ -27,7 +27,7 @@ namespace System
Assert.Contains(expectedMessageContent, Assert.Throws<T>(action).Message);
}
public static void Throws<T>(string netCoreParamName, string netFxParamName, Action action)
public static T Throws<T>(string netCoreParamName, string netFxParamName, Action action)
where T : ArgumentException
{
T exception = Assert.Throws<T>(action);
@ -35,7 +35,7 @@ namespace System
if (netFxParamName == null && IsNetFramework)
{
// Param name varies between .NET Framework versions -- skip checking it
return;
return exception;
}
string expectedParamName =
@ -43,6 +43,7 @@ namespace System
netFxParamName : netCoreParamName;
Assert.Equal(expectedParamName, exception.ParamName);
return exception;
}
public static void Throws<T>(string netCoreParamName, string netFxParamName, Func<object> testCode)

View file

@ -29,7 +29,7 @@ namespace Microsoft.Extensions.Configuration
}
if (source.Configuration == null)
{
throw new ArgumentNullException(nameof(source.Configuration));
throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "source.Configuration"), nameof(source));
}
_config = source.Configuration;

View file

@ -120,4 +120,7 @@
<data name="Error_NoSources" xml:space="preserve">
<value>A configuration source is not registered. Please register one before setting a value.</value>
</data>
<data name="InvalidNullArgument" xml:space="preserve">
<value>Null is not a valid value for '{0}'.</value>
</data>
</root>

View file

@ -13,11 +13,11 @@ namespace Microsoft.Extensions.DependencyModel
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException(nameof(name));
throw new ArgumentException(null, nameof(name));
}
if (string.IsNullOrEmpty(version))
{
throw new ArgumentException(nameof(version));
throw new ArgumentException(null, nameof(version));
}
Name = name;
Version = version;

View file

@ -43,15 +43,15 @@ namespace Microsoft.Extensions.DependencyModel
{
if (string.IsNullOrEmpty(type))
{
throw new ArgumentException(nameof(type));
throw new ArgumentException(null, nameof(type));
}
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException(nameof(name));
throw new ArgumentException(null, nameof(name));
}
if (string.IsNullOrEmpty(version))
{
throw new ArgumentException(nameof(version));
throw new ArgumentException(null, nameof(version));
}
if (dependencies == null)
{

View file

@ -12,11 +12,11 @@ namespace Microsoft.Extensions.DependencyModel
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentException(nameof(path));
throw new ArgumentException(null, nameof(path));
}
if (string.IsNullOrEmpty(locale))
{
throw new ArgumentException(nameof(locale));
throw new ArgumentException(null, nameof(locale));
}
Locale = locale;
Path = path;
@ -27,4 +27,4 @@ namespace Microsoft.Extensions.DependencyModel
public string Path { get; set; }
}
}
}

View file

@ -16,11 +16,11 @@ namespace Microsoft.Extensions.DependencyModel
{
if (string.IsNullOrEmpty(assemblyName))
{
throw new ArgumentException(nameof(assemblyName));
throw new ArgumentException(null, nameof(assemblyName));
}
if (string.IsNullOrEmpty(path))
{
throw new ArgumentException(nameof(path));
throw new ArgumentException(null, nameof(path));
}
_assemblyName = assemblyName;
Path = path;
@ -45,4 +45,4 @@ namespace Microsoft.Extensions.DependencyModel
return new RuntimeAssembly(assemblyName, path);
}
}
}
}

View file

@ -18,7 +18,7 @@ namespace Microsoft.Extensions.DependencyModel
{
if (string.IsNullOrEmpty(runtime))
{
throw new ArgumentException(nameof(runtime));
throw new ArgumentException(null, nameof(runtime));
}
if (fallbacks == null)
{
@ -28,4 +28,4 @@ namespace Microsoft.Extensions.DependencyModel
Fallbacks = fallbacks.ToArray();
}
}
}
}

View file

@ -12,7 +12,7 @@ namespace Microsoft.Extensions.DependencyModel
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentException(nameof(path));
throw new ArgumentException(null, nameof(path));
}
Path = path;

View file

@ -14,7 +14,7 @@ namespace Microsoft.Extensions.DependencyModel
{
if (string.IsNullOrEmpty(framework))
{
throw new ArgumentException(nameof(framework));
throw new ArgumentException(null, nameof(framework));
}
Framework = framework;
@ -32,4 +32,4 @@ namespace Microsoft.Extensions.DependencyModel
public bool IsPortable { get; }
}
}
}

View file

@ -1,4 +1,5 @@
<root>
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
@ -76,16 +77,16 @@
<value>The value '{0}' is not a valid value for the enum '{1}'.</value>
</data>
<data name="ErrorInvalidEventHandler" xml:space="preserve">
<value>Invalid event handler for the {0} event.</value>
<value>Invalid event handler for the {0} event.</value>
</data>
<data name="ErrorInvalidEventType" xml:space="preserve">
<value>Invalid type for the {0} event.</value>
<value>Invalid type for the {0} event.</value>
</data>
<data name="ErrorInvalidPropertyType" xml:space="preserve">
<value>Invalid type for the {0} property</value>
</data>
<data name="ErrorMissingEventAccessors" xml:space="preserve">
<value>Accessor methods for the {0} event are missing.</value>
<value>Accessor methods for the {0} event are missing.</value>
</data>
<data name="ErrorMissingPropertyAccessors" xml:space="preserve">
<value>Accessor methods for the {0} property are missing.</value>
@ -170,7 +171,7 @@
</data>
<data name="CultureInfoConverterInvalidCulture" xml:space="preserve">
<value>The {0} culture cannot be converted to a CultureInfo object on this computer.</value>
</data>
</data>
<data name="ErrorInvalidServiceInstance" xml:space="preserve">
<value>The service instance must derive from or implement {0}.</value>
</data>
@ -178,7 +179,7 @@
<value>The service {0} already exists in the service container.</value>
</data>
<data name="InvalidArgumentValue" xml:space="preserve">
<value>Value of '{1}' is not valid for '{0}'.</value>
<value>Value of '{0}' cannot be empty.</value>
</data>
<data name="InvalidNullArgument" xml:space="preserve">
<value>Null is not a valid value for {0}.</value>
@ -242,11 +243,11 @@
</data>
<data name="CHECKOUTCanceled" xml:space="preserve">
<value>The checkout was canceled by the user.</value>
</data>
<data name="toStringNone" xml:space="preserve">
</data>
<data name="toStringNone" xml:space="preserve">
<value>(none)</value>
</data>
<data name="MemberRelationshipService_RelationshipNotSupported" xml:space="preserve">
<data name="MemberRelationshipService_RelationshipNotSupported" xml:space="preserve">
<value>Relationships between {0}.{1} and {2}.{3} are not supported.</value>
</data>
</root>
</root>

View file

@ -47,7 +47,7 @@ namespace System.ComponentModel.Design
if (name.Length == 0)
{
throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, name.Length.ToString(), "0"), "name.Length");
throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, "name.Length"), nameof(name));
}
return new DesignerOptionCollection(this, parent, name, value);

View file

@ -44,7 +44,7 @@ namespace System.ComponentModel.Design.Serialization
// and not the other as the main constructor performs argument validation.
if (source.Owner == null)
{
throw new ArgumentNullException(nameof(MemberRelationship.Owner));
throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "source.Owner"), nameof(source));
}
Debug.Assert(source.Member != null);
@ -57,7 +57,7 @@ namespace System.ComponentModel.Design.Serialization
// and not the other as the main constructor performs argument validation.
if (source.Owner == null)
{
throw new ArgumentNullException(nameof(MemberRelationship.Owner));
throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "source.Owner"), nameof(source));
}
Debug.Assert(source.Member != null);

View file

@ -53,7 +53,7 @@ namespace System.ComponentModel.Design.Tests
public void CreateOptionCollection_EmptyName_ThrowsArgumentException()
{
var service = new TestDesignerOptionService();
AssertExtensions.Throws<ArgumentException>("name.Length", () => service.DoCreateOptionCollection(service.Options, string.Empty, "value"));
AssertExtensions.Throws<ArgumentException>("name", () => service.DoCreateOptionCollection(service.Options, string.Empty, "value"));
}
[Fact]

View file

@ -56,8 +56,8 @@ namespace System.ComponentModel.Design.Serialization.Tests
Assert.Throws<ArgumentNullException>("sourceOwner", () => service[null, member]);
Assert.Throws<ArgumentNullException>("sourceOwner", () => service[null, member] = new MemberRelationship());
Assert.Throws<ArgumentNullException>("Owner", () => service[new MemberRelationship()]);
Assert.Throws<ArgumentNullException>("Owner", () => service[new MemberRelationship()] = new MemberRelationship());
Assert.Throws<ArgumentException>("source", () => service[new MemberRelationship()]);
Assert.Throws<ArgumentException>("source", () => service[new MemberRelationship()] = new MemberRelationship());
}
[Fact]

View file

@ -195,7 +195,7 @@ namespace System.Diagnostics.PerformanceData
{
if (_provider == null)
{
throw new ArgumentException(SR.Format(SR.Perflib_Argument_ProviderNotFound, _providerGuid), "ProviderGuid");
throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid));
}
if (_provider._hProvider.IsInvalid)
{
@ -256,7 +256,7 @@ namespace System.Diagnostics.PerformanceData
{
throw Status switch
{
(uint)Interop.Errors.ERROR_ALREADY_EXISTS => new ArgumentException(SR.Format(SR.Perflib_Argument_CounterSetAlreadyRegister, _counterSet), "CounterSetGuid"),
(uint)Interop.Errors.ERROR_ALREADY_EXISTS => new InvalidOperationException(SR.Format(SR.Perflib_Argument_CounterSetAlreadyRegister, _counterSet)),
_ => new Win32Exception((int)Status),
};

View file

@ -124,7 +124,7 @@ namespace System.DirectoryServices.AccountManagement
set
{
if (null == value || 0 == value.Length)
throw new ArgumentNullException(PropertyNames.PrincipalSamAccountName);
throw new ArgumentNullException(nameof(value));
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalSamAccountName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);
@ -244,7 +244,7 @@ namespace System.DirectoryServices.AccountManagement
set
{
if (null == value || 0 == value.Length)
throw new ArgumentNullException(PropertyNames.PrincipalName);
throw new ArgumentNullException(nameof(value));
if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.PrincipalName))
throw new InvalidOperationException(SR.InvalidPropertyForStore);

View file

@ -23,7 +23,7 @@ namespace System.DirectoryServices.AccountManagement
public PrincipalSearcher(Principal queryFilter)
{
if (null == queryFilter)
throw new ArgumentException(nameof(queryFilter));
throw new ArgumentException(null, nameof(queryFilter));
_ctx = queryFilter.Context;
this.QueryFilter = queryFilter; // use property to enforce "no persisted principals" check

View file

@ -35,7 +35,7 @@ namespace System.DirectoryServices.AccountManagement.Tests
public void Ctor_EmptySamAccountName_ThrowsArgumentNullException()
{
var context = new PrincipalContext(ContextType.Machine);
AssertExtensions.Throws<ArgumentNullException>("Principal.SamAccountName", null, () => new ComputerPrincipal(context, string.Empty, "password", enabled: true));
AssertExtensions.Throws<ArgumentNullException>("value", null, () => new ComputerPrincipal(context, string.Empty, "password", enabled: true));
}
[Fact]

View file

@ -59,7 +59,7 @@ namespace System.DirectoryServices.ActiveDirectory
public ActiveDirectorySchedule(ActiveDirectorySchedule schedule) : this()
{
if (schedule == null)
throw new ArgumentNullException();
throw new ArgumentNullException(nameof(schedule));
bool[] tmpSchedule = schedule._scheduleArray;
for (int i = 0; i < 672; i++)

View file

@ -111,7 +111,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (schemaClass == null)
{
throw new ArgumentException(nameof(schemaClasses));
throw new ArgumentException(null, nameof(schemaClasses));
}
}
@ -132,7 +132,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (schemaClass == null)
{
throw new ArgumentException(nameof(schemaClasses));
throw new ArgumentException(null, nameof(schemaClasses));
}
}
@ -154,7 +154,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (schemaClass == null)
{
throw new ArgumentException(nameof(schemaClasses));
throw new ArgumentException(null, nameof(schemaClasses));
}
}
@ -360,7 +360,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (!(value is ActiveDirectorySchemaClass))
{
throw new ArgumentException(nameof(value));
throw new ArgumentException(null, nameof(value));
}
if (!((ActiveDirectorySchemaClass)value).isBound)

View file

@ -109,7 +109,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (property == null)
{
throw new ArgumentException(nameof(properties));
throw new ArgumentException(null, nameof(properties));
}
}
@ -130,7 +130,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (property == null)
{
throw new ArgumentException(nameof(properties));
throw new ArgumentException(null, nameof(properties));
}
}
@ -153,7 +153,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (property == null)
{
throw new ArgumentException(nameof(properties));
throw new ArgumentException(null, nameof(properties));
}
}
@ -369,7 +369,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (value == null) throw new ArgumentNullException(nameof(value));
if (!(value is ActiveDirectorySchemaProperty))
throw new ArgumentException(nameof(value));
throw new ArgumentException(null, nameof(value));
if (!((ActiveDirectorySchemaProperty)value).isBound)
throw new InvalidOperationException(SR.Format(SR.SchemaObjectNotCommitted, ((ActiveDirectorySchemaProperty)value).Name));

View file

@ -232,7 +232,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (value == null) throw new ArgumentNullException(nameof(value));
if (!(value is ActiveDirectorySite))
throw new ArgumentException(nameof(value));
throw new ArgumentException(null, nameof(value));
if (!((ActiveDirectorySite)value).existing)
throw new InvalidOperationException(SR.Format(SR.SiteNotCommitted, ((ActiveDirectorySite)value).Name));

View file

@ -268,7 +268,7 @@ namespace System.DirectoryServices.ActiveDirectory
throw new ObjectDisposedException(GetType().Name);
if (value < 0)
throw new ArgumentException(nameof(value));
throw new ArgumentException(null, nameof(value));
try
{

View file

@ -226,7 +226,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (value == null) throw new ArgumentNullException(nameof(value));
if (!(value is ActiveDirectorySiteLink))
throw new ArgumentException(nameof(value));
throw new ArgumentException(null, nameof(value));
if (!((ActiveDirectorySiteLink)value).existing)
throw new InvalidOperationException(SR.Format(SR.SiteLinkNotCommitted, ((ActiveDirectorySiteLink)value).Name));

View file

@ -68,7 +68,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (s == null)
{
throw new ArgumentException(nameof(subnets));
throw new ArgumentException(null, nameof(subnets));
}
}
@ -263,7 +263,7 @@ namespace System.DirectoryServices.ActiveDirectory
if (value == null) throw new ArgumentNullException(nameof(value));
if (!(value is ActiveDirectorySubnet))
throw new ArgumentException(nameof(value));
throw new ArgumentException(null, nameof(value));
if (!((ActiveDirectorySubnet)value).existing)
throw new InvalidOperationException(SR.Format(SR.SubnetNotCommitted, ((ActiveDirectorySubnet)value).Name));

View file

@ -115,7 +115,7 @@ namespace System.DirectoryServices.ActiveDirectory
{
if (s == null)
{
throw new ArgumentException(nameof(servers));
throw new ArgumentException(null, nameof(servers));
}
}
@ -386,7 +386,7 @@ namespace System.DirectoryServices.ActiveDirectory
else
{
if (!(value is DirectoryServer))
throw new ArgumentException(nameof(value));
throw new ArgumentException(null, nameof(value));
}
}

View file

@ -232,14 +232,14 @@ namespace System.Drawing.Drawing2D
throw new NullReferenceException();
if (value.Positions == null)
throw new ArgumentNullException("source");
throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, "value.Positions", value.Positions), nameof(value));
int count = value.Factors.Length;
if (count == 0 || value.Positions.Length == 0)
throw new ArgumentException(SR.BlendObjectMustHaveTwoElements);
if (count >= 2 && count != value.Positions.Length)
throw new ArgumentOutOfRangeException();
throw new ArgumentOutOfRangeException(nameof(value));
if (count >= 2 && value.Positions[0] != 0.0F)
throw new ArgumentException(SR.BlendObjectFirstElementInvalid);
if (count >= 2 && value.Positions[count - 1] != 1.0F)

View file

@ -185,10 +185,8 @@ namespace System.Drawing.Drawing2D
if (value == null || value.Factors == null)
throw new NullReferenceException();
// The Desktop implementation throws ArgumentNullException("source") because it never validates the value of value.Positions, and then passes it
// on to Marshal.Copy(value.Positions, 0, positions, count);. The first argument of Marshal.Copy is source, hence this exception.
if (value.Positions == null)
throw new ArgumentNullException("source");
throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, "value.Positions", value.Positions), nameof(value));
int count = value.Factors.Length;
@ -196,7 +194,7 @@ namespace System.Drawing.Drawing2D
if (count == 0 || value.Positions.Length == 0)
throw new ArgumentException(SR.BlendObjectMustHaveTwoElements);
if (count >= 2 && count != value.Positions.Length)
throw new ArgumentOutOfRangeException();
throw new ArgumentOutOfRangeException(nameof(value));
if (count >= 2 && value.Positions[0] != 0.0F)
throw new ArgumentException(SR.BlendObjectFirstElementInvalid);
if (count >= 2 && value.Positions[count - 1] != 1.0F)
@ -298,16 +296,12 @@ namespace System.Drawing.Drawing2D
}
set
{
// The Desktop implementation will throw various exceptions - ranging from NullReferenceExceptions to Argument(OutOfRange)Exceptions
// depending on how sane the input is. These checks exist to replicate the exact Desktop behavior.
int count = value.Colors.Length;
if (value.Positions == null)
throw new ArgumentNullException("source");
if (value.Colors.Length > value.Positions.Length)
throw new ArgumentOutOfRangeException();
if (value.Colors.Length < value.Positions.Length)
throw new ArgumentException();
throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, "value.Positions", value.Positions), nameof(value));
if (value.Colors.Length != value.Positions.Length)
throw new ArgumentOutOfRangeException(nameof(value));
float[] positions = value.Positions;
int[] argbs = new int[count];

View file

@ -306,7 +306,7 @@ namespace System.Drawing
{
// If we don't actually have an object that is LOGFONT in size, trying to pass
// it to GDI+ is likely to cause an AV.
throw new ArgumentException();
throw new ArgumentException(null, nameof(lf));
}
// Now that we know the marshalled size is the same as LOGFONT, copy in the data

View file

@ -285,7 +285,7 @@ namespace System.Drawing
{
// If we don't actually have an object that is LOGFONT in size, trying to pass
// it to GDI+ is likely to cause an AV.
throw new ArgumentException();
throw new ArgumentException(null, nameof(logFont));
}
Interop.User32.LOGFONT nativeLogFont = ToLogFontInternal(graphics);

View file

@ -639,9 +639,8 @@ namespace System.Drawing
{
try
{
// We threw this way on NetFX
if (outputStream == null)
throw new ArgumentNullException("dataStream");
throw new ArgumentNullException(nameof(outputStream));
picture.SaveAsFile(new GPStream(outputStream, makeSeekable: false), -1, out int temp);
}

View file

@ -60,16 +60,16 @@ namespace System.Drawing.Text
{
if (_nativeFontCollection == IntPtr.Zero)
{
#pragma warning disable CA2208 // Instantiate argument exceptions correctly
// This is the default behavior on Desktop. The ArgumentException originates from GdipPrivateAddFontFile which would
// refuse the null pointer.
throw new ArgumentException();
#pragma warning restore CA2208
}
if (filename == null)
{
// This is the default behavior on Desktop. The name "path" originates from Path.GetFullPath or similar which would refuse
// a null value.
throw new ArgumentNullException("path");
throw new ArgumentNullException(nameof(filename));
}
// this ensure the filename is valid (or throw the correct exception)

View file

@ -358,11 +358,11 @@ namespace System.Drawing.Drawing2D.Tests
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Blend_SetNullBlendPositions_ThrowsArgumentNullException()
public void Blend_SetNullBlendPositions_ThrowsArgumentException()
{
using (var brush = new LinearGradientBrush(new Rectangle(1, 2, 3, 4), Color.Plum, Color.Red, 45, true))
{
AssertExtensions.Throws<ArgumentNullException>("source", () => brush.Blend = new Blend { Factors = new float[2], Positions = null });
AssertExtensions.Throws<ArgumentException, ArgumentNullException>("value", "source", () => brush.Blend = new Blend { Factors = new float[2], Positions = null });
}
}
@ -371,7 +371,7 @@ namespace System.Drawing.Drawing2D.Tests
{
using (var brush = new LinearGradientBrush(new Rectangle(1, 2, 3, 4), Color.Plum, Color.Red, 45, true))
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => brush.Blend = new Blend { Factors = new float[2], Positions = new float[1] });
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", null, () => brush.Blend = new Blend { Factors = new float[2], Positions = new float[1] });
}
}

View file

@ -350,7 +350,7 @@ namespace System.Drawing.Drawing2D.Tests
using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
{
AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => brush.Blend = invalidBlend);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", null, () => brush.Blend = invalidBlend);
}
}
@ -366,11 +366,11 @@ namespace System.Drawing.Drawing2D.Tests
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void Blend_NullBlendProperites_ThrowsArgumentNullException()
public void Blend_NullBlendProperites_ThrowsArgumentException()
{
using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
{
AssertExtensions.Throws<ArgumentNullException>("source", () =>
AssertExtensions.Throws<ArgumentException, ArgumentNullException>("value", "source", () =>
brush.Blend = new Blend() { Factors = new float[0], Positions = null });
}
}
@ -651,11 +651,11 @@ namespace System.Drawing.Drawing2D.Tests
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void InterpolationColors_NullPoints_ArgumentNullException()
public void InterpolationColors_NullPoints_ArgumentException()
{
using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
{
AssertExtensions.Throws<ArgumentNullException>("source", () =>
AssertExtensions.Throws<ArgumentException, ArgumentNullException>("value", "source", () =>
brush.InterpolationColors = new ColorBlend() { Colors = new Color[1], Positions = null });
}
}
@ -680,11 +680,11 @@ namespace System.Drawing.Drawing2D.Tests
}
[ConditionalFact(Helpers.IsDrawingSupported)]
public void InterpolationColors_PointsLengthGreaterThenColorsLength_ArgumentException()
public void InterpolationColors_PointsLengthGreaterThenColorsLength_ArgumentOutOfRangeException()
{
using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints))
{
AssertExtensions.Throws<ArgumentException>(null, () =>
AssertExtensions.Throws<ArgumentOutOfRangeException, ArgumentException>("value", null, () =>
brush.InterpolationColors = new ColorBlend() { Colors = new Color[1], Positions = new float[2] });
}
}

View file

@ -525,7 +525,7 @@ namespace System.Drawing.Tests
var icon = Icon.FromHandle(source.Handle);
icon.Dispose();
AssertExtensions.Throws<ArgumentNullException>("dataStream", () => icon.Save(null));
AssertExtensions.Throws<ArgumentNullException>("outputStream", "dataStream", () => icon.Save(null));
}
}

View file

@ -107,7 +107,7 @@ namespace System.Drawing.Text.Tests
{
using (var fontCollection = new PrivateFontCollection())
{
AssertExtensions.Throws<ArgumentNullException>("path", () => fontCollection.AddFontFile(null));
AssertExtensions.Throws<ArgumentNullException>("filename", "path", () => fontCollection.AddFontFile(null));
}
}

View file

@ -1,4 +1,5 @@
<root>
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
@ -292,4 +293,7 @@
<data name="PlatformNotSupported_FrameworkUpdatedRequired" xml:space="preserve">
<value>The native library '{0}' does not have all required functions. Please, update the .NET Framework.</value>
</data>
</root>
<data name="InvalidQueryTokenExpected" xml:space="preserve">
<value>The Query string supplied was invalid or improperly formed. Token `{0}` is expected</value>
</data>
</root>

View file

@ -415,7 +415,7 @@ namespace System.Management
// and also negative timespan cannot be represented in DMTF
if (timespan.Days > MAXDATE_INTIMESPAN || timespan < TimeSpan.Zero)
{
throw new System.ArgumentOutOfRangeException();
throw new System.ArgumentOutOfRangeException(nameof(timespan));
}
dmtftimespan = (dmtftimespan + timespan.Hours.ToString(frmInt32).PadLeft(2, '0'));

View file

@ -1040,13 +1040,13 @@ namespace System.Management
// Should start with "select"
if ((q.Length < keyword.Length) ||
(0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
throw new ArgumentException(SR.InvalidQuery, "select");
throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, keyword), nameof(query));
q = q.Remove(0, keyword.Length).TrimStart(null);
// Next should be a '*'
if (0 != q.IndexOf('*', 0))
throw new ArgumentException(SR.InvalidQuery, "*");
throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, "*"), nameof(query));
q = q.Remove(0, 1).TrimStart(null);
@ -1055,7 +1055,7 @@ namespace System.Management
if ((q.Length < keyword.Length) ||
(0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
throw new ArgumentException(SR.InvalidQuery, "from");
throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, keyword), nameof(query));
q = q.Remove(0, keyword.Length).TrimStart(null);
@ -1064,7 +1064,7 @@ namespace System.Management
if ((q.Length < keyword.Length) ||
(0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
throw new ArgumentException(SR.InvalidQuery, "meta_class");
throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, keyword), nameof(query));
q = q.Remove(0, keyword.Length).TrimStart(null);
@ -1076,7 +1076,7 @@ namespace System.Management
if ((q.Length < keyword.Length) ||
(0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
throw new ArgumentException(SR.InvalidQuery, "where");
throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, keyword), nameof(query));
q = q.Remove(0, keyword.Length);
@ -1650,7 +1650,7 @@ namespace System.Management
//Find "associators" clause
if (0 != string.Compare(q, 0, TokenAssociators, 0, TokenAssociators.Length, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(SR.InvalidQuery, "associators"); // Invalid query
throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, TokenAssociators), nameof(query)); // Invalid query
// Strip off the clause
q = q.Remove(0, TokenAssociators.Length);
@ -1663,7 +1663,7 @@ namespace System.Management
// Next token should be "of"
if (0 != string.Compare(q, 0, TokenOf, 0, TokenOf.Length, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(SR.InvalidQuery, "of"); // Invalid query
throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, TokenOf), nameof(query)); // Invalid query
// Strip off the clause and leading WS
q = q.Remove(0, TokenOf.Length).TrimStart(null);
@ -1687,7 +1687,7 @@ namespace System.Management
{
// Next should be the "where" clause
if (0 != string.Compare(q, 0, TokenWhere, 0, TokenWhere.Length, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(SR.InvalidQuery, "where"); // Invalid query
throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, TokenWhere), nameof(query)); // Invalid query
q = q.Remove(0, TokenWhere.Length);
@ -2167,7 +2167,7 @@ namespace System.Management
//Find "references" clause
if (0 != string.Compare(q, 0, TokenReferences, 0, TokenReferences.Length, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(SR.InvalidQuery, "references"); // Invalid query
throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, TokenReferences), nameof(query)); // Invalid query
// Strip off the clause
q = q.Remove(0, TokenReferences.Length);
@ -2180,7 +2180,7 @@ namespace System.Management
// Next token should be "of"
if (0 != string.Compare(q, 0, TokenOf, 0, TokenOf.Length, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(SR.InvalidQuery, "of"); // Invalid query
throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, TokenOf), nameof(query)); // Invalid query
// Strip off the clause and leading WS
q = q.Remove(0, TokenOf.Length).TrimStart(null);
@ -2204,7 +2204,7 @@ namespace System.Management
{
// Next should be the "where" clause
if (0 != string.Compare(q, 0, TokenWhere, 0, TokenWhere.Length, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException(SR.InvalidQuery, "where"); // Invalid query
throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, TokenWhere), nameof(query)); // Invalid query
q = q.Remove(0, TokenWhere.Length);
@ -3043,13 +3043,13 @@ namespace System.Management
q = q.Remove(0, keyword.Length).TrimStart(null);
if (!q.StartsWith("*", StringComparison.Ordinal))
throw new ArgumentException(SR.InvalidQuery, "*");
throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, "*"), nameof(query));
q = q.Remove(0, 1).TrimStart(null);
//Find "from" clause
keyword = "from ";
if ((q.Length < keyword.Length) || (0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase)))
throw new ArgumentException(SR.InvalidQuery, "from");
throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, keyword), nameof(query));
ParseToken(ref q, keyword, null, ref bFound, ref eventClassName);
//Find "within" clause
@ -3119,7 +3119,7 @@ namespace System.Management
q = q.Remove(0, keyword.Length);
if (q.Length == 0) //bad query
throw new ArgumentException(SR.InvalidQuery, "having");
throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, keyword), nameof(query));
havingCondition = q;
}

View file

@ -188,7 +188,7 @@ namespace System.Net
char c = (char)(0x000000ff & (uint)value[i]);
if ((c <= 31 && c != (byte)'\t') || c == 127)
{
throw new ArgumentException(SR.net_WebHeaderInvalidControlChars, "name");
throw new ArgumentException(SR.net_WebHeaderInvalidControlChars, nameof(value));
}
}

View file

@ -436,7 +436,7 @@ namespace System.Net.Tests
{
using (HttpListenerResponse response = await GetResponse())
{
AssertExtensions.Throws<ArgumentException>("name", () => response.StatusDescription = statusDescription);
AssertExtensions.Throws<ArgumentException>("value", () => response.StatusDescription = statusDescription);
Assert.Equal("OK", response.StatusDescription);
}
}

View file

@ -380,7 +380,7 @@ namespace System.Net.NetworkInformation
public override async Task<UnicastIPAddressInformationCollection> GetUnicastAddressesAsync()
{
// Wait for the address table to stabilize.
var tcs = new TaskCompletionSource<bool>(TaskContinuationOptions.RunContinuationsAsynchronously);
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
if (!TeredoHelper.UnsafeNotifyStableUnicastIpAddressTable(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
{
await tcs.Task.ConfigureAwait(false);

View file

@ -118,7 +118,7 @@ namespace System.Net
{
if (capacity <= 0)
{
throw new ArgumentException(SR.net_toosmall, "Capacity");
throw new ArgumentException(SR.net_toosmall, nameof(capacity));
}
m_maxCookies = capacity;
}
@ -132,7 +132,7 @@ namespace System.Net
m_maxCookiesPerDomain = perDomainCapacity;
if (maxCookieSize <= 0)
{
throw new ArgumentException(SR.net_toosmall, "MaxCookieSize");
throw new ArgumentException(SR.net_toosmall, nameof(maxCookieSize));
}
m_maxCookieSize = maxCookieSize;
}
@ -230,7 +230,7 @@ namespace System.Net
{
throw new ArgumentException(
SR.Format(SR.net_emptystringcall, nameof(cookie) + "." + nameof(cookie.Domain)),
nameof(cookie) + "." + nameof(cookie.Domain));
nameof(cookie));
}
Uri? uri;

View file

@ -486,7 +486,7 @@ namespace System.Net.Primitives.Unit.Tests
[Fact]
public void Ctor_Capacity_Invalid()
{
AssertExtensions.Throws<ArgumentException>("Capacity", () => new CookieContainer(0)); // Capacity <= 0
AssertExtensions.Throws<ArgumentException>("capacity", () => new CookieContainer(0)); // Capacity <= 0
}
[Fact]
@ -595,7 +595,7 @@ namespace System.Net.Primitives.Unit.Tests
{
CookieContainer cc = new CookieContainer();
Assert.Throws<ArgumentNullException>(() => cc.Add((Cookie)null)); // Null cookie
AssertExtensions.Throws<ArgumentException>("cookie.Domain", () => cc.Add(new Cookie("name", "value", "", ""))); // Empty domain
AssertExtensions.Throws<ArgumentException>("cookie", () => cc.Add(new Cookie("name", "value", "", ""))); // Empty domain
cc.MaxCookieSize = 1;
Assert.Throws<CookieException>(() => cc.Add(new Cookie("name", "long-text", "", "contoso.com"))); // Value.Length > MaxCookieSize
@ -625,11 +625,11 @@ namespace System.Net.Primitives.Unit.Tests
[Fact]
public void Ctor_CapacityPerDomainCapacityMaxCookieSize_Invalid()
{
AssertExtensions.Throws<ArgumentException>("Capacity", () => new CookieContainer(0, 10, 5)); // Capacity <= 0
AssertExtensions.Throws<ArgumentException>("capacity", () => new CookieContainer(0, 10, 5)); // Capacity <= 0
Assert.Throws<ArgumentOutOfRangeException>(() => new CookieContainer(5, 0, 5)); // Per domain capacity <= 0
Assert.Throws<ArgumentOutOfRangeException>(() => new CookieContainer(5, 10, 5)); // Per domain capacity > Capacity
AssertExtensions.Throws<ArgumentException>("MaxCookieSize", () => new CookieContainer(15, 10, 0)); // Max cookie size <= 0
AssertExtensions.Throws<ArgumentException>("maxCookieSize", () => new CookieContainer(15, 10, 0)); // Max cookie size <= 0
}
[Fact]

View file

@ -1,4 +1,5 @@
<root>
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
@ -192,8 +193,8 @@
<data name="net_value_cannot_be_negative" xml:space="preserve">
<value>The specified value cannot be negative.</value>
</data>
<data name="ArgumentOutOfRange_Bounds_Lower_Upper" xml:space="preserve">
<value>Argument must be between {0} and {1}.</value>
<data name="ArgumentOutOfRange_Bounds_Lower_Upper_Named" xml:space="preserve">
<value>Argument '{2}' must be between {0} and {1}.</value>
</data>
<data name="net_sockets_connect_multiconnect_notsupported" xml:space="preserve">
<value>Sockets on this platform are invalid for use after a failed connection attempt.</value>
@ -258,4 +259,7 @@
<data name="net_sockets_asyncoperations_notallowed" xml:space="preserve">
<value>Asynchronous operations are not allowed on this socket. The underlying OS handle might have been already bound to an IO completion port.</value>
</data>
</root>
<data name="InvalidNullArgument" xml:space="preserve">
<value>Null is not a valid value for {0}.</value>
</data>
</root>

View file

@ -1908,7 +1908,7 @@ namespace System.Net.Sockets
}
if (lingerOption.LingerTime < 0 || lingerOption.LingerTime > (int)ushort.MaxValue)
{
throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 0, (int)ushort.MaxValue), "optionValue.LingerTime");
throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper_Named, 0, (int)ushort.MaxValue, "optionValue.LingerTime"), nameof(optionValue));
}
SetLingerOption(lingerOption);
}
@ -3816,7 +3816,7 @@ namespace System.Net.Sockets
}
if (e.HasMultipleBuffers)
{
throw new ArgumentException(SR.net_multibuffernotsupported, "BufferList");
throw new ArgumentException(SR.net_multibuffernotsupported, nameof(e));
}
if (_rightEndPoint == null)
{
@ -3979,11 +3979,11 @@ namespace System.Net.Sockets
}
if (e.HasMultipleBuffers)
{
throw new ArgumentException(SR.net_multibuffernotsupported, "BufferList");
throw new ArgumentException(SR.net_multibuffernotsupported, nameof(e));
}
if (e.RemoteEndPoint == null)
{
throw new ArgumentNullException("remoteEP");
throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e));
}
EndPoint endPointSnapshot = e.RemoteEndPoint;
@ -4116,11 +4116,11 @@ namespace System.Net.Sockets
}
if (e.RemoteEndPoint == null)
{
throw new ArgumentNullException(nameof(e.RemoteEndPoint));
throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e));
}
if (!CanTryAddressFamily(e.RemoteEndPoint.AddressFamily))
{
throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, e.RemoteEndPoint.AddressFamily, _addressFamily), "RemoteEndPoint");
throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, e.RemoteEndPoint.AddressFamily, _addressFamily), nameof(e));
}
SocketPal.CheckDualModeReceiveSupport(this);
@ -4166,11 +4166,11 @@ namespace System.Net.Sockets
}
if (e.RemoteEndPoint == null)
{
throw new ArgumentNullException(nameof(e.RemoteEndPoint));
throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e));
}
if (!CanTryAddressFamily(e.RemoteEndPoint.AddressFamily))
{
throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, e.RemoteEndPoint.AddressFamily, _addressFamily), "RemoteEndPoint");
throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, e.RemoteEndPoint.AddressFamily, _addressFamily), nameof(e));
}
SocketPal.CheckDualModeReceiveSupport(this);
@ -4250,7 +4250,7 @@ namespace System.Net.Sockets
}
if (e.SendPacketsElements == null)
{
throw new ArgumentNullException("e.SendPacketsElements");
throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.SendPacketsElements"), nameof(e));
}
if (!Connected)
{
@ -4288,7 +4288,7 @@ namespace System.Net.Sockets
}
if (e.RemoteEndPoint == null)
{
throw new ArgumentNullException(nameof(RemoteEndPoint));
throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e));
}
// Prepare SocketAddress

View file

@ -454,8 +454,8 @@ namespace System.Net.Sockets.Tests
[Fact]
public void SetSocketOption_Linger_InvalidLingerTime_Throws_Argument()
{
AssertExtensions.Throws<ArgumentException>("optionValue.LingerTime", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1)));
AssertExtensions.Throws<ArgumentException>("optionValue.LingerTime", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1)));
AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1)));
AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1)));
}
[Fact]
@ -516,7 +516,7 @@ namespace System.Net.Sockets.Tests
BufferList = s_buffers
};
AssertExtensions.Throws<ArgumentException>("BufferList", () => GetSocket().AcceptAsync(eventArgs));
AssertExtensions.Throws<ArgumentException>("e", () => GetSocket().AcceptAsync(eventArgs));
}
[Fact]
@ -598,13 +598,13 @@ namespace System.Net.Sockets.Tests
BufferList = s_buffers
};
AssertExtensions.Throws<ArgumentException>("BufferList", () => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs));
AssertExtensions.Throws<ArgumentException>("e", () => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs));
}
[Fact]
public void ConnectAsync_Static_NullRemoteEndPoint_Throws_ArgumentNull()
public void ConnectAsync_Static_NullRemoteEndPoint_Throws_ArgumentException()
{
Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, s_eventArgs));
Assert.Throws<ArgumentException>("e", () => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, s_eventArgs));
}
[Fact]
@ -620,9 +620,9 @@ namespace System.Net.Sockets.Tests
}
[Fact]
public void ReceiveFromAsync_NullRemoteEndPoint_Throws_ArgumentNull()
public void ReceiveFromAsync_NullRemoteEndPoint_Throws_ArgumentException()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(s_eventArgs));
Assert.Throws<ArgumentException>("e", () => GetSocket().ReceiveFromAsync(s_eventArgs));
}
[Fact]
@ -632,7 +632,7 @@ namespace System.Net.Sockets.Tests
RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1)
};
AssertExtensions.Throws<ArgumentException>("RemoteEndPoint", () => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs));
AssertExtensions.Throws<ArgumentException>("e", () => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs));
}
[Fact]
@ -642,9 +642,9 @@ namespace System.Net.Sockets.Tests
}
[Fact]
public void ReceiveMessageFromAsync_NullRemoteEndPoint_Throws_ArgumentNull()
public void ReceiveMessageFromAsync_NullRemoteEndPoint_Throws_ArgumentException()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(s_eventArgs));
Assert.Throws<ArgumentException>("e", () => GetSocket().ReceiveMessageFromAsync(s_eventArgs));
}
[Fact]
@ -654,7 +654,7 @@ namespace System.Net.Sockets.Tests
RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1)
};
AssertExtensions.Throws<ArgumentException>("RemoteEndPoint", () => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs));
AssertExtensions.Throws<ArgumentException>("e", () => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs));
}
[Fact]
@ -670,9 +670,9 @@ namespace System.Net.Sockets.Tests
}
[Fact]
public void SendPacketsAsync_NullSendPacketsElements_Throws_ArgumentNull()
public void SendPacketsAsync_NullSendPacketsElements_Throws_ArgumentException()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(s_eventArgs));
Assert.Throws<ArgumentException>("e", () => GetSocket().SendPacketsAsync(s_eventArgs));
}
[Fact]
@ -694,7 +694,7 @@ namespace System.Net.Sockets.Tests
[Fact]
public void SendToAsync_NullRemoteEndPoint_Throws_ArgumentNull()
{
Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(s_eventArgs));
Assert.Throws<ArgumentException>(() => GetSocket().SendToAsync(s_eventArgs));
}
[Theory]

View file

@ -47,7 +47,7 @@ namespace System.Net.Sockets.Tests
{
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
await Assert.ThrowsAsync<ArgumentNullException>(() => SendToAsync(socket, new byte[1], null));
await Assert.ThrowsAnyAsync<ArgumentException>(() => SendToAsync(socket, new byte[1], null));
}
[Fact]

View file

@ -378,7 +378,7 @@ namespace System.Net
{
if (value != null && value.Length > ushort.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(CultureInfo.InvariantCulture, SR.net_headers_toolong, ushort.MaxValue));
throw new ArgumentOutOfRangeException(nameof(header), value, SR.Format(CultureInfo.InvariantCulture, SR.net_headers_toolong, ushort.MaxValue));
}
}
InvalidateCachedArrays();

View file

@ -581,9 +581,7 @@ namespace System
{
if (value < -10000 || value > 10000)
{
// DateTimeOffset.AddYears(int years) is implemented on top of DateTime.AddYears(int value). Use the more appropriate
// parameter name out of the two for the exception.
throw new ArgumentOutOfRangeException("years", SR.ArgumentOutOfRange_DateTimeBadYears);
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_DateTimeBadYears);
}
return AddMonths(value * 12);
}

View file

@ -1103,7 +1103,9 @@ namespace System.Globalization
}
catch (ArgumentException)
{
#pragma warning disable CA2208 // Instantiate argument exceptions correctly, combination of arguments used
throw new CultureNotFoundException("name/altName", SR.Format(SR.Argument_OneOfCulturesNotSupported, name, altName));
#pragma warning restore CA2208
}
lock (nameTable)

View file

@ -394,7 +394,7 @@ namespace System.IO
{
if (charStart < 0 || charCount < 0 || charStart > value.Length - charCount)
{
throw new ArgumentOutOfRangeException(nameof(charCount));
throw new ArgumentOutOfRangeException(nameof(value));
}
fixed (char* pChars = value)
{

View file

@ -408,7 +408,7 @@ namespace System.IO
throw new IOException(SR.IO_SeekBeforeBegin);
long newPosition = (long)value - (long)_mem;
if (newPosition < 0)
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_UnmanagedMemStreamLength);
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_UnmanagedMemStreamLength);
Interlocked.Exchange(ref _position, newPosition);
}

View file

@ -1144,7 +1144,9 @@ namespace System.Text
return this;
}
#pragma warning disable CA1830 // Prefer strongly-typed Append and Insert method overloads on StringBuilder. No need to fix for the builder itself
public StringBuilder Append(bool value) => Append(value.ToString());
#pragma warning restore CA1830
public StringBuilder Append(char value)
{

View file

@ -243,7 +243,7 @@ namespace System.Threading
break;
default:
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Enum, nameof(state));
throw new ArgumentOutOfRangeException(nameof(state), SR.ArgumentOutOfRange_Enum);
}
return TrySetApartmentStateUnchecked(state);

View file

@ -23,7 +23,7 @@ namespace System
throw new ArgumentNullException(nameof(value));
if (!IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(value));
// Check if both of them are of the same type
Type valueType = value.GetType();
@ -70,7 +70,7 @@ namespace System
throw new ArgumentNullException(nameof(value));
if (!IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(value));
Type valueType = value.GetType();

View file

@ -267,7 +267,7 @@ namespace System
for (int i = 0; i < cls.Length; i++)
{
if (args[i] == null)
throw new ArgumentNullException();
throw new ArgumentException(SR.ArgumentNull_ArrayValue, nameof(args));
cls[i] = args[i].GetType();
}
return cls;

View file

@ -192,6 +192,9 @@
<data name="Arg_KeyNotFoundWithKey" xml:space="preserve">
<value>The given key '{0}' was not present in the dictionary.</value>
</data>
<data name="InvalidNullArgument" xml:space="preserve">
<value>Null is not a valid value for {0}.</value>
</data>
<data name="net_uri_InitializeCalledAlreadyOrTooLate" xml:space="preserve">
<value>UriParser's base InitializeAndValidate may only be called once on a single Uri instance and only from an override of InitializeAndValidate.</value>
</data>

View file

@ -436,7 +436,7 @@ namespace System
uriString = serializationInfo.GetString("RelativeUri"); // Do not rename (binary serialization)
if ((object?)uriString == null)
throw new ArgumentNullException(nameof(uriString));
throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "RelativeUri"), nameof(serializationInfo));
CreateThis(uriString, false, UriKind.Relative);
DebugSetLeftCtor();
@ -1504,7 +1504,7 @@ namespace System
(uint)(digit - '0') <= '9' - '0' ? digit - '0' :
(uint)(digit - 'A') <= 'F' - 'A' ? digit - 'A' + 10 :
(uint)(digit - 'a') <= 'f' - 'a' ? digit - 'a' + 10 :
throw new ArgumentException(nameof(digit));
throw new ArgumentException(null, nameof(digit));
public override int GetHashCode()
{

View file

@ -180,7 +180,7 @@ namespace System.PrivateUri.Tests
[Fact]
public static void TestHexMethods_Invalid()
{
AssertExtensions.Throws<ArgumentException>(null, () => Uri.FromHex('?'));
AssertExtensions.Throws<ArgumentException>("digit", () => Uri.FromHex('?'));
Assert.Throws<ArgumentOutOfRangeException>(() => Uri.HexEscape('\x100'));
int index = -1;
Assert.Throws<ArgumentOutOfRangeException>(() => Uri.HexUnescape("%75", ref index));

View file

@ -103,7 +103,7 @@ namespace System.Xml
// Compatibility check for len < 0, just throw the same exception as new string(key, start, len)
if (len < 0)
{
throw new ArgumentOutOfRangeException();
throw new ArgumentOutOfRangeException(nameof(len));
}
int hashCode = ComputeHash32(key, start, len);

View file

@ -165,7 +165,7 @@ namespace System.Reflection.Tests
});
Assert.Throws<ArgumentNullException>(null, () =>
Assert.Throws<ArgumentNullException>("name", () =>
{
typeof(RuntimeReflectionExtensionsTests).GetRuntimeEvent(null);
});

View file

@ -39,7 +39,7 @@ namespace System.Runtime.InteropServices.Tests
[Fact]
public void Ctor_NullEventName_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>(null, () => new ComAwareEventInfo(typeof(NonComObject), null));
AssertExtensions.Throws<ArgumentNullException>("name", () => new ComAwareEventInfo(typeof(NonComObject), null));
}
[Fact]

View file

@ -357,8 +357,8 @@ namespace System.Tests
[Fact]
public static void AddYears_NewDateOutOfRange_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("years", () => DateTimeOffset.Now.AddYears(10001));
AssertExtensions.Throws<ArgumentOutOfRangeException>("years", () => DateTimeOffset.Now.AddYears(-10001));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTimeOffset.Now.AddYears(10001));
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => DateTimeOffset.Now.AddYears(-10001));
AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => DateTimeOffset.MaxValue.AddYears(1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("months", () => DateTimeOffset.MinValue.AddYears(-1));

View file

@ -383,8 +383,8 @@ namespace System.Tests
public static IEnumerable<object[]> AddYears_OutOfRange_TestData()
{
yield return new object[] { DateTime.Now, 10001, "years" };
yield return new object[] { DateTime.Now, -10001, "years" };
yield return new object[] { DateTime.Now, 10001, "value" };
yield return new object[] { DateTime.Now, -10001, "value" };
yield return new object[] { DateTime.MaxValue, 1, "months" };
yield return new object[] { DateTime.MinValue, -1, "months" };
}

View file

@ -25,7 +25,7 @@ namespace System.Tests
if (s_is32Bits)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("pressure", () => GC.AddMemoryPressure((long)int.MaxValue + 1)); // Bytes allocated > int.MaxValue on 32 bit platforms
AssertExtensions.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.AddMemoryPressure((long)int.MaxValue + 1)); // Bytes allocated > int.MaxValue on 32 bit platforms
}
}

View file

@ -71,7 +71,7 @@ namespace System.Tests
[Fact]
public void GetInterface_NullName_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>(null, () => typeof(int).GetInterface(null));
AssertExtensions.Throws<ArgumentNullException>("fullname", () => typeof(int).GetInterface(null));
}
[Fact]

View file

@ -336,7 +336,7 @@ namespace System.Security.AccessControl
else
{
Debug.Fail("rule.AccessControlType unrecognized");
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)rule.AccessControlType), "rule.AccessControlType");
throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)rule.AccessControlType), nameof(rule));
}
modified = result;

View file

@ -127,10 +127,12 @@ namespace System.Security.Cryptography
{
if (keyParameters.X == null)
{
#pragma warning disable CA2208 // Instantiate argument exceptions correctly
// .NET Framework compat when a 3rd party type lets X be null when
// includePrivateParameters is true
// (the exception would have been from Convert.ToBase64String)
throw new ArgumentNullException("inArray");
#pragma warning restore CA2208
}
XmlKeyHelper.WriteCryptoBinary(nameof(DSAParameters.X), keyParameters.X, builder);

View file

@ -438,7 +438,7 @@ namespace System.Security.Cryptography
if (!success)
{
Debug.Fail("Convert.TryToBase64Chars failed with a pre-sized buffer");
throw new ArgumentException();
throw new ArgumentException(null, nameof(destination));
}
return base64Written;
@ -528,7 +528,7 @@ namespace System.Security.Cryptography
if (!TryWrite(label, data, buffer, out int charsWritten))
{
Debug.Fail("TryWrite failed with a pre-sized buffer");
throw new ArgumentException();
throw new ArgumentException(null, nameof(data));
}
Debug.Assert(charsWritten == encodedSize);

View file

@ -1,4 +1,5 @@
<root>
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
@ -57,8 +58,8 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Arg_EmptyOrNullString" xml:space="preserve">
<value>String cannot be empty or null.</value>
<data name="Arg_EmptyOrNullString_Named" xml:space="preserve">
<value>The `{0}` string cannot be empty or null.</value>
</data>
<data name="Arg_RankMultiDimNotSupported" xml:space="preserve">
<value>Only single dimensional arrays are supported for the requested action.</value>
@ -214,10 +215,10 @@
<value>New Pkcs12SafeBag values cannot be added to a Pkcs12SafeContents that was read from existing data.</value>
</data>
<data name="Cryptography_Pkcs12_WrongModeForDecrypt" xml:space="preserve">
<value>This decryption operation applies to 'Pkcs12ConfidentialityMode.{0}', but the target object is in 'Pkcs12ConfidentialityMode.{1}'.</value>
<value>This decryption operation applies to 'Pkcs12ConfidentialityMode.{0}', but the target object is in 'Pkcs12ConfidentialityMode.{1}'.</value>
</data>
<data name="Cryptography_Pkcs12_WrongModeForVerify" xml:space="preserve">
<value>This verification operation applies to 'Pkcs12IntegrityMode.{0}', but the target object is in 'Pkcs12IntegrityMode.{1}'.</value>
<value>This verification operation applies to 'Pkcs12IntegrityMode.{0}', but the target object is in 'Pkcs12IntegrityMode.{1}'.</value>
</data>
<data name="Cryptography_Pkcs_InvalidSignatureParameters" xml:space="preserve">
<value>Invalid signature paramters.</value>
@ -294,4 +295,4 @@
<data name="Cryptography_Cms_CertificateAlreadyInCollection" xml:space="preserve">
<value>Certificate already present in the collection.</value>
</data>
</root>
</root>

View file

@ -41,7 +41,7 @@ namespace System.Security.Cryptography.Pkcs
if (pbeParameters == null)
throw new ArgumentNullException(nameof(pbeParameters));
if (pbeParameters.IterationCount < 1)
throw new ArgumentOutOfRangeException(nameof(pbeParameters.IterationCount));
throw new ArgumentOutOfRangeException(nameof(pbeParameters));
if (safeContents.ConfidentialityMode != Pkcs12ConfidentialityMode.None)
throw new ArgumentException(SR.Cryptography_Pkcs12_CannotProcessEncryptedSafeContents, nameof(safeContents));
if (IsSealed)
@ -89,7 +89,7 @@ namespace System.Security.Cryptography.Pkcs
if (pbeParameters == null)
throw new ArgumentNullException(nameof(pbeParameters));
if (pbeParameters.IterationCount < 1)
throw new ArgumentOutOfRangeException(nameof(pbeParameters.IterationCount));
throw new ArgumentOutOfRangeException(nameof(pbeParameters));
if (safeContents.ConfidentialityMode != Pkcs12ConfidentialityMode.None)
throw new ArgumentException(SR.Cryptography_Pkcs12_CannotProcessEncryptedSafeContents, nameof(safeContents));
if (IsSealed)

View file

@ -32,12 +32,12 @@ namespace System.Security.Cryptography.Pkcs
: base(asnEncodedData)
{
if (asnEncodedData.Oid == null)
throw new ArgumentNullException(nameof(asnEncodedData.Oid));
throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "asnEncodedData.Oid"), nameof(asnEncodedData));
string? szOid = base.Oid!.Value;
if (szOid == null)
throw new ArgumentNullException("oid.Value");
throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "oid.Value"), nameof(asnEncodedData));
if (szOid.Length == 0)
throw new ArgumentException(SR.Arg_EmptyOrNullString, "oid.Value");
throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "oid.Value"), nameof(asnEncodedData));
}
internal Pkcs9AttributeObject(Oid oid)

View file

@ -45,7 +45,7 @@ namespace System.Security.Cryptography.Pkcs
if (contentInfo == null)
throw new ArgumentNullException(nameof(contentInfo));
if (contentInfo.Content == null)
throw new ArgumentNullException("contentInfo.Content");
throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "contentInfo.Content"), nameof(contentInfo));
// Normalize the subject identifier type the same way as .NET Framework.
// This value is only used in the zero-argument ComputeSignature overload,

View file

@ -358,9 +358,7 @@ namespace System.Security.Cryptography.Pkcs
{
if (index < 0)
{
// In .NET Framework RemoveCounterSignature doesn't bounds check, but the helper it calls does.
// In the helper the argument is called "childIndex".
throw new ArgumentOutOfRangeException("childIndex");
throw new ArgumentOutOfRangeException(nameof(index));
}
// The SignerInfo class is a projection of data contained within the SignedCms.

View file

@ -24,7 +24,7 @@ namespace System.Security.Cryptography.Pkcs.Tests
{
AsnEncodedData a = new AsnEncodedData(new byte[3]);
object ign;
Assert.Throws<ArgumentNullException>(() => ign = new Pkcs9AttributeObject(a));
AssertExtensions.Throws<ArgumentException, ArgumentNullException>("asnEncodedData", "asnEncodedData.Oid", () => ign = new Pkcs9AttributeObject(a));
}
[Fact]
@ -112,7 +112,7 @@ namespace System.Security.Cryptography.Pkcs.Tests
AsnEncodedData a = new AsnEncodedData(oid, new byte[3]);
object ign;
Assert.Throws<ArgumentNullException>(() => ign = new Pkcs9AttributeObject(a));
AssertExtensions.Throws<ArgumentException, ArgumentNullException>("asnEncodedData", "oid.Value", () => ign = new Pkcs9AttributeObject(a));
}
[Fact]
@ -123,7 +123,7 @@ namespace System.Security.Cryptography.Pkcs.Tests
AsnEncodedData a = new AsnEncodedData(oid, new byte[3]);
object ign;
AssertExtensions.Throws<ArgumentException>("oid.Value", () => ign = new Pkcs9AttributeObject(a));
AssertExtensions.Throws<ArgumentException>("asnEncodedData", "oid.Value", () => ign = new Pkcs9AttributeObject(a));
}
[Fact]

View file

@ -481,6 +481,7 @@ namespace System.Security.Cryptography.Pkcs.Tests
SignerInfo signer = cms.SignerInfos[0];
ArgumentOutOfRangeException ex = AssertExtensions.Throws<ArgumentOutOfRangeException>(
"index",
"childIndex",
() => signer.RemoveCounterSignature(-1));

View file

@ -1,4 +1,5 @@
<root>
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
@ -66,6 +67,9 @@
<data name="Arg_EmptyOrNullString" xml:space="preserve">
<value>String cannot be empty or null.</value>
</data>
<data name="Arg_EmptyOrNullString_Named" xml:space="preserve">
<value>The '{0}' string cannot be empty or null.</value>
</data>
<data name="Arg_EnumIllegalVal" xml:space="preserve">
<value>Illegal enum value: {0}.</value>
</data>
@ -74,7 +78,7 @@
</data>
<data name="Arg_InvalidType" xml:space="preserve">
<value>Invalid type.</value>
</data>
</data>
<data name="Arg_OutOfRange_NeedNonNegNum" xml:space="preserve">
<value>Non-negative number required.</value>
</data>
@ -223,7 +227,7 @@
<value>The provided hash value is not the expected size for the specified hash algorithm.</value>
</data>
<data name="Cryptography_Unix_X509_DisallowedStoreNotEmpty" xml:space="preserve">
<value>The Disallowed store is not supported on this platform, but already has data. All files under '{0}' must be removed.</value>
<value>The Disallowed store is not supported on this platform, but already has data. All files under '{0}' must be removed.</value>
</data>
<data name="Cryptography_Unix_X509_MachineStoresReadOnly" xml:space="preserve">
<value>Unix LocalMachine X509Stores are read-only for all users.</value>
@ -235,7 +239,7 @@
<value>The Disallowed store is not supported on this platform.</value>
</data>
<data name="Cryptography_Unix_X509_PropertyNotSettable" xml:space="preserve">
<value>The {0} value cannot be set on Unix.</value>
<value>The {0} value cannot be set on Unix.</value>
</data>
<data name="Cryptography_UnknownHashAlgorithm" xml:space="preserve">
<value>'{0}' is not a known hash algorithm.</value>
@ -286,7 +290,7 @@
<value>The X509 certificate store is read-only.</value>
</data>
<data name="Cryptography_X509_StoreCannotCreate" xml:space="preserve">
<value>The platform does not have a definition for an X509 certificate store named '{0}' with a StoreLocation of '{1}', and does not support creating it.</value>
<value>The platform does not have a definition for an X509 certificate store named '{0}' with a StoreLocation of '{1}', and does not support creating it.</value>
</data>
<data name="InvalidOperation_EnumNotStarted" xml:space="preserve">
<value>Enumeration has not started. Call MoveNext.</value>
@ -417,4 +421,4 @@
<data name="Cryptography_NotValidPrivateKey" xml:space="preserve">
<value>Key is not a valid private key.</value>
</data>
</root>
</root>

View file

@ -31,7 +31,7 @@ namespace System.Security.Cryptography.X509Certificates
if (base.Oid == null || base.Oid.Value == null)
throw new ArgumentNullException(nameof(oid));
if (base.Oid.Value.Length == 0)
throw new ArgumentException(SR.Arg_EmptyOrNullString, "oid.Value");
throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString_Named, "oid.Value"), nameof(oid));
Critical = critical;
}

View file

@ -640,7 +640,9 @@ namespace System.Security.Principal
if (error == Interop.Errors.ERROR_INVALID_PARAMETER)
{
#pragma warning disable CA2208 // Instantiate argument exceptions correctly, combination of arguments used
throw new ArgumentException(new Win32Exception(error).Message, "sidType/domainSid");
#pragma warning restore CS2208
}
else if (error != Interop.Errors.ERROR_SUCCESS)
{

View file

@ -134,11 +134,8 @@ namespace System.Security.Principal
sourceContext.SourceName = new byte[TOKEN_SOURCE.TOKEN_SOURCE_LENGTH];
Buffer.BlockCopy(sourceName, 0, sourceContext.SourceName, 0, sourceName.Length);
// .NET Framework compat: Desktop never null-checks sUserPrincipalName. Actual behavior is that the null makes it down to Encoding.Unicode.GetBytes() which then throws
// the ArgumentNullException (provided that the prior LSA calls didn't fail first.) To make this compat decision explicit, we'll null check ourselves
// and simulate the exception from Encoding.Unicode.GetBytes().
if (sUserPrincipalName == null)
throw new ArgumentNullException("s");
throw new ArgumentNullException(nameof(sUserPrincipalName));
byte[] upnBytes = Encoding.Unicode.GetBytes(sUserPrincipalName);
if (upnBytes.Length > ushort.MaxValue)

View file

@ -211,7 +211,7 @@ namespace System.Transactions
// If the requested IsolationLevel is stronger than that of the specified transaction, throw.
if ((IsolationLevel.Unspecified != transactionOptions.IsolationLevel) && (_expectedCurrent.IsolationLevel != transactionOptions.IsolationLevel))
{
throw new ArgumentException(SR.TransactionScopeIsolationLevelDifferentFromTransaction, "transactionOptions.IsolationLevel");
throw new ArgumentException(SR.TransactionScopeIsolationLevelDifferentFromTransaction, nameof(transactionOptions));
}
}
}
@ -293,7 +293,7 @@ namespace System.Transactions
// If the requested IsolationLevel is stronger than that of the specified transaction, throw.
if ((IsolationLevel.Unspecified != transactionOptions.IsolationLevel) && (_expectedCurrent.IsolationLevel != transactionOptions.IsolationLevel))
{
throw new ArgumentException(SR.TransactionScopeIsolationLevelDifferentFromTransaction, "transactionOptions.IsolationLevel");
throw new ArgumentException(SR.TransactionScopeIsolationLevelDifferentFromTransaction, nameof(transactionOptions));
}
}
}

View file

@ -173,7 +173,7 @@ namespace System.Drawing
catch
{
// Exception from converter is too generic.
throw new ArgumentException(SR.Format(SR.TextParseFailedFormat, font, $"name{separator} size[units[{separator} style=style1[{separator} style2{separator} ...]]]"), nameof(sizeStr));
throw new ArgumentException(SR.Format(SR.TextParseFailedFormat, font, $"name{separator} size[units[{separator} style=style1[{separator} style2{separator} ...]]]"), nameof(value));
}
}

View file

@ -131,7 +131,7 @@ namespace System.ComponentModel.TypeConverterTests
public static TheoryData<string, string, string> ArgumentExceptionFontConverterData() => new TheoryData<string, string, string>()
{
{ $"Courier New{s_Separator} 11 px{s_Separator} type=Bold{s_Separator} Italic", "units", null },
{ $"Courier New{s_Separator} {s_Separator} Style=Bold", "sizeStr", null },
{ $"Courier New{s_Separator} {s_Separator} Style=Bold", "value", null },
{ $"Courier New{s_Separator} 11{s_Separator} Style=", "value", null },
{ $"Courier New{s_Separator} 11{s_Separator} Style=RandomEnum", null, null },
{ $"Arial{s_Separator} 10{s_Separator} style=bold{s_Separator}", "value", null },

View file

@ -113,7 +113,7 @@ namespace System
{
object? obj = wo.Target;
if (obj == null)
throw new ArgumentException();
throw new ArgumentException(null, nameof(wo));
return GetGeneration(obj);
}

View file

@ -261,7 +261,7 @@ namespace System.Reflection.Emit
if (interfaceType == null)
throw new ArgumentNullException(nameof(interfaceType));
if (interfaceType.IsByRef)
throw new ArgumentException(nameof(interfaceType));
throw new ArgumentException(SR.Argument_CannotGetTypeTokenForByRef);
check_not_created();
if (interfaces != null)
@ -479,7 +479,7 @@ namespace System.Reflection.Emit
if (IsInterface)
throw new InvalidOperationException();
if ((attributes & (MethodAttributes.Static | MethodAttributes.Virtual)) > 0)
throw new ArgumentException(nameof(attributes));
throw new ArgumentException(SR.Arg_NoStaticVirtual);
if (parent != null)
parent_type = parent;
@ -1515,7 +1515,7 @@ namespace System.Reflection.Emit
{
check_name(nameof(name), name);
if (eventtype == null)
throw new ArgumentNullException("type");
throw new ArgumentNullException(nameof(eventtype));
check_not_created();
if (eventtype.IsByRef)
throw new ArgumentException(SR.Argument_CannotGetTypeTokenForByRef);
@ -1597,7 +1597,7 @@ namespace System.Reflection.Emit
else
{
if (parent.IsInterface)
throw new ArgumentException(nameof(parent));
throw new ArgumentException(SR.Argument_CannotSetParentToInterface);
this.parent = parent;
}
this.parent = ResolveUserType(this.parent);
@ -1878,7 +1878,7 @@ namespace System.Reflection.Emit
throw new ArgumentException("The specified field must be declared on a generic type definition.", nameof(field));
if (field.DeclaringType != type.GetGenericTypeDefinition())
throw new ArgumentException("field declaring type is not the generic type definition of type", "method");
throw new ArgumentException("field declaring type is not the generic type definition of type", nameof(field));
FieldInfo res = type.GetField(field);
if (res == null)

View file

@ -8,8 +8,10 @@ namespace System.Runtime.CompilerServices
{
public static void InitializeArray(Array array, RuntimeFieldHandle fldHandle)
{
if (array == null || fldHandle.Value == IntPtr.Zero)
throw new ArgumentNullException();
if (array == null)
throw new ArgumentNullException(nameof(array));
if (fldHandle.Value == IntPtr.Zero)
throw new ArgumentNullException(nameof(fldHandle));
InitializeArray(array, fldHandle.Value);
}

View file

@ -873,7 +873,7 @@ namespace System
protected override PropertyInfo? GetPropertyImpl(
string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers)
{
if (name == null) throw new ArgumentNullException();
if (name == null) throw new ArgumentNullException(nameof(name));
ListBuilder<PropertyInfo> candidates = GetPropertyCandidates(name, bindingAttr, types, false);
@ -911,7 +911,7 @@ namespace System
public override EventInfo? GetEvent(string name, BindingFlags bindingAttr)
{
if (name == null) throw new ArgumentNullException();
if (name == null) throw new ArgumentNullException(nameof(name));
bool ignoreCase;
MemberListType listType;
@ -978,7 +978,7 @@ namespace System
public override Type? GetInterface(string fullname, bool ignoreCase)
{
if (fullname == null) throw new ArgumentNullException();
if (fullname == null) throw new ArgumentNullException(nameof(fullname));
BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic;
@ -1031,7 +1031,7 @@ namespace System
public override Type? GetNestedType(string fullname, BindingFlags bindingAttr)
{
if (fullname == null) throw new ArgumentNullException();
if (fullname == null) throw new ArgumentNullException(nameof(fullname));
bool ignoreCase;
bindingAttr &= ~BindingFlags.Static;
@ -1059,7 +1059,7 @@ namespace System
public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr)
{
if (name == null) throw new ArgumentNullException();
if (name == null) throw new ArgumentNullException(nameof(name));
ListBuilder<MethodInfo> methods = default;
ListBuilder<ConstructorInfo> constructors = default;