From 47f902460b709acc57fd848b4844deb3619c846b Mon Sep 17 00:00:00 2001 From: Buyaa Namnan Date: Fri, 1 May 2020 09:01:21 -0700 Subject: [PATCH 1/7] Fix argument exception warnings on runtime --- .editorconfig | 1 + eng/CodeAnalysis.ruleset | 2 +- .../Runtime/InteropServices/ComActivator.cs | 8 +++--- .../src/System/ArgIterator.cs | 2 ++ .../System.Private.CoreLib/src/System/GC.cs | 2 +- .../Runtime/InteropServices/ComWrappers.cs | 8 +++--- .../src/System/RuntimeType.CoreCLR.cs | 12 ++++---- .../System/Threading/ThreadPool.CoreCLR.cs | 2 +- .../src/System/Buffers/ArrayBufferWriter.cs | 4 +-- .../src/System/Threading/Tasks/TaskToApm.cs | 4 +-- .../src/ChainedConfigurationProvider.cs | 2 ++ .../src/Dependency.cs | 4 +-- .../src/Library.cs | 6 ++-- .../src/ResourceAssembly.cs | 6 ++-- .../src/RuntimeAssembly.cs | 6 ++-- .../src/RuntimeFallbacks.cs | 4 +-- .../src/RuntimeFile.cs | 2 +- .../src/TargetInfo.cs | 4 +-- .../Design/DesignerOptionService.cs | 2 +- .../MemberRelationshipService.cs | 4 +++ .../Design/DesignerOptionServiceTests.cs | 2 +- .../Diagnostics/PerformanceData/CounterSet.cs | 4 +-- .../AccountManagement/Principal.cs | 4 +-- .../AccountManagement/PrincipalSearcher.cs | 2 +- .../tests/ComputerPrincipalTest.cs | 2 +- .../ActiveDirectorySchedule.cs | 2 +- .../ActiveDirectorySchemaClassCollection.cs | 8 +++--- ...ActiveDirectorySchemaPropertyCollection.cs | 8 +++--- .../ActiveDirectorySiteCollection.cs | 2 +- .../ActiveDirectorySiteLink.cs | 2 +- .../ActiveDirectorySiteLinkCollection.cs | 2 +- .../ActiveDirectorySubnetCollection.cs | 4 +-- .../DirectoryServerCollection.cs | 4 +-- .../Drawing/Drawing2D/LinearGradientBrush.cs | 4 ++- .../Drawing/Drawing2D/PathGradientBrush.cs | 6 +++- .../src/System/Drawing/Font.Windows.cs | 2 +- .../src/System/Drawing/Font.cs | 2 +- .../src/System/Drawing/Icon.Windows.cs | 2 ++ .../Drawing/Text/PrivateFontCollection.cs | 2 ++ .../Drawing2D/LinearGradientBrushTests.cs | 2 +- .../tests/Drawing2D/PathGradientBrushTests.cs | 2 +- .../System/Management/ManagementDateTime.cs | 2 +- .../src/System/Management/ManagementQuery.cs | 28 +++++++++---------- .../src/System/Net/HttpListenerResponse.cs | 2 +- .../HttpListenerResponseTests.Headers.cs | 2 +- .../src/System/Net/CookieContainer.cs | 6 ++-- .../tests/UnitTests/CookieContainerTest.cs | 8 +++--- .../src/Resources/Strings.resx | 7 +++-- .../src/System/Net/Sockets/Socket.cs | 20 +++++++++---- .../src/System/Net/WebHeaderCollection.cs | 2 +- .../src/System/DateTime.cs | 2 ++ .../src/System/Globalization/CultureInfo.cs | 2 ++ .../src/System/IO/BinaryWriter.cs | 2 +- .../src/System/IO/UnmanagedMemoryStream.cs | 2 +- .../src/System/Text/StringBuilder.cs | 2 ++ .../src/System/Threading/Thread.cs | 2 +- .../src/System/Type.Enum.cs | 4 +-- .../System.Private.CoreLib/src/System/Type.cs | 2 ++ .../System.Private.Uri/src/System/Uri.cs | 4 ++- .../tests/ExtendedFunctionalTests/UriTests.cs | 2 +- .../src/System/Xml/NameTable.cs | 2 +- .../tests/RuntimeReflectionExtensionTests.cs | 4 +-- .../InteropServices/ComAwareEventInfoTests.cs | 2 +- .../InteropServices/Marshal/OffsetOfTests.cs | 4 +-- .../tests/System/Type/TypeTests.Get.cs | 2 +- .../AccessControl/CommonObjectSecurity.cs | 2 +- .../System/Security/Cryptography/DSA.Xml.cs | 2 ++ .../Security/Cryptography/PemEncoding.cs | 4 +-- .../src/Resources/Strings.resx | 11 ++++---- .../Cryptography/Pkcs/Pkcs12Builder.cs | 4 +-- .../Cryptography/Pkcs/Pkcs9AttributeObject.cs | 4 ++- .../Security/Cryptography/Pkcs/SignedCms.cs | 2 ++ .../Security/Cryptography/Pkcs/SignerInfo.cs | 2 ++ .../tests/Pkcs9AttributeTests.cs | 2 +- .../X509Certificates/X509Extension.cs | 2 +- .../src/System/Security/Principal/SID.cs | 2 ++ .../Security/Principal/WindowsIdentity.cs | 2 ++ .../System/Transactions/TransactionScope.cs | 4 +-- .../src/System/Drawing/FontConverter.cs | 2 +- .../System/Drawing/FontConverterTests.cs | 2 +- .../src/System/GC.Mono.cs | 2 +- .../Reflection/Emit/TypeBuilder.Mono.cs | 10 +++---- .../CompilerServices/RuntimeHelpers.Mono.cs | 6 ++-- 83 files changed, 194 insertions(+), 139 deletions(-) diff --git a/.editorconfig b/.editorconfig index 6c6dcb40761745..bbcab4fb85de86 100644 --- a/.editorconfig +++ b/.editorconfig @@ -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}] diff --git a/eng/CodeAnalysis.ruleset b/eng/CodeAnalysis.ruleset index cf97025667a2bd..408bc1b422fe31 100644 --- a/eng/CodeAnalysis.ruleset +++ b/eng/CodeAnalysis.ruleset @@ -106,7 +106,7 @@ - + diff --git a/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs b/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs index 8f7d8ecd550be9..a5232b25091025 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/Internal/Runtime/InteropServices/ComActivator.cs @@ -124,7 +124,7 @@ public static object GetClassFactoryForType(ComActivationContext cxt) 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 @@ public static void ClassRegistrationScenarioForType(ComActivationContext cxt, bo 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 @@ public static unsafe int RegisterClassForTypeInternal(ComActivationContextIntern if (cxtInt.InterfaceId != Guid.Empty || cxtInt.ClassFactoryDest != IntPtr.Zero) { - throw new ArgumentException(); + throw new ArgumentException(null, nameof(pCxtInt)); } try @@ -328,7 +328,7 @@ public static unsafe int UnregisterClassForTypeInternal(ComActivationContextInte if (cxtInt.InterfaceId != Guid.Empty || cxtInt.ClassFactoryDest != IntPtr.Zero) { - throw new ArgumentException(); + throw new ArgumentException(null, nameof(pCxtInt)); } try diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/ArgIterator.cs b/src/coreclr/src/System.Private.CoreLib/src/System/ArgIterator.cs index d32d53ae753b6e..8c7039e557b457 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/ArgIterator.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/ArgIterator.cs @@ -85,7 +85,9 @@ public TypedReference GetNextArg(RuntimeTypeHandle rth) // 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 diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/GC.cs b/src/coreclr/src/System.Private.CoreLib/src/System/GC.cs index fc8a9650f63b7e..e3e1b54373fa5e 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/GC.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/GC.cs @@ -135,7 +135,7 @@ public static void AddMemoryPressure(long bytesAllocated) if ((4 == IntPtr.Size) && (bytesAllocated > int.MaxValue)) { - throw new ArgumentOutOfRangeException("pressure", + throw new ArgumentOutOfRangeException(nameof(bytesAllocated), SR.ArgumentOutOfRange_MustBeNonNegInt32); } diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs index 0229ac9c0dbc55..d72d783389f020 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Runtime/InteropServices/ComWrappers.cs @@ -121,7 +121,7 @@ public IntPtr GetOrCreateComInterfaceForObject(object instance, CreateComInterfa { IntPtr ptr; if (!TryGetOrCreateComInterfaceForObjectInternal(this, instance, flags, out ptr)) - throw new ArgumentException(); + throw new ArgumentException(null, nameof(instance)); return ptr; } @@ -187,7 +187,7 @@ public object GetOrCreateObjectForComInstance(IntPtr externalComObject, CreateOb { object? obj; if (!TryGetOrCreateObjectForComInstanceInternal(this, externalComObject, flags, null, out obj)) - throw new ArgumentNullException(); + throw new ArgumentNullException(nameof(externalComObject)); return obj!; } @@ -230,7 +230,7 @@ public object GetOrRegisterObjectForComInstance(IntPtr externalComObject, Create object? obj; if (!TryGetOrCreateObjectForComInstanceInternal(this, externalComObject, flags, wrapper, out obj)) - throw new ArgumentNullException(); + throw new ArgumentNullException(nameof(externalComObject)); return obj!; } @@ -319,4 +319,4 @@ internal static int CallICustomQueryInterface(object customQueryInterfaceMaybe, return (int)customQueryInterface.GetInterface(ref iid, out ppObject); } } -} \ No newline at end of file +} diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs index 93cfd86bc167b1..429f5d90da6df8 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs @@ -2752,7 +2752,7 @@ public override InterfaceMapping GetInterfaceMap(Type ifaceType) 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 candidates = GetPropertyCandidates(name, bindingAttr, types, false); @@ -2788,7 +2788,7 @@ public override InterfaceMapping GetInterfaceMap(Type ifaceType) 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); @@ -2814,7 +2814,7 @@ public override InterfaceMapping GetInterfaceMap(Type ifaceType) public override FieldInfo? GetField(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); @@ -2851,7 +2851,7 @@ public override InterfaceMapping GetInterfaceMap(Type ifaceType) 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; @@ -2885,7 +2885,7 @@ public override InterfaceMapping GetInterfaceMap(Type ifaceType) 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; @@ -2913,7 +2913,7 @@ public override InterfaceMapping GetInterfaceMap(Type ifaceType) 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 methods = default; ListBuilder constructors = default; diff --git a/src/coreclr/src/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.cs b/src/coreclr/src/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.cs index c2d72e3915cae7..9752c3cbde3667 100644 --- a/src/coreclr/src/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.cs +++ b/src/coreclr/src/System.Private.CoreLib/src/System/Threading/ThreadPool.CoreCLR.cs @@ -260,7 +260,7 @@ private static extern long PendingUnmanagedWorkItemCount get; } - private static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException + private static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, diff --git a/src/libraries/Common/src/System/Buffers/ArrayBufferWriter.cs b/src/libraries/Common/src/System/Buffers/ArrayBufferWriter.cs index 71b23e1f7cd3f7..a7b047119d5d5f 100644 --- a/src/libraries/Common/src/System/Buffers/ArrayBufferWriter.cs +++ b/src/libraries/Common/src/System/Buffers/ArrayBufferWriter.cs @@ -42,7 +42,7 @@ public ArrayBufferWriter() 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 @@ public void Clear() 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); diff --git a/src/libraries/Common/src/System/Threading/Tasks/TaskToApm.cs b/src/libraries/Common/src/System/Threading/Tasks/TaskToApm.cs index ecd9f27ecb8dd8..96b41501f3407d 100644 --- a/src/libraries/Common/src/System/Threading/Tasks/TaskToApm.cs +++ b/src/libraries/Common/src/System/Threading/Tasks/TaskToApm.cs @@ -43,7 +43,7 @@ public static void End(IAsyncResult asyncResult) return; } - throw new ArgumentNullException(); + throw new ArgumentNullException(nameof(asyncResult)); } /// Processes an IAsyncResult returned by Begin. @@ -55,7 +55,7 @@ public static TResult End(IAsyncResult asyncResult) return task.GetAwaiter().GetResult(); } - throw new ArgumentNullException(); + throw new ArgumentNullException(nameof(asyncResult)); } /// Provides a simple IAsyncResult that wraps a Task. diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs index ffc3a406b9f8fd..110c53fba0a8cf 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs @@ -29,7 +29,9 @@ public ChainedConfigurationProvider(ChainedConfigurationSource source) } if (source.Configuration == null) { +#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentNullException(nameof(source.Configuration)); +#pragma warning restore CA2208 } _config = source.Configuration; diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Dependency.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/Dependency.cs index e60989f77a5c86..6c26416a9359e6 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Dependency.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Dependency.cs @@ -13,11 +13,11 @@ public Dependency(string name, string version) { 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; diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/Library.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/Library.cs index cef2b76d2c9c97..eb64ac5fc95da6 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/Library.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/Library.cs @@ -43,15 +43,15 @@ public Library(string type, { 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) { diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/ResourceAssembly.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/ResourceAssembly.cs index 998789b51001eb..4e754367b7791a 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/ResourceAssembly.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/ResourceAssembly.cs @@ -12,11 +12,11 @@ public ResourceAssembly(string path, string locale) { 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 @@ public ResourceAssembly(string path, string locale) public string Path { get; set; } } -} \ No newline at end of file +} diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeAssembly.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeAssembly.cs index c4e07fe7deb4ba..edf908e9766c6a 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeAssembly.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeAssembly.cs @@ -16,11 +16,11 @@ public RuntimeAssembly(string assemblyName, string path) { 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 @@ public static RuntimeAssembly Create(string path) return new RuntimeAssembly(assemblyName, path); } } -} \ No newline at end of file +} diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.cs index 32b3635c92f669..9ce186d557b6ce 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFallbacks.cs @@ -18,7 +18,7 @@ public RuntimeFallbacks(string runtime, IEnumerable fallbacks) { if (string.IsNullOrEmpty(runtime)) { - throw new ArgumentException(nameof(runtime)); + throw new ArgumentException(null, nameof(runtime)); } if (fallbacks == null) { @@ -28,4 +28,4 @@ public RuntimeFallbacks(string runtime, IEnumerable fallbacks) Fallbacks = fallbacks.ToArray(); } } -} \ No newline at end of file +} diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFile.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFile.cs index 542a5b65a51aae..5777a34dfa2c47 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFile.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/RuntimeFile.cs @@ -12,7 +12,7 @@ public RuntimeFile(string path, string assemblyVersion, string fileVersion) { if (string.IsNullOrEmpty(path)) { - throw new ArgumentException(nameof(path)); + throw new ArgumentException(null, nameof(path)); } Path = path; diff --git a/src/libraries/Microsoft.Extensions.DependencyModel/src/TargetInfo.cs b/src/libraries/Microsoft.Extensions.DependencyModel/src/TargetInfo.cs index 0b2f53607b8634..485ff58d3eb23e 100644 --- a/src/libraries/Microsoft.Extensions.DependencyModel/src/TargetInfo.cs +++ b/src/libraries/Microsoft.Extensions.DependencyModel/src/TargetInfo.cs @@ -14,7 +14,7 @@ public TargetInfo(string framework, { if (string.IsNullOrEmpty(framework)) { - throw new ArgumentException(nameof(framework)); + throw new ArgumentException(null, nameof(framework)); } Framework = framework; @@ -32,4 +32,4 @@ public TargetInfo(string framework, public bool IsPortable { get; } } -} \ No newline at end of file +} diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs index f80f2c00babdd0..e43b6749b8950c 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs @@ -48,7 +48,7 @@ protected DesignerOptionCollection CreateOptionCollection(DesignerOptionCollecti 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", "0"), nameof(name)); } return new DesignerOptionCollection(this, parent, name, value); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs index c5bceb6e9d450a..b2a9eccb54a876 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs @@ -44,7 +44,9 @@ public MemberRelationship this[MemberRelationship source] // and not the other as the main constructor performs argument validation. if (source.Owner == null) { +#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentNullException(nameof(MemberRelationship.Owner)); +#pragma warning restore CA2208 } Debug.Assert(source.Member != null); @@ -57,7 +59,9 @@ public MemberRelationship this[MemberRelationship source] // and not the other as the main constructor performs argument validation. if (source.Owner == null) { +#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentNullException(nameof(MemberRelationship.Owner)); +#pragma warning restore CA2208 } Debug.Assert(source.Member != null); diff --git a/src/libraries/System.ComponentModel.TypeConverter/tests/Design/DesignerOptionServiceTests.cs b/src/libraries/System.ComponentModel.TypeConverter/tests/Design/DesignerOptionServiceTests.cs index 37aaf190737886..78778d048a330a 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/tests/Design/DesignerOptionServiceTests.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/tests/Design/DesignerOptionServiceTests.cs @@ -53,7 +53,7 @@ public void CreateOptionCollection_NullName_ThrowsArgumentNullException() public void CreateOptionCollection_EmptyName_ThrowsArgumentException() { var service = new TestDesignerOptionService(); - AssertExtensions.Throws("name.Length", () => service.DoCreateOptionCollection(service.Options, string.Empty, "value")); + AssertExtensions.Throws("name", () => service.DoCreateOptionCollection(service.Options, string.Empty, "value")); } [Fact] diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.cs index 13ac7471b69685..d1a12257a9926b 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.cs @@ -195,7 +195,7 @@ public CounterSetInstance CreateCounterSetInstance(string instanceName) { if (_provider == null) { - throw new ArgumentException(SR.Format(SR.Perflib_Argument_ProviderNotFound, _providerGuid), "ProviderGuid"); + throw new ArgumentException(SR.Format(SR.Perflib_Argument_ProviderNotFound, _providerGuid), nameof(instanceName)); } if (_provider._hProvider.IsInvalid) { @@ -256,7 +256,7 @@ public CounterSetInstance CreateCounterSetInstance(string instanceName) { 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 ArgumentException(SR.Format(SR.Perflib_Argument_CounterSetAlreadyRegister, _counterSet), nameof(instanceName)), _ => new Win32Exception((int)Status), }; diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs index 040de0d0c932cb..8c2bcb0871291b 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/Principal.cs @@ -124,7 +124,7 @@ public string SamAccountName 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 @@ public string Name 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); diff --git a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalSearcher.cs b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalSearcher.cs index 62b8e52e5239de..68d1811c0a0eba 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalSearcher.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/src/System/DirectoryServices/AccountManagement/PrincipalSearcher.cs @@ -23,7 +23,7 @@ public PrincipalSearcher() 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 diff --git a/src/libraries/System.DirectoryServices.AccountManagement/tests/ComputerPrincipalTest.cs b/src/libraries/System.DirectoryServices.AccountManagement/tests/ComputerPrincipalTest.cs index e17eaf3f60aac8..9d83710d151682 100644 --- a/src/libraries/System.DirectoryServices.AccountManagement/tests/ComputerPrincipalTest.cs +++ b/src/libraries/System.DirectoryServices.AccountManagement/tests/ComputerPrincipalTest.cs @@ -35,7 +35,7 @@ public void Ctor_NullSamAccountName_ThrowsArgumentException() public void Ctor_EmptySamAccountName_ThrowsArgumentNullException() { var context = new PrincipalContext(ContextType.Machine); - AssertExtensions.Throws("Principal.SamAccountName", null, () => new ComputerPrincipal(context, string.Empty, "password", enabled: true)); + AssertExtensions.Throws("value", null, () => new ComputerPrincipal(context, string.Empty, "password", enabled: true)); } [Fact] diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs index e4eee6a47e26dd..2ae4757c6f3b93 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchedule.cs @@ -59,7 +59,7 @@ public ActiveDirectorySchedule() 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++) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs index ae07de8d521e54..c506669acc8359 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaClassCollection.cs @@ -111,7 +111,7 @@ public void AddRange(ActiveDirectorySchemaClass[] schemaClasses) { if (schemaClass == null) { - throw new ArgumentException(nameof(schemaClasses)); + throw new ArgumentException(null, nameof(schemaClasses)); } } @@ -132,7 +132,7 @@ public void AddRange(ActiveDirectorySchemaClassCollection schemaClasses) { if (schemaClass == null) { - throw new ArgumentException(nameof(schemaClasses)); + throw new ArgumentException(null, nameof(schemaClasses)); } } @@ -154,7 +154,7 @@ public void AddRange(ReadOnlyActiveDirectorySchemaClassCollection schemaClasses) { if (schemaClass == null) { - throw new ArgumentException(nameof(schemaClasses)); + throw new ArgumentException(null, nameof(schemaClasses)); } } @@ -360,7 +360,7 @@ protected override void OnValidate(object value) if (!(value is ActiveDirectorySchemaClass)) { - throw new ArgumentException(nameof(value)); + throw new ArgumentException(null, nameof(value)); } if (!((ActiveDirectorySchemaClass)value).isBound) diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs index 0e312f9b392cb8..5bea1fa12e76e1 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySchemaPropertyCollection.cs @@ -109,7 +109,7 @@ public void AddRange(ActiveDirectorySchemaProperty[] properties) { if (property == null) { - throw new ArgumentException(nameof(properties)); + throw new ArgumentException(null, nameof(properties)); } } @@ -130,7 +130,7 @@ public void AddRange(ActiveDirectorySchemaPropertyCollection properties) { if (property == null) { - throw new ArgumentException(nameof(properties)); + throw new ArgumentException(null, nameof(properties)); } } @@ -153,7 +153,7 @@ public void AddRange(ReadOnlyActiveDirectorySchemaPropertyCollection properties) { if (property == null) { - throw new ArgumentException(nameof(properties)); + throw new ArgumentException(null, nameof(properties)); } } @@ -369,7 +369,7 @@ protected override void OnValidate(object value) 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)); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs index 88beabbb7b3750..5e85364b26da9c 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteCollection.cs @@ -232,7 +232,7 @@ protected override void OnValidate(object value) 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)); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs index e35ece7285cfe1..244b020f7b3f32 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLink.cs @@ -268,7 +268,7 @@ public int Cost throw new ObjectDisposedException(GetType().Name); if (value < 0) - throw new ArgumentException(nameof(value)); + throw new ArgumentException(null, nameof(value)); try { diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs index 24d230c920a802..3f6afc747b36a9 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySiteLinkCollection.cs @@ -226,7 +226,7 @@ protected override void OnValidate(object value) 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)); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs index b270eab2247fbc..540be8cbfc5c01 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/ActiveDirectorySubnetCollection.cs @@ -68,7 +68,7 @@ public void AddRange(ActiveDirectorySubnet[] subnets) { if (s == null) { - throw new ArgumentException(nameof(subnets)); + throw new ArgumentException(null, nameof(subnets)); } } @@ -263,7 +263,7 @@ protected override void OnValidate(object value) 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)); diff --git a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs index 20ee51fd55c607..64de6d61b67e86 100644 --- a/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs +++ b/src/libraries/System.DirectoryServices/src/System/DirectoryServices/ActiveDirectory/DirectoryServerCollection.cs @@ -115,7 +115,7 @@ public void AddRange(DirectoryServer[] servers) { if (s == null) { - throw new ArgumentException(nameof(servers)); + throw new ArgumentException(null, nameof(servers)); } } @@ -386,7 +386,7 @@ protected override void OnValidate(object value) else { if (!(value is DirectoryServer)) - throw new ArgumentException(nameof(value)); + throw new ArgumentException(null, nameof(value)); } } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs index 19228b5266f031..8cfd1bf2643d38 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs @@ -232,14 +232,16 @@ public Blend? Blend throw new NullReferenceException(); if (value.Positions == null) +#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentNullException("source"); +#pragma warning restore CA2208 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) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs index bae8b7a6121d23..2e7f47491045d3 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs @@ -188,7 +188,9 @@ public Blend Blend // 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) +#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentNullException("source"); +#pragma warning restore CA2208 int count = value.Factors.Length; @@ -196,7 +198,7 @@ public Blend Blend 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) @@ -302,12 +304,14 @@ public ColorBlend InterpolationColors // depending on how sane the input is. These checks exist to replicate the exact Desktop behavior. int count = value.Colors.Length; +#pragma warning disable CA2208 // Instantiate argument exceptions correctly 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(); +#pragma warning restore CS2208 float[] positions = value.Positions; int[] argbs = new int[count]; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Windows.cs index bfa06594420bc7..41ed7b89b7b408 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.Windows.cs @@ -306,7 +306,7 @@ public static unsafe Font FromLogFont(object lf, IntPtr hdc) { // 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 diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.cs index b030638dda6138..bbabbf88ed0b89 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Font.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Font.cs @@ -285,7 +285,7 @@ public unsafe void ToLogFont(object logFont, Graphics graphics) { // 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); diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs index 02021231f9f292..ec2199805bd3f1 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs @@ -641,7 +641,9 @@ public void Save(Stream outputStream) { // We threw this way on NetFX if (outputStream == null) +#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentNullException("dataStream"); +#pragma warning restore CA2208 picture.SaveAsFile(new GPStream(outputStream, makeSeekable: false), -1, out int temp); } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs index 3b150283b5dd60..73333c46f949fe 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs @@ -60,6 +60,7 @@ public void AddFontFile(string filename) { 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(); @@ -70,6 +71,7 @@ public void AddFontFile(string filename) // 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"); +#pragma warning restore CA2208 } // this ensure the filename is valid (or throw the correct exception) diff --git a/src/libraries/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs b/src/libraries/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs index bcc33b61b72d5e..5464ba0c16e951 100644 --- a/src/libraries/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs +++ b/src/libraries/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs @@ -371,7 +371,7 @@ public void Blend_SetFactorsLengthGreaterThanPositionsLength_ThrowsArgumentOutOf { using (var brush = new LinearGradientBrush(new Rectangle(1, 2, 3, 4), Color.Plum, Color.Red, 45, true)) { - AssertExtensions.Throws(null, () => brush.Blend = new Blend { Factors = new float[2], Positions = new float[1] }); + AssertExtensions.Throws("value", () => brush.Blend = new Blend { Factors = new float[2], Positions = new float[1] }); } } diff --git a/src/libraries/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs b/src/libraries/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs index 3046c016418469..7cc603bb798898 100644 --- a/src/libraries/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs +++ b/src/libraries/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs @@ -350,7 +350,7 @@ public void Blend_InvalidFactorPositionsLengthMismatch_ThrowsArgumentOutOfRangeE using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { - AssertExtensions.Throws(null, () => brush.Blend = invalidBlend); + AssertExtensions.Throws("value", () => brush.Blend = invalidBlend); } } diff --git a/src/libraries/System.Management/src/System/Management/ManagementDateTime.cs b/src/libraries/System.Management/src/System/Management/ManagementDateTime.cs index 27114f9453b219..6a71452dc11204 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementDateTime.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementDateTime.cs @@ -415,7 +415,7 @@ public static string ToDmtfTimeInterval(TimeSpan timespan) // 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')); diff --git a/src/libraries/System.Management/src/System/Management/ManagementQuery.cs b/src/libraries/System.Management/src/System/Management/ManagementQuery.cs index 62797f9dbd3e5d..e9c380f2256bb8 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementQuery.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementQuery.cs @@ -1040,13 +1040,13 @@ protected internal override void ParseQuery(string query) // 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.InvalidQuery, 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.InvalidQuery, nameof(query)); q = q.Remove(0, 1).TrimStart(null); @@ -1055,7 +1055,7 @@ protected internal override void ParseQuery(string query) 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.InvalidQuery, nameof(query)); q = q.Remove(0, keyword.Length).TrimStart(null); @@ -1064,7 +1064,7 @@ protected internal override void ParseQuery(string query) 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.InvalidQuery, nameof(query)); q = q.Remove(0, keyword.Length).TrimStart(null); @@ -1076,7 +1076,7 @@ protected internal override void ParseQuery(string query) 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.InvalidQuery, nameof(query)); q = q.Remove(0, keyword.Length); @@ -1650,7 +1650,7 @@ protected internal override void ParseQuery(string query) //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.InvalidQuery, nameof(query)); // Invalid query // Strip off the clause q = q.Remove(0, TokenAssociators.Length); @@ -1663,7 +1663,7 @@ protected internal override void ParseQuery(string query) // 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.InvalidQuery, nameof(query)); // Invalid query // Strip off the clause and leading WS q = q.Remove(0, TokenOf.Length).TrimStart(null); @@ -1687,7 +1687,7 @@ protected internal override void ParseQuery(string query) { // 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.InvalidQuery, nameof(query)); // Invalid query q = q.Remove(0, TokenWhere.Length); @@ -2167,7 +2167,7 @@ protected internal override void ParseQuery(string query) //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.InvalidQuery, nameof(query)); // Invalid query // Strip off the clause q = q.Remove(0, TokenReferences.Length); @@ -2180,7 +2180,7 @@ protected internal override void ParseQuery(string query) // 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.InvalidQuery, nameof(query)); // Invalid query // Strip off the clause and leading WS q = q.Remove(0, TokenOf.Length).TrimStart(null); @@ -2204,7 +2204,7 @@ protected internal override void ParseQuery(string query) { // 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.InvalidQuery, nameof(query)); // Invalid query q = q.Remove(0, TokenWhere.Length); @@ -3043,13 +3043,13 @@ protected internal override void ParseQuery(string query) q = q.Remove(0, keyword.Length).TrimStart(null); if (!q.StartsWith("*", StringComparison.Ordinal)) - throw new ArgumentException(SR.InvalidQuery, "*"); + throw new ArgumentException(SR.InvalidQuery, 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.InvalidQuery, nameof(query)); ParseToken(ref q, keyword, null, ref bFound, ref eventClassName); //Find "within" clause @@ -3119,7 +3119,7 @@ protected internal override void ParseQuery(string query) q = q.Remove(0, keyword.Length); if (q.Length == 0) //bad query - throw new ArgumentException(SR.InvalidQuery, "having"); + throw new ArgumentException(SR.InvalidQuery, nameof(query)); havingCondition = q; } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs index 41e3f78d340c82..97c8339c3b95f6 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs @@ -188,7 +188,7 @@ public string StatusDescription 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)); } } diff --git a/src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.Headers.cs b/src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.Headers.cs index 112c841b8594a6..f52b79f355844b 100644 --- a/src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.Headers.cs +++ b/src/libraries/System.Net.HttpListener/tests/HttpListenerResponseTests.Headers.cs @@ -436,7 +436,7 @@ public async Task StatusDescription_SetInvalid_ThrowsArgumentException(string st { using (HttpListenerResponse response = await GetResponse()) { - AssertExtensions.Throws("name", () => response.StatusDescription = statusDescription); + AssertExtensions.Throws("value", () => response.StatusDescription = statusDescription); Assert.Equal("OK", response.StatusDescription); } } diff --git a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs index 75f68bb98086e5..af1f75ebc9d490 100644 --- a/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs +++ b/src/libraries/System.Net.Primitives/src/System/Net/CookieContainer.cs @@ -118,7 +118,7 @@ public CookieContainer(int capacity) { 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 @@ public CookieContainer(int capacity, int perDomainCapacity, int maxCookieSize) : 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 @@ public void Add(Cookie cookie) { throw new ArgumentException( SR.Format(SR.net_emptystringcall, nameof(cookie) + "." + nameof(cookie.Domain)), - nameof(cookie) + "." + nameof(cookie.Domain)); + nameof(cookie)); } Uri? uri; diff --git a/src/libraries/System.Net.Primitives/tests/UnitTests/CookieContainerTest.cs b/src/libraries/System.Net.Primitives/tests/UnitTests/CookieContainerTest.cs index d3ce1f523d0ecc..7bd84309abf0ce 100644 --- a/src/libraries/System.Net.Primitives/tests/UnitTests/CookieContainerTest.cs +++ b/src/libraries/System.Net.Primitives/tests/UnitTests/CookieContainerTest.cs @@ -486,7 +486,7 @@ public void Ctor_Capacity_Success() [Fact] public void Ctor_Capacity_Invalid() { - AssertExtensions.Throws("Capacity", () => new CookieContainer(0)); // Capacity <= 0 + AssertExtensions.Throws("capacity", () => new CookieContainer(0)); // Capacity <= 0 } [Fact] @@ -595,7 +595,7 @@ public void Add_Cookie_Invalid() { CookieContainer cc = new CookieContainer(); Assert.Throws(() => cc.Add((Cookie)null)); // Null cookie - AssertExtensions.Throws("cookie.Domain", () => cc.Add(new Cookie("name", "value", "", ""))); // Empty domain + AssertExtensions.Throws("cookie", () => cc.Add(new Cookie("name", "value", "", ""))); // Empty domain cc.MaxCookieSize = 1; Assert.Throws(() => cc.Add(new Cookie("name", "long-text", "", "contoso.com"))); // Value.Length > MaxCookieSize @@ -625,11 +625,11 @@ public void Capacity_ShrinkNoneExpired_RemovesAll() [Fact] public void Ctor_CapacityPerDomainCapacityMaxCookieSize_Invalid() { - AssertExtensions.Throws("Capacity", () => new CookieContainer(0, 10, 5)); // Capacity <= 0 + AssertExtensions.Throws("capacity", () => new CookieContainer(0, 10, 5)); // Capacity <= 0 Assert.Throws(() => new CookieContainer(5, 0, 5)); // Per domain capacity <= 0 Assert.Throws(() => new CookieContainer(5, 10, 5)); // Per domain capacity > Capacity - AssertExtensions.Throws("MaxCookieSize", () => new CookieContainer(15, 10, 0)); // Max cookie size <= 0 + AssertExtensions.Throws("maxCookieSize", () => new CookieContainer(15, 10, 0)); // Max cookie size <= 0 } [Fact] diff --git a/src/libraries/System.Net.Sockets/src/Resources/Strings.resx b/src/libraries/System.Net.Sockets/src/Resources/Strings.resx index 3078fabf5d5fd6..7c348e17785a68 100644 --- a/src/libraries/System.Net.Sockets/src/Resources/Strings.resx +++ b/src/libraries/System.Net.Sockets/src/Resources/Strings.resx @@ -1,4 +1,5 @@ - + + @@ -193,7 +194,7 @@ The specified value cannot be negative. - Argument must be between {0} and {1}. + Argument {2} must be between {0} and {1}. Sockets on this platform are invalid for use after a failed connection attempt. @@ -258,4 +259,4 @@ Asynchronous operations are not allowed on this socket. The underlying OS handle might have been already bound to an IO completion port. - + \ No newline at end of file diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs index 2e3f3d50ada638..6e23df42f3cbbe 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs @@ -1908,7 +1908,7 @@ public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName opti } 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, 0, (int)ushort.MaxValue, "optionValue.LingerTime"), nameof(optionValue)); } SetLingerOption(lingerOption); } @@ -3816,7 +3816,7 @@ public bool AcceptAsync(SocketAsyncEventArgs e) } if (e.HasMultipleBuffers) { - throw new ArgumentException(SR.net_multibuffernotsupported, "BufferList"); + throw new ArgumentException(SR.net_multibuffernotsupported, nameof(e)); } if (_rightEndPoint == null) { @@ -3979,11 +3979,13 @@ public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType } if (e.HasMultipleBuffers) { - throw new ArgumentException(SR.net_multibuffernotsupported, "BufferList"); + throw new ArgumentException(SR.net_multibuffernotsupported, nameof(e)); } if (e.RemoteEndPoint == null) { +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, the argument not applicable throw new ArgumentNullException("remoteEP"); +#pragma warning restore CA2208 } EndPoint endPointSnapshot = e.RemoteEndPoint; @@ -4116,11 +4118,13 @@ public bool ReceiveFromAsync(SocketAsyncEventArgs e) } if (e.RemoteEndPoint == null) { +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applcable throw new ArgumentNullException(nameof(e.RemoteEndPoint)); +#pragma warning restore CA2208 } 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 +4170,13 @@ public bool ReceiveMessageFromAsync(SocketAsyncEventArgs e) } if (e.RemoteEndPoint == null) { +#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentNullException(nameof(e.RemoteEndPoint)); +#pragma warning restore CA2208 } 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 +4256,9 @@ public bool SendPacketsAsync(SocketAsyncEventArgs e) } if (e.SendPacketsElements == null) { +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable throw new ArgumentNullException("e.SendPacketsElements"); +#pragma warning restore CA2208 } if (!Connected) { @@ -4288,7 +4296,9 @@ public bool SendToAsync(SocketAsyncEventArgs e) } if (e.RemoteEndPoint == null) { +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable throw new ArgumentNullException(nameof(RemoteEndPoint)); +#pragma warning restore CA2208 } // Prepare SocketAddress diff --git a/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs b/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs index 875caac4c46fd7..4cc1c8555e7948 100644 --- a/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs +++ b/src/libraries/System.Net.WebHeaderCollection/src/System/Net/WebHeaderCollection.cs @@ -378,7 +378,7 @@ public void Add(string header) { 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(); diff --git a/src/libraries/System.Private.CoreLib/src/System/DateTime.cs b/src/libraries/System.Private.CoreLib/src/System/DateTime.cs index 023d795019d41b..ab903a6541a9c1 100644 --- a/src/libraries/System.Private.CoreLib/src/System/DateTime.cs +++ b/src/libraries/System.Private.CoreLib/src/System/DateTime.cs @@ -583,7 +583,9 @@ public DateTime AddYears(int value) { // 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. +#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentOutOfRangeException("years", SR.ArgumentOutOfRange_DateTimeBadYears); +#pragma warning restore CA2208 } return AddMonths(value * 12); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs index f4daf5c08555ec..55709493daba21 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs @@ -1111,7 +1111,9 @@ public static CultureInfo GetCultureInfo(string name, string altName) } 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) diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs b/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs index 80fd193b5824b7..b4393da162f445 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/BinaryWriter.cs @@ -394,7 +394,7 @@ public virtual unsafe void Write(string value) { if (charStart < 0 || charCount < 0 || charStart > value.Length - charCount) { - throw new ArgumentOutOfRangeException(nameof(charCount)); + throw new ArgumentOutOfRangeException(nameof(value)); } fixed (char* pChars = value) { diff --git a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs index ecdb454203bf4e..21541fc26066fb 100644 --- a/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs +++ b/src/libraries/System.Private.CoreLib/src/System/IO/UnmanagedMemoryStream.cs @@ -415,7 +415,7 @@ public unsafe byte* PositionPointer 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); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs index 1b18fd5eca51f1..bdff2d05df01e5 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Text/StringBuilder.cs @@ -1144,7 +1144,9 @@ public StringBuilder Remove(int startIndex, int length) 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) { diff --git a/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs b/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs index 8bdf89070a9adc..9abd9ac2aa98a9 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs @@ -243,7 +243,7 @@ public bool TrySetApartmentState(ApartmentState state) break; default: - throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Enum, nameof(state)); + throw new ArgumentOutOfRangeException(nameof(state), SR.ArgumentOutOfRange_Enum); } return TrySetApartmentStateUnchecked(state); diff --git a/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs b/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs index 59f244f6c3477f..d041c32b7b5349 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.Enum.cs @@ -23,7 +23,7 @@ public virtual bool IsEnumDefined(object value) 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 @@ public virtual bool IsEnumDefined(object value) 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(); diff --git a/src/libraries/System.Private.CoreLib/src/System/Type.cs b/src/libraries/System.Private.CoreLib/src/System/Type.cs index aeb60457d9741f..df0e828e750993 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.cs @@ -267,7 +267,9 @@ public static Type[] GetTypeArray(object[] args) for (int i = 0; i < cls.Length; i++) { if (args[i] == null) +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable throw new ArgumentNullException(); +#pragma warning restore CA2208 cls[i] = args[i].GetType(); } return cls; diff --git a/src/libraries/System.Private.Uri/src/System/Uri.cs b/src/libraries/System.Private.Uri/src/System/Uri.cs index 79240050d95921..b12ed024051821 100644 --- a/src/libraries/System.Private.Uri/src/System/Uri.cs +++ b/src/libraries/System.Private.Uri/src/System/Uri.cs @@ -386,7 +386,9 @@ protected Uri(SerializationInfo serializationInfo, StreamingContext streamingCon uriString = serializationInfo.GetString("RelativeUri"); // Do not rename (binary serialization) if ((object?)uriString == null) +#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentNullException(nameof(uriString)); +#pragma warning restore CA2208 CreateThis(uriString, false, UriKind.Relative); } @@ -1503,7 +1505,7 @@ public static int FromHex(char digit) => (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)); // // GetHashCode diff --git a/src/libraries/System.Private.Uri/tests/ExtendedFunctionalTests/UriTests.cs b/src/libraries/System.Private.Uri/tests/ExtendedFunctionalTests/UriTests.cs index 6f558948ea4e3f..a2e1b0cec049dd 100644 --- a/src/libraries/System.Private.Uri/tests/ExtendedFunctionalTests/UriTests.cs +++ b/src/libraries/System.Private.Uri/tests/ExtendedFunctionalTests/UriTests.cs @@ -237,7 +237,7 @@ public static void TestHexMethods() [Fact] public static void TestHexMethods_Invalid() { - AssertExtensions.Throws(null, () => Uri.FromHex('?')); + AssertExtensions.Throws("digit", () => Uri.FromHex('?')); Assert.Throws(() => Uri.HexEscape('\x100')); int index = -1; Assert.Throws(() => Uri.HexUnescape("%75", ref index)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs index 5bb3c734340a71..0ee36591cc7d79 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs @@ -103,7 +103,7 @@ public override string Add(char[] key, int start, int len) // 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); diff --git a/src/libraries/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs b/src/libraries/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs index f3ca59bbca6871..e5d7fedd7b5355 100644 --- a/src/libraries/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs +++ b/src/libraries/System.Reflection.Extensions/tests/RuntimeReflectionExtensionTests.cs @@ -165,7 +165,7 @@ public void GetRuntimeEvent() }); - Assert.Throws(null, () => + Assert.Throws("name", () => { typeof(RuntimeReflectionExtensionsTests).GetRuntimeEvent(null); }); @@ -250,7 +250,7 @@ public void GetRuntimeField() }); - Assert.Throws(null, () => + Assert.Throws("name", () => { typeof(RuntimeReflectionExtensionsTests).GetRuntimeField(null); }); diff --git a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/ComAwareEventInfoTests.cs b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/ComAwareEventInfoTests.cs index f3513d414c075f..243133c3b3cb08 100644 --- a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/ComAwareEventInfoTests.cs +++ b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/ComAwareEventInfoTests.cs @@ -39,7 +39,7 @@ public void Ctor_NullType_ThrowsNullReferenceException() [Fact] public void Ctor_NullEventName_ThrowsArgumentNullException() { - AssertExtensions.Throws(null, () => new ComAwareEventInfo(typeof(NonComObject), null)); + AssertExtensions.Throws("name", () => new ComAwareEventInfo(typeof(NonComObject), null)); } [Fact] diff --git a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/OffsetOfTests.cs b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/OffsetOfTests.cs index fff08985672610..950f55ad0e1406 100644 --- a/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/OffsetOfTests.cs +++ b/src/libraries/System.Runtime.InteropServices/tests/System/Runtime/InteropServices/Marshal/OffsetOfTests.cs @@ -186,8 +186,8 @@ public void OffsetOf_NullType_ThrowsArgumentNullException() [Fact] public void OffsetOf_NullFieldName_ThrowsArgumentNullException() { - AssertExtensions.Throws(null, () => Marshal.OffsetOf(new object().GetType(), null)); - AssertExtensions.Throws(null, () => Marshal.OffsetOf(null)); + AssertExtensions.Throws("name", () => Marshal.OffsetOf(new object().GetType(), null)); + AssertExtensions.Throws("name", () => Marshal.OffsetOf(null)); } [Fact] diff --git a/src/libraries/System.Runtime/tests/System/Type/TypeTests.Get.cs b/src/libraries/System.Runtime/tests/System/Type/TypeTests.Get.cs index 124687962d0f0f..6e7bfc156eb85d 100644 --- a/src/libraries/System.Runtime/tests/System/Type/TypeTests.Get.cs +++ b/src/libraries/System.Runtime/tests/System/Type/TypeTests.Get.cs @@ -71,7 +71,7 @@ public void GetInterface_Invoke_ReturnsExpected(Type type, string name, bool ign [Fact] public void GetInterface_NullName_ThrowsArgumentNullException() { - AssertExtensions.Throws(null, () => typeof(int).GetInterface(null)); + AssertExtensions.Throws("fullname", () => typeof(int).GetInterface(null)); } [Fact] diff --git a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs index 1ff7c7c416486d..a1665aa92070c7 100644 --- a/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs +++ b/src/libraries/System.Security.AccessControl/src/System/Security/AccessControl/CommonObjectSecurity.cs @@ -336,7 +336,7 @@ protected override bool ModifyAccess(AccessControlModification modification, Acc 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; diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.Xml.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.Xml.cs index cfa242d50fb96c..32227e28f4f873 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.Xml.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.Xml.cs @@ -130,7 +130,9 @@ public override string ToXmlString(bool includePrivateParameters) // .NET Framework compat when a 3rd party type lets X be null when // includePrivateParameters is true // (the exception would have been from Convert.ToBase64String) +#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentNullException("inArray"); +#pragma warning restore CA2208 } XmlKeyHelper.WriteCryptoBinary(nameof(DSAParameters.X), keyParameters.X, builder); diff --git a/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/PemEncoding.cs b/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/PemEncoding.cs index 7232a72205c9c2..0315d5ba4b3e00 100644 --- a/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/PemEncoding.cs +++ b/src/libraries/System.Security.Cryptography.Encoding/src/System/Security/Cryptography/PemEncoding.cs @@ -438,7 +438,7 @@ static int WriteBase64(ReadOnlySpan bytes, Span dest, int offset) 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 @@ public static char[] Write(ReadOnlySpan label, ReadOnlySpan data) 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); diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/Resources/Strings.resx b/src/libraries/System.Security.Cryptography.Pkcs/src/Resources/Strings.resx index 117980b01ba6e5..890c9ed054805d 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/Resources/Strings.resx +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/Resources/Strings.resx @@ -1,4 +1,5 @@ - + + @@ -58,7 +59,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - String cannot be empty or null. + String cannot be empty or null {0}. Only single dimensional arrays are supported for the requested action. @@ -214,10 +215,10 @@ New Pkcs12SafeBag values cannot be added to a Pkcs12SafeContents that was read from existing data. - This decryption operation applies to 'Pkcs12ConfidentialityMode.{0}', but the target object is in 'Pkcs12ConfidentialityMode.{1}'. + This decryption operation applies to 'Pkcs12ConfidentialityMode.{0}', but the target object is in 'Pkcs12ConfidentialityMode.{1}'. - This verification operation applies to 'Pkcs12IntegrityMode.{0}', but the target object is in 'Pkcs12IntegrityMode.{1}'. + This verification operation applies to 'Pkcs12IntegrityMode.{0}', but the target object is in 'Pkcs12IntegrityMode.{1}'. Invalid signature paramters. @@ -294,4 +295,4 @@ Certificate already present in the collection. - + \ No newline at end of file diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs index 4290deb59336b6..be3874b32d4bb1 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs12Builder.cs @@ -41,7 +41,7 @@ public void AddSafeContentsEncrypted( 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 @@ public void AddSafeContentsEncrypted( 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) diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs index 11bb644cafa871..727aa275d54a9e 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Pkcs9AttributeObject.cs @@ -32,12 +32,14 @@ public Pkcs9AttributeObject(AsnEncodedData asnEncodedData) : base(asnEncodedData) { if (asnEncodedData.Oid == null) +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable throw new ArgumentNullException(nameof(asnEncodedData.Oid)); string? szOid = base.Oid!.Value; if (szOid == null) throw new ArgumentNullException("oid.Value"); +#pragma warning restore CA2208 if (szOid.Length == 0) - throw new ArgumentException(SR.Arg_EmptyOrNullString, "oid.Value"); + throw new ArgumentException(SR.Format(SR.Arg_EmptyOrNullString, "oid.Value"), nameof(asnEncodedData)); } internal Pkcs9AttributeObject(Oid oid) diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs index d45d274e7639bd..5bf544f6f4d415 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignedCms.cs @@ -45,7 +45,9 @@ public SignedCms(SubjectIdentifierType signerIdentifierType, ContentInfo content if (contentInfo == null) throw new ArgumentNullException(nameof(contentInfo)); if (contentInfo.Content == null) +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable throw new ArgumentNullException("contentInfo.Content"); +#pragma warning restore CA2208 // Normalize the subject identifier type the same way as .NET Framework. // This value is only used in the zero-argument ComputeSignature overload, diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs index 9247ae50b14bf8..b68f85f2e6ea32 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs @@ -360,7 +360,9 @@ public void RemoveCounterSignature(int index) { // In .NET Framework RemoveCounterSignature doesn't bounds check, but the helper it calls does. // In the helper the argument is called "childIndex". +#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentOutOfRangeException("childIndex"); +#pragma warning restore CA2208 } // The SignerInfo class is a projection of data contained within the SignedCms. diff --git a/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs9AttributeTests.cs b/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs9AttributeTests.cs index 9591a1bce1a5b3..432fedcd7a5032 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs9AttributeTests.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs9AttributeTests.cs @@ -123,7 +123,7 @@ public static void Pkcs9AttributeAsnEncodedDataCtorEmptyOidValue() AsnEncodedData a = new AsnEncodedData(oid, new byte[3]); object ign; - AssertExtensions.Throws("oid.Value", () => ign = new Pkcs9AttributeObject(a)); + AssertExtensions.Throws("asnEncodedData", () => ign = new Pkcs9AttributeObject(a)); } [Fact] diff --git a/src/libraries/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Extension.cs b/src/libraries/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Extension.cs index af338130269227..53e91b776245ad 100644 --- a/src/libraries/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Extension.cs +++ b/src/libraries/System.Security.Cryptography.X509Certificates/src/System/Security/Cryptography/X509Certificates/X509Extension.cs @@ -31,7 +31,7 @@ public X509Extension(Oid oid, byte[] rawData, bool critical) 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.Arg_EmptyOrNullString, nameof(oid)); Critical = critical; } diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs index 81da0b439bb038..19782152c0169d 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/SID.cs @@ -640,7 +640,9 @@ public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier? domainSi 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) { diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs index be5c623b29967e..66f492bf4a517d 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs @@ -138,7 +138,9 @@ public WindowsIdentity(string sUserPrincipalName) // 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) +#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentNullException("s"); +#pragma warning restore C2208 byte[] upnBytes = Encoding.Unicode.GetBytes(sUserPrincipalName); if (upnBytes.Length > ushort.MaxValue) diff --git a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs index 71e2285e792a5f..acd51f7c186fc6 100644 --- a/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs +++ b/src/libraries/System.Transactions.Local/src/System/Transactions/TransactionScope.cs @@ -211,7 +211,7 @@ TransactionScopeAsyncFlowOption asyncFlowOption // 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 @@ public TransactionScope( // 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)); } } } diff --git a/src/libraries/System.Windows.Extensions/src/System/Drawing/FontConverter.cs b/src/libraries/System.Windows.Extensions/src/System/Drawing/FontConverter.cs index aaea6553cf5983..af1308e860eacd 100644 --- a/src/libraries/System.Windows.Extensions/src/System/Drawing/FontConverter.cs +++ b/src/libraries/System.Windows.Extensions/src/System/Drawing/FontConverter.cs @@ -173,7 +173,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c 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)); } } diff --git a/src/libraries/System.Windows.Extensions/tests/System/Drawing/FontConverterTests.cs b/src/libraries/System.Windows.Extensions/tests/System/Drawing/FontConverterTests.cs index 02a01346d208ff..951ccfaeb9193e 100644 --- a/src/libraries/System.Windows.Extensions/tests/System/Drawing/FontConverterTests.cs +++ b/src/libraries/System.Windows.Extensions/tests/System/Drawing/FontConverterTests.cs @@ -131,7 +131,7 @@ private static bool EmptyFontPresent public static TheoryData ArgumentExceptionFontConverterData() => new TheoryData() { { $"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 }, diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/GC.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/GC.Mono.cs index 945356c17dec59..b7ac9cfaf4cdfb 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/GC.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/GC.Mono.cs @@ -113,7 +113,7 @@ public static int GetGeneration(WeakReference wo) { object? obj = wo.Target; if (obj == null) - throw new ArgumentException(); + throw new ArgumentException(null, nameof(wo)); return GetGeneration(obj); } diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs index 00bcc90d59bf8c..ff2505fe4cab7a 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Reflection/Emit/TypeBuilder.Mono.cs @@ -261,7 +261,7 @@ public void AddInterfaceImplementation(Type interfaceType) if (interfaceType == null) throw new ArgumentNullException(nameof(interfaceType)); if (interfaceType.IsByRef) - throw new ArgumentException(nameof(interfaceType)); + throw new ArgumentException(null, nameof(interfaceType)); check_not_created(); if (interfaces != null) @@ -479,7 +479,7 @@ public ConstructorBuilder DefineDefaultConstructor(MethodAttributes attributes) if (IsInterface) throw new InvalidOperationException(); if ((attributes & (MethodAttributes.Static | MethodAttributes.Virtual)) > 0) - throw new ArgumentException(nameof(attributes)); + throw new ArgumentException(null, nameof(attributes)); if (parent != null) parent_type = parent; @@ -1515,7 +1515,7 @@ public EventBuilder DefineEvent(string name, EventAttributes attributes, Type ev { 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 @@ public void SetParent(Type? parent) else { if (parent.IsInterface) - throw new ArgumentException(nameof(parent)); + throw new ArgumentException(null, nameof(parent)); this.parent = parent; } this.parent = ResolveUserType(this.parent); @@ -1878,7 +1878,7 @@ public static FieldInfo GetField(Type type, FieldInfo field) 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) diff --git a/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs b/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs index 5dcda6d90fed66..7c80ba8fb5c6b4 100644 --- a/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs +++ b/src/mono/netcore/System.Private.CoreLib/src/System/Runtime/CompilerServices/RuntimeHelpers.Mono.cs @@ -8,8 +8,10 @@ public partial class RuntimeHelpers { 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); } From b2710dc23b76e8ae28f360ffd08a7c080b4aabe2 Mon Sep 17 00:00:00 2001 From: Buyaa Namnan Date: Fri, 1 May 2020 12:36:29 -0700 Subject: [PATCH 2/7] Apply feedback --- .../src/ChainedConfigurationProvider.cs | 2 +- .../src/Resources/Strings.resx | 21 ++++++++++--------- .../Design/DesignerOptionService.cs | 2 +- .../MemberRelationshipService.cs | 4 ++-- .../Drawing/Drawing2D/LinearGradientBrush.cs | 2 +- .../Drawing/Drawing2D/PathGradientBrush.cs | 4 ++-- .../src/System/Drawing/Icon.Windows.cs | 2 +- .../Drawing/Text/PrivateFontCollection.cs | 2 +- .../src/System/Net/Sockets/Socket.cs | 4 ++-- .../ArgumentValidationTests.cs | 12 +++++------ .../src/System/DateTime.cs | 2 +- .../System.Private.Uri/src/System/Uri.cs | 2 +- .../System/Security/Cryptography/DSA.Xml.cs | 2 +- .../Security/Cryptography/Pkcs/SignerInfo.cs | 2 +- .../Security/Principal/WindowsIdentity.cs | 2 +- 15 files changed, 33 insertions(+), 32 deletions(-) diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs index 110c53fba0a8cf..8bdab0e1a1f23e 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs @@ -29,7 +29,7 @@ public ChainedConfigurationProvider(ChainedConfigurationSource source) } if (source.Configuration == null) { -#pragma warning disable CA2208 // Instantiate argument exceptions correctly +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable throw new ArgumentNullException(nameof(source.Configuration)); #pragma warning restore CA2208 } diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/Resources/Strings.resx b/src/libraries/System.ComponentModel.TypeConverter/src/Resources/Strings.resx index 84fd677ad67636..7de9810d591ed2 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/Resources/Strings.resx +++ b/src/libraries/System.ComponentModel.TypeConverter/src/Resources/Strings.resx @@ -1,4 +1,5 @@ - + + @@ -76,16 +77,16 @@ The value '{0}' is not a valid value for the enum '{1}'. - Invalid event handler for the {0} event. + Invalid event handler for the {0} event. - Invalid type for the {0} event. + Invalid type for the {0} event. Invalid type for the {0} property - Accessor methods for the {0} event are missing. + Accessor methods for the {0} event are missing. Accessor methods for the {0} property are missing. @@ -170,7 +171,7 @@ The {0} culture cannot be converted to a CultureInfo object on this computer. - + The service instance must derive from or implement {0}. @@ -178,7 +179,7 @@ The service {0} already exists in the service container. - Value of '{1}' is not valid for '{0}'. + Value of '{0}' cannot be empty. Null is not a valid value for {0}. @@ -242,11 +243,11 @@ The checkout was canceled by the user. - - + + (none) - + Relationships between {0}.{1} and {2}.{3} are not supported. - + \ No newline at end of file diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs index e43b6749b8950c..63a87afebe2015 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/DesignerOptionService.cs @@ -48,7 +48,7 @@ protected DesignerOptionCollection CreateOptionCollection(DesignerOptionCollecti if (name.Length == 0) { - throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, "name.Length", "0"), nameof(name)); + throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, "name.Length"), nameof(name)); } return new DesignerOptionCollection(this, parent, name, value); diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs index b2a9eccb54a876..45910aac9c6d4c 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs @@ -44,7 +44,7 @@ public MemberRelationship this[MemberRelationship source] // and not the other as the main constructor performs argument validation. if (source.Owner == null) { -#pragma warning disable CA2208 // Instantiate argument exceptions correctly +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable throw new ArgumentNullException(nameof(MemberRelationship.Owner)); #pragma warning restore CA2208 } @@ -59,7 +59,7 @@ public MemberRelationship this[MemberRelationship source] // and not the other as the main constructor performs argument validation. if (source.Owner == null) { -#pragma warning disable CA2208 // Instantiate argument exceptions correctly +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable throw new ArgumentNullException(nameof(MemberRelationship.Owner)); #pragma warning restore CA2208 } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs index 8cfd1bf2643d38..1ef018625021f4 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs @@ -232,7 +232,7 @@ public Blend? Blend throw new NullReferenceException(); if (value.Positions == null) -#pragma warning disable CA2208 // Instantiate argument exceptions correctly +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, Desktop compatability throw new ArgumentNullException("source"); #pragma warning restore CA2208 diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs index 2e7f47491045d3..10694bd49744ce 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs @@ -188,7 +188,7 @@ public Blend Blend // 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) -#pragma warning disable CA2208 // Instantiate argument exceptions correctly +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, Desktop compatability throw new ArgumentNullException("source"); #pragma warning restore CA2208 @@ -304,7 +304,7 @@ public ColorBlend InterpolationColors // depending on how sane the input is. These checks exist to replicate the exact Desktop behavior. int count = value.Colors.Length; -#pragma warning disable CA2208 // Instantiate argument exceptions correctly +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, Desktop compatability if (value.Positions == null) throw new ArgumentNullException("source"); if (value.Colors.Length > value.Positions.Length) diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs index ec2199805bd3f1..c80e12c0de6c99 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs @@ -641,7 +641,7 @@ public void Save(Stream outputStream) { // We threw this way on NetFX if (outputStream == null) -#pragma warning disable CA2208 // Instantiate argument exceptions correctly +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, NetFX compatability throw new ArgumentNullException("dataStream"); #pragma warning restore CA2208 diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs index 73333c46f949fe..a19827178926c4 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs @@ -60,7 +60,7 @@ public void AddFontFile(string filename) { if (_nativeFontCollection == IntPtr.Zero) { -#pragma warning disable CA2208 // Instantiate argument exceptions correctly +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, Desktop compatability // This is the default behavior on Desktop. The ArgumentException originates from GdipPrivateAddFontFile which would // refuse the null pointer. throw new ArgumentException(); diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs index 6e23df42f3cbbe..d3708ea33f6e74 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs @@ -3983,7 +3983,7 @@ public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType } if (e.RemoteEndPoint == null) { -#pragma warning disable CA2208 // Instantiate argument exceptions correctly, the argument not applicable +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable throw new ArgumentNullException("remoteEP"); #pragma warning restore CA2208 } @@ -4170,7 +4170,7 @@ public bool ReceiveMessageFromAsync(SocketAsyncEventArgs e) } if (e.RemoteEndPoint == null) { -#pragma warning disable CA2208 // Instantiate argument exceptions correctly +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable throw new ArgumentNullException(nameof(e.RemoteEndPoint)); #pragma warning restore CA2208 } diff --git a/src/libraries/System.Net.Sockets/tests/FunctionalTests/ArgumentValidationTests.cs b/src/libraries/System.Net.Sockets/tests/FunctionalTests/ArgumentValidationTests.cs index 655534f857ca09..fab0bec7c2857f 100644 --- a/src/libraries/System.Net.Sockets/tests/FunctionalTests/ArgumentValidationTests.cs +++ b/src/libraries/System.Net.Sockets/tests/FunctionalTests/ArgumentValidationTests.cs @@ -454,8 +454,8 @@ public void SetSocketOption_Linger_NotLingerOption_Throws_Argument() [Fact] public void SetSocketOption_Linger_InvalidLingerTime_Throws_Argument() { - AssertExtensions.Throws("optionValue.LingerTime", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1))); - AssertExtensions.Throws("optionValue.LingerTime", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1))); + AssertExtensions.Throws("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1))); + AssertExtensions.Throws("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1))); } [Fact] @@ -516,7 +516,7 @@ public void AcceptAsync_BufferList_Throws_Argument() BufferList = s_buffers }; - AssertExtensions.Throws("BufferList", () => GetSocket().AcceptAsync(eventArgs)); + AssertExtensions.Throws("e", () => GetSocket().AcceptAsync(eventArgs)); } [Fact] @@ -598,7 +598,7 @@ public void ConnectAsync_Static_BufferList_Throws_Argument() BufferList = s_buffers }; - AssertExtensions.Throws("BufferList", () => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs)); + AssertExtensions.Throws("e", () => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs)); } [Fact] @@ -632,7 +632,7 @@ public void ReceiveFromAsync_AddressFamily_Throws_Argument() RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1) }; - AssertExtensions.Throws("RemoteEndPoint", () => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs)); + AssertExtensions.Throws("e", () => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs)); } [Fact] @@ -654,7 +654,7 @@ public void ReceiveMessageFromAsync_AddressFamily_Throws_Argument() RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1) }; - AssertExtensions.Throws("RemoteEndPoint", () => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs)); + AssertExtensions.Throws("e", () => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs)); } [Fact] diff --git a/src/libraries/System.Private.CoreLib/src/System/DateTime.cs b/src/libraries/System.Private.CoreLib/src/System/DateTime.cs index ab903a6541a9c1..7343779600027d 100644 --- a/src/libraries/System.Private.CoreLib/src/System/DateTime.cs +++ b/src/libraries/System.Private.CoreLib/src/System/DateTime.cs @@ -581,9 +581,9 @@ public DateTime AddYears(int value) { if (value < -10000 || value > 10000) { +#pragma warning disable CA2208 // Instantiate argument exceptions correctly // 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. -#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentOutOfRangeException("years", SR.ArgumentOutOfRange_DateTimeBadYears); #pragma warning restore CA2208 } diff --git a/src/libraries/System.Private.Uri/src/System/Uri.cs b/src/libraries/System.Private.Uri/src/System/Uri.cs index b12ed024051821..cc95d97a156877 100644 --- a/src/libraries/System.Private.Uri/src/System/Uri.cs +++ b/src/libraries/System.Private.Uri/src/System/Uri.cs @@ -386,7 +386,7 @@ protected Uri(SerializationInfo serializationInfo, StreamingContext streamingCon uriString = serializationInfo.GetString("RelativeUri"); // Do not rename (binary serialization) if ((object?)uriString == null) -#pragma warning disable CA2208 // Instantiate argument exceptions correctly +#pragma warning disable CA2208 // Instantiate argument exceptions correctly, arguments not applicable throw new ArgumentNullException(nameof(uriString)); #pragma warning restore CA2208 diff --git a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.Xml.cs b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.Xml.cs index 32227e28f4f873..f32e384c70e94a 100644 --- a/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.Xml.cs +++ b/src/libraries/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/DSA.Xml.cs @@ -127,10 +127,10 @@ public override string ToXmlString(bool includePrivateParameters) { 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) -#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentNullException("inArray"); #pragma warning restore CA2208 } diff --git a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs index b68f85f2e6ea32..58fbe521bd358b 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/SignerInfo.cs @@ -358,9 +358,9 @@ public void RemoveCounterSignature(int index) { if (index < 0) { +#pragma warning disable CA2208 // Instantiate argument exceptions correctly // In .NET Framework RemoveCounterSignature doesn't bounds check, but the helper it calls does. // In the helper the argument is called "childIndex". -#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentOutOfRangeException("childIndex"); #pragma warning restore CA2208 } diff --git a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs index 66f492bf4a517d..b716ff38d1deaa 100644 --- a/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs +++ b/src/libraries/System.Security.Principal.Windows/src/System/Security/Principal/WindowsIdentity.cs @@ -134,11 +134,11 @@ public WindowsIdentity(string sUserPrincipalName) sourceContext.SourceName = new byte[TOKEN_SOURCE.TOKEN_SOURCE_LENGTH]; Buffer.BlockCopy(sourceName, 0, sourceContext.SourceName, 0, sourceName.Length); +#pragma warning disable CA2208 // Instantiate argument exceptions correctly // .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) -#pragma warning disable CA2208 // Instantiate argument exceptions correctly throw new ArgumentNullException("s"); #pragma warning restore C2208 From d76a41a6569c5f58ee6eda5aa349b69e5640e382 Mon Sep 17 00:00:00 2001 From: Buyaa Namnan Date: Thu, 7 May 2020 17:35:24 -0700 Subject: [PATCH 3/7] Addressing feedback and test fix --- .../src/ChainedConfigurationProvider.cs | 4 +-- .../src/Resources/Strings.resx | 3 ++ .../MemberRelationshipService.cs | 8 ++---- .../MemberRelationshipServiceTests.cs | 4 +-- .../Diagnostics/PerformanceData/CounterSet.cs | 4 +-- .../Drawing/Drawing2D/LinearGradientBrush.cs | 4 +-- .../Drawing/Drawing2D/PathGradientBrush.cs | 16 +++-------- .../src/System/Drawing/Icon.Windows.cs | 5 +--- .../Drawing/Text/PrivateFontCollection.cs | 8 ++---- .../Drawing2D/LinearGradientBrushTests.cs | 4 +-- .../tests/Drawing2D/PathGradientBrushTests.cs | 12 ++++---- .../System.Drawing.Common/tests/IconTests.cs | 2 +- .../tests/Text/PrivateFontCollectionTests.cs | 2 +- .../src/Resources/Strings.resx | 8 ++++-- .../src/System/Management/ManagementQuery.cs | 28 +++++++++---------- .../SystemIPGlobalProperties.cs | 2 +- .../src/Resources/Strings.resx | 5 +++- .../src/System/Net/Sockets/Socket.cs | 16 +++-------- .../ArgumentValidationTests.cs | 8 +++--- .../src/System/DateTime.cs | 6 +--- .../System.Private.CoreLib/src/System/Type.cs | 4 +-- .../src/Resources/Strings.resx | 6 +++- .../System.Private.Uri/src/System/Uri.cs | 4 +-- .../System.Runtime/tests/System/GCTests.cs | 2 +- .../src/Resources/Strings.resx | 2 +- .../Cryptography/Pkcs/Pkcs9AttributeObject.cs | 6 ++-- .../Security/Cryptography/Pkcs/SignedCms.cs | 4 +-- .../Security/Cryptography/Pkcs/SignerInfo.cs | 6 +--- .../tests/Pkcs9AttributeTests.cs | 4 +-- .../tests/SignedCms/SignerInfoTests.cs | 2 +- .../src/Resources/Strings.resx | 15 +++++----- .../X509Certificates/X509Extension.cs | 2 +- .../Security/Principal/WindowsIdentity.cs | 7 +---- .../Reflection/Emit/TypeBuilder.Mono.cs | 6 ++-- .../src/System/RuntimeType.Mono.cs | 12 ++++---- 35 files changed, 98 insertions(+), 133 deletions(-) diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs index 8bdab0e1a1f23e..56802e813c7955 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs +++ b/src/libraries/Microsoft.Extensions.Configuration/src/ChainedConfigurationProvider.cs @@ -29,9 +29,7 @@ public ChainedConfigurationProvider(ChainedConfigurationSource source) } if (source.Configuration == null) { -#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable - throw new ArgumentNullException(nameof(source.Configuration)); -#pragma warning restore CA2208 + throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "source.Configuration"), nameof(source)); } _config = source.Configuration; diff --git a/src/libraries/Microsoft.Extensions.Configuration/src/Resources/Strings.resx b/src/libraries/Microsoft.Extensions.Configuration/src/Resources/Strings.resx index 52fb2be3e50a17..1c4c38af9b51b8 100644 --- a/src/libraries/Microsoft.Extensions.Configuration/src/Resources/Strings.resx +++ b/src/libraries/Microsoft.Extensions.Configuration/src/Resources/Strings.resx @@ -120,4 +120,7 @@ A configuration source is not registered. Please register one before setting a value. + + Null is not a valid value for '{0}'. + \ No newline at end of file diff --git a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs index 45910aac9c6d4c..81889b0ca6327c 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/src/System/ComponentModel/Design/Serialization/MemberRelationshipService.cs @@ -44,9 +44,7 @@ public MemberRelationship this[MemberRelationship source] // and not the other as the main constructor performs argument validation. if (source.Owner == null) { -#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable - throw new ArgumentNullException(nameof(MemberRelationship.Owner)); -#pragma warning restore CA2208 + throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "source.Owner"), nameof(source)); } Debug.Assert(source.Member != null); @@ -59,9 +57,7 @@ public MemberRelationship this[MemberRelationship source] // and not the other as the main constructor performs argument validation. if (source.Owner == null) { -#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable - throw new ArgumentNullException(nameof(MemberRelationship.Owner)); -#pragma warning restore CA2208 + throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "source.Owner"), nameof(source)); } Debug.Assert(source.Member != null); diff --git a/src/libraries/System.ComponentModel.TypeConverter/tests/Design/Serialization/MemberRelationshipServiceTests.cs b/src/libraries/System.ComponentModel.TypeConverter/tests/Design/Serialization/MemberRelationshipServiceTests.cs index 9f85a1eeff671f..5bc0242ca9ed56 100644 --- a/src/libraries/System.ComponentModel.TypeConverter/tests/Design/Serialization/MemberRelationshipServiceTests.cs +++ b/src/libraries/System.ComponentModel.TypeConverter/tests/Design/Serialization/MemberRelationshipServiceTests.cs @@ -56,8 +56,8 @@ public void Indexer_NullSourceOwner_ThrowsArgumentNullException() Assert.Throws("sourceOwner", () => service[null, member]); Assert.Throws("sourceOwner", () => service[null, member] = new MemberRelationship()); - Assert.Throws("Owner", () => service[new MemberRelationship()]); - Assert.Throws("Owner", () => service[new MemberRelationship()] = new MemberRelationship()); + Assert.Throws("source", () => service[new MemberRelationship()]); + Assert.Throws("source", () => service[new MemberRelationship()] = new MemberRelationship()); } [Fact] diff --git a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.cs b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.cs index d1a12257a9926b..3a62324c074619 100644 --- a/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.cs +++ b/src/libraries/System.Diagnostics.PerformanceCounter/src/System/Diagnostics/PerformanceData/CounterSet.cs @@ -195,7 +195,7 @@ public CounterSetInstance CreateCounterSetInstance(string instanceName) { if (_provider == null) { - throw new ArgumentException(SR.Format(SR.Perflib_Argument_ProviderNotFound, _providerGuid), nameof(instanceName)); + throw new InvalidOperationException(SR.Format(SR.Perflib_InvalidOperation_NoActiveProvider, _providerGuid)); } if (_provider._hProvider.IsInvalid) { @@ -256,7 +256,7 @@ public CounterSetInstance CreateCounterSetInstance(string instanceName) { throw Status switch { - (uint)Interop.Errors.ERROR_ALREADY_EXISTS => new ArgumentException(SR.Format(SR.Perflib_Argument_CounterSetAlreadyRegister, _counterSet), nameof(instanceName)), + (uint)Interop.Errors.ERROR_ALREADY_EXISTS => new InvalidOperationException(SR.Format(SR.Perflib_Argument_CounterSetAlreadyRegister, _counterSet)), _ => new Win32Exception((int)Status), }; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs index 1ef018625021f4..666eb631d7b37e 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/LinearGradientBrush.cs @@ -232,9 +232,7 @@ public Blend? Blend throw new NullReferenceException(); if (value.Positions == null) -#pragma warning disable CA2208 // Instantiate argument exceptions correctly, Desktop compatability - throw new ArgumentNullException("source"); -#pragma warning restore CA2208 + throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, "value.Positions", value.Positions), nameof(value)); int count = value.Factors.Length; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs index 10694bd49744ce..4c2ba1d97c5059 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Drawing2D/PathGradientBrush.cs @@ -185,12 +185,8 @@ public Blend Blend 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) -#pragma warning disable CA2208 // Instantiate argument exceptions correctly, Desktop compatability - throw new ArgumentNullException("source"); -#pragma warning restore CA2208 + throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, "value.Positions", value.Positions), nameof(value)); int count = value.Factors.Length; @@ -300,18 +296,14 @@ public ColorBlend InterpolationColors } 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; -#pragma warning disable CA2208 // Instantiate argument exceptions correctly, Desktop compatability if (value.Positions == null) - throw new ArgumentNullException("source"); + throw new ArgumentException(SR.Format(SR.InvalidArgumentValue, "value.Positions", value.Positions), nameof(value)); if (value.Colors.Length > value.Positions.Length) - throw new ArgumentOutOfRangeException(); + throw new ArgumentOutOfRangeException(nameof(value)); if (value.Colors.Length < value.Positions.Length) - throw new ArgumentException(); -#pragma warning restore CS2208 + throw new ArgumentOutOfRangeException(nameof(value)); float[] positions = value.Positions; int[] argbs = new int[count]; diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs index c80e12c0de6c99..a71a09d6e793e4 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Icon.Windows.cs @@ -639,11 +639,8 @@ public void Save(Stream outputStream) { try { - // We threw this way on NetFX if (outputStream == null) -#pragma warning disable CA2208 // Instantiate argument exceptions correctly, NetFX compatability - throw new ArgumentNullException("dataStream"); -#pragma warning restore CA2208 + throw new ArgumentNullException(nameof(outputStream)); picture.SaveAsFile(new GPStream(outputStream, makeSeekable: false), -1, out int temp); } diff --git a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs index a19827178926c4..60c016124d99e0 100644 --- a/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs +++ b/src/libraries/System.Drawing.Common/src/System/Drawing/Text/PrivateFontCollection.cs @@ -60,18 +60,16 @@ public void AddFontFile(string filename) { if (_nativeFontCollection == IntPtr.Zero) { -#pragma warning disable CA2208 // Instantiate argument exceptions correctly, Desktop compatability +#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"); -#pragma warning restore CA2208 + throw new ArgumentNullException(nameof(filename)); } // this ensure the filename is valid (or throw the correct exception) diff --git a/src/libraries/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs b/src/libraries/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs index 5464ba0c16e951..91b6508665323e 100644 --- a/src/libraries/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs +++ b/src/libraries/System.Drawing.Common/tests/Drawing2D/LinearGradientBrushTests.cs @@ -358,11 +358,11 @@ public void Blend_SetNullBlendFactors_ThrowsNullReferenceException() } [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("source", () => brush.Blend = new Blend { Factors = new float[2], Positions = null }); + AssertExtensions.Throws("value", () => brush.Blend = new Blend { Factors = new float[2], Positions = null }); } } diff --git a/src/libraries/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs b/src/libraries/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs index 7cc603bb798898..1c850c1525c4e3 100644 --- a/src/libraries/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs +++ b/src/libraries/System.Drawing.Common/tests/Drawing2D/PathGradientBrushTests.cs @@ -366,11 +366,11 @@ public void Blend_Null_ThrowsNullReferenceException() } [ConditionalFact(Helpers.IsDrawingSupported)] - public void Blend_NullBlendProperites_ThrowsArgumentNullException() + public void Blend_NullBlendProperites_ThrowsArgumentException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { - AssertExtensions.Throws("source", () => + AssertExtensions.Throws("value", () => brush.Blend = new Blend() { Factors = new float[0], Positions = null }); } } @@ -651,11 +651,11 @@ public void InterpolationColors_NullColors_ThrowsNullReferenceException() } [ConditionalFact(Helpers.IsDrawingSupported)] - public void InterpolationColors_NullPoints_ArgumentNullException() + public void InterpolationColors_NullPoints_ArgumentException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { - AssertExtensions.Throws("source", () => + AssertExtensions.Throws("value", () => brush.InterpolationColors = new ColorBlend() { Colors = new Color[1], Positions = null }); } } @@ -680,11 +680,11 @@ public void InterpolationColors_EmptyColors_ArgumentException() } [ConditionalFact(Helpers.IsDrawingSupported)] - public void InterpolationColors_PointsLengthGreaterThenColorsLength_ArgumentException() + public void InterpolationColors_PointsLengthGreaterThenColorsLength_ArgumentOutOfRangeException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { - AssertExtensions.Throws(null, () => + AssertExtensions.Throws("value", () => brush.InterpolationColors = new ColorBlend() { Colors = new Color[1], Positions = new float[2] }); } } diff --git a/src/libraries/System.Drawing.Common/tests/IconTests.cs b/src/libraries/System.Drawing.Common/tests/IconTests.cs index a201c9bce16e36..390d20712de734 100644 --- a/src/libraries/System.Drawing.Common/tests/IconTests.cs +++ b/src/libraries/System.Drawing.Common/tests/IconTests.cs @@ -525,7 +525,7 @@ public void Save_NullOutputStreamNoIconData_ThrowsArgumentNullException() var icon = Icon.FromHandle(source.Handle); icon.Dispose(); - AssertExtensions.Throws("dataStream", () => icon.Save(null)); + AssertExtensions.Throws("outputStream", () => icon.Save(null)); } } diff --git a/src/libraries/System.Drawing.Common/tests/Text/PrivateFontCollectionTests.cs b/src/libraries/System.Drawing.Common/tests/Text/PrivateFontCollectionTests.cs index af934a15f458a6..de1a7faa5af3c0 100644 --- a/src/libraries/System.Drawing.Common/tests/Text/PrivateFontCollectionTests.cs +++ b/src/libraries/System.Drawing.Common/tests/Text/PrivateFontCollectionTests.cs @@ -107,7 +107,7 @@ public void AddFontFile_NullFileName_ThrowsArgumentNullException() { using (var fontCollection = new PrivateFontCollection()) { - AssertExtensions.Throws("path", () => fontCollection.AddFontFile(null)); + AssertExtensions.Throws("filename", () => fontCollection.AddFontFile(null)); } } diff --git a/src/libraries/System.Management/src/Resources/Strings.resx b/src/libraries/System.Management/src/Resources/Strings.resx index f740f60b40f998..40f915ba6f640e 100644 --- a/src/libraries/System.Management/src/Resources/Strings.resx +++ b/src/libraries/System.Management/src/Resources/Strings.resx @@ -1,4 +1,5 @@ - + + @@ -292,4 +293,7 @@ The native library '{0}' does not have all required functions. Please, update the .NET Framework. - + + The Query string supplied was invalid or improperly formed. Token `{0}` is expected + + \ No newline at end of file diff --git a/src/libraries/System.Management/src/System/Management/ManagementQuery.cs b/src/libraries/System.Management/src/System/Management/ManagementQuery.cs index e9c380f2256bb8..1c49c3019e4de6 100644 --- a/src/libraries/System.Management/src/System/Management/ManagementQuery.cs +++ b/src/libraries/System.Management/src/System/Management/ManagementQuery.cs @@ -1040,13 +1040,13 @@ protected internal override void ParseQuery(string query) // 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, nameof(query)); + 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, nameof(query)); + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, "*"), nameof(query)); q = q.Remove(0, 1).TrimStart(null); @@ -1055,7 +1055,7 @@ protected internal override void ParseQuery(string query) if ((q.Length < keyword.Length) || (0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase))) - throw new ArgumentException(SR.InvalidQuery, nameof(query)); + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, keyword), nameof(query)); q = q.Remove(0, keyword.Length).TrimStart(null); @@ -1064,7 +1064,7 @@ protected internal override void ParseQuery(string query) if ((q.Length < keyword.Length) || (0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase))) - throw new ArgumentException(SR.InvalidQuery, nameof(query)); + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, keyword), nameof(query)); q = q.Remove(0, keyword.Length).TrimStart(null); @@ -1076,7 +1076,7 @@ protected internal override void ParseQuery(string query) if ((q.Length < keyword.Length) || (0 != string.Compare(q, 0, keyword, 0, keyword.Length, StringComparison.OrdinalIgnoreCase))) - throw new ArgumentException(SR.InvalidQuery, nameof(query)); + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, keyword), nameof(query)); q = q.Remove(0, keyword.Length); @@ -1650,7 +1650,7 @@ protected internal override void ParseQuery(string query) //Find "associators" clause if (0 != string.Compare(q, 0, TokenAssociators, 0, TokenAssociators.Length, StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException(SR.InvalidQuery, nameof(query)); // 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 @@ protected internal override void ParseQuery(string query) // Next token should be "of" if (0 != string.Compare(q, 0, TokenOf, 0, TokenOf.Length, StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException(SR.InvalidQuery, nameof(query)); // 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 @@ protected internal override void ParseQuery(string query) { // Next should be the "where" clause if (0 != string.Compare(q, 0, TokenWhere, 0, TokenWhere.Length, StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException(SR.InvalidQuery, nameof(query)); // Invalid query + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, TokenWhere), nameof(query)); // Invalid query q = q.Remove(0, TokenWhere.Length); @@ -2167,7 +2167,7 @@ protected internal override void ParseQuery(string query) //Find "references" clause if (0 != string.Compare(q, 0, TokenReferences, 0, TokenReferences.Length, StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException(SR.InvalidQuery, nameof(query)); // 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 @@ protected internal override void ParseQuery(string query) // Next token should be "of" if (0 != string.Compare(q, 0, TokenOf, 0, TokenOf.Length, StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException(SR.InvalidQuery, nameof(query)); // 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 @@ protected internal override void ParseQuery(string query) { // Next should be the "where" clause if (0 != string.Compare(q, 0, TokenWhere, 0, TokenWhere.Length, StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException(SR.InvalidQuery, nameof(query)); // Invalid query + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, TokenWhere), nameof(query)); // Invalid query q = q.Remove(0, TokenWhere.Length); @@ -3043,13 +3043,13 @@ protected internal override void ParseQuery(string query) q = q.Remove(0, keyword.Length).TrimStart(null); if (!q.StartsWith("*", StringComparison.Ordinal)) - throw new ArgumentException(SR.InvalidQuery, nameof(query)); + 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, nameof(query)); + 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 @@ protected internal override void ParseQuery(string query) q = q.Remove(0, keyword.Length); if (q.Length == 0) //bad query - throw new ArgumentException(SR.InvalidQuery, nameof(query)); + throw new ArgumentException(SR.Format(SR.InvalidQueryTokenExpected, keyword), nameof(query)); havingCondition = q; } diff --git a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemIPGlobalProperties.cs b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemIPGlobalProperties.cs index 315915b5ed0c3b..39220cab5c2042 100644 --- a/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemIPGlobalProperties.cs +++ b/src/libraries/System.Net.NetworkInformation/src/System/Net/NetworkInformation/SystemIPGlobalProperties.cs @@ -380,7 +380,7 @@ public override UnicastIPAddressInformationCollection GetUnicastAddresses() => public override async Task GetUnicastAddressesAsync() { // Wait for the address table to stabilize. - var tcs = new TaskCompletionSource(TaskContinuationOptions.RunContinuationsAsynchronously); + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); if (!TeredoHelper.UnsafeNotifyStableUnicastIpAddressTable(s => ((TaskCompletionSource)s).TrySetResult(true), tcs)) { await tcs.Task.ConfigureAwait(false); diff --git a/src/libraries/System.Net.Sockets/src/Resources/Strings.resx b/src/libraries/System.Net.Sockets/src/Resources/Strings.resx index 7c348e17785a68..75014c7b88c970 100644 --- a/src/libraries/System.Net.Sockets/src/Resources/Strings.resx +++ b/src/libraries/System.Net.Sockets/src/Resources/Strings.resx @@ -194,7 +194,7 @@ The specified value cannot be negative. - Argument {2} must be between {0} and {1}. + Argument '{2}' must be between {0} and {1}. Sockets on this platform are invalid for use after a failed connection attempt. @@ -259,4 +259,7 @@ Asynchronous operations are not allowed on this socket. The underlying OS handle might have been already bound to an IO completion port. + + Null is not a valid value for {0}. + \ No newline at end of file diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs index d3708ea33f6e74..b7f115c5a25455 100644 --- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs +++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/Socket.cs @@ -3983,9 +3983,7 @@ public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType } if (e.RemoteEndPoint == null) { -#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable - throw new ArgumentNullException("remoteEP"); -#pragma warning restore CA2208 + throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e)); } EndPoint endPointSnapshot = e.RemoteEndPoint; @@ -4118,9 +4116,7 @@ public bool ReceiveFromAsync(SocketAsyncEventArgs e) } if (e.RemoteEndPoint == null) { -#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applcable - throw new ArgumentNullException(nameof(e.RemoteEndPoint)); -#pragma warning restore CA2208 + throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e)); } if (!CanTryAddressFamily(e.RemoteEndPoint.AddressFamily)) { @@ -4170,9 +4166,7 @@ public bool ReceiveMessageFromAsync(SocketAsyncEventArgs e) } if (e.RemoteEndPoint == null) { -#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable - throw new ArgumentNullException(nameof(e.RemoteEndPoint)); -#pragma warning restore CA2208 + throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.RemoteEndPoint"), nameof(e)); } if (!CanTryAddressFamily(e.RemoteEndPoint.AddressFamily)) { @@ -4256,9 +4250,7 @@ public bool SendPacketsAsync(SocketAsyncEventArgs e) } if (e.SendPacketsElements == null) { -#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable - throw new ArgumentNullException("e.SendPacketsElements"); -#pragma warning restore CA2208 + throw new ArgumentException(SR.Format(SR.InvalidNullArgument, "e.SendPacketsElements"), nameof(e)); } if (!Connected) { diff --git a/src/libraries/System.Net.Sockets/tests/FunctionalTests/ArgumentValidationTests.cs b/src/libraries/System.Net.Sockets/tests/FunctionalTests/ArgumentValidationTests.cs index fab0bec7c2857f..e830eec7ee6005 100644 --- a/src/libraries/System.Net.Sockets/tests/FunctionalTests/ArgumentValidationTests.cs +++ b/src/libraries/System.Net.Sockets/tests/FunctionalTests/ArgumentValidationTests.cs @@ -604,7 +604,7 @@ public void ConnectAsync_Static_BufferList_Throws_Argument() [Fact] public void ConnectAsync_Static_NullRemoteEndPoint_Throws_ArgumentNull() { - Assert.Throws(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, s_eventArgs)); + Assert.Throws("e", () => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, s_eventArgs)); } [Fact] @@ -622,7 +622,7 @@ public void ReceiveFromAsync_NullAsyncEventArgs_Throws_ArgumentNull() [Fact] public void ReceiveFromAsync_NullRemoteEndPoint_Throws_ArgumentNull() { - Assert.Throws(() => GetSocket().ReceiveFromAsync(s_eventArgs)); + Assert.Throws("e", () => GetSocket().ReceiveFromAsync(s_eventArgs)); } [Fact] @@ -644,7 +644,7 @@ public void ReceiveMessageFromAsync_NullAsyncEventArgs_Throws_ArgumentNull() [Fact] public void ReceiveMessageFromAsync_NullRemoteEndPoint_Throws_ArgumentNull() { - Assert.Throws(() => GetSocket().ReceiveMessageFromAsync(s_eventArgs)); + Assert.Throws("e", () => GetSocket().ReceiveMessageFromAsync(s_eventArgs)); } [Fact] @@ -672,7 +672,7 @@ public void SendPacketsAsync_NullAsyncEventArgs_Throws_ArgumentNull() [Fact] public void SendPacketsAsync_NullSendPacketsElements_Throws_ArgumentNull() { - Assert.Throws(() => GetSocket().SendPacketsAsync(s_eventArgs)); + Assert.Throws("e", () => GetSocket().SendPacketsAsync(s_eventArgs)); } [Fact] diff --git a/src/libraries/System.Private.CoreLib/src/System/DateTime.cs b/src/libraries/System.Private.CoreLib/src/System/DateTime.cs index 7343779600027d..1561e99a724349 100644 --- a/src/libraries/System.Private.CoreLib/src/System/DateTime.cs +++ b/src/libraries/System.Private.CoreLib/src/System/DateTime.cs @@ -581,11 +581,7 @@ public DateTime AddYears(int value) { if (value < -10000 || value > 10000) { -#pragma warning disable CA2208 // Instantiate argument exceptions correctly - // 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); -#pragma warning restore CA2208 + throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_DateTimeBadYears); } return AddMonths(value * 12); } diff --git a/src/libraries/System.Private.CoreLib/src/System/Type.cs b/src/libraries/System.Private.CoreLib/src/System/Type.cs index df0e828e750993..9c7a22813f0477 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Type.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Type.cs @@ -267,9 +267,7 @@ public static Type[] GetTypeArray(object[] args) for (int i = 0; i < cls.Length; i++) { if (args[i] == null) -#pragma warning disable CA2208 // Instantiate argument exceptions correctly, argument not applicable - throw new ArgumentNullException(); -#pragma warning restore CA2208 + throw new ArgumentException(SR.ArgumentNull_ArrayValue); cls[i] = args[i].GetType(); } return cls; diff --git a/src/libraries/System.Private.Uri/src/Resources/Strings.resx b/src/libraries/System.Private.Uri/src/Resources/Strings.resx index 655f2820692e2c..2df1569e6d5b41 100644 --- a/src/libraries/System.Private.Uri/src/Resources/Strings.resx +++ b/src/libraries/System.Private.Uri/src/Resources/Strings.resx @@ -1,4 +1,5 @@ - + +