Skip to content

Commit

Permalink
Use ArgumentException.ThrowIfNullOrEmpty and ThrowIfNullOrWhitespace (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
joegoldman2 authored Jan 20, 2024
1 parent 15a4a77 commit 6372a53
Show file tree
Hide file tree
Showing 93 changed files with 450 additions and 872 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

<ItemGroup>
<Compile Include="$(SharedSourceRoot)ThrowHelpers\ArgumentNullThrowHelper.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)ThrowHelpers\ArgumentThrowHelper.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)CallerArgument\CallerArgumentExpressionAttribute.cs" LinkBase="Shared" />
</ItemGroup>

Expand Down
19 changes: 4 additions & 15 deletions src/Caching/SqlServer/src/SqlServerCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,21 +35,10 @@ public SqlServerCache(IOptions<SqlServerCacheOptions> options)
{
var cacheOptions = options.Value;

if (string.IsNullOrEmpty(cacheOptions.ConnectionString))
{
throw new ArgumentException(
$"{nameof(SqlServerCacheOptions.ConnectionString)} cannot be empty or null.");
}
if (string.IsNullOrEmpty(cacheOptions.SchemaName))
{
throw new ArgumentException(
$"{nameof(SqlServerCacheOptions.SchemaName)} cannot be empty or null.");
}
if (string.IsNullOrEmpty(cacheOptions.TableName))
{
throw new ArgumentException(
$"{nameof(SqlServerCacheOptions.TableName)} cannot be empty or null.");
}
ArgumentThrowHelper.ThrowIfNullOrEmpty(cacheOptions.ConnectionString);
ArgumentThrowHelper.ThrowIfNullOrEmpty(cacheOptions.SchemaName);
ArgumentThrowHelper.ThrowIfNullOrEmpty(cacheOptions.TableName);

if (cacheOptions.ExpiredItemsDeletionInterval.HasValue &&
cacheOptions.ExpiredItemsDeletionInterval.Value < MinimumExpiredItemsDeletionInterval)
{
Expand Down
3 changes: 0 additions & 3 deletions src/Components/Components/src/Routing/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,6 @@
<data name="ArgumentMustBeGreaterThanOrEqualTo" xml:space="preserve">
<value>Value must be greater than or equal to {0}.</value>
</data>
<data name="Argument_NullOrEmpty" xml:space="preserve">
<value>Value cannot be null or empty.</value>
</data>
<data name="TemplateRoute_CannotHaveCatchAllInMultiSegment" xml:space="preserve">
<value>A path segment that contains more than one section, such as a literal section or a parameter, cannot contain a catch-all parameter.</value>
</data>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,7 @@ private protected ProtectedBrowserStorage(string storeName, IJSRuntime jsRuntime
throw new PlatformNotSupportedException($"{GetType()} cannot be used when running in a browser.");
}

if (string.IsNullOrEmpty(storeName))
{
throw new ArgumentException("The value cannot be null or empty", nameof(storeName));
}
ArgumentException.ThrowIfNullOrEmpty(storeName);

_storeName = storeName;
_jsRuntime = jsRuntime ?? throw new ArgumentNullException(nameof(jsRuntime));
Expand Down Expand Up @@ -71,15 +68,8 @@ public ValueTask SetAsync(string key, object value)
/// <returns>A <see cref="ValueTask"/> representing the completion of the operation.</returns>
public ValueTask SetAsync(string purpose, string key, object value)
{
if (string.IsNullOrEmpty(purpose))
{
throw new ArgumentException("Cannot be null or empty", nameof(purpose));
}

if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Cannot be null or empty", nameof(key));
}
ArgumentException.ThrowIfNullOrEmpty(purpose);
ArgumentException.ThrowIfNullOrEmpty(key);

return SetProtectedJsonAsync(key, Protect(purpose, value));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,7 @@ internal void Add([DynamicallyAccessedMembers(LinkerFlags.Component)] Type compo
{
Add(componentType, identifier);

if (string.IsNullOrEmpty(javaScriptInitializer))
{
throw new ArgumentException($"'{nameof(javaScriptInitializer)}' cannot be null or empty.", nameof(javaScriptInitializer));
}
ArgumentException.ThrowIfNullOrEmpty(javaScriptInitializer);

// Since it has a JS initializer, prepare the metadata we'll supply to JS code
if (!JSComponentIdentifiersByInitializer.TryGetValue(javaScriptInitializer, out var identifiersForInitializer))
Expand Down
6 changes: 1 addition & 5 deletions src/FileProviders/Embedded/src/Manifest/ManifestDirectory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,7 @@ public override ManifestEntry Traverse(StringSegment segment)

public static ManifestDirectory CreateDirectory(string name, ManifestEntry[] children)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException($"'{nameof(name)}' must not be null, empty or whitespace.", nameof(name));
}

ArgumentThrowHelper.ThrowIfNullOrWhiteSpace(name);
ArgumentNullThrowHelper.ThrowIfNull(children);

var result = new ManifestDirectory(name, children);
Expand Down
12 changes: 3 additions & 9 deletions src/FileProviders/Embedded/src/Manifest/ManifestFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using Microsoft.AspNetCore.Shared;
using Microsoft.Extensions.Primitives;

namespace Microsoft.Extensions.FileProviders.Embedded.Manifest;
Expand All @@ -11,15 +12,8 @@ internal sealed class ManifestFile : ManifestEntry
public ManifestFile(string name, string resourcePath)
: base(name)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentException($"'{nameof(name)}' must not be null, empty or whitespace.", nameof(name));
}

if (string.IsNullOrWhiteSpace(resourcePath))
{
throw new ArgumentException($"'{nameof(resourcePath)}' must not be null, empty or whitespace.", nameof(resourcePath));
}
ArgumentThrowHelper.ThrowIfNullOrWhiteSpace(name);
ArgumentThrowHelper.ThrowIfNullOrWhiteSpace(resourcePath);

ResourcePath = resourcePath;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@

<ItemGroup>
<Compile Include="$(SharedSourceRoot)ThrowHelpers\ArgumentNullThrowHelper.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)ThrowHelpers\ArgumentThrowHelper.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)CallerArgument\CallerArgumentExpressionAttribute.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)TrimmingAttributes.cs" LinkBase="Shared"
Condition="'$(TargetFramework)' != '$(DefaultNetCoreTargetFramework)'" />
Expand Down
10 changes: 2 additions & 8 deletions src/Hosting/Hosting/src/Internal/HostingEnvironmentExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,7 @@ internal static void Initialize(this IHostingEnvironment hostingEnvironment, str
#pragma warning restore CS0618 // Type or member is obsolete
{
ArgumentNullException.ThrowIfNull(options);
if (string.IsNullOrEmpty(contentRootPath))
{
throw new ArgumentException("A valid non-empty content root must be provided.", nameof(contentRootPath));
}
ArgumentException.ThrowIfNullOrEmpty(contentRootPath);
if (!Directory.Exists(contentRootPath))
{
throw new ArgumentException($"The content root '{contentRootPath}' does not exist.", nameof(contentRootPath));
Expand Down Expand Up @@ -67,10 +64,7 @@ internal static void Initialize(
IHostEnvironment? baseEnvironment = null)
{
ArgumentNullException.ThrowIfNull(options);
if (string.IsNullOrEmpty(contentRootPath))
{
throw new ArgumentException("A valid non-empty content root must be provided.", nameof(contentRootPath));
}
ArgumentException.ThrowIfNullOrEmpty(contentRootPath);
if (!Directory.Exists(contentRootPath))
{
throw new ArgumentException($"The content root '{contentRootPath}' does not exist.", nameof(contentRootPath));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,7 @@ public DeploymentParameters(
RuntimeFlavor runtimeFlavor,
RuntimeArchitecture runtimeArchitecture)
{
if (string.IsNullOrEmpty(applicationPath))
{
throw new ArgumentException("Value cannot be null.", nameof(applicationPath));
}
ArgumentException.ThrowIfNullOrEmpty(applicationPath);

if (!Directory.Exists(applicationPath))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,7 @@ private void ValidateParameters()

if (DeploymentParameters.ApplicationPublisher == null)
{
if (string.IsNullOrEmpty(DeploymentParameters.ApplicationPath))
{
throw new ArgumentException("ApplicationPath cannot be null.");
}
ArgumentException.ThrowIfNullOrEmpty(DeploymentParameters.ApplicationPath);

if (!Directory.Exists(DeploymentParameters.ApplicationPath))
{
Expand Down
22 changes: 5 additions & 17 deletions src/Http/Http.Results/src/TypedResults.cs
Original file line number Diff line number Diff line change
Expand Up @@ -511,10 +511,7 @@ public static PhysicalFileHttpResult PhysicalFile(
EntityTagHeaderValue? entityTag = null,
bool enableRangeProcessing = false)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentException("Argument cannot be null or empty", nameof(path));
}
ArgumentException.ThrowIfNullOrEmpty(path);

return new(path, contentType)
{
Expand Down Expand Up @@ -547,10 +544,7 @@ public static VirtualFileHttpResult VirtualFile(
EntityTagHeaderValue? entityTag = null,
bool enableRangeProcessing = false)
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentException("Argument cannot be null or empty", nameof(path));
}
ArgumentException.ThrowIfNullOrEmpty(path);

return new(path, contentType)
{
Expand All @@ -576,10 +570,7 @@ public static VirtualFileHttpResult VirtualFile(
/// <returns>The created <see cref="RedirectHttpResult"/> for the response.</returns>
public static RedirectHttpResult Redirect([StringSyntax(StringSyntaxAttribute.Uri)] string url, bool permanent = false, bool preserveMethod = false)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentException("Argument cannot be null or empty", nameof(url));
}
ArgumentException.ThrowIfNullOrEmpty(url);

return new(url, permanent, preserveMethod);
}
Expand All @@ -599,10 +590,7 @@ public static RedirectHttpResult Redirect([StringSyntax(StringSyntaxAttribute.Ur
/// <returns>The created <see cref="RedirectHttpResult"/> for the response.</returns>
public static RedirectHttpResult LocalRedirect([StringSyntax(StringSyntaxAttribute.Uri, UriKind.Relative)] string localUrl, bool permanent = false, bool preserveMethod = false)
{
if (string.IsNullOrEmpty(localUrl))
{
throw new ArgumentException("Argument cannot be null or empty", nameof(localUrl));
}
ArgumentException.ThrowIfNullOrEmpty(localUrl);

return new(localUrl, acceptLocalUrlOnly: true, permanent, preserveMethod);
}
Expand Down Expand Up @@ -837,7 +825,7 @@ public static ValidationProblem ValidationProblem(

/// <summary>
/// Produces a <see cref="StatusCodes.Status201Created"/> response.
/// </summary>
/// </summary>
/// <returns>The created <see cref="HttpResults.Created"/> for the response.</returns>
public static Created Created()
{
Expand Down
12 changes: 6 additions & 6 deletions src/Http/Http.Results/test/ResultsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -666,7 +666,7 @@ public void Created_WithNullStringUriAndValue_SetsLocationNull()
//Arrange
object value = new { };

// Act
// Act
var result = Results.Created(default(string), value) as Created<object>;

//Assert
Expand All @@ -680,7 +680,7 @@ public void Created_WithEmptyStringUriAndValue_SetsLocationEmpty()
//Arrange
object value = new { };

// Act
// Act
var result = Results.Created(string.Empty, value) as Created<object>;

//Assert
Expand All @@ -694,7 +694,7 @@ public void Created_WithNullUriAndValue_SetsLocationNull()
//Arrange
object value = new { };

// Act
// Act
var result = Results.Created(default(Uri), value) as Created<object>;

//Assert
Expand Down Expand Up @@ -895,7 +895,7 @@ public void Json_WithAllArgs_ResultHasCorrectValues()
var options = new JsonSerializerOptions();
var contentType = "application/custom+json";
var statusCode = StatusCodes.Status208AlreadyReported;

// Act
var result = Results.Json(data, options, contentType, statusCode) as JsonHttpResult<object>;

Expand Down Expand Up @@ -1035,7 +1035,7 @@ public void JsonOfT_WithNullTypeInfo_ThrowsArgException()
[Fact]
public void LocalRedirect_WithNullStringUrl_ThrowsArgException()
{
Assert.Throws<ArgumentException>("localUrl", () => Results.LocalRedirect(default(string)));
Assert.Throws<ArgumentNullException>("localUrl", () => Results.LocalRedirect(default(string)));
}

[Fact]
Expand Down Expand Up @@ -1339,7 +1339,7 @@ public void ValidationProblem_WithValidationProblemArg_ResultHasCorrectValues()
[Fact]
public void Redirect_WithNullStringUrl_ThrowsArgException()
{
Assert.Throws<ArgumentException>("url", () => Results.Redirect(default(string)));
Assert.Throws<ArgumentNullException>("url", () => Results.Redirect(default(string)));
}

[Fact]
Expand Down
8 changes: 4 additions & 4 deletions src/Http/Http.Results/test/TypedResultsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ public void Stream_WithNullCallback_ThrowsArgNullException()
[Fact]
public void PhysicalFile_WithNullPath_ThrowsArgException()
{
Assert.Throws<ArgumentException>("path", () => TypedResults.PhysicalFile(default(string)));
Assert.Throws<ArgumentNullException>("path", () => TypedResults.PhysicalFile(default(string)));
}

[Fact]
Expand All @@ -361,7 +361,7 @@ public void PhysicalFile_WithEmptyPath_ThrowsArgException()
[Fact]
public void VirtualFile_WithNullPath_ThrowsArgException()
{
Assert.Throws<ArgumentException>("path", () => TypedResults.VirtualFile(default(string)));
Assert.Throws<ArgumentNullException>("path", () => TypedResults.VirtualFile(default(string)));
}

[Fact]
Expand Down Expand Up @@ -916,7 +916,7 @@ public void Json_WithNullTypeInfo_ThrowsArgException()
[Fact]
public void LocalRedirect_WithNullStringUrl_ThrowsArgException()
{
Assert.Throws<ArgumentException>("localUrl", () => TypedResults.LocalRedirect(default(string)));
Assert.Throws<ArgumentNullException>("localUrl", () => TypedResults.LocalRedirect(default(string)));
}

[Fact]
Expand Down Expand Up @@ -1187,7 +1187,7 @@ public void ValidationProblem_WithValidationProblemArg_ResultHasCorrectValues()
[Fact]
public void Redirect_WithNullStringUrl_ThrowsArgException()
{
Assert.Throws<ArgumentException>("url", () => TypedResults.Redirect(default(string)));
Assert.Throws<ArgumentNullException>("url", () => TypedResults.Redirect(default(string)));
}

[Fact]
Expand Down
5 changes: 1 addition & 4 deletions src/Http/Routing/src/DefaultLinkGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -155,10 +155,7 @@ public DefaultLinkGenerator(
FragmentString fragment = default,
LinkOptions? options = null)
{
if (string.IsNullOrEmpty(scheme))
{
throw new ArgumentException("A scheme must be provided.", nameof(scheme));
}
ArgumentException.ThrowIfNullOrEmpty(scheme);

if (!host.HasValue)
{
Expand Down
12 changes: 2 additions & 10 deletions src/Http/Routing/src/LinkGeneratorEndpointNameAddressExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -305,11 +305,7 @@ public static class LinkGeneratorEndpointNameAddressExtensions
{
ArgumentNullException.ThrowIfNull(generator);
ArgumentNullException.ThrowIfNull(endpointName);

if (string.IsNullOrEmpty(scheme))
{
throw new ArgumentException("A scheme must be provided.", nameof(scheme));
}
ArgumentException.ThrowIfNullOrEmpty(scheme);

if (!host.HasValue)
{
Expand Down Expand Up @@ -358,11 +354,7 @@ public static class LinkGeneratorEndpointNameAddressExtensions
{
ArgumentNullException.ThrowIfNull(generator);
ArgumentNullException.ThrowIfNull(endpointName);

if (string.IsNullOrEmpty(scheme))
{
throw new ArgumentException("A scheme must be provided.", nameof(scheme));
}
ArgumentException.ThrowIfNullOrEmpty(scheme);

if (!host.HasValue)
{
Expand Down
Loading

0 comments on commit 6372a53

Please sign in to comment.