Skip to content

Commit 887c7b3

Browse files
captainsafiamla-alm
andauthored
Change incorrect usage of ArgumentNullException (#48243)
* Change incorrect usage of ArgumentNullException * Fix tests * Split exception * Try using shared source * Fix argument helpers for netstandard and netfx * Address feedback from review * Fix nullability attributes in shared helpers * Fix null or empty check for netfx and netstandard * Use EmptyString again for checks * Update check again --------- Co-authored-by: mla-alm <[email protected]>
1 parent ba58563 commit 887c7b3

File tree

41 files changed

+123
-148
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+123
-148
lines changed

src/DataProtection/Extensions/src/DataProtectionProvider.cs

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,7 @@ public static class DataProtectionProvider
2424
/// applications on the machine.</param>
2525
public static IDataProtectionProvider Create(string applicationName)
2626
{
27-
if (string.IsNullOrEmpty(applicationName))
28-
{
29-
throw new ArgumentNullException(nameof(applicationName));
30-
}
27+
ArgumentThrowHelper.ThrowIfNullOrEmpty(applicationName);
3128

3229
return CreateProvider(
3330
keyDirectory: null,
@@ -74,10 +71,7 @@ public static IDataProtectionProvider Create(
7471
/// <param name="certificate">The <see cref="X509Certificate2"/> to be used for encryption.</param>
7572
public static IDataProtectionProvider Create(string applicationName, X509Certificate2 certificate)
7673
{
77-
if (string.IsNullOrEmpty(applicationName))
78-
{
79-
throw new ArgumentNullException(nameof(applicationName));
80-
}
74+
ArgumentThrowHelper.ThrowIfNullOrEmpty(applicationName);
8175
ArgumentNullThrowHelper.ThrowIfNull(certificate);
8276

8377
return CreateProvider(

src/DataProtection/Extensions/src/Microsoft.AspNetCore.DataProtection.Extensions.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
<Compile Include="..\..\shared\src\*.cs" LinkBase="Shared" />
1515
<Compile Include="$(SharedSourceRoot)TrimmingAttributes.cs" LinkBase="Shared"
1616
Condition="'$(TargetFramework)' != '$(DefaultNetCoreTargetFramework)'" />
17+
<Compile Include="$(SharedSourceRoot)ThrowHelpers\ArgumentThrowHelper.cs" LinkBase="Shared" />
1718
<Compile Include="$(SharedSourceRoot)ThrowHelpers\ArgumentNullThrowHelper.cs" LinkBase="Shared" />
1819
<Compile Include="$(SharedSourceRoot)CallerArgument\CallerArgumentExpressionAttribute.cs" LinkBase="Shared" />
1920
</ItemGroup>

src/Http/Authentication.Abstractions/src/TokenExtensions.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public static void StoreTokens(this AuthenticationProperties properties, IEnumer
3636
{
3737
if (token.Name is null)
3838
{
39-
throw new ArgumentNullException(nameof(tokens), "Token name cannot be null.");
39+
throw new ArgumentException("Token name cannot be null for any token.", nameof(tokens));
4040
}
4141

4242
// REVIEW: should probably check that there are no ; in the token name and throw or encode

src/Http/Http.Abstractions/src/Internal/ParsingHelpers.cs

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,8 @@ public static StringValues GetHeaderUnmodified(IHeaderDictionary headers, string
4646
public static void SetHeaderJoined(IHeaderDictionary headers, string key, StringValues value)
4747
{
4848
ArgumentNullException.ThrowIfNull(headers);
49+
ArgumentException.ThrowIfNullOrEmpty(key);
4950

50-
if (string.IsNullOrEmpty(key))
51-
{
52-
throw new ArgumentNullException(nameof(key));
53-
}
5451
if (StringValues.IsNullOrEmpty(value))
5552
{
5653
headers.Remove(key);
@@ -87,11 +84,8 @@ public static void SetHeaderJoined(IHeaderDictionary headers, string key, String
8784
public static void SetHeaderUnmodified(IHeaderDictionary headers, string key, StringValues? values)
8885
{
8986
ArgumentNullException.ThrowIfNull(headers);
87+
ArgumentException.ThrowIfNullOrEmpty(key);
9088

91-
if (string.IsNullOrEmpty(key))
92-
{
93-
throw new ArgumentNullException(nameof(key));
94-
}
9589
if (!values.HasValue || StringValues.IsNullOrEmpty(values.GetValueOrDefault()))
9690
{
9791
headers.Remove(key);

src/Http/Routing/src/Patterns/RoutePatternFactory.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -823,7 +823,7 @@ public static RoutePatternParameterPart ParameterPart(
823823

824824
if (@default != null && parameterKind == RoutePatternParameterKind.Optional)
825825
{
826-
throw new ArgumentNullException(nameof(parameterKind), Resources.TemplateRoute_OptionalCannotHaveDefaultValue);
826+
throw new ArgumentException(Resources.TemplateRoute_OptionalCannotHaveDefaultValue);
827827
}
828828

829829
return ParameterPartCore(
@@ -860,7 +860,7 @@ public static RoutePatternParameterPart ParameterPart(
860860

861861
if (@default != null && parameterKind == RoutePatternParameterKind.Optional)
862862
{
863-
throw new ArgumentNullException(nameof(parameterKind), Resources.TemplateRoute_OptionalCannotHaveDefaultValue);
863+
throw new ArgumentException(Resources.TemplateRoute_OptionalCannotHaveDefaultValue);
864864
}
865865

866866
ArgumentNullException.ThrowIfNull(parameterPolicies);
@@ -899,7 +899,7 @@ public static RoutePatternParameterPart ParameterPart(
899899

900900
if (@default != null && parameterKind == RoutePatternParameterKind.Optional)
901901
{
902-
throw new ArgumentNullException(nameof(parameterKind), Resources.TemplateRoute_OptionalCannotHaveDefaultValue);
902+
throw new ArgumentException(Resources.TemplateRoute_OptionalCannotHaveDefaultValue);
903903
}
904904

905905
ArgumentNullException.ThrowIfNull(parameterPolicies);

src/Identity/EntityFrameworkCore/src/UserStore.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -611,10 +611,7 @@ join user in Users on userclaims.UserId equals user.Id
611611
{
612612
cancellationToken.ThrowIfCancellationRequested();
613613
ThrowIfDisposed();
614-
if (string.IsNullOrEmpty(normalizedRoleName))
615-
{
616-
throw new ArgumentNullException(nameof(normalizedRoleName));
617-
}
614+
ArgumentException.ThrowIfNullOrEmpty(normalizedRoleName);
618615

619616
var role = await FindRoleAsync(normalizedRoleName, cancellationToken);
620617

src/Identity/Extensions.Core/src/UserClaimsPrincipalFactory.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@ public UserClaimsPrincipalFactory(
2828
ArgumentNullThrowHelper.ThrowIfNull(userManager);
2929
if (optionsAccessor == null || optionsAccessor.Value == null)
3030
{
31-
throw new ArgumentNullException(nameof(optionsAccessor));
31+
ArgumentNullThrowHelper.ThrowIfNull(optionsAccessor);
32+
throw new ArgumentException($"{nameof(optionsAccessor)} cannot wrap a null value.", nameof(optionsAccessor));
3233
}
3334
UserManager = userManager;
3435
Options = optionsAccessor.Value;

src/Identity/test/Identity.Test/UserClaimsPrincipalFactoryTest.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ public async Task CreateIdentityNullChecks()
1515
var userManager = MockHelpers.MockUserManager<PocoUser>().Object;
1616
var roleManager = MockHelpers.MockRoleManager<PocoRole>().Object;
1717
var options = new Mock<IOptions<IdentityOptions>>();
18-
Assert.Throws<ArgumentNullException>("optionsAccessor",
18+
Assert.Throws<ArgumentException>("optionsAccessor",
1919
() => new UserClaimsPrincipalFactory<PocoUser, PocoRole>(userManager, roleManager, options.Object));
2020
var identityOptions = new IdentityOptions();
2121
options.Setup(a => a.Value).Returns(identityOptions);

src/Identity/test/InMemory.Test/InMemoryStore.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,7 @@ public class InMemoryStore<TUser, TRole> :
5757
// RoleId == rolename for inmemory store tests
5858
public Task<IList<TUser>> GetUsersInRoleAsync(string roleName, CancellationToken cancellationToken = default(CancellationToken))
5959
{
60-
if (String.IsNullOrEmpty(roleName))
61-
{
62-
throw new ArgumentNullException(nameof(roleName));
63-
}
60+
ArgumentException.ThrowIfNullOrEmpty(roleName);
6461

6562
var role = _roles.Values.Where(x => x.NormalizedName.Equals(roleName)).SingleOrDefault();
6663
if (role == null)

src/Localization/Localization/src/Microsoft.Extensions.Localization.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
</ItemGroup>
2424

2525
<ItemGroup>
26+
<Compile Include="$(SharedSourceRoot)ThrowHelpers\ArgumentThrowHelper.cs" LinkBase="Shared" />
2627
<Compile Include="$(SharedSourceRoot)ThrowHelpers\ArgumentNullThrowHelper.cs" LinkBase="Shared" />
2728
<Compile Include="$(SharedSourceRoot)CallerArgument\CallerArgumentExpressionAttribute.cs" LinkBase="Shared" />
2829
</ItemGroup>

src/Localization/Localization/src/ResourceLocationAttribute.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33

44
using System;
5+
using Microsoft.AspNetCore.Shared;
56

67
namespace Microsoft.Extensions.Localization;
78

@@ -17,10 +18,7 @@ public class ResourceLocationAttribute : Attribute
1718
/// <param name="resourceLocation">The location of resources for this Assembly.</param>
1819
public ResourceLocationAttribute(string resourceLocation)
1920
{
20-
if (string.IsNullOrEmpty(resourceLocation))
21-
{
22-
throw new ArgumentNullException(nameof(resourceLocation));
23-
}
21+
ArgumentThrowHelper.ThrowIfNullOrEmpty(resourceLocation);
2422

2523
ResourceLocation = resourceLocation;
2624
}

src/Localization/Localization/src/ResourceManagerStringLocalizerFactory.cs

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -76,11 +76,7 @@ protected virtual string GetResourcePrefix(TypeInfo typeInfo)
7676
protected virtual string GetResourcePrefix(TypeInfo typeInfo, string? baseNamespace, string? resourcesRelativePath)
7777
{
7878
ArgumentNullThrowHelper.ThrowIfNull(typeInfo);
79-
80-
if (string.IsNullOrEmpty(baseNamespace))
81-
{
82-
throw new ArgumentNullException(nameof(baseNamespace));
83-
}
79+
ArgumentThrowHelper.ThrowIfNullOrEmpty(baseNamespace);
8480

8581
if (string.IsNullOrEmpty(typeInfo.FullName))
8682
{
@@ -107,15 +103,8 @@ protected virtual string GetResourcePrefix(TypeInfo typeInfo, string? baseNamesp
107103
/// <returns>The prefix for resource lookup.</returns>
108104
protected virtual string GetResourcePrefix(string baseResourceName, string baseNamespace)
109105
{
110-
if (string.IsNullOrEmpty(baseResourceName))
111-
{
112-
throw new ArgumentNullException(nameof(baseResourceName));
113-
}
114-
115-
if (string.IsNullOrEmpty(baseNamespace))
116-
{
117-
throw new ArgumentNullException(nameof(baseNamespace));
118-
}
106+
ArgumentThrowHelper.ThrowIfNullOrEmpty(baseResourceName);
107+
ArgumentThrowHelper.ThrowIfNullOrEmpty(baseNamespace);
119108

120109
var assemblyName = new AssemblyName(baseNamespace);
121110
var assembly = Assembly.Load(assemblyName);

src/Localization/Localization/src/RootNamespaceAttribute.cs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33

44
using System;
5+
using Microsoft.AspNetCore.Shared;
56

67
namespace Microsoft.Extensions.Localization;
78

@@ -18,10 +19,7 @@ public class RootNamespaceAttribute : Attribute
1819
/// <param name="rootNamespace">The RootNamespace for this Assembly.</param>
1920
public RootNamespaceAttribute(string rootNamespace)
2021
{
21-
if (string.IsNullOrEmpty(rootNamespace))
22-
{
23-
throw new ArgumentNullException(nameof(rootNamespace));
24-
}
22+
ArgumentThrowHelper.ThrowIfNullOrEmpty(rootNamespace);
2523

2624
RootNamespace = rootNamespace;
2725
}

src/Logging.AzureAppServices/src/AzureFileLoggerOptions.cs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33

44
using System;
5+
using Microsoft.AspNetCore.Shared;
56

67
namespace Microsoft.Extensions.Logging.AzureAppServices;
78

@@ -59,10 +60,8 @@ public string FileName
5960
get { return _fileName; }
6061
set
6162
{
62-
if (string.IsNullOrEmpty(value))
63-
{
64-
throw new ArgumentNullException(nameof(value));
65-
}
63+
ArgumentThrowHelper.ThrowIfNullOrEmpty(value);
64+
6665
_fileName = value;
6766
}
6867
}

src/Logging.AzureAppServices/src/Microsoft.Extensions.Logging.AzureAppServices.csproj

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,11 @@
2828
<ItemGroup>
2929
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" />
3030
</ItemGroup>
31+
32+
<ItemGroup>
33+
<Compile Include="$(SharedSourceRoot)ThrowHelpers\ArgumentThrowHelper.cs" LinkBase="Shared" />
34+
<Compile Include="$(SharedSourceRoot)ThrowHelpers\ArgumentNullThrowHelper.cs" LinkBase="Shared" />
35+
<Compile Include="$(SharedSourceRoot)CallerArgument\CallerArgumentExpressionAttribute.cs" LinkBase="Shared" />
36+
</ItemGroup>
37+
3138
</Project>

src/Middleware/HttpLogging/src/W3CLoggerOptions.cs

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,7 @@ public string FileName
6464
get { return _fileName; }
6565
set
6666
{
67-
if (string.IsNullOrEmpty(value))
68-
{
69-
throw new ArgumentNullException(nameof(value));
70-
}
67+
ArgumentException.ThrowIfNullOrEmpty(value);
7168
_fileName = value;
7269
}
7370
}
@@ -83,10 +80,7 @@ public string LogDirectory
8380
get { return _logDirectory; }
8481
set
8582
{
86-
if (string.IsNullOrEmpty(value))
87-
{
88-
throw new ArgumentNullException(nameof(value));
89-
}
83+
ArgumentException.ThrowIfNullOrEmpty(value);
9084
_logDirectory = value;
9185
}
9286
}

src/Middleware/HttpLogging/test/W3CLoggerOptionsTests.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,14 @@ public void ThrowsOnNegativeFileSizeLimit()
2626
public void ThrowsOnEmptyFileName()
2727
{
2828
var options = new W3CLoggerOptions();
29-
Assert.Throws<ArgumentNullException>(() => options.FileName = "");
29+
Assert.Throws<ArgumentException>(() => options.FileName = "");
3030
}
3131

3232
[Fact]
3333
public void ThrowsOnEmptyLogDirectory()
3434
{
3535
var options = new W3CLoggerOptions();
36-
Assert.Throws<ArgumentNullException>(() => options.LogDirectory = "");
36+
Assert.Throws<ArgumentException>(() => options.LogDirectory = "");
3737
}
3838

3939
[Fact]

src/Middleware/Rewrite/src/ApacheModRewrite/CookieActionFactory.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,7 @@ internal sealed class CookieActionFactory
1616
/// <returns>The action</returns>
1717
public static ChangeCookieAction Create(string flagValue)
1818
{
19-
if (string.IsNullOrEmpty(flagValue))
20-
{
21-
throw new ArgumentNullException(nameof(flagValue));
22-
}
19+
ArgumentException.ThrowIfNullOrEmpty(flagValue);
2320

2421
var i = 0;
2522
var separator = ':';

src/Middleware/Rewrite/src/IISUrlRewrite/IISRewriteMap.cs

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,7 @@ internal sealed class IISRewriteMap
99

1010
public IISRewriteMap(string name)
1111
{
12-
if (string.IsNullOrEmpty(name))
13-
{
14-
throw new ArgumentNullException(nameof(name));
15-
}
12+
ArgumentException.ThrowIfNullOrEmpty(name);
1613
Name = name;
1714
}
1815

@@ -26,14 +23,8 @@ public string? this[string key]
2623
}
2724
set
2825
{
29-
if (string.IsNullOrEmpty(key))
30-
{
31-
throw new ArgumentNullException(nameof(key));
32-
}
33-
if (string.IsNullOrEmpty(value))
34-
{
35-
throw new ArgumentNullException(nameof(value));
36-
}
26+
ArgumentException.ThrowIfNullOrEmpty(key);
27+
ArgumentException.ThrowIfNullOrEmpty(value);
3728
_map[key] = value;
3829
}
3930
}

src/Middleware/Rewrite/src/RedirectRule.cs

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,8 @@ internal sealed class RedirectRule : IRule
1616
public int StatusCode { get; }
1717
public RedirectRule(string regex, string replacement, int statusCode)
1818
{
19-
if (string.IsNullOrEmpty(regex))
20-
{
21-
throw new ArgumentNullException(nameof(regex));
22-
}
23-
24-
if (string.IsNullOrEmpty(replacement))
25-
{
26-
throw new ArgumentNullException(nameof(replacement));
27-
}
19+
ArgumentException.ThrowIfNullOrEmpty(regex);
20+
ArgumentException.ThrowIfNullOrEmpty(replacement);
2821

2922
InitialMatch = new Regex(regex, RegexOptions.Compiled | RegexOptions.CultureInvariant, _regexTimeout);
3023
Replacement = replacement;

src/Middleware/Rewrite/src/RewriteRule.cs

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,8 @@ internal sealed class RewriteRule : IRule
1616
public bool StopProcessing { get; }
1717
public RewriteRule(string regex, string replacement, bool stopProcessing)
1818
{
19-
if (string.IsNullOrEmpty(regex))
20-
{
21-
throw new ArgumentNullException(nameof(regex));
22-
}
23-
24-
if (string.IsNullOrEmpty(replacement))
25-
{
26-
throw new ArgumentNullException(nameof(replacement));
27-
}
19+
ArgumentException.ThrowIfNullOrEmpty(regex);
20+
ArgumentException.ThrowIfNullOrEmpty(replacement);
2821

2922
InitialMatch = new Regex(regex, RegexOptions.Compiled | RegexOptions.CultureInvariant, _regexTimeout);
3023
Replacement = replacement;

src/Middleware/Rewrite/src/UrlActions/ChangeCookieAction.cs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,9 @@ public ChangeCookieAction(string name)
1818
// for testing
1919
internal ChangeCookieAction(string name, Func<DateTimeOffset> timeSource)
2020
{
21-
_timeSource = timeSource;
22-
23-
if (string.IsNullOrEmpty(name))
24-
{
25-
throw new ArgumentNullException(nameof(name));
26-
}
21+
ArgumentException.ThrowIfNullOrEmpty(name);
2722

23+
_timeSource = timeSource;
2824
Name = name;
2925
}
3026

src/Middleware/StaticFiles/src/StaticFileContext.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ public StaticFileContext(HttpContext context, StaticFileOptions options, ILogger
4545
{
4646
if (subPath.Value == null)
4747
{
48-
throw new ArgumentNullException(nameof(subPath));
48+
throw new ArgumentException($"{nameof(subPath)} cannot wrap a null value.", nameof(subPath));
4949
}
5050

5151
_context = context;

0 commit comments

Comments
 (0)