diff --git a/Directory.Build.targets b/Directory.Build.targets index 5f4fbc649ae7..1980cdcc77b2 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -28,12 +28,6 @@ $(NoWarn);CS1591 - - - $(NoWarn);CA1510;CA1511;CA1512;CA1513 diff --git a/src/Caching/SqlServer/src/Microsoft.Extensions.Caching.SqlServer.csproj b/src/Caching/SqlServer/src/Microsoft.Extensions.Caching.SqlServer.csproj index 3c6e790be27e..4be0de35b382 100644 --- a/src/Caching/SqlServer/src/Microsoft.Extensions.Caching.SqlServer.csproj +++ b/src/Caching/SqlServer/src/Microsoft.Extensions.Caching.SqlServer.csproj @@ -21,4 +21,9 @@ + + + + + diff --git a/src/Caching/SqlServer/src/SqlServerCache.cs b/src/Caching/SqlServer/src/SqlServerCache.cs index 968dbb843002..e24192b6d1f5 100644 --- a/src/Caching/SqlServer/src/SqlServerCache.cs +++ b/src/Caching/SqlServer/src/SqlServerCache.cs @@ -4,6 +4,7 @@ using System; using System.Threading; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Internal; using Microsoft.Extensions.Options; @@ -80,10 +81,7 @@ public SqlServerCache(IOptions options) /// public byte[]? Get(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); var value = _dbOperations.GetCacheItem(key); @@ -95,10 +93,7 @@ public SqlServerCache(IOptions options) /// public async Task GetAsync(string key, CancellationToken token = default(CancellationToken)) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); token.ThrowIfCancellationRequested(); @@ -112,10 +107,7 @@ public SqlServerCache(IOptions options) /// public void Refresh(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); _dbOperations.RefreshCacheItem(key); @@ -125,10 +117,7 @@ public void Refresh(string key) /// public async Task RefreshAsync(string key, CancellationToken token = default(CancellationToken)) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); token.ThrowIfCancellationRequested(); @@ -140,10 +129,7 @@ public void Refresh(string key) /// public void Remove(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); _dbOperations.DeleteCacheItem(key); @@ -153,10 +139,7 @@ public void Remove(string key) /// public async Task RemoveAsync(string key, CancellationToken token = default(CancellationToken)) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); token.ThrowIfCancellationRequested(); @@ -168,20 +151,9 @@ public void Remove(string key) /// public void Set(string key, byte[] value, DistributedCacheEntryOptions options) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); + ArgumentNullThrowHelper.ThrowIfNull(value); + ArgumentNullThrowHelper.ThrowIfNull(options); GetOptions(ref options); @@ -197,20 +169,9 @@ public async Task SetAsync( DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken)) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); + ArgumentNullThrowHelper.ThrowIfNull(value); + ArgumentNullThrowHelper.ThrowIfNull(options); token.ThrowIfCancellationRequested(); diff --git a/src/Caching/SqlServer/src/SqlServerCachingServicesExtensions.cs b/src/Caching/SqlServer/src/SqlServerCachingServicesExtensions.cs index 6fbc3e2e15f5..24de1f9d370b 100644 --- a/src/Caching/SqlServer/src/SqlServerCachingServicesExtensions.cs +++ b/src/Caching/SqlServer/src/SqlServerCachingServicesExtensions.cs @@ -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.Caching.Distributed; using Microsoft.Extensions.Caching.SqlServer; @@ -20,15 +21,8 @@ public static class SqlServerCachingServicesExtensions /// The so that additional calls can be chained. public static IServiceCollection AddDistributedSqlServerCache(this IServiceCollection services, Action setupAction) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullThrowHelper.ThrowIfNull(services); + ArgumentNullThrowHelper.ThrowIfNull(setupAction); services.AddOptions(); AddSqlServerCacheServices(services); diff --git a/src/Caching/StackExchangeRedis/src/Microsoft.Extensions.Caching.StackExchangeRedis.csproj b/src/Caching/StackExchangeRedis/src/Microsoft.Extensions.Caching.StackExchangeRedis.csproj index 1cc286f7adc1..b73694371d1e 100644 --- a/src/Caching/StackExchangeRedis/src/Microsoft.Extensions.Caching.StackExchangeRedis.csproj +++ b/src/Caching/StackExchangeRedis/src/Microsoft.Extensions.Caching.StackExchangeRedis.csproj @@ -17,4 +17,10 @@ + + + + + + diff --git a/src/Caching/StackExchangeRedis/src/RedisCache.cs b/src/Caching/StackExchangeRedis/src/RedisCache.cs index 2a309d7f9054..47a38f0fc072 100644 --- a/src/Caching/StackExchangeRedis/src/RedisCache.cs +++ b/src/Caching/StackExchangeRedis/src/RedisCache.cs @@ -6,6 +6,7 @@ using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -79,15 +80,8 @@ public RedisCache(IOptions optionsAccessor) /// The logger. internal RedisCache(IOptions optionsAccessor, ILogger logger) { - if (optionsAccessor == null) - { - throw new ArgumentNullException(nameof(optionsAccessor)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullThrowHelper.ThrowIfNull(optionsAccessor); + ArgumentNullThrowHelper.ThrowIfNull(logger); _options = optionsAccessor.Value; _logger = logger; @@ -99,10 +93,7 @@ internal RedisCache(IOptions optionsAccessor, ILogger logger) /// public byte[]? Get(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); return GetAndRefresh(key, getData: true); } @@ -110,10 +101,7 @@ internal RedisCache(IOptions optionsAccessor, ILogger logger) /// public async Task GetAsync(string key, CancellationToken token = default(CancellationToken)) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); token.ThrowIfCancellationRequested(); @@ -123,20 +111,9 @@ internal RedisCache(IOptions optionsAccessor, ILogger logger) /// public void Set(string key, byte[] value, DistributedCacheEntryOptions options) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); + ArgumentNullThrowHelper.ThrowIfNull(value); + ArgumentNullThrowHelper.ThrowIfNull(options); Connect(); @@ -157,20 +134,9 @@ public void Set(string key, byte[] value, DistributedCacheEntryOptions options) /// public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken)) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); + ArgumentNullThrowHelper.ThrowIfNull(value); + ArgumentNullThrowHelper.ThrowIfNull(options); token.ThrowIfCancellationRequested(); @@ -194,10 +160,7 @@ public void Set(string key, byte[] value, DistributedCacheEntryOptions options) /// public void Refresh(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); GetAndRefresh(key, getData: false); } @@ -205,10 +168,7 @@ public void Refresh(string key) /// public async Task RefreshAsync(string key, CancellationToken token = default(CancellationToken)) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); token.ThrowIfCancellationRequested(); @@ -343,10 +303,7 @@ private void TryRegisterProfiler() private byte[]? GetAndRefresh(string key, bool getData) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); Connect(); @@ -379,10 +336,7 @@ private void TryRegisterProfiler() private async Task GetAndRefreshAsync(string key, bool getData, CancellationToken token = default(CancellationToken)) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); token.ThrowIfCancellationRequested(); @@ -419,10 +373,7 @@ private void TryRegisterProfiler() /// public void Remove(string key) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); Connect(); @@ -433,10 +384,7 @@ public void Remove(string key) /// public async Task RemoveAsync(string key, CancellationToken token = default(CancellationToken)) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); await ConnectAsync(token).ConfigureAwait(false); Debug.Assert(_cache is not null); @@ -463,10 +411,7 @@ private static void MapMetadata(RedisValue[] results, out DateTimeOffset? absolu private void Refresh(IDatabase cache, string key, DateTimeOffset? absExpr, TimeSpan? sldExpr) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); // Note Refresh has no effect if there is just an absolute expiration (or neither). if (sldExpr.HasValue) @@ -488,10 +433,7 @@ private void Refresh(IDatabase cache, string key, DateTimeOffset? absExpr, TimeS private async Task RefreshAsync(IDatabase cache, string key, DateTimeOffset? absExpr, TimeSpan? sldExpr, CancellationToken token = default(CancellationToken)) { - if (key == null) - { - throw new ArgumentNullException(nameof(key)); - } + ArgumentNullThrowHelper.ThrowIfNull(key); token.ThrowIfCancellationRequested(); @@ -564,9 +506,6 @@ public void Dispose() private void CheckDisposed() { - if (_disposed) - { - throw new ObjectDisposedException(this.GetType().FullName); - } + ObjectDisposedThrowHelper.ThrowIf(_disposed, this); } } diff --git a/src/Caching/StackExchangeRedis/src/StackExchangeRedisCacheServiceCollectionExtensions.cs b/src/Caching/StackExchangeRedis/src/StackExchangeRedisCacheServiceCollectionExtensions.cs index 061bde7f61cc..dc9bc9ca5357 100644 --- a/src/Caching/StackExchangeRedis/src/StackExchangeRedisCacheServiceCollectionExtensions.cs +++ b/src/Caching/StackExchangeRedis/src/StackExchangeRedisCacheServiceCollectionExtensions.cs @@ -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.Caching.Distributed; using Microsoft.Extensions.Caching.StackExchangeRedis; @@ -21,15 +22,8 @@ public static class StackExchangeRedisCacheServiceCollectionExtensions /// The so that additional calls can be chained. public static IServiceCollection AddStackExchangeRedisCache(this IServiceCollection services, Action setupAction) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullThrowHelper.ThrowIfNull(services); + ArgumentNullThrowHelper.ThrowIfNull(setupAction); services.AddOptions(); diff --git a/src/DataProtection/Cryptography.KeyDerivation/src/KeyDerivation.cs b/src/DataProtection/Cryptography.KeyDerivation/src/KeyDerivation.cs index 6c836cb4996c..f2902335dd1b 100644 --- a/src/DataProtection/Cryptography.KeyDerivation/src/KeyDerivation.cs +++ b/src/DataProtection/Cryptography.KeyDerivation/src/KeyDerivation.cs @@ -3,6 +3,7 @@ using System; using Microsoft.AspNetCore.Cryptography.KeyDerivation.PBKDF2; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Cryptography.KeyDerivation; @@ -26,29 +27,16 @@ public static class KeyDerivation /// public static byte[] Pbkdf2(string password, byte[] salt, KeyDerivationPrf prf, int iterationCount, int numBytesRequested) { - if (password == null) - { - throw new ArgumentNullException(nameof(password)); - } - - if (salt == null) - { - throw new ArgumentNullException(nameof(salt)); - } + ArgumentNullThrowHelper.ThrowIfNull(password); + ArgumentNullThrowHelper.ThrowIfNull(salt); // parameter checking if (prf < KeyDerivationPrf.HMACSHA1 || prf > KeyDerivationPrf.HMACSHA512) { throw new ArgumentOutOfRangeException(nameof(prf)); } - if (iterationCount <= 0) - { - throw new ArgumentOutOfRangeException(nameof(iterationCount)); - } - if (numBytesRequested <= 0) - { - throw new ArgumentOutOfRangeException(nameof(numBytesRequested)); - } + ArgumentOutOfRangeThrowHelper.ThrowIfNegativeOrZero(iterationCount); + ArgumentOutOfRangeThrowHelper.ThrowIfNegativeOrZero(numBytesRequested); return Pbkdf2Util.Pbkdf2Provider.DeriveKey(password, salt, prf, iterationCount, numBytesRequested); } diff --git a/src/DataProtection/Cryptography.KeyDerivation/src/Microsoft.AspNetCore.Cryptography.KeyDerivation.csproj b/src/DataProtection/Cryptography.KeyDerivation/src/Microsoft.AspNetCore.Cryptography.KeyDerivation.csproj index dd01cd6e1cda..5bed939bca80 100644 --- a/src/DataProtection/Cryptography.KeyDerivation/src/Microsoft.AspNetCore.Cryptography.KeyDerivation.csproj +++ b/src/DataProtection/Cryptography.KeyDerivation/src/Microsoft.AspNetCore.Cryptography.KeyDerivation.csproj @@ -7,8 +7,9 @@ true true aspnetcore;dataprotection + true true - annotations + annotations @@ -18,4 +19,10 @@ + + + + + + diff --git a/src/DataProtection/Extensions/src/DataProtectionAdvancedExtensions.cs b/src/DataProtection/Extensions/src/DataProtectionAdvancedExtensions.cs index 28bd26c82f04..2b318cd1e8db 100644 --- a/src/DataProtection/Extensions/src/DataProtectionAdvancedExtensions.cs +++ b/src/DataProtection/Extensions/src/DataProtectionAdvancedExtensions.cs @@ -3,6 +3,7 @@ using System; using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.DataProtection; @@ -21,15 +22,8 @@ public static class DataProtectionAdvancedExtensions /// The protected form of the plaintext data. public static byte[] Protect(this ITimeLimitedDataProtector protector, byte[] plaintext, TimeSpan lifetime) { - if (protector == null) - { - throw new ArgumentNullException(nameof(protector)); - } - - if (plaintext == null) - { - throw new ArgumentNullException(nameof(plaintext)); - } + ArgumentNullThrowHelper.ThrowIfNull(protector); + ArgumentNullThrowHelper.ThrowIfNull(plaintext); return protector.Protect(plaintext, DateTimeOffset.UtcNow + lifetime); } @@ -44,15 +38,8 @@ public static byte[] Protect(this ITimeLimitedDataProtector protector, byte[] pl /// The protected form of the plaintext data. public static string Protect(this ITimeLimitedDataProtector protector, string plaintext, DateTimeOffset expiration) { - if (protector == null) - { - throw new ArgumentNullException(nameof(protector)); - } - - if (plaintext == null) - { - throw new ArgumentNullException(nameof(plaintext)); - } + ArgumentNullThrowHelper.ThrowIfNull(protector); + ArgumentNullThrowHelper.ThrowIfNull(plaintext); var wrappingProtector = new TimeLimitedWrappingProtector(protector) { Expiration = expiration }; return wrappingProtector.Protect(plaintext); @@ -68,15 +55,8 @@ public static string Protect(this ITimeLimitedDataProtector protector, string pl /// The protected form of the plaintext data. public static string Protect(this ITimeLimitedDataProtector protector, string plaintext, TimeSpan lifetime) { - if (protector == null) - { - throw new ArgumentNullException(nameof(protector)); - } - - if (plaintext == null) - { - throw new ArgumentNullException(nameof(plaintext)); - } + ArgumentNullThrowHelper.ThrowIfNull(protector); + ArgumentNullThrowHelper.ThrowIfNull(plaintext); return Protect(protector, plaintext, DateTimeOffset.Now + lifetime); } @@ -89,10 +69,7 @@ public static string Protect(this ITimeLimitedDataProtector protector, string pl /// An . public static ITimeLimitedDataProtector ToTimeLimitedDataProtector(this IDataProtector protector) { - if (protector == null) - { - throw new ArgumentNullException(nameof(protector)); - } + ArgumentNullThrowHelper.ThrowIfNull(protector); return (protector as ITimeLimitedDataProtector) ?? new TimeLimitedDataProtector(protector); } @@ -110,15 +87,8 @@ public static ITimeLimitedDataProtector ToTimeLimitedDataProtector(this IDataPro /// public static string Unprotect(this ITimeLimitedDataProtector protector, string protectedData, out DateTimeOffset expiration) { - if (protector == null) - { - throw new ArgumentNullException(nameof(protector)); - } - - if (protectedData == null) - { - throw new ArgumentNullException(nameof(protectedData)); - } + ArgumentNullThrowHelper.ThrowIfNull(protector); + ArgumentNullThrowHelper.ThrowIfNull(protectedData); var wrappingProtector = new TimeLimitedWrappingProtector(protector); string retVal = wrappingProtector.Unprotect(protectedData); @@ -138,30 +108,21 @@ public TimeLimitedWrappingProtector(ITimeLimitedDataProtector innerProtector) public IDataProtector CreateProtector(string purpose) { - if (purpose == null) - { - throw new ArgumentNullException(nameof(purpose)); - } + ArgumentNullThrowHelper.ThrowIfNull(purpose); throw new NotImplementedException(); } public byte[] Protect(byte[] plaintext) { - if (plaintext == null) - { - throw new ArgumentNullException(nameof(plaintext)); - } + ArgumentNullThrowHelper.ThrowIfNull(plaintext); return _innerProtector.Protect(plaintext, Expiration); } public byte[] Unprotect(byte[] protectedData) { - if (protectedData == null) - { - throw new ArgumentNullException(nameof(protectedData)); - } + ArgumentNullThrowHelper.ThrowIfNull(protectedData); return _innerProtector.Unprotect(protectedData, out Expiration); } diff --git a/src/DataProtection/Extensions/src/DataProtectionProvider.cs b/src/DataProtection/Extensions/src/DataProtectionProvider.cs index 1cf6632495d7..895444333d16 100644 --- a/src/DataProtection/Extensions/src/DataProtectionProvider.cs +++ b/src/DataProtection/Extensions/src/DataProtectionProvider.cs @@ -4,6 +4,7 @@ using System; using System.IO; using System.Security.Cryptography.X509Certificates; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.DataProtection; @@ -41,10 +42,7 @@ public static IDataProtectionProvider Create(string applicationName) /// represent a directory on a local disk or a UNC share. public static IDataProtectionProvider Create(DirectoryInfo keyDirectory) { - if (keyDirectory == null) - { - throw new ArgumentNullException(nameof(keyDirectory)); - } + ArgumentNullThrowHelper.ThrowIfNull(keyDirectory); return CreateProvider(keyDirectory, setupAction: builder => { }, certificate: null); } @@ -61,14 +59,8 @@ public static IDataProtectionProvider Create( DirectoryInfo keyDirectory, Action setupAction) { - if (keyDirectory == null) - { - throw new ArgumentNullException(nameof(keyDirectory)); - } - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullThrowHelper.ThrowIfNull(keyDirectory); + ArgumentNullThrowHelper.ThrowIfNull(setupAction); return CreateProvider(keyDirectory, setupAction, certificate: null); } @@ -86,10 +78,7 @@ public static IDataProtectionProvider Create(string applicationName, X509Certifi { throw new ArgumentNullException(nameof(applicationName)); } - if (certificate == null) - { - throw new ArgumentNullException(nameof(certificate)); - } + ArgumentNullThrowHelper.ThrowIfNull(certificate); return CreateProvider( keyDirectory: null, @@ -108,14 +97,8 @@ public static IDataProtectionProvider Create( DirectoryInfo keyDirectory, X509Certificate2 certificate) { - if (keyDirectory == null) - { - throw new ArgumentNullException(nameof(keyDirectory)); - } - if (certificate == null) - { - throw new ArgumentNullException(nameof(certificate)); - } + ArgumentNullThrowHelper.ThrowIfNull(keyDirectory); + ArgumentNullThrowHelper.ThrowIfNull(certificate); return CreateProvider(keyDirectory, setupAction: builder => { }, certificate: certificate); } @@ -134,18 +117,9 @@ public static IDataProtectionProvider Create( Action setupAction, X509Certificate2 certificate) { - if (keyDirectory == null) - { - throw new ArgumentNullException(nameof(keyDirectory)); - } - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } - if (certificate == null) - { - throw new ArgumentNullException(nameof(certificate)); - } + ArgumentNullThrowHelper.ThrowIfNull(keyDirectory); + ArgumentNullThrowHelper.ThrowIfNull(setupAction); + ArgumentNullThrowHelper.ThrowIfNull(certificate); return CreateProvider(keyDirectory, setupAction, certificate); } diff --git a/src/DataProtection/Extensions/src/Microsoft.AspNetCore.DataProtection.Extensions.csproj b/src/DataProtection/Extensions/src/Microsoft.AspNetCore.DataProtection.Extensions.csproj index 8c8ab2f2a823..f50d8f9e7c48 100644 --- a/src/DataProtection/Extensions/src/Microsoft.AspNetCore.DataProtection.Extensions.csproj +++ b/src/DataProtection/Extensions/src/Microsoft.AspNetCore.DataProtection.Extensions.csproj @@ -14,6 +14,8 @@ + + diff --git a/src/DataProtection/Extensions/src/TimeLimitedDataProtector.cs b/src/DataProtection/Extensions/src/TimeLimitedDataProtector.cs index 94c1d2cb35ac..6cdddd7c88b6 100644 --- a/src/DataProtection/Extensions/src/TimeLimitedDataProtector.cs +++ b/src/DataProtection/Extensions/src/TimeLimitedDataProtector.cs @@ -6,6 +6,7 @@ using System.Security.Cryptography; using System.Threading; using Microsoft.AspNetCore.DataProtection.Extensions; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.DataProtection; @@ -27,10 +28,7 @@ public TimeLimitedDataProtector(IDataProtector innerProtector) public ITimeLimitedDataProtector CreateProtector(string purpose) { - if (purpose == null) - { - throw new ArgumentNullException(nameof(purpose)); - } + ArgumentNullThrowHelper.ThrowIfNull(purpose); return new TimeLimitedDataProtector(_innerProtector.CreateProtector(purpose)); } @@ -49,10 +47,7 @@ private IDataProtector GetInnerProtectorWithTimeLimitedPurpose() public byte[] Protect(byte[] plaintext, DateTimeOffset expiration) { - if (plaintext == null) - { - throw new ArgumentNullException(nameof(plaintext)); - } + ArgumentNullThrowHelper.ThrowIfNull(plaintext); // We prepend the expiration time (as a 64-bit UTC tick count) to the unprotected data. byte[] plaintextWithHeader = new byte[checked(8 + plaintext.Length)]; @@ -64,20 +59,14 @@ public byte[] Protect(byte[] plaintext, DateTimeOffset expiration) public byte[] Unprotect(byte[] protectedData, out DateTimeOffset expiration) { - if (protectedData == null) - { - throw new ArgumentNullException(nameof(protectedData)); - } + ArgumentNullThrowHelper.ThrowIfNull(protectedData); return UnprotectCore(protectedData, DateTimeOffset.UtcNow, out expiration); } internal byte[] UnprotectCore(byte[] protectedData, DateTimeOffset now, out DateTimeOffset expiration) { - if (protectedData == null) - { - throw new ArgumentNullException(nameof(protectedData)); - } + ArgumentNullThrowHelper.ThrowIfNull(protectedData); try { @@ -117,20 +106,14 @@ internal byte[] UnprotectCore(byte[] protectedData, DateTimeOffset now, out Date IDataProtector IDataProtectionProvider.CreateProtector(string purpose) { - if (purpose == null) - { - throw new ArgumentNullException(nameof(purpose)); - } + ArgumentNullThrowHelper.ThrowIfNull(purpose); return CreateProtector(purpose); } byte[] IDataProtector.Protect(byte[] plaintext) { - if (plaintext == null) - { - throw new ArgumentNullException(nameof(plaintext)); - } + ArgumentNullThrowHelper.ThrowIfNull(plaintext); // MaxValue essentially means 'no expiration' return Protect(plaintext, DateTimeOffset.MaxValue); @@ -138,10 +121,7 @@ byte[] IDataProtector.Protect(byte[] plaintext) byte[] IDataProtector.Unprotect(byte[] protectedData) { - if (protectedData == null) - { - throw new ArgumentNullException(nameof(protectedData)); - } + ArgumentNullThrowHelper.ThrowIfNull(protectedData); return Unprotect(protectedData, out _); } diff --git a/src/DataProtection/StackExchangeRedis/src/Microsoft.AspNetCore.DataProtection.StackExchangeRedis.csproj b/src/DataProtection/StackExchangeRedis/src/Microsoft.AspNetCore.DataProtection.StackExchangeRedis.csproj index 8e2eabffec2f..a53ec8f13207 100644 --- a/src/DataProtection/StackExchangeRedis/src/Microsoft.AspNetCore.DataProtection.StackExchangeRedis.csproj +++ b/src/DataProtection/StackExchangeRedis/src/Microsoft.AspNetCore.DataProtection.StackExchangeRedis.csproj @@ -1,4 +1,4 @@ - + Support for storing data protection keys in Redis. @@ -14,4 +14,9 @@ + + + + + diff --git a/src/DataProtection/StackExchangeRedis/src/RedisDataProtectionBuilderExtensions.cs b/src/DataProtection/StackExchangeRedis/src/RedisDataProtectionBuilderExtensions.cs index 36a1abbaf405..82a8a8c69012 100644 --- a/src/DataProtection/StackExchangeRedis/src/RedisDataProtectionBuilderExtensions.cs +++ b/src/DataProtection/StackExchangeRedis/src/RedisDataProtectionBuilderExtensions.cs @@ -1,9 +1,10 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Microsoft.AspNetCore.DataProtection.KeyManagement; using Microsoft.AspNetCore.DataProtection.StackExchangeRedis; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.DependencyInjection; using StackExchange.Redis; @@ -25,14 +26,8 @@ public static class StackExchangeRedisDataProtectionBuilderExtensions /// A reference to the after this operation has completed. public static IDataProtectionBuilder PersistKeysToStackExchangeRedis(this IDataProtectionBuilder builder, Func databaseFactory, RedisKey key) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - if (databaseFactory == null) - { - throw new ArgumentNullException(nameof(databaseFactory)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(databaseFactory); return PersistKeysToStackExchangeRedisInternal(builder, databaseFactory, key); } @@ -56,14 +51,8 @@ public static IDataProtectionBuilder PersistKeysToStackExchangeRedis(this IDataP /// A reference to the after this operation has completed. public static IDataProtectionBuilder PersistKeysToStackExchangeRedis(this IDataProtectionBuilder builder, IConnectionMultiplexer connectionMultiplexer, RedisKey key) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - if (connectionMultiplexer == null) - { - throw new ArgumentNullException(nameof(connectionMultiplexer)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(connectionMultiplexer); return PersistKeysToStackExchangeRedisInternal(builder, () => connectionMultiplexer.GetDatabase(), key); } diff --git a/src/Features/JsonPatch/src/Adapters/AdapterFactory.cs b/src/Features/JsonPatch/src/Adapters/AdapterFactory.cs index 9c716be243f7..b26352bfd8db 100644 --- a/src/Features/JsonPatch/src/Adapters/AdapterFactory.cs +++ b/src/Features/JsonPatch/src/Adapters/AdapterFactory.cs @@ -1,9 +1,10 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using Microsoft.AspNetCore.JsonPatch.Internal; +using Microsoft.AspNetCore.Shared; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; @@ -21,15 +22,8 @@ public class AdapterFactory : IAdapterFactory public virtual IAdapter Create(object target, IContractResolver contractResolver) #pragma warning restore PUB0001 { - if (target == null) - { - throw new ArgumentNullException(nameof(target)); - } - - if (contractResolver == null) - { - throw new ArgumentNullException(nameof(contractResolver)); - } + ArgumentNullThrowHelper.ThrowIfNull(target); + ArgumentNullThrowHelper.ThrowIfNull(contractResolver); var jsonContract = contractResolver.ResolveContract(target.GetType()); diff --git a/src/Features/JsonPatch/src/Adapters/ObjectAdapter.cs b/src/Features/JsonPatch/src/Adapters/ObjectAdapter.cs index 36491e800145..2391e302d2c3 100644 --- a/src/Features/JsonPatch/src/Adapters/ObjectAdapter.cs +++ b/src/Features/JsonPatch/src/Adapters/ObjectAdapter.cs @@ -1,9 +1,10 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Microsoft.AspNetCore.JsonPatch.Internal; using Microsoft.AspNetCore.JsonPatch.Operations; +using Microsoft.AspNetCore.Shared; using Newtonsoft.Json.Serialization; namespace Microsoft.AspNetCore.JsonPatch.Adapters; @@ -56,15 +57,8 @@ public ObjectAdapter( public void Add(Operation operation, object objectToApplyTo) { - if (operation == null) - { - throw new ArgumentNullException(nameof(operation)); - } - - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } + ArgumentNullThrowHelper.ThrowIfNull(operation); + ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); Add(operation.path, operation.value, objectToApplyTo, operation); } @@ -79,20 +73,9 @@ private void Add( object objectToApplyTo, Operation operation) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } - - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } - - if (operation == null) - { - throw new ArgumentNullException(nameof(operation)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); + ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); + ArgumentNullThrowHelper.ThrowIfNull(operation); var parsedPath = new ParsedPath(path); var visitor = new ObjectVisitor(parsedPath, ContractResolver, AdapterFactory); @@ -115,15 +98,8 @@ private void Add( public void Move(Operation operation, object objectToApplyTo) { - if (operation == null) - { - throw new ArgumentNullException(nameof(operation)); - } - - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } + ArgumentNullThrowHelper.ThrowIfNull(operation); + ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); // Get value at 'from' location and add that value to the 'path' location if (TryGetValue(operation.from, objectToApplyTo, operation, out var propertyValue)) @@ -141,15 +117,8 @@ public void Move(Operation operation, object objectToApplyTo) public void Remove(Operation operation, object objectToApplyTo) { - if (operation == null) - { - throw new ArgumentNullException(nameof(operation)); - } - - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } + ArgumentNullThrowHelper.ThrowIfNull(operation); + ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); Remove(operation.path, objectToApplyTo, operation); } @@ -184,15 +153,8 @@ private void Remove(string path, object objectToApplyTo, Operation operationToRe public void Replace(Operation operation, object objectToApplyTo) { - if (operation == null) - { - throw new ArgumentNullException(nameof(operation)); - } - - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } + ArgumentNullThrowHelper.ThrowIfNull(operation); + ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); var parsedPath = new ParsedPath(operation.path); var visitor = new ObjectVisitor(parsedPath, ContractResolver, AdapterFactory); @@ -215,15 +177,8 @@ public void Replace(Operation operation, object objectToApplyTo) public void Copy(Operation operation, object objectToApplyTo) { - if (operation == null) - { - throw new ArgumentNullException(nameof(operation)); - } - - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } + ArgumentNullThrowHelper.ThrowIfNull(operation); + ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); // Get value at 'from' location and add that value to the 'path' location if (TryGetValue(operation.from, objectToApplyTo, operation, out var propertyValue)) @@ -248,15 +203,8 @@ public void Copy(Operation operation, object objectToApplyTo) public void Test(Operation operation, object objectToApplyTo) { - if (operation == null) - { - throw new ArgumentNullException(nameof(operation)); - } - - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } + ArgumentNullThrowHelper.ThrowIfNull(operation); + ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); var parsedPath = new ParsedPath(operation.path); var visitor = new ObjectVisitor(parsedPath, ContractResolver, AdapterFactory); @@ -283,20 +231,9 @@ private bool TryGetValue( Operation operation, out object propertyValue) { - if (fromLocation == null) - { - throw new ArgumentNullException(nameof(fromLocation)); - } - - if (objectToGetValueFrom == null) - { - throw new ArgumentNullException(nameof(objectToGetValueFrom)); - } - - if (operation == null) - { - throw new ArgumentNullException(nameof(operation)); - } + ArgumentNullThrowHelper.ThrowIfNull(fromLocation); + ArgumentNullThrowHelper.ThrowIfNull(objectToGetValueFrom); + ArgumentNullThrowHelper.ThrowIfNull(operation); propertyValue = null; diff --git a/src/Features/JsonPatch/src/Helpers/JsonPatchProperty.cs b/src/Features/JsonPatch/src/Helpers/JsonPatchProperty.cs index d9df1228b788..74068b764f5e 100644 --- a/src/Features/JsonPatch/src/Helpers/JsonPatchProperty.cs +++ b/src/Features/JsonPatch/src/Helpers/JsonPatchProperty.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using Microsoft.AspNetCore.Shared; using Newtonsoft.Json.Serialization; namespace Microsoft.AspNetCore.JsonPatch; @@ -16,15 +17,8 @@ public class JsonPatchProperty /// public JsonPatchProperty(JsonProperty property, object parent) { - if (property == null) - { - throw new ArgumentNullException(nameof(property)); - } - - if (parent == null) - { - throw new ArgumentNullException(nameof(parent)); - } + ArgumentNullThrowHelper.ThrowIfNull(property); + ArgumentNullThrowHelper.ThrowIfNull(parent); Property = property; Parent = parent; diff --git a/src/Features/JsonPatch/src/Internal/ParsedPath.cs b/src/Features/JsonPatch/src/Internal/ParsedPath.cs index b35149f90725..44ac3f75df92 100644 --- a/src/Features/JsonPatch/src/Internal/ParsedPath.cs +++ b/src/Features/JsonPatch/src/Internal/ParsedPath.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Text; using Microsoft.AspNetCore.JsonPatch.Exceptions; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.JsonPatch.Internal; @@ -18,10 +19,7 @@ public readonly struct ParsedPath public ParsedPath(string path) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); _segments = ParsePath(path); } diff --git a/src/Features/JsonPatch/src/JsonPatchDocument.cs b/src/Features/JsonPatch/src/JsonPatchDocument.cs index 5552c7cad177..5b9152ccdb12 100644 --- a/src/Features/JsonPatch/src/JsonPatchDocument.cs +++ b/src/Features/JsonPatch/src/JsonPatchDocument.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.JsonPatch.Exceptions; using Microsoft.AspNetCore.JsonPatch.Internal; using Microsoft.AspNetCore.JsonPatch.Operations; +using Microsoft.AspNetCore.Shared; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; @@ -32,15 +33,8 @@ public JsonPatchDocument() public JsonPatchDocument(List operations, IContractResolver contractResolver) { - if (operations == null) - { - throw new ArgumentNullException(nameof(operations)); - } - - if (contractResolver == null) - { - throw new ArgumentNullException(nameof(contractResolver)); - } + ArgumentNullThrowHelper.ThrowIfNull(operations); + ArgumentNullThrowHelper.ThrowIfNull(contractResolver); Operations = operations; ContractResolver = contractResolver; @@ -55,10 +49,7 @@ public JsonPatchDocument(List operations, IContractResolver contractR /// The for chaining. public JsonPatchDocument Add(string path, object value) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation("add", PathHelpers.ValidateAndNormalizePath(path), null, value)); return this; @@ -72,10 +63,7 @@ public JsonPatchDocument Add(string path, object value) /// The for chaining. public JsonPatchDocument Remove(string path) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation("remove", PathHelpers.ValidateAndNormalizePath(path), null, null)); return this; @@ -90,10 +78,7 @@ public JsonPatchDocument Remove(string path) /// The for chaining. public JsonPatchDocument Replace(string path, object value) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation("replace", PathHelpers.ValidateAndNormalizePath(path), null, value)); return this; @@ -108,10 +93,7 @@ public JsonPatchDocument Replace(string path, object value) /// The for chaining. public JsonPatchDocument Test(string path, object value) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation("test", PathHelpers.ValidateAndNormalizePath(path), null, value)); return this; @@ -126,15 +108,8 @@ public JsonPatchDocument Test(string path, object value) /// The for chaining. public JsonPatchDocument Move(string from, string path) { - if (from == null) - { - throw new ArgumentNullException(nameof(from)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(from); + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation("move", PathHelpers.ValidateAndNormalizePath(path), PathHelpers.ValidateAndNormalizePath(from))); return this; @@ -149,15 +124,8 @@ public JsonPatchDocument Move(string from, string path) /// The for chaining. public JsonPatchDocument Copy(string from, string path) { - if (from == null) - { - throw new ArgumentNullException(nameof(from)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(from); + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation("copy", PathHelpers.ValidateAndNormalizePath(path), PathHelpers.ValidateAndNormalizePath(from))); return this; @@ -169,10 +137,7 @@ public JsonPatchDocument Copy(string from, string path) /// Object to apply the JsonPatchDocument to public void ApplyTo(object objectToApplyTo) { - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } + ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); ApplyTo(objectToApplyTo, new ObjectAdapter(ContractResolver, null, AdapterFactory.Default)); } @@ -195,15 +160,8 @@ public void ApplyTo(object objectToApplyTo, Action logErrorActio /// Action to log errors public void ApplyTo(object objectToApplyTo, IObjectAdapter adapter, Action logErrorAction) { - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } - - if (adapter == null) - { - throw new ArgumentNullException(nameof(adapter)); - } + ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); + ArgumentNullThrowHelper.ThrowIfNull(adapter); foreach (var op in Operations) { @@ -229,15 +187,8 @@ public void ApplyTo(object objectToApplyTo, IObjectAdapter adapter, ActionIObjectAdapter instance to use when applying public void ApplyTo(object objectToApplyTo, IObjectAdapter adapter) { - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } - - if (adapter == null) - { - throw new ArgumentNullException(nameof(adapter)); - } + ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); + ArgumentNullThrowHelper.ThrowIfNull(adapter); // apply each operation in order foreach (var op in Operations) diff --git a/src/Features/JsonPatch/src/JsonPatchDocumentOfT.cs b/src/Features/JsonPatch/src/JsonPatchDocumentOfT.cs index 1e23d853f424..a5340ef515c4 100644 --- a/src/Features/JsonPatch/src/JsonPatchDocumentOfT.cs +++ b/src/Features/JsonPatch/src/JsonPatchDocumentOfT.cs @@ -11,6 +11,7 @@ using Microsoft.AspNetCore.JsonPatch.Exceptions; using Microsoft.AspNetCore.JsonPatch.Internal; using Microsoft.AspNetCore.JsonPatch.Operations; +using Microsoft.AspNetCore.Shared; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; @@ -51,10 +52,7 @@ public JsonPatchDocument(List> operations, IContractResolver c /// The for chaining. public JsonPatchDocument Add(Expression> path, TProp value) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "add", @@ -78,10 +76,7 @@ public JsonPatchDocument Add( TProp value, int position) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "add", @@ -101,10 +96,7 @@ public JsonPatchDocument Add( /// The for chaining. public JsonPatchDocument Add(Expression>> path, TProp value) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "add", @@ -123,10 +115,7 @@ public JsonPatchDocument Add(Expression /// The for chaining. public JsonPatchDocument Remove(Expression> path) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation("remove", GetPath(path, null), from: null)); @@ -142,10 +131,7 @@ public JsonPatchDocument Remove(Expression> p /// The for chaining. public JsonPatchDocument Remove(Expression>> path, int position) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "remove", @@ -163,10 +149,7 @@ public JsonPatchDocument Remove(ExpressionThe for chaining. public JsonPatchDocument Remove(Expression>> path) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "remove", @@ -185,10 +168,7 @@ public JsonPatchDocument Remove(ExpressionThe for chaining. public JsonPatchDocument Replace(Expression> path, TProp value) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "replace", @@ -210,10 +190,7 @@ public JsonPatchDocument Replace(Expression> public JsonPatchDocument Replace(Expression>> path, TProp value, int position) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "replace", @@ -233,10 +210,7 @@ public JsonPatchDocument Replace(ExpressionThe for chaining. public JsonPatchDocument Replace(Expression>> path, TProp value) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "replace", @@ -256,10 +230,7 @@ public JsonPatchDocument Replace(ExpressionThe for chaining. public JsonPatchDocument Test(Expression> path, TProp value) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "test", @@ -281,10 +252,7 @@ public JsonPatchDocument Test(Expression> pat public JsonPatchDocument Test(Expression>> path, TProp value, int position) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "test", @@ -304,10 +272,7 @@ public JsonPatchDocument Test(ExpressionThe for chaining. public JsonPatchDocument Test(Expression>> path, TProp value) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "test", @@ -329,15 +294,8 @@ public JsonPatchDocument Move( Expression> from, Expression> path) { - if (from == null) - { - throw new ArgumentNullException(nameof(from)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(from); + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "move", @@ -360,15 +318,8 @@ public JsonPatchDocument Move( int positionFrom, Expression> path) { - if (from == null) - { - throw new ArgumentNullException(nameof(from)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(from); + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "move", @@ -391,15 +342,8 @@ public JsonPatchDocument Move( Expression>> path, int positionTo) { - if (from == null) - { - throw new ArgumentNullException(nameof(from)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(from); + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "move", @@ -424,15 +368,8 @@ public JsonPatchDocument Move( Expression>> path, int positionTo) { - if (from == null) - { - throw new ArgumentNullException(nameof(from)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(from); + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "move", @@ -455,15 +392,8 @@ public JsonPatchDocument Move( int positionFrom, Expression>> path) { - if (from == null) - { - throw new ArgumentNullException(nameof(from)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(from); + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "move", @@ -484,15 +414,8 @@ public JsonPatchDocument Move( Expression> from, Expression>> path) { - if (from == null) - { - throw new ArgumentNullException(nameof(from)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(from); + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "move", @@ -513,15 +436,8 @@ public JsonPatchDocument Copy( Expression> from, Expression> path) { - if (from == null) - { - throw new ArgumentNullException(nameof(from)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(from); + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "copy", @@ -544,15 +460,8 @@ public JsonPatchDocument Copy( int positionFrom, Expression> path) { - if (from == null) - { - throw new ArgumentNullException(nameof(from)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(from); + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "copy", @@ -575,15 +484,8 @@ public JsonPatchDocument Copy( Expression>> path, int positionTo) { - if (from == null) - { - throw new ArgumentNullException(nameof(from)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(from); + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "copy", @@ -608,15 +510,8 @@ public JsonPatchDocument Copy( Expression>> path, int positionTo) { - if (from == null) - { - throw new ArgumentNullException(nameof(from)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(from); + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "copy", @@ -639,15 +534,8 @@ public JsonPatchDocument Copy( int positionFrom, Expression>> path) { - if (from == null) - { - throw new ArgumentNullException(nameof(from)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(from); + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "copy", @@ -668,15 +556,8 @@ public JsonPatchDocument Copy( Expression> from, Expression>> path) { - if (from == null) - { - throw new ArgumentNullException(nameof(from)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(from); + ArgumentNullThrowHelper.ThrowIfNull(path); Operations.Add(new Operation( "copy", @@ -692,10 +573,7 @@ public JsonPatchDocument Copy( /// Object to apply the JsonPatchDocument to public void ApplyTo(TModel objectToApplyTo) { - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } + ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); ApplyTo(objectToApplyTo, new ObjectAdapter(ContractResolver, null, AdapterFactory.Default)); } @@ -718,15 +596,8 @@ public void ApplyTo(TModel objectToApplyTo, Action logErrorActio /// Action to log errors public void ApplyTo(TModel objectToApplyTo, IObjectAdapter adapter, Action logErrorAction) { - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } - - if (adapter == null) - { - throw new ArgumentNullException(nameof(adapter)); - } + ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); + ArgumentNullThrowHelper.ThrowIfNull(adapter); foreach (var op in Operations) { @@ -752,15 +623,8 @@ public void ApplyTo(TModel objectToApplyTo, IObjectAdapter adapter, ActionIObjectAdapter instance to use when applying public void ApplyTo(TModel objectToApplyTo, IObjectAdapter adapter) { - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } - - if (adapter == null) - { - throw new ArgumentNullException(nameof(adapter)); - } + ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); + ArgumentNullThrowHelper.ThrowIfNull(adapter); // apply each operation in order foreach (var op in Operations) diff --git a/src/Features/JsonPatch/src/JsonPatchError.cs b/src/Features/JsonPatch/src/JsonPatchError.cs index 3ebe5b86a743..e533d92f25fc 100644 --- a/src/Features/JsonPatch/src/JsonPatchError.cs +++ b/src/Features/JsonPatch/src/JsonPatchError.cs @@ -3,6 +3,7 @@ using System; using Microsoft.AspNetCore.JsonPatch.Operations; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.JsonPatch; @@ -22,10 +23,7 @@ public JsonPatchError( Operation operation, string errorMessage) { - if (errorMessage == null) - { - throw new ArgumentNullException(nameof(errorMessage)); - } + ArgumentNullThrowHelper.ThrowIfNull(errorMessage); AffectedObject = affectedObject; Operation = operation; diff --git a/src/Features/JsonPatch/src/Operations/Operation.cs b/src/Features/JsonPatch/src/Operations/Operation.cs index 9ce29c3a5c16..851bb554e18e 100644 --- a/src/Features/JsonPatch/src/Operations/Operation.cs +++ b/src/Features/JsonPatch/src/Operations/Operation.cs @@ -3,6 +3,7 @@ using System; using Microsoft.AspNetCore.JsonPatch.Adapters; +using Microsoft.AspNetCore.Shared; using Newtonsoft.Json; namespace Microsoft.AspNetCore.JsonPatch.Operations; @@ -29,15 +30,8 @@ public Operation(string op, string path, string from) public void Apply(object objectToApplyTo, IObjectAdapter adapter) { - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } - - if (adapter == null) - { - throw new ArgumentNullException(nameof(adapter)); - } + ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); + ArgumentNullThrowHelper.ThrowIfNull(adapter); switch (OperationType) { diff --git a/src/Features/JsonPatch/src/Operations/OperationBase.cs b/src/Features/JsonPatch/src/Operations/OperationBase.cs index 7ae24f6c7fc2..6eb9ca172b92 100644 --- a/src/Features/JsonPatch/src/Operations/OperationBase.cs +++ b/src/Features/JsonPatch/src/Operations/OperationBase.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using Microsoft.AspNetCore.Shared; using Newtonsoft.Json; namespace Microsoft.AspNetCore.JsonPatch.Operations; @@ -51,15 +52,8 @@ public OperationBase() public OperationBase(string op, string path, string from) { - if (op == null) - { - throw new ArgumentNullException(nameof(op)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(op); + ArgumentNullThrowHelper.ThrowIfNull(path); this.op = op; this.path = path; diff --git a/src/Features/JsonPatch/src/Operations/OperationOfT.cs b/src/Features/JsonPatch/src/Operations/OperationOfT.cs index 671fd64645d3..f346f68e85d3 100644 --- a/src/Features/JsonPatch/src/Operations/OperationOfT.cs +++ b/src/Features/JsonPatch/src/Operations/OperationOfT.cs @@ -4,6 +4,7 @@ using System; using Microsoft.AspNetCore.JsonPatch.Adapters; using Microsoft.AspNetCore.JsonPatch.Exceptions; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.JsonPatch.Operations; @@ -16,15 +17,8 @@ public Operation() public Operation(string op, string path, string from, object value) : base(op, path, from) { - if (op == null) - { - throw new ArgumentNullException(nameof(op)); - } - - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(op); + ArgumentNullThrowHelper.ThrowIfNull(path); this.value = value; } @@ -32,27 +26,14 @@ public Operation(string op, string path, string from, object value) public Operation(string op, string path, string from) : base(op, path, from) { - if (op == null) - { - throw new ArgumentNullException(nameof(op)); - } - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullThrowHelper.ThrowIfNull(op); + ArgumentNullThrowHelper.ThrowIfNull(path); } public void Apply(TModel objectToApplyTo, IObjectAdapter adapter) { - if (objectToApplyTo == null) - { - throw new ArgumentNullException(nameof(objectToApplyTo)); - } - - if (adapter == null) - { - throw new ArgumentNullException(nameof(adapter)); - } + ArgumentNullThrowHelper.ThrowIfNull(objectToApplyTo); + ArgumentNullThrowHelper.ThrowIfNull(adapter); switch (OperationType) { diff --git a/src/FileProviders/Embedded/src/EmbeddedFileProvider.cs b/src/FileProviders/Embedded/src/EmbeddedFileProvider.cs index ba520c63ce8b..470976082dee 100644 --- a/src/FileProviders/Embedded/src/EmbeddedFileProvider.cs +++ b/src/FileProviders/Embedded/src/EmbeddedFileProvider.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Reflection; using System.Text; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.FileProviders.Embedded; using Microsoft.Extensions.Primitives; @@ -43,10 +44,7 @@ public EmbeddedFileProvider(Assembly assembly) /// The base namespace that contains the embedded resources. public EmbeddedFileProvider(Assembly assembly, string? baseNamespace) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } + ArgumentNullThrowHelper.ThrowIfNull(assembly); _baseNamespace = string.IsNullOrEmpty(baseNamespace) ? string.Empty : baseNamespace + "."; _assembly = assembly; diff --git a/src/FileProviders/Embedded/src/EnumerableDirectoryContents.cs b/src/FileProviders/Embedded/src/EnumerableDirectoryContents.cs index d189a6100fe0..7be7b348e5e7 100644 --- a/src/FileProviders/Embedded/src/EnumerableDirectoryContents.cs +++ b/src/FileProviders/Embedded/src/EnumerableDirectoryContents.cs @@ -4,6 +4,7 @@ using System; using System.Collections; using System.Collections.Generic; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.FileProviders.Embedded; @@ -13,10 +14,7 @@ internal sealed class EnumerableDirectoryContents : IDirectoryContents public EnumerableDirectoryContents(IEnumerable entries) { - if (entries == null) - { - throw new ArgumentNullException(nameof(entries)); - } + ArgumentNullThrowHelper.ThrowIfNull(entries); _entries = entries; } diff --git a/src/FileProviders/Embedded/src/Manifest/EmbeddedFilesManifest.cs b/src/FileProviders/Embedded/src/Manifest/EmbeddedFilesManifest.cs index 8db0baa1082b..f21e34b5b0e9 100644 --- a/src/FileProviders/Embedded/src/Manifest/EmbeddedFilesManifest.cs +++ b/src/FileProviders/Embedded/src/Manifest/EmbeddedFilesManifest.cs @@ -5,6 +5,7 @@ using System.Diagnostics; using System.IO; using System.Linq; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Primitives; namespace Microsoft.Extensions.FileProviders.Embedded.Manifest; @@ -20,10 +21,7 @@ internal sealed class EmbeddedFilesManifest internal EmbeddedFilesManifest(ManifestDirectory rootDirectory) { - if (rootDirectory == null) - { - throw new ArgumentNullException(nameof(rootDirectory)); - } + ArgumentNullThrowHelper.ThrowIfNull(rootDirectory); _rootDirectory = rootDirectory; } diff --git a/src/FileProviders/Embedded/src/Manifest/ManifestDirectory.cs b/src/FileProviders/Embedded/src/Manifest/ManifestDirectory.cs index 2403e3f5e13f..36f4dc5f0559 100644 --- a/src/FileProviders/Embedded/src/Manifest/ManifestDirectory.cs +++ b/src/FileProviders/Embedded/src/Manifest/ManifestDirectory.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Primitives; namespace Microsoft.Extensions.FileProviders.Embedded.Manifest; @@ -12,10 +13,7 @@ internal class ManifestDirectory : ManifestEntry protected ManifestDirectory(string name, ManifestEntry[] children) : base(name) { - if (children == null) - { - throw new ArgumentNullException(nameof(children)); - } + ArgumentNullThrowHelper.ThrowIfNull(children); Children = children; } @@ -54,10 +52,7 @@ public static ManifestDirectory CreateDirectory(string name, ManifestEntry[] chi throw new ArgumentException($"'{nameof(name)}' must not be null, empty or whitespace.", nameof(name)); } - if (children == null) - { - throw new ArgumentNullException(nameof(children)); - } + ArgumentNullThrowHelper.ThrowIfNull(children); var result = new ManifestDirectory(name, children); ValidateChildrenAndSetParent(children, result); @@ -67,10 +62,7 @@ public static ManifestDirectory CreateDirectory(string name, ManifestEntry[] chi public static ManifestRootDirectory CreateRootDirectory(ManifestEntry[] children) { - if (children == null) - { - throw new ArgumentNullException(nameof(children)); - } + ArgumentNullThrowHelper.ThrowIfNull(children); var result = new ManifestRootDirectory(children); ValidateChildrenAndSetParent(children, result); diff --git a/src/FileProviders/Embedded/src/Manifest/ManifestDirectoryContents.cs b/src/FileProviders/Embedded/src/Manifest/ManifestDirectoryContents.cs index 29d22cd1c2d1..04ba255a947a 100644 --- a/src/FileProviders/Embedded/src/Manifest/ManifestDirectoryContents.cs +++ b/src/FileProviders/Embedded/src/Manifest/ManifestDirectoryContents.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.FileProviders.Embedded.Manifest; @@ -16,15 +17,8 @@ internal sealed class ManifestDirectoryContents : IDirectoryContents public ManifestDirectoryContents(Assembly assembly, ManifestDirectory directory, DateTimeOffset lastModified) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } - - if (directory == null) - { - throw new ArgumentNullException(nameof(directory)); - } + ArgumentNullThrowHelper.ThrowIfNull(assembly); + ArgumentNullThrowHelper.ThrowIfNull(directory); Assembly = assembly; Directory = directory; diff --git a/src/FileProviders/Embedded/src/Manifest/ManifestDirectoryInfo.cs b/src/FileProviders/Embedded/src/Manifest/ManifestDirectoryInfo.cs index edda279fe119..3267e31c785e 100644 --- a/src/FileProviders/Embedded/src/Manifest/ManifestDirectoryInfo.cs +++ b/src/FileProviders/Embedded/src/Manifest/ManifestDirectoryInfo.cs @@ -3,6 +3,7 @@ using System; using System.IO; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.FileProviders.Embedded.Manifest; @@ -10,10 +11,7 @@ internal sealed class ManifestDirectoryInfo : IFileInfo { public ManifestDirectoryInfo(ManifestDirectory directory, DateTimeOffset lastModified) { - if (directory == null) - { - throw new ArgumentNullException(nameof(directory)); - } + ArgumentNullThrowHelper.ThrowIfNull(directory); Directory = directory; LastModified = lastModified; diff --git a/src/FileProviders/Embedded/src/Manifest/ManifestFileInfo.cs b/src/FileProviders/Embedded/src/Manifest/ManifestFileInfo.cs index a3c97a0985c4..ac0bf476c2fd 100644 --- a/src/FileProviders/Embedded/src/Manifest/ManifestFileInfo.cs +++ b/src/FileProviders/Embedded/src/Manifest/ManifestFileInfo.cs @@ -4,6 +4,7 @@ using System; using System.IO; using System.Reflection; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.FileProviders.Embedded.Manifest; @@ -13,15 +14,8 @@ internal sealed class ManifestFileInfo : IFileInfo public ManifestFileInfo(Assembly assembly, ManifestFile file, DateTimeOffset lastModified) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } - - if (file == null) - { - throw new ArgumentNullException(nameof(file)); - } + ArgumentNullThrowHelper.ThrowIfNull(assembly); + ArgumentNullThrowHelper.ThrowIfNull(file); Assembly = assembly; ManifestFile = file; diff --git a/src/FileProviders/Embedded/src/Manifest/ManifestParser.cs b/src/FileProviders/Embedded/src/Manifest/ManifestParser.cs index e691fd9a02f2..0c1300e70f93 100644 --- a/src/FileProviders/Embedded/src/Manifest/ManifestParser.cs +++ b/src/FileProviders/Embedded/src/Manifest/ManifestParser.cs @@ -8,6 +8,7 @@ using System.Runtime.CompilerServices; using System.Xml; using System.Xml.Linq; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.FileProviders.Embedded.Manifest; @@ -22,15 +23,8 @@ public static EmbeddedFilesManifest Parse(Assembly assembly) public static EmbeddedFilesManifest Parse(Assembly assembly, string name) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullThrowHelper.ThrowIfNull(assembly); + ArgumentNullThrowHelper.ThrowIfNull(name); var stream = assembly.GetManifestResourceStream(name); if (stream == null) diff --git a/src/FileProviders/Embedded/src/ManifestEmbeddedFileProvider.cs b/src/FileProviders/Embedded/src/ManifestEmbeddedFileProvider.cs index f0c9c227f2e3..65afbc68332f 100644 --- a/src/FileProviders/Embedded/src/ManifestEmbeddedFileProvider.cs +++ b/src/FileProviders/Embedded/src/ManifestEmbeddedFileProvider.cs @@ -1,9 +1,10 @@ -// Licensed to the .NET Foundation under one or more agreements. +// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; using System.Reflection; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.FileProviders.Embedded.Manifest; using Microsoft.Extensions.Primitives; @@ -62,15 +63,8 @@ public ManifestEmbeddedFileProvider(Assembly assembly, string root, string manif internal ManifestEmbeddedFileProvider(Assembly assembly, EmbeddedFilesManifest manifest, DateTimeOffset lastModified) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } - - if (manifest == null) - { - throw new ArgumentNullException(nameof(manifest)); - } + ArgumentNullThrowHelper.ThrowIfNull(assembly); + ArgumentNullThrowHelper.ThrowIfNull(manifest); Assembly = assembly; Manifest = manifest; @@ -121,10 +115,7 @@ public IFileInfo GetFileInfo(string subpath) /// public IChangeToken Watch(string filter) { - if (filter == null) - { - throw new ArgumentNullException(nameof(filter)); - } + ArgumentNullThrowHelper.ThrowIfNull(filter); return NullChangeToken.Singleton; } diff --git a/src/FileProviders/Embedded/src/Microsoft.Extensions.FileProviders.Embedded.csproj b/src/FileProviders/Embedded/src/Microsoft.Extensions.FileProviders.Embedded.csproj index 01f6643e37a9..00f534dc1891 100644 --- a/src/FileProviders/Embedded/src/Microsoft.Extensions.FileProviders.Embedded.csproj +++ b/src/FileProviders/Embedded/src/Microsoft.Extensions.FileProviders.Embedded.csproj @@ -37,4 +37,9 @@ + + + + + diff --git a/src/Framework/App.Ref/src/CompatibilitySuppressions.xml b/src/Framework/App.Ref/src/CompatibilitySuppressions.xml index 053fd4d1b580..5e0a19c24b5d 100644 --- a/src/Framework/App.Ref/src/CompatibilitySuppressions.xml +++ b/src/Framework/App.Ref/src/CompatibilitySuppressions.xml @@ -1,6 +1,6 @@  - + PKV004 net7.0 diff --git a/src/Framework/App.Runtime/src/CompatibilitySuppressions.xml b/src/Framework/App.Runtime/src/CompatibilitySuppressions.xml index 36fe412dc72d..a5bc9f2a9b13 100644 --- a/src/Framework/App.Runtime/src/CompatibilitySuppressions.xml +++ b/src/Framework/App.Runtime/src/CompatibilitySuppressions.xml @@ -1,6 +1,6 @@  - + PKV0001 net7.0 diff --git a/src/HealthChecks/Abstractions/src/HealthCheckRegistration.cs b/src/HealthChecks/Abstractions/src/HealthCheckRegistration.cs index 573bd0fecd32..34ea3ce41119 100644 --- a/src/HealthChecks/Abstractions/src/HealthCheckRegistration.cs +++ b/src/HealthChecks/Abstractions/src/HealthCheckRegistration.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.Diagnostics.HealthChecks; @@ -54,15 +55,8 @@ public HealthCheckRegistration(string name, IHealthCheck instance, HealthStatus? /// An optional representing the timeout of the check. public HealthCheckRegistration(string name, IHealthCheck instance, HealthStatus? failureStatus, IEnumerable? tags, TimeSpan? timeout) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } + ArgumentNullThrowHelper.ThrowIfNull(name); + ArgumentNullThrowHelper.ThrowIfNull(instance); if (timeout <= TimeSpan.Zero && timeout != System.Threading.Timeout.InfiniteTimeSpan) { @@ -113,15 +107,8 @@ public HealthCheckRegistration( IEnumerable? tags, TimeSpan? timeout) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullThrowHelper.ThrowIfNull(name); + ArgumentNullThrowHelper.ThrowIfNull(factory); if (timeout <= TimeSpan.Zero && timeout != System.Threading.Timeout.InfiniteTimeSpan) { @@ -143,10 +130,7 @@ public Func Factory get => _factory; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullThrowHelper.ThrowIfNull(value); _factory = value; } @@ -182,10 +166,7 @@ public string Name get => _name; set { - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullThrowHelper.ThrowIfNull(value); _name = value; } diff --git a/src/HealthChecks/Abstractions/src/Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions.csproj b/src/HealthChecks/Abstractions/src/Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions.csproj index bcd1333e1e9f..6d81e7629eb9 100644 --- a/src/HealthChecks/Abstractions/src/Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions.csproj +++ b/src/HealthChecks/Abstractions/src/Microsoft.Extensions.Diagnostics.HealthChecks.Abstractions.csproj @@ -1,4 +1,4 @@ - + Abstractions for defining health checks in .NET applications @@ -15,4 +15,9 @@ Microsoft.Extensions.Diagnostics.HealthChecks.IHealthCheck true + + + + + diff --git a/src/HealthChecks/HealthChecks/src/DependencyInjection/HealthChecksBuilder.cs b/src/HealthChecks/HealthChecks/src/DependencyInjection/HealthChecksBuilder.cs index b0e0b782572f..e8b57bcfeab4 100644 --- a/src/HealthChecks/HealthChecks/src/DependencyInjection/HealthChecksBuilder.cs +++ b/src/HealthChecks/HealthChecks/src/DependencyInjection/HealthChecksBuilder.cs @@ -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.Diagnostics.HealthChecks; namespace Microsoft.Extensions.DependencyInjection; @@ -17,10 +18,7 @@ public HealthChecksBuilder(IServiceCollection services) public IHealthChecksBuilder Add(HealthCheckRegistration registration) { - if (registration == null) - { - throw new ArgumentNullException(nameof(registration)); - } + ArgumentNullThrowHelper.ThrowIfNull(registration); Services.Configure(options => { diff --git a/src/HealthChecks/HealthChecks/src/DependencyInjection/HealthChecksBuilderAddCheckExtensions.cs b/src/HealthChecks/HealthChecks/src/DependencyInjection/HealthChecksBuilderAddCheckExtensions.cs index 44f2436f1d00..0ab960a68fe0 100644 --- a/src/HealthChecks/HealthChecks/src/DependencyInjection/HealthChecksBuilderAddCheckExtensions.cs +++ b/src/HealthChecks/HealthChecks/src/DependencyInjection/HealthChecksBuilderAddCheckExtensions.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Diagnostics.HealthChecks; namespace Microsoft.Extensions.DependencyInjection; @@ -58,20 +59,9 @@ public static IHealthChecksBuilder AddCheck( IEnumerable? tags = null, TimeSpan? timeout = null) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (instance == null) - { - throw new ArgumentNullException(nameof(instance)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(name); + ArgumentNullThrowHelper.ThrowIfNull(instance); return builder.Add(new HealthCheckRegistration(name, instance, failureStatus, tags, timeout)); } @@ -130,15 +120,8 @@ public static IHealthChecksBuilder AddCheck( IEnumerable? tags = null, TimeSpan? timeout = null) where T : class, IHealthCheck { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(name); return builder.Add(new HealthCheckRegistration(name, GetServiceOrCreateInstance, failureStatus, tags, timeout)); @@ -167,15 +150,8 @@ public static IHealthChecksBuilder AddTypeActivatedCheck< [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>( this IHealthChecksBuilder builder, string name, params object[] args) where T : class, IHealthCheck { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(name); return AddTypeActivatedCheck(builder, name, failureStatus: null, tags: null, args); } @@ -203,15 +179,8 @@ public static IHealthChecksBuilder AddTypeActivatedCheck< HealthStatus? failureStatus, params object[] args) where T : class, IHealthCheck { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(name); return AddTypeActivatedCheck(builder, name, failureStatus, tags: null, args); } @@ -241,15 +210,8 @@ public static IHealthChecksBuilder AddTypeActivatedCheck< IEnumerable? tags, params object[] args) where T : class, IHealthCheck { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(name); return builder.Add(new HealthCheckRegistration(name, CreateInstance, failureStatus, tags)); @@ -286,15 +248,8 @@ public static IHealthChecksBuilder AddTypeActivatedCheck< TimeSpan timeout, params object[] args) where T : class, IHealthCheck { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(name); return builder.Add(new HealthCheckRegistration(name, CreateInstance, failureStatus, tags, timeout)); diff --git a/src/HealthChecks/HealthChecks/src/DependencyInjection/HealthChecksBuilderDelegateExtensions.cs b/src/HealthChecks/HealthChecks/src/DependencyInjection/HealthChecksBuilderDelegateExtensions.cs index 441e70152dac..b8fc99359b1d 100644 --- a/src/HealthChecks/HealthChecks/src/DependencyInjection/HealthChecksBuilderDelegateExtensions.cs +++ b/src/HealthChecks/HealthChecks/src/DependencyInjection/HealthChecksBuilderDelegateExtensions.cs @@ -6,6 +6,7 @@ using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Diagnostics.HealthChecks; namespace Microsoft.Extensions.DependencyInjection; @@ -50,20 +51,9 @@ public static IHealthChecksBuilder AddCheck( IEnumerable? tags = null, TimeSpan? timeout = default) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (check == null) - { - throw new ArgumentNullException(nameof(check)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(name); + ArgumentNullThrowHelper.ThrowIfNull(check); var instance = new DelegateHealthCheck((ct) => Task.FromResult(check())); return builder.Add(new HealthCheckRegistration(name, instance, failureStatus: null, tags, timeout)); @@ -104,20 +94,9 @@ public static IHealthChecksBuilder AddCheck( IEnumerable? tags = null, TimeSpan? timeout = default) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (check == null) - { - throw new ArgumentNullException(nameof(check)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(name); + ArgumentNullThrowHelper.ThrowIfNull(check); var instance = new DelegateHealthCheck((ct) => Task.FromResult(check(ct))); return builder.Add(new HealthCheckRegistration(name, instance, failureStatus: null, tags, timeout)); @@ -158,20 +137,9 @@ public static IHealthChecksBuilder AddAsyncCheck( IEnumerable? tags = null, TimeSpan? timeout = default) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (check == null) - { - throw new ArgumentNullException(nameof(check)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(name); + ArgumentNullThrowHelper.ThrowIfNull(check); var instance = new DelegateHealthCheck((ct) => check()); return builder.Add(new HealthCheckRegistration(name, instance, failureStatus: null, tags, timeout)); @@ -212,20 +180,9 @@ public static IHealthChecksBuilder AddAsyncCheck( IEnumerable? tags = null, TimeSpan? timeout = default) { - if (builder == null) - { - throw new ArgumentNullException(nameof(builder)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (check == null) - { - throw new ArgumentNullException(nameof(check)); - } + ArgumentNullThrowHelper.ThrowIfNull(builder); + ArgumentNullThrowHelper.ThrowIfNull(name); + ArgumentNullThrowHelper.ThrowIfNull(check); var instance = new DelegateHealthCheck((ct) => check(ct)); return builder.Add(new HealthCheckRegistration(name, instance, failureStatus: null, tags, timeout)); diff --git a/src/HealthChecks/HealthChecks/src/HealthCheckPublisherHostedService.cs b/src/HealthChecks/HealthChecks/src/HealthCheckPublisherHostedService.cs index f96b2dbf324c..ea0cbe5de69a 100644 --- a/src/HealthChecks/HealthChecks/src/HealthCheckPublisherHostedService.cs +++ b/src/HealthChecks/HealthChecks/src/HealthCheckPublisherHostedService.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Internal; using Microsoft.Extensions.Logging; @@ -30,25 +31,10 @@ public HealthCheckPublisherHostedService( ILogger logger, IEnumerable publishers) { - if (healthCheckService == null) - { - throw new ArgumentNullException(nameof(healthCheckService)); - } - - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } - - if (publishers == null) - { - throw new ArgumentNullException(nameof(publishers)); - } + ArgumentNullThrowHelper.ThrowIfNull(healthCheckService); + ArgumentNullThrowHelper.ThrowIfNull(options); + ArgumentNullThrowHelper.ThrowIfNull(logger); + ArgumentNullThrowHelper.ThrowIfNull(publishers); _healthCheckService = healthCheckService; _options = options; diff --git a/src/Identity/Extensions.Core/src/Microsoft.Extensions.Identity.Core.csproj b/src/Identity/Extensions.Core/src/Microsoft.Extensions.Identity.Core.csproj index 87e7f976b40d..226822a67031 100644 --- a/src/Identity/Extensions.Core/src/Microsoft.Extensions.Identity.Core.csproj +++ b/src/Identity/Extensions.Core/src/Microsoft.Extensions.Identity.Core.csproj @@ -18,6 +18,7 @@ + diff --git a/src/Identity/Extensions.Core/src/PasswordHasher.cs b/src/Identity/Extensions.Core/src/PasswordHasher.cs index 9164e1ef70e6..cdd9a1ff3cec 100644 --- a/src/Identity/Extensions.Core/src/PasswordHasher.cs +++ b/src/Identity/Extensions.Core/src/PasswordHasher.cs @@ -5,6 +5,7 @@ using System.Runtime.CompilerServices; using System.Security.Cryptography; using Microsoft.AspNetCore.Cryptography.KeyDerivation; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Identity.Core; using Microsoft.Extensions.Options; @@ -97,10 +98,7 @@ private static bool ByteArraysEqual(byte[] a, byte[] b) /// A hashed representation of the supplied for the specified . public virtual string HashPassword(TUser user, string password) { - if (password == null) - { - throw new ArgumentNullException(nameof(password)); - } + ArgumentNullThrowHelper.ThrowIfNull(password); if (_compatibilityMode == PasswordHasherCompatibilityMode.IdentityV2) { @@ -167,14 +165,8 @@ private static byte[] HashPasswordV3(string password, RandomNumberGenerator rng, /// Implementations of this method should be time consistent. public virtual PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword, string providedPassword) { - if (hashedPassword == null) - { - throw new ArgumentNullException(nameof(hashedPassword)); - } - if (providedPassword == null) - { - throw new ArgumentNullException(nameof(providedPassword)); - } + ArgumentNullThrowHelper.ThrowIfNull(hashedPassword); + ArgumentNullThrowHelper.ThrowIfNull(providedPassword); byte[] decodedHashedPassword = Convert.FromBase64String(hashedPassword); diff --git a/src/Identity/Extensions.Core/src/PasswordValidator.cs b/src/Identity/Extensions.Core/src/PasswordValidator.cs index 3675bebb66b8..719918fb435d 100644 --- a/src/Identity/Extensions.Core/src/PasswordValidator.cs +++ b/src/Identity/Extensions.Core/src/PasswordValidator.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Identity; @@ -38,14 +39,8 @@ public PasswordValidator(IdentityErrorDescriber? errors = null) /// The task object representing the asynchronous operation. public virtual Task ValidateAsync(UserManager manager, TUser user, string? password) { - if (password == null) - { - throw new ArgumentNullException(nameof(password)); - } - if (manager == null) - { - throw new ArgumentNullException(nameof(manager)); - } + ArgumentNullThrowHelper.ThrowIfNull(password); + ArgumentNullThrowHelper.ThrowIfNull(manager); List? errors = null; var options = manager.Options.Password; if (string.IsNullOrWhiteSpace(password) || password.Length < options.RequiredLength) diff --git a/src/Identity/Extensions.Core/src/PhoneNumberTokenProvider.cs b/src/Identity/Extensions.Core/src/PhoneNumberTokenProvider.cs index 6de45d6a6080..baf3297f9529 100644 --- a/src/Identity/Extensions.Core/src/PhoneNumberTokenProvider.cs +++ b/src/Identity/Extensions.Core/src/PhoneNumberTokenProvider.cs @@ -3,6 +3,7 @@ using System; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Identity; @@ -28,10 +29,7 @@ public class PhoneNumberTokenProvider : TotpSecurityStampBasedTokenProvid /// public override async Task CanGenerateTwoFactorTokenAsync(UserManager manager, TUser user) { - if (manager == null) - { - throw new ArgumentNullException(nameof(manager)); - } + ArgumentNullThrowHelper.ThrowIfNull(manager); var phoneNumber = await manager.GetPhoneNumberAsync(user).ConfigureAwait(false); @@ -50,10 +48,7 @@ public override async Task CanGenerateTwoFactorTokenAsync(UserManager public override async Task GetUserModifierAsync(string purpose, UserManager manager, TUser user) { - if (manager == null) - { - throw new ArgumentNullException(nameof(manager)); - } + ArgumentNullThrowHelper.ThrowIfNull(manager); var phoneNumber = await manager.GetPhoneNumberAsync(user).ConfigureAwait(false); diff --git a/src/Identity/Extensions.Core/src/PrincipalExtensions.cs b/src/Identity/Extensions.Core/src/PrincipalExtensions.cs index d9d5572310f2..629264046121 100644 --- a/src/Identity/Extensions.Core/src/PrincipalExtensions.cs +++ b/src/Identity/Extensions.Core/src/PrincipalExtensions.cs @@ -1,6 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using Microsoft.AspNetCore.Shared; + namespace System.Security.Claims; /// @@ -16,10 +18,7 @@ public static class PrincipalExtensions /// The value of the first instance of the specified claim type, or null if the claim is not present. public static string? FindFirstValue(this ClaimsPrincipal principal, string claimType) { - if (principal == null) - { - throw new ArgumentNullException(nameof(principal)); - } + ArgumentNullThrowHelper.ThrowIfNull(principal); var claim = principal.FindFirst(claimType); return claim?.Value; } diff --git a/src/Identity/Extensions.Core/src/RoleManager.cs b/src/Identity/Extensions.Core/src/RoleManager.cs index 82dc0010ba19..c355c646f1ab 100644 --- a/src/Identity/Extensions.Core/src/RoleManager.cs +++ b/src/Identity/Extensions.Core/src/RoleManager.cs @@ -8,6 +8,7 @@ using System.Security.Claims; using System.Threading; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Identity.Core; using Microsoft.Extensions.Logging; @@ -40,10 +41,7 @@ public RoleManager(IRoleStore store, IdentityErrorDescriber errors, ILogger> logger) { - if (store == null) - { - throw new ArgumentNullException(nameof(store)); - } + ArgumentNullThrowHelper.ThrowIfNull(store); Store = store; KeyNormalizer = keyNormalizer; ErrorDescriber = errors; @@ -157,10 +155,7 @@ public virtual bool SupportsRoleClaims public virtual async Task CreateAsync(TRole role) { ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullThrowHelper.ThrowIfNull(role); var result = await ValidateRoleAsync(role).ConfigureAwait(false); if (!result.Succeeded) { @@ -194,10 +189,7 @@ public virtual async Task UpdateNormalizedRoleNameAsync(TRole role) public virtual Task UpdateAsync(TRole role) { ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullThrowHelper.ThrowIfNull(role); return UpdateRoleAsync(role); } @@ -212,10 +204,7 @@ public virtual Task UpdateAsync(TRole role) public virtual Task DeleteAsync(TRole role) { ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullThrowHelper.ThrowIfNull(role); return Store.DeleteAsync(role, CancellationToken); } @@ -230,10 +219,7 @@ public virtual Task DeleteAsync(TRole role) public virtual async Task RoleExistsAsync(string roleName) { ThrowIfDisposed(); - if (roleName == null) - { - throw new ArgumentNullException(nameof(roleName)); - } + ArgumentNullThrowHelper.ThrowIfNull(roleName); return await FindByNameAsync(roleName).ConfigureAwait(false) != null; } @@ -320,10 +306,7 @@ public virtual Task GetRoleIdAsync(TRole role) public virtual Task FindByNameAsync(string roleName) { ThrowIfDisposed(); - if (roleName == null) - { - throw new ArgumentNullException(nameof(roleName)); - } + ArgumentNullThrowHelper.ThrowIfNull(roleName); return Store.FindByNameAsync(NormalizeKey(roleName), CancellationToken); } @@ -341,14 +324,8 @@ public virtual async Task AddClaimAsync(TRole role, Claim claim) { ThrowIfDisposed(); var claimStore = GetClaimStore(); - if (claim == null) - { - throw new ArgumentNullException(nameof(claim)); - } - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullThrowHelper.ThrowIfNull(claim); + ArgumentNullThrowHelper.ThrowIfNull(role); await claimStore.AddClaimAsync(role, claim, CancellationToken).ConfigureAwait(false); return await UpdateRoleAsync(role).ConfigureAwait(false); @@ -367,10 +344,7 @@ public virtual async Task RemoveClaimAsync(TRole role, Claim cla { ThrowIfDisposed(); var claimStore = GetClaimStore(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullThrowHelper.ThrowIfNull(role); await claimStore.RemoveClaimAsync(role, claim, CancellationToken).ConfigureAwait(false); return await UpdateRoleAsync(role).ConfigureAwait(false); @@ -388,10 +362,7 @@ public virtual Task> GetClaimsAsync(TRole role) { ThrowIfDisposed(); var claimStore = GetClaimStore(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullThrowHelper.ThrowIfNull(role); return claimStore.GetClaimsAsync(role, CancellationToken); } @@ -478,9 +449,6 @@ private IRoleClaimStore GetClaimStore() /// protected void ThrowIfDisposed() { - if (_disposed) - { - throw new ObjectDisposedException(GetType().Name); - } + ObjectDisposedThrowHelper.ThrowIf(_disposed, this); } } diff --git a/src/Identity/Extensions.Core/src/RoleValidator.cs b/src/Identity/Extensions.Core/src/RoleValidator.cs index 26e44558b8c4..740118015b50 100644 --- a/src/Identity/Extensions.Core/src/RoleValidator.cs +++ b/src/Identity/Extensions.Core/src/RoleValidator.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Identity; @@ -32,14 +33,8 @@ public RoleValidator(IdentityErrorDescriber? errors = null) /// A that represents the of the asynchronous validation. public virtual async Task ValidateAsync(RoleManager manager, TRole role) { - if (manager == null) - { - throw new ArgumentNullException(nameof(manager)); - } - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullThrowHelper.ThrowIfNull(manager); + ArgumentNullThrowHelper.ThrowIfNull(role); var errors = await ValidateRoleName(manager, role).ConfigureAwait(false); if (errors?.Count > 0) { diff --git a/src/Identity/Extensions.Core/src/TotpSecurityStampBasedTokenProvider.cs b/src/Identity/Extensions.Core/src/TotpSecurityStampBasedTokenProvider.cs index 557a2d8b9cac..3ab4bc5b0c51 100644 --- a/src/Identity/Extensions.Core/src/TotpSecurityStampBasedTokenProvider.cs +++ b/src/Identity/Extensions.Core/src/TotpSecurityStampBasedTokenProvider.cs @@ -4,6 +4,7 @@ using System; using System.Globalization; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Identity; @@ -35,10 +36,7 @@ public abstract class TotpSecurityStampBasedTokenProvider : IUserTwoFacto /// public virtual async Task GenerateAsync(string purpose, UserManager manager, TUser user) { - if (manager == null) - { - throw new ArgumentNullException(nameof(manager)); - } + ArgumentNullThrowHelper.ThrowIfNull(manager); var token = await manager.CreateSecurityTokenAsync(user).ConfigureAwait(false); var modifier = await GetUserModifierAsync(purpose, manager, user).ConfigureAwait(false); @@ -60,10 +58,7 @@ public virtual async Task GenerateAsync(string purpose, UserManager public virtual async Task ValidateAsync(string purpose, string token, UserManager manager, TUser user) { - if (manager == null) - { - throw new ArgumentNullException(nameof(manager)); - } + ArgumentNullThrowHelper.ThrowIfNull(manager); int code; if (!int.TryParse(token, out code)) { @@ -87,10 +82,7 @@ public virtual async Task ValidateAsync(string purpose, string token, User /// public virtual async Task GetUserModifierAsync(string purpose, UserManager manager, TUser user) { - if (manager == null) - { - throw new ArgumentNullException(nameof(manager)); - } + ArgumentNullThrowHelper.ThrowIfNull(manager); var userId = await manager.GetUserIdAsync(user).ConfigureAwait(false); return $"Totp:{purpose}:{userId}"; diff --git a/src/Identity/Extensions.Core/src/UserClaimsPrincipalFactory.cs b/src/Identity/Extensions.Core/src/UserClaimsPrincipalFactory.cs index 223815b351d2..f25cd3c0f7b4 100644 --- a/src/Identity/Extensions.Core/src/UserClaimsPrincipalFactory.cs +++ b/src/Identity/Extensions.Core/src/UserClaimsPrincipalFactory.cs @@ -4,6 +4,7 @@ using System; using System.Security.Claims; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Identity; @@ -24,10 +25,7 @@ public UserClaimsPrincipalFactory( UserManager userManager, IOptions optionsAccessor) { - if (userManager == null) - { - throw new ArgumentNullException(nameof(userManager)); - } + ArgumentNullThrowHelper.ThrowIfNull(userManager); if (optionsAccessor == null || optionsAccessor.Value == null) { throw new ArgumentNullException(nameof(optionsAccessor)); @@ -59,10 +57,7 @@ public UserClaimsPrincipalFactory( /// The that represents the asynchronous creation operation, containing the created . public virtual async Task CreateAsync(TUser user) { - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); var id = await GenerateClaimsAsync(user).ConfigureAwait(false); return new ClaimsPrincipal(id); } @@ -120,10 +115,7 @@ public class UserClaimsPrincipalFactory : UserClaimsPrincipalFacto public UserClaimsPrincipalFactory(UserManager userManager, RoleManager roleManager, IOptions options) : base(userManager, options) { - if (roleManager == null) - { - throw new ArgumentNullException(nameof(roleManager)); - } + ArgumentNullThrowHelper.ThrowIfNull(roleManager); RoleManager = roleManager; } diff --git a/src/Identity/Extensions.Core/src/UserManager.cs b/src/Identity/Extensions.Core/src/UserManager.cs index 668dc024ac0f..427f45ee5ea5 100644 --- a/src/Identity/Extensions.Core/src/UserManager.cs +++ b/src/Identity/Extensions.Core/src/UserManager.cs @@ -11,6 +11,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Identity.Core; using Microsoft.Extensions.Logging; @@ -75,10 +76,7 @@ public UserManager(IUserStore store, IServiceProvider services, ILogger> logger) { - if (store == null) - { - throw new ArgumentNullException(nameof(store)); - } + ArgumentNullThrowHelper.ThrowIfNull(store); Store = store; Options = optionsAccessor?.Value ?? new IdentityOptions(); PasswordHasher = passwordHasher; @@ -404,10 +402,7 @@ public void Dispose() /// The Name claim is identified by . public virtual string? GetUserName(ClaimsPrincipal principal) { - if (principal == null) - { - throw new ArgumentNullException(nameof(principal)); - } + ArgumentNullThrowHelper.ThrowIfNull(principal); return principal.FindFirstValue(Options.ClaimsIdentity.UserNameClaimType); } @@ -419,10 +414,7 @@ public void Dispose() /// The User ID claim is identified by . public virtual string? GetUserId(ClaimsPrincipal principal) { - if (principal == null) - { - throw new ArgumentNullException(nameof(principal)); - } + ArgumentNullThrowHelper.ThrowIfNull(principal); return principal.FindFirstValue(Options.ClaimsIdentity.UserIdClaimType); } @@ -435,10 +427,7 @@ public void Dispose() /// the principal or null public virtual Task GetUserAsync(ClaimsPrincipal principal) { - if (principal == null) - { - throw new ArgumentNullException(nameof(principal)); - } + ArgumentNullThrowHelper.ThrowIfNull(principal); var id = GetUserId(principal); return id == null ? Task.FromResult(null) : FindByIdAsync(id); } @@ -495,10 +484,7 @@ public virtual async Task CreateAsync(TUser user) public virtual Task UpdateAsync(TUser user) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return UpdateUserAsync(user); } @@ -514,10 +500,7 @@ public virtual Task UpdateAsync(TUser user) public virtual Task DeleteAsync(TUser user) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return Store.DeleteAsync(user, CancellationToken); } @@ -545,10 +528,7 @@ public virtual Task DeleteAsync(TUser user) public virtual async Task FindByNameAsync(string userName) { ThrowIfDisposed(); - if (userName == null) - { - throw new ArgumentNullException(nameof(userName)); - } + ArgumentNullThrowHelper.ThrowIfNull(userName); userName = NormalizeName(userName); var user = await Store.FindByNameAsync(userName, CancellationToken).ConfigureAwait(false); @@ -588,14 +568,8 @@ public virtual async Task CreateAsync(TUser user, string passwor { ThrowIfDisposed(); var passwordStore = GetPasswordStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (password == null) - { - throw new ArgumentNullException(nameof(password)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); + ArgumentNullThrowHelper.ThrowIfNull(password); var result = await UpdatePasswordHash(passwordStore, user, password).ConfigureAwait(false); if (!result.Succeeded) { @@ -654,10 +628,7 @@ public virtual async Task UpdateNormalizedUserNameAsync(TUser user) public virtual async Task GetUserNameAsync(TUser user) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return await Store.GetUserNameAsync(user, CancellationToken).ConfigureAwait(false); } @@ -670,10 +641,7 @@ public virtual async Task UpdateNormalizedUserNameAsync(TUser user) public virtual async Task SetUserNameAsync(TUser user, string? userName) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); await Store.SetUserNameAsync(user, userName, CancellationToken).ConfigureAwait(false); await UpdateSecurityStampInternal(user).ConfigureAwait(false); @@ -736,10 +704,7 @@ public virtual Task HasPasswordAsync(TUser user) { ThrowIfDisposed(); var passwordStore = GetPasswordStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return passwordStore.HasPasswordAsync(user, CancellationToken); } @@ -758,10 +723,7 @@ public virtual async Task AddPasswordAsync(TUser user, string pa { ThrowIfDisposed(); var passwordStore = GetPasswordStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); var hash = await passwordStore.GetPasswordHashAsync(user, CancellationToken).ConfigureAwait(false); if (hash != null) @@ -792,10 +754,7 @@ public virtual async Task ChangePasswordAsync(TUser user, string { ThrowIfDisposed(); var passwordStore = GetPasswordStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); if (await VerifyPasswordAsync(passwordStore, user, currentPassword).ConfigureAwait(false) != PasswordVerificationResult.Failed) { @@ -822,10 +781,7 @@ public virtual async Task RemovePasswordAsync(TUser user) { ThrowIfDisposed(); var passwordStore = GetPasswordStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); await UpdatePasswordHash(passwordStore, user, null, validatePassword: false).ConfigureAwait(false); return await UpdateUserAsync(user).ConfigureAwait(false); @@ -860,10 +816,7 @@ public virtual async Task GetSecurityStampAsync(TUser user) { ThrowIfDisposed(); var securityStore = GetSecurityStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); var stamp = await securityStore.GetSecurityStampAsync(user, CancellationToken).ConfigureAwait(false); if (stamp == null) { @@ -888,10 +841,7 @@ public virtual async Task UpdateSecurityStampAsync(TUser user) { ThrowIfDisposed(); GetSecurityStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); await UpdateSecurityStampInternal(user).ConfigureAwait(false); return await UpdateUserAsync(user).ConfigureAwait(false); @@ -924,10 +874,7 @@ public virtual Task GeneratePasswordResetTokenAsync(TUser user) public virtual async Task ResetPasswordAsync(TUser user, string token, string newPassword) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); // Make sure the token is valid and the stamp matches if (!await VerifyUserTokenAsync(user, Options.Tokens.PasswordResetTokenProvider, ResetPasswordTokenPurpose, token).ConfigureAwait(false)) @@ -954,14 +901,8 @@ public virtual async Task ResetPasswordAsync(TUser user, string { ThrowIfDisposed(); var loginStore = GetLoginStore(); - if (loginProvider == null) - { - throw new ArgumentNullException(nameof(loginProvider)); - } - if (providerKey == null) - { - throw new ArgumentNullException(nameof(providerKey)); - } + ArgumentNullThrowHelper.ThrowIfNull(loginProvider); + ArgumentNullThrowHelper.ThrowIfNull(providerKey); return loginStore.FindByLoginAsync(loginProvider, providerKey, CancellationToken); } @@ -980,18 +921,9 @@ public virtual async Task RemoveLoginAsync(TUser user, string lo { ThrowIfDisposed(); var loginStore = GetLoginStore(); - if (loginProvider == null) - { - throw new ArgumentNullException(nameof(loginProvider)); - } - if (providerKey == null) - { - throw new ArgumentNullException(nameof(providerKey)); - } - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(loginProvider); + ArgumentNullThrowHelper.ThrowIfNull(providerKey); + ArgumentNullThrowHelper.ThrowIfNull(user); await loginStore.RemoveLoginAsync(user, loginProvider, providerKey, CancellationToken).ConfigureAwait(false); await UpdateSecurityStampInternal(user).ConfigureAwait(false); @@ -1011,14 +943,8 @@ public virtual async Task AddLoginAsync(TUser user, UserLoginInf { ThrowIfDisposed(); var loginStore = GetLoginStore(); - if (login == null) - { - throw new ArgumentNullException(nameof(login)); - } - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(login); + ArgumentNullThrowHelper.ThrowIfNull(user); var existingUser = await FindByLoginAsync(login.LoginProvider, login.ProviderKey).ConfigureAwait(false); if (existingUser != null) @@ -1041,10 +967,7 @@ public virtual async Task> GetLoginsAsync(TUser user) { ThrowIfDisposed(); var loginStore = GetLoginStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return await loginStore.GetLoginsAsync(user, CancellationToken).ConfigureAwait(false); } @@ -1061,14 +984,8 @@ public virtual Task AddClaimAsync(TUser user, Claim claim) { ThrowIfDisposed(); GetClaimStore(); - if (claim == null) - { - throw new ArgumentNullException(nameof(claim)); - } - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(claim); + ArgumentNullThrowHelper.ThrowIfNull(user); return AddClaimsAsync(user, new Claim[] { claim }); } @@ -1085,14 +1002,8 @@ public virtual async Task AddClaimsAsync(TUser user, IEnumerable { ThrowIfDisposed(); var claimStore = GetClaimStore(); - if (claims == null) - { - throw new ArgumentNullException(nameof(claims)); - } - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(claims); + ArgumentNullThrowHelper.ThrowIfNull(user); await claimStore.AddClaimsAsync(user, claims, CancellationToken).ConfigureAwait(false); return await UpdateUserAsync(user).ConfigureAwait(false); @@ -1112,18 +1023,9 @@ public virtual async Task ReplaceClaimAsync(TUser user, Claim cl { ThrowIfDisposed(); var claimStore = GetClaimStore(); - if (claim == null) - { - throw new ArgumentNullException(nameof(claim)); - } - if (newClaim == null) - { - throw new ArgumentNullException(nameof(newClaim)); - } - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(claim); + ArgumentNullThrowHelper.ThrowIfNull(newClaim); + ArgumentNullThrowHelper.ThrowIfNull(user); await claimStore.ReplaceClaimAsync(user, claim, newClaim, CancellationToken).ConfigureAwait(false); return await UpdateUserAsync(user).ConfigureAwait(false); @@ -1142,14 +1044,8 @@ public virtual Task RemoveClaimAsync(TUser user, Claim claim) { ThrowIfDisposed(); GetClaimStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (claim == null) - { - throw new ArgumentNullException(nameof(claim)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); + ArgumentNullThrowHelper.ThrowIfNull(claim); return RemoveClaimsAsync(user, new Claim[] { claim }); } @@ -1166,14 +1062,8 @@ public virtual async Task RemoveClaimsAsync(TUser user, IEnumera { ThrowIfDisposed(); var claimStore = GetClaimStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (claims == null) - { - throw new ArgumentNullException(nameof(claims)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); + ArgumentNullThrowHelper.ThrowIfNull(claims); await claimStore.RemoveClaimsAsync(user, claims, CancellationToken).ConfigureAwait(false); return await UpdateUserAsync(user).ConfigureAwait(false); @@ -1190,10 +1080,7 @@ public virtual async Task> GetClaimsAsync(TUser user) { ThrowIfDisposed(); var claimStore = GetClaimStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return await claimStore.GetClaimsAsync(user, CancellationToken).ConfigureAwait(false); } @@ -1210,10 +1097,7 @@ public virtual async Task AddToRoleAsync(TUser user, string role { ThrowIfDisposed(); var userRoleStore = GetUserRoleStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); var normalizedRole = NormalizeName(role); if (await userRoleStore.IsInRoleAsync(user, normalizedRole, CancellationToken).ConfigureAwait(false)) @@ -1237,14 +1121,8 @@ public virtual async Task AddToRolesAsync(TUser user, IEnumerabl { ThrowIfDisposed(); var userRoleStore = GetUserRoleStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (roles == null) - { - throw new ArgumentNullException(nameof(roles)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); + ArgumentNullThrowHelper.ThrowIfNull(roles); foreach (var role in roles.Distinct()) { @@ -1271,10 +1149,7 @@ public virtual async Task RemoveFromRoleAsync(TUser user, string { ThrowIfDisposed(); var userRoleStore = GetUserRoleStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); var normalizedRole = NormalizeName(role); if (!await userRoleStore.IsInRoleAsync(user, normalizedRole, CancellationToken).ConfigureAwait(false)) @@ -1310,14 +1185,8 @@ public virtual async Task RemoveFromRolesAsync(TUser user, IEnum { ThrowIfDisposed(); var userRoleStore = GetUserRoleStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (roles == null) - { - throw new ArgumentNullException(nameof(roles)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); + ArgumentNullThrowHelper.ThrowIfNull(roles); foreach (var role in roles) { @@ -1340,10 +1209,7 @@ public virtual async Task> GetRolesAsync(TUser user) { ThrowIfDisposed(); var userRoleStore = GetUserRoleStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return await userRoleStore.GetRolesAsync(user, CancellationToken).ConfigureAwait(false); } @@ -1360,10 +1226,7 @@ public virtual async Task IsInRoleAsync(TUser user, string role) { ThrowIfDisposed(); var userRoleStore = GetUserRoleStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return await userRoleStore.IsInRoleAsync(user, NormalizeName(role), CancellationToken).ConfigureAwait(false); } @@ -1376,10 +1239,7 @@ public virtual async Task IsInRoleAsync(TUser user, string role) { ThrowIfDisposed(); var store = GetEmailStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return await store.GetEmailAsync(user, CancellationToken).ConfigureAwait(false); } @@ -1396,10 +1256,7 @@ public virtual async Task SetEmailAsync(TUser user, string? emai { ThrowIfDisposed(); var store = GetEmailStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); await store.SetEmailAsync(user, email, CancellationToken).ConfigureAwait(false); await store.SetEmailConfirmedAsync(user, false, CancellationToken).ConfigureAwait(false); @@ -1420,10 +1277,7 @@ public virtual async Task SetEmailAsync(TUser user, string? emai { ThrowIfDisposed(); var store = GetEmailStore(); - if (email == null) - { - throw new ArgumentNullException(nameof(email)); - } + ArgumentNullThrowHelper.ThrowIfNull(email); email = NormalizeEmail(email); var user = await store.FindByEmailAsync(email, CancellationToken).ConfigureAwait(false); @@ -1490,10 +1344,7 @@ public virtual async Task ConfirmEmailAsync(TUser user, string t { ThrowIfDisposed(); var store = GetEmailStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); if (!await VerifyUserTokenAsync(user, Options.Tokens.EmailConfirmationTokenProvider, ConfirmEmailTokenPurpose, token).ConfigureAwait(false)) { @@ -1516,10 +1367,7 @@ public virtual async Task IsEmailConfirmedAsync(TUser user) { ThrowIfDisposed(); var store = GetEmailStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return await store.GetEmailConfirmedAsync(user, CancellationToken).ConfigureAwait(false); } @@ -1550,10 +1398,7 @@ public virtual Task GenerateChangeEmailTokenAsync(TUser user, string new public virtual async Task ChangeEmailAsync(TUser user, string newEmail, string token) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); // Make sure the token is valid and the stamp matches if (!await VerifyUserTokenAsync(user, Options.Tokens.ChangeEmailTokenProvider, GetChangeEmailTokenPurpose(newEmail), token).ConfigureAwait(false)) @@ -1576,10 +1421,7 @@ public virtual async Task ChangeEmailAsync(TUser user, string ne { ThrowIfDisposed(); var store = GetPhoneNumberStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return await store.GetPhoneNumberAsync(user, CancellationToken).ConfigureAwait(false); } @@ -1596,10 +1438,7 @@ public virtual async Task SetPhoneNumberAsync(TUser user, string { ThrowIfDisposed(); var store = GetPhoneNumberStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); await store.SetPhoneNumberAsync(user, phoneNumber, CancellationToken).ConfigureAwait(false); await store.SetPhoneNumberConfirmedAsync(user, false, CancellationToken).ConfigureAwait(false); @@ -1622,10 +1461,7 @@ public virtual async Task ChangePhoneNumberAsync(TUser user, str { ThrowIfDisposed(); var store = GetPhoneNumberStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); if (!await VerifyChangePhoneNumberTokenAsync(user, token, phoneNumber).ConfigureAwait(false)) { @@ -1650,10 +1486,7 @@ public virtual Task IsPhoneNumberConfirmedAsync(TUser user) { ThrowIfDisposed(); var store = GetPhoneNumberStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return store.GetPhoneNumberConfirmedAsync(user, CancellationToken); } @@ -1685,10 +1518,7 @@ public virtual Task GenerateChangePhoneNumberTokenAsync(TUser user, stri public virtual Task VerifyChangePhoneNumberTokenAsync(TUser user, string token, string phoneNumber) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); // Make sure the token is valid and the stamp matches return VerifyUserTokenAsync(user, Options.Tokens.ChangePhoneNumberTokenProvider, ChangePhoneNumberTokenPurpose + ":" + phoneNumber, token); @@ -1709,14 +1539,8 @@ public virtual Task VerifyChangePhoneNumberTokenAsync(TUser user, string t public virtual async Task VerifyUserTokenAsync(TUser user, string tokenProvider, string purpose, string token) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (tokenProvider == null) - { - throw new ArgumentNullException(nameof(tokenProvider)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); + ArgumentNullThrowHelper.ThrowIfNull(tokenProvider); if (!_tokenProviders.ContainsKey(tokenProvider)) { @@ -1745,14 +1569,8 @@ public virtual async Task VerifyUserTokenAsync(TUser user, string tokenPro public virtual Task GenerateUserTokenAsync(TUser user, string tokenProvider, string purpose) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (tokenProvider == null) - { - throw new ArgumentNullException(nameof(tokenProvider)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); + ArgumentNullThrowHelper.ThrowIfNull(tokenProvider); if (!_tokenProviders.ContainsKey(tokenProvider)) { throw new NotSupportedException(Resources.FormatNoTokenProvider(nameof(TUser), tokenProvider)); @@ -1769,10 +1587,7 @@ public virtual Task GenerateUserTokenAsync(TUser user, string tokenProvi public virtual void RegisterTokenProvider(string providerName, IUserTwoFactorTokenProvider provider) { ThrowIfDisposed(); - if (provider == null) - { - throw new ArgumentNullException(nameof(provider)); - } + ArgumentNullThrowHelper.ThrowIfNull(provider); _tokenProviders[providerName] = provider; } @@ -1788,10 +1603,7 @@ public virtual void RegisterTokenProvider(string providerName, IUserTwoFactorTok public virtual async Task> GetValidTwoFactorProvidersAsync(TUser user) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); var results = new List(); foreach (var f in _tokenProviders) { @@ -1816,10 +1628,7 @@ public virtual async Task> GetValidTwoFactorProvidersAsync(TUser u public virtual async Task VerifyTwoFactorTokenAsync(TUser user, string tokenProvider, string token) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); if (!_tokenProviders.ContainsKey(tokenProvider)) { throw new NotSupportedException(Resources.FormatNoTokenProvider(nameof(TUser), tokenProvider)); @@ -1846,10 +1655,7 @@ public virtual async Task VerifyTwoFactorTokenAsync(TUser user, string tok public virtual Task GenerateTwoFactorTokenAsync(TUser user, string tokenProvider) { ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); if (!_tokenProviders.ContainsKey(tokenProvider)) { throw new NotSupportedException(Resources.FormatNoTokenProvider(nameof(TUser), tokenProvider)); @@ -1871,10 +1677,7 @@ public virtual async Task GetTwoFactorEnabledAsync(TUser user) { ThrowIfDisposed(); var store = GetUserTwoFactorStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return await store.GetTwoFactorEnabledAsync(user, CancellationToken).ConfigureAwait(false); } @@ -1891,10 +1694,7 @@ public virtual async Task SetTwoFactorEnabledAsync(TUser user, b { ThrowIfDisposed(); var store = GetUserTwoFactorStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); await store.SetTwoFactorEnabledAsync(user, enabled, CancellationToken).ConfigureAwait(false); await UpdateSecurityStampInternal(user).ConfigureAwait(false); @@ -1914,10 +1714,7 @@ public virtual async Task IsLockedOutAsync(TUser user) { ThrowIfDisposed(); var store = GetUserLockoutStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); if (!await store.GetLockoutEnabledAsync(user, CancellationToken).ConfigureAwait(false)) { return false; @@ -1939,10 +1736,7 @@ public virtual async Task SetLockoutEnabledAsync(TUser user, boo { ThrowIfDisposed(); var store = GetUserLockoutStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); await store.SetLockoutEnabledAsync(user, enabled, CancellationToken).ConfigureAwait(false); return await UpdateUserAsync(user).ConfigureAwait(false); @@ -1959,10 +1753,7 @@ public virtual async Task GetLockoutEnabledAsync(TUser user) { ThrowIfDisposed(); var store = GetUserLockoutStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return await store.GetLockoutEnabledAsync(user, CancellationToken).ConfigureAwait(false); } @@ -1978,10 +1769,7 @@ public virtual async Task GetLockoutEnabledAsync(TUser user) { ThrowIfDisposed(); var store = GetUserLockoutStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return await store.GetLockoutEndDateAsync(user, CancellationToken).ConfigureAwait(false); } @@ -1995,10 +1783,7 @@ public virtual async Task SetLockoutEndDateAsync(TUser user, Dat { ThrowIfDisposed(); var store = GetUserLockoutStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); if (!await store.GetLockoutEnabledAsync(user, CancellationToken).ConfigureAwait(false)) { @@ -2020,10 +1805,7 @@ public virtual async Task AccessFailedAsync(TUser user) { ThrowIfDisposed(); var store = GetUserLockoutStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); // If this puts the user over the threshold for lockout, lock them out and reset the access failed count var count = await store.IncrementAccessFailedCountAsync(user, CancellationToken).ConfigureAwait(false); @@ -2047,10 +1829,7 @@ public virtual async Task ResetAccessFailedCountAsync(TUser user { ThrowIfDisposed(); var store = GetUserLockoutStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); if (await GetAccessFailedCountAsync(user).ConfigureAwait(false) == 0) { @@ -2070,10 +1849,7 @@ public virtual async Task GetAccessFailedCountAsync(TUser user) { ThrowIfDisposed(); var store = GetUserLockoutStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return await store.GetAccessFailedCountAsync(user, CancellationToken).ConfigureAwait(false); } @@ -2089,10 +1865,7 @@ public virtual Task> GetUsersForClaimAsync(Claim claim) { ThrowIfDisposed(); var store = GetClaimStore(); - if (claim == null) - { - throw new ArgumentNullException(nameof(claim)); - } + ArgumentNullThrowHelper.ThrowIfNull(claim); return store.GetUsersForClaimAsync(claim, CancellationToken); } @@ -2108,10 +1881,7 @@ public virtual Task> GetUsersInRoleAsync(string roleName) { ThrowIfDisposed(); var store = GetUserRoleStore(); - if (roleName == null) - { - throw new ArgumentNullException(nameof(roleName)); - } + ArgumentNullThrowHelper.ThrowIfNull(roleName); return store.GetUsersInRoleAsync(NormalizeName(roleName), CancellationToken); } @@ -2127,18 +1897,9 @@ public virtual Task> GetUsersInRoleAsync(string roleName) { ThrowIfDisposed(); var store = GetAuthenticationTokenStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (loginProvider == null) - { - throw new ArgumentNullException(nameof(loginProvider)); - } - if (tokenName == null) - { - throw new ArgumentNullException(nameof(tokenName)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); + ArgumentNullThrowHelper.ThrowIfNull(loginProvider); + ArgumentNullThrowHelper.ThrowIfNull(tokenName); return store.GetTokenAsync(user, loginProvider, tokenName, CancellationToken); } @@ -2155,18 +1916,9 @@ public virtual async Task SetAuthenticationTokenAsync(TUser user { ThrowIfDisposed(); var store = GetAuthenticationTokenStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (loginProvider == null) - { - throw new ArgumentNullException(nameof(loginProvider)); - } - if (tokenName == null) - { - throw new ArgumentNullException(nameof(tokenName)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); + ArgumentNullThrowHelper.ThrowIfNull(loginProvider); + ArgumentNullThrowHelper.ThrowIfNull(tokenName); // REVIEW: should updating any tokens affect the security stamp? await store.SetTokenAsync(user, loginProvider, tokenName, tokenValue, CancellationToken).ConfigureAwait(false); @@ -2184,18 +1936,9 @@ public virtual async Task RemoveAuthenticationTokenAsync(TUser u { ThrowIfDisposed(); var store = GetAuthenticationTokenStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (loginProvider == null) - { - throw new ArgumentNullException(nameof(loginProvider)); - } - if (tokenName == null) - { - throw new ArgumentNullException(nameof(tokenName)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); + ArgumentNullThrowHelper.ThrowIfNull(loginProvider); + ArgumentNullThrowHelper.ThrowIfNull(tokenName); await store.RemoveTokenAsync(user, loginProvider, tokenName, CancellationToken).ConfigureAwait(false); return await UpdateUserAsync(user).ConfigureAwait(false); @@ -2210,10 +1953,7 @@ public virtual async Task RemoveAuthenticationTokenAsync(TUser u { ThrowIfDisposed(); var store = GetAuthenticatorKeyStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return store.GetAuthenticatorKeyAsync(user, CancellationToken); } @@ -2226,10 +1966,7 @@ public virtual async Task ResetAuthenticatorKeyAsync(TUser user) { ThrowIfDisposed(); var store = GetAuthenticatorKeyStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); await store.SetAuthenticatorKeyAsync(user, GenerateNewAuthenticatorKey(), CancellationToken).ConfigureAwait(false); await UpdateSecurityStampInternal(user).ConfigureAwait(false); return await UpdateAsync(user).ConfigureAwait(false); @@ -2252,10 +1989,7 @@ public virtual string GenerateNewAuthenticatorKey() { ThrowIfDisposed(); var store = GetRecoveryCodeStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); var newCodes = new List(number); for (var i = 0; i < number; i++) @@ -2359,10 +2093,7 @@ public virtual async Task RedeemTwoFactorRecoveryCodeAsync(TUser { ThrowIfDisposed(); var store = GetRecoveryCodeStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); var success = await store.RedeemCodeAsync(user, code, CancellationToken).ConfigureAwait(false); if (success) @@ -2381,10 +2112,7 @@ public virtual Task CountRecoveryCodesAsync(TUser user) { ThrowIfDisposed(); var store = GetRecoveryCodeStore(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return store.CountCodesAsync(user, CancellationToken); } @@ -2680,10 +2408,6 @@ private IUserPasswordStore GetPasswordStore() /// protected void ThrowIfDisposed() { - if (_disposed) - { - throw new ObjectDisposedException(GetType().Name); - } + ObjectDisposedThrowHelper.ThrowIf(_disposed, this); } - } diff --git a/src/Identity/Extensions.Core/src/UserValidator.cs b/src/Identity/Extensions.Core/src/UserValidator.cs index 1d67942d3c02..cf530106a663 100644 --- a/src/Identity/Extensions.Core/src/UserValidator.cs +++ b/src/Identity/Extensions.Core/src/UserValidator.cs @@ -6,6 +6,7 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Identity; @@ -38,14 +39,8 @@ public UserValidator(IdentityErrorDescriber? errors = null) /// The that represents the asynchronous operation, containing the of the validation operation. public virtual async Task ValidateAsync(UserManager manager, TUser user) { - if (manager == null) - { - throw new ArgumentNullException(nameof(manager)); - } - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(manager); + ArgumentNullThrowHelper.ThrowIfNull(user); var errors = await ValidateUserName(manager, user).ConfigureAwait(false); if (manager.Options.User.RequireUniqueEmail) { diff --git a/src/Identity/Extensions.Stores/src/Microsoft.Extensions.Identity.Stores.csproj b/src/Identity/Extensions.Stores/src/Microsoft.Extensions.Identity.Stores.csproj index d5bd23af79ee..4f4347618740 100644 --- a/src/Identity/Extensions.Stores/src/Microsoft.Extensions.Identity.Stores.csproj +++ b/src/Identity/Extensions.Stores/src/Microsoft.Extensions.Identity.Stores.csproj @@ -17,6 +17,9 @@ + + + diff --git a/src/Identity/Extensions.Stores/src/RoleStoreBase.cs b/src/Identity/Extensions.Stores/src/RoleStoreBase.cs index 59c0f3176bd3..34454dca3dc1 100644 --- a/src/Identity/Extensions.Stores/src/RoleStoreBase.cs +++ b/src/Identity/Extensions.Stores/src/RoleStoreBase.cs @@ -9,6 +9,7 @@ using System.Security.Claims; using System.Threading; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Identity; @@ -33,10 +34,7 @@ public abstract class RoleStoreBaseThe . public RoleStoreBase(IdentityErrorDescriber describer) { - if (describer == null) - { - throw new ArgumentNullException(nameof(describer)); - } + ArgumentNullThrowHelper.ThrowIfNull(describer); ErrorDescriber = describer; } @@ -82,10 +80,7 @@ public RoleStoreBase(IdentityErrorDescriber describer) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullThrowHelper.ThrowIfNull(role); return Task.FromResult(ConvertIdToString(role.Id)!); } @@ -99,10 +94,7 @@ public RoleStoreBase(IdentityErrorDescriber describer) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullThrowHelper.ThrowIfNull(role); return Task.FromResult(role.Name); } @@ -117,10 +109,7 @@ public RoleStoreBase(IdentityErrorDescriber describer) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullThrowHelper.ThrowIfNull(role); role.Name = roleName; return Task.CompletedTask; } @@ -181,10 +170,7 @@ public RoleStoreBase(IdentityErrorDescriber describer) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullThrowHelper.ThrowIfNull(role); return Task.FromResult(role.NormalizedName); } @@ -199,10 +185,7 @@ public RoleStoreBase(IdentityErrorDescriber describer) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (role == null) - { - throw new ArgumentNullException(nameof(role)); - } + ArgumentNullThrowHelper.ThrowIfNull(role); role.NormalizedName = normalizedName; return Task.CompletedTask; } @@ -212,10 +195,7 @@ public RoleStoreBase(IdentityErrorDescriber describer) /// protected void ThrowIfDisposed() { - if (_disposed) - { - throw new ObjectDisposedException(GetType().Name); - } + ObjectDisposedThrowHelper.ThrowIf(_disposed, this); } /// diff --git a/src/Identity/Extensions.Stores/src/UserStoreBase.cs b/src/Identity/Extensions.Stores/src/UserStoreBase.cs index 7eb2173358ae..0a3a7103c9c4 100644 --- a/src/Identity/Extensions.Stores/src/UserStoreBase.cs +++ b/src/Identity/Extensions.Stores/src/UserStoreBase.cs @@ -9,6 +9,7 @@ using System.Security.Claims; using System.Threading; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Identity; @@ -45,10 +46,7 @@ public abstract class UserStoreBaseThe used to describe store errors. public UserStoreBase(IdentityErrorDescriber describer) { - if (describer == null) - { - throw new ArgumentNullException(nameof(describer)); - } + ArgumentNullThrowHelper.ThrowIfNull(describer); ErrorDescriber = describer; } @@ -119,10 +117,7 @@ protected virtual TUserToken CreateUserToken(TUser user, string loginProvider, s { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return Task.FromResult(ConvertIdToString(user.Id)!); } @@ -136,10 +131,7 @@ protected virtual TUserToken CreateUserToken(TUser user, string loginProvider, s { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return Task.FromResult(user.UserName); } @@ -154,10 +146,7 @@ protected virtual TUserToken CreateUserToken(TUser user, string loginProvider, s { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); user.UserName = userName; return Task.CompletedTask; } @@ -172,10 +161,7 @@ protected virtual TUserToken CreateUserToken(TUser user, string loginProvider, s { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return Task.FromResult(user.NormalizedUserName); } @@ -190,10 +176,7 @@ protected virtual TUserToken CreateUserToken(TUser user, string loginProvider, s { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); user.NormalizedUserName = normalizedName; return Task.CompletedTask; } @@ -291,10 +274,7 @@ public abstract IQueryable Users { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); user.PasswordHash = passwordHash; return Task.CompletedTask; } @@ -309,10 +289,7 @@ public abstract IQueryable Users { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return Task.FromResult(user.PasswordHash); } @@ -361,10 +338,7 @@ public abstract IQueryable Users /// protected void ThrowIfDisposed() { - if (_disposed) - { - throw new ObjectDisposedException(GetType().Name); - } + ObjectDisposedThrowHelper.ThrowIf(_disposed, this); } /// @@ -476,10 +450,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return Task.FromResult(user.EmailConfirmed); } @@ -494,10 +465,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); user.EmailConfirmed = confirmed; return Task.CompletedTask; } @@ -513,10 +481,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); user.Email = email; return Task.CompletedTask; } @@ -531,10 +496,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return Task.FromResult(user.Email); } @@ -550,10 +512,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return Task.FromResult(user.NormalizedEmail); } @@ -568,10 +527,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); user.NormalizedEmail = normalizedEmail; return Task.CompletedTask; } @@ -600,10 +556,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return Task.FromResult(user.LockoutEnd); } @@ -618,10 +571,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); user.LockoutEnd = lockoutEnd; return Task.CompletedTask; } @@ -636,10 +586,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); user.AccessFailedCount++; return Task.FromResult(user.AccessFailedCount); } @@ -655,10 +602,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); user.AccessFailedCount = 0; return Task.CompletedTask; } @@ -673,10 +617,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return Task.FromResult(user.AccessFailedCount); } @@ -692,10 +633,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return Task.FromResult(user.LockoutEnabled); } @@ -710,10 +648,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); user.LockoutEnabled = enabled; return Task.CompletedTask; } @@ -729,10 +664,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); user.PhoneNumber = phoneNumber; return Task.CompletedTask; } @@ -747,10 +679,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return Task.FromResult(user.PhoneNumber); } @@ -767,10 +696,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return Task.FromResult(user.PhoneNumberConfirmed); } @@ -785,10 +711,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); user.PhoneNumberConfirmed = confirmed; return Task.CompletedTask; } @@ -804,14 +727,8 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (stamp == null) - { - throw new ArgumentNullException(nameof(stamp)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); + ArgumentNullThrowHelper.ThrowIfNull(stamp); user.SecurityStamp = stamp; return Task.CompletedTask; } @@ -826,10 +743,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return Task.FromResult(user.SecurityStamp); } @@ -845,10 +759,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); user.TwoFactorEnabled = enabled; return Task.CompletedTask; } @@ -867,10 +778,7 @@ public void Dispose() { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); return Task.FromResult(user.TwoFactorEnabled); } @@ -922,10 +830,7 @@ public virtual async Task SetTokenAsync(TUser user, string loginProvider, string cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); var token = await FindTokenAsync(user, loginProvider, name, cancellationToken).ConfigureAwait(false); if (token == null) @@ -951,10 +856,7 @@ public virtual async Task RemoveTokenAsync(TUser user, string loginProvider, str cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); var entry = await FindTokenAsync(user, loginProvider, name, cancellationToken).ConfigureAwait(false); if (entry != null) { @@ -975,10 +877,7 @@ public virtual async Task RemoveTokenAsync(TUser user, string loginProvider, str cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); var entry = await FindTokenAsync(user, loginProvider, name, cancellationToken).ConfigureAwait(false); return entry?.Value; } @@ -1017,10 +916,7 @@ public virtual async Task CountCodesAsync(TUser user, CancellationToken can cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); var mergedCodes = await GetTokenAsync(user, InternalLoginProvider, RecoveryCodeTokenName, cancellationToken).ConfigureAwait(false) ?? ""; if (mergedCodes.Length > 0) { @@ -1055,14 +951,8 @@ public virtual async Task RedeemCodeAsync(TUser user, string code, Cancell cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); - if (user == null) - { - throw new ArgumentNullException(nameof(user)); - } - if (code == null) - { - throw new ArgumentNullException(nameof(code)); - } + ArgumentNullThrowHelper.ThrowIfNull(user); + ArgumentNullThrowHelper.ThrowIfNull(code); var mergedCodes = await GetTokenAsync(user, InternalLoginProvider, RecoveryCodeTokenName, cancellationToken).ConfigureAwait(false) ?? ""; var splitCodes = mergedCodes.Split(';'); diff --git a/src/Localization/Abstractions/src/LocalizedString.cs b/src/Localization/Abstractions/src/LocalizedString.cs index e386686b99c0..33d0b63d67f8 100644 --- a/src/Localization/Abstractions/src/LocalizedString.cs +++ b/src/Localization/Abstractions/src/LocalizedString.cs @@ -3,6 +3,7 @@ using System; using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.Localization; @@ -41,15 +42,8 @@ public LocalizedString(string name, string value, bool resourceNotFound) /// The location which was searched for a localization value. public LocalizedString(string name, string value, bool resourceNotFound, string? searchedLocation) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } - - if (value == null) - { - throw new ArgumentNullException(nameof(value)); - } + ArgumentNullThrowHelper.ThrowIfNull(name); + ArgumentNullThrowHelper.ThrowIfNull(value); Name = name; Value = value; diff --git a/src/Localization/Abstractions/src/Microsoft.Extensions.Localization.Abstractions.csproj b/src/Localization/Abstractions/src/Microsoft.Extensions.Localization.Abstractions.csproj index d9945fec8dd6..bfe3bf7541c1 100644 --- a/src/Localization/Abstractions/src/Microsoft.Extensions.Localization.Abstractions.csproj +++ b/src/Localization/Abstractions/src/Microsoft.Extensions.Localization.Abstractions.csproj @@ -15,4 +15,9 @@ Microsoft.Extensions.Localization.IStringLocalizer<T> true + + + + + diff --git a/src/Localization/Abstractions/src/StringLocalizerExtensions.cs b/src/Localization/Abstractions/src/StringLocalizerExtensions.cs index 1c974596f595..a197a0eec0a0 100644 --- a/src/Localization/Abstractions/src/StringLocalizerExtensions.cs +++ b/src/Localization/Abstractions/src/StringLocalizerExtensions.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.Localization; @@ -21,15 +22,8 @@ public static LocalizedString GetString( this IStringLocalizer stringLocalizer, string name) { - if (stringLocalizer == null) - { - throw new ArgumentNullException(nameof(stringLocalizer)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullThrowHelper.ThrowIfNull(stringLocalizer); + ArgumentNullThrowHelper.ThrowIfNull(name); return stringLocalizer[name]; } @@ -46,15 +40,8 @@ public static LocalizedString GetString( string name, params object[] arguments) { - if (stringLocalizer == null) - { - throw new ArgumentNullException(nameof(stringLocalizer)); - } - - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullThrowHelper.ThrowIfNull(stringLocalizer); + ArgumentNullThrowHelper.ThrowIfNull(name); return stringLocalizer[name, arguments]; } @@ -66,10 +53,7 @@ public static LocalizedString GetString( /// The string resources. public static IEnumerable GetAllStrings(this IStringLocalizer stringLocalizer) { - if (stringLocalizer == null) - { - throw new ArgumentNullException(nameof(stringLocalizer)); - } + ArgumentNullThrowHelper.ThrowIfNull(stringLocalizer); return stringLocalizer.GetAllStrings(includeParentCultures: true); } diff --git a/src/Localization/Abstractions/src/StringLocalizerOfT.cs b/src/Localization/Abstractions/src/StringLocalizerOfT.cs index 878bcc902588..aab5ec19d8e6 100644 --- a/src/Localization/Abstractions/src/StringLocalizerOfT.cs +++ b/src/Localization/Abstractions/src/StringLocalizerOfT.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.Localization; @@ -20,10 +21,7 @@ public class StringLocalizer : IStringLocalizerThe to use. public StringLocalizer(IStringLocalizerFactory factory) { - if (factory == null) - { - throw new ArgumentNullException(nameof(factory)); - } + ArgumentNullThrowHelper.ThrowIfNull(factory); _localizer = factory.Create(typeof(TResourceSource)); } @@ -33,10 +31,7 @@ public virtual LocalizedString this[string name] { get { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullThrowHelper.ThrowIfNull(name); return _localizer[name]; } @@ -47,10 +42,7 @@ public virtual LocalizedString this[string name] { get { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullThrowHelper.ThrowIfNull(name); return _localizer[name, arguments]; } diff --git a/src/Localization/Localization/src/Internal/AssemblyWrapper.cs b/src/Localization/Localization/src/Internal/AssemblyWrapper.cs index 573348d1e07e..406cc3bd9b78 100644 --- a/src/Localization/Localization/src/Internal/AssemblyWrapper.cs +++ b/src/Localization/Localization/src/Internal/AssemblyWrapper.cs @@ -4,6 +4,7 @@ using System; using System.IO; using System.Reflection; +using Microsoft.AspNetCore.Shared; namespace Microsoft.Extensions.Localization; @@ -17,10 +18,7 @@ internal class AssemblyWrapper { public AssemblyWrapper(Assembly assembly) { - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } + ArgumentNullThrowHelper.ThrowIfNull(assembly); Assembly = assembly; } diff --git a/src/Localization/Localization/src/LocalizationServiceCollectionExtensions.cs b/src/Localization/Localization/src/LocalizationServiceCollectionExtensions.cs index f4015f87542a..cfd08174f046 100644 --- a/src/Localization/Localization/src/LocalizationServiceCollectionExtensions.cs +++ b/src/Localization/Localization/src/LocalizationServiceCollectionExtensions.cs @@ -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.DependencyInjection.Extensions; using Microsoft.Extensions.Localization; @@ -19,10 +20,7 @@ public static class LocalizationServiceCollectionExtensions /// The so that additional calls can be chained. public static IServiceCollection AddLocalization(this IServiceCollection services) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } + ArgumentNullThrowHelper.ThrowIfNull(services); services.AddOptions(); @@ -43,15 +41,8 @@ public static IServiceCollection AddLocalization( this IServiceCollection services, Action setupAction) { - if (services == null) - { - throw new ArgumentNullException(nameof(services)); - } - - if (setupAction == null) - { - throw new ArgumentNullException(nameof(setupAction)); - } + ArgumentNullThrowHelper.ThrowIfNull(services); + ArgumentNullThrowHelper.ThrowIfNull(setupAction); AddLocalizationServices(services, setupAction); diff --git a/src/Localization/Localization/src/Microsoft.Extensions.Localization.csproj b/src/Localization/Localization/src/Microsoft.Extensions.Localization.csproj index 8847d3d0fb85..8ee85dd904d3 100644 --- a/src/Localization/Localization/src/Microsoft.Extensions.Localization.csproj +++ b/src/Localization/Localization/src/Microsoft.Extensions.Localization.csproj @@ -1,4 +1,4 @@ - + Microsoft .NET Extensions @@ -22,4 +22,9 @@ + + + + + diff --git a/src/Localization/Localization/src/ResourceManagerStringLocalizer.cs b/src/Localization/Localization/src/ResourceManagerStringLocalizer.cs index 5ea053a4065c..3a180d20071c 100644 --- a/src/Localization/Localization/src/ResourceManagerStringLocalizer.cs +++ b/src/Localization/Localization/src/ResourceManagerStringLocalizer.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Reflection; using System.Resources; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; namespace Microsoft.Extensions.Localization; @@ -81,30 +82,11 @@ internal ResourceManagerStringLocalizer( IResourceNamesCache resourceNamesCache, ILogger logger) { - if (resourceManager == null) - { - throw new ArgumentNullException(nameof(resourceManager)); - } - - if (resourceStringProvider == null) - { - throw new ArgumentNullException(nameof(resourceStringProvider)); - } - - if (baseName == null) - { - throw new ArgumentNullException(nameof(baseName)); - } - - if (resourceNamesCache == null) - { - throw new ArgumentNullException(nameof(resourceNamesCache)); - } - - if (logger == null) - { - throw new ArgumentNullException(nameof(logger)); - } + ArgumentNullThrowHelper.ThrowIfNull(resourceManager); + ArgumentNullThrowHelper.ThrowIfNull(resourceStringProvider); + ArgumentNullThrowHelper.ThrowIfNull(baseName); + ArgumentNullThrowHelper.ThrowIfNull(resourceNamesCache); + ArgumentNullThrowHelper.ThrowIfNull(logger); _resourceStringProvider = resourceStringProvider; _resourceManager = resourceManager; @@ -118,10 +100,7 @@ public virtual LocalizedString this[string name] { get { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullThrowHelper.ThrowIfNull(name); var value = GetStringSafely(name, null); @@ -134,10 +113,7 @@ public virtual LocalizedString this[string name] { get { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullThrowHelper.ThrowIfNull(name); var format = GetStringSafely(name, null); var value = string.Format(CultureInfo.CurrentCulture, format ?? name, arguments); @@ -158,10 +134,7 @@ public virtual IEnumerable GetAllStrings(bool includeParentCult /// The strings. protected IEnumerable GetAllStrings(bool includeParentCultures, CultureInfo culture) { - if (culture == null) - { - throw new ArgumentNullException(nameof(culture)); - } + ArgumentNullThrowHelper.ThrowIfNull(culture); var resourceNames = includeParentCultures ? GetResourceNamesFromCultureHierarchy(culture) @@ -183,10 +156,7 @@ protected IEnumerable GetAllStrings(bool includeParentCultures, /// The resource string, or null if none was found. protected string? GetStringSafely(string name, CultureInfo? culture) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullThrowHelper.ThrowIfNull(name); var keyCulture = culture ?? CultureInfo.CurrentUICulture; diff --git a/src/Localization/Localization/src/ResourceManagerStringLocalizerFactory.cs b/src/Localization/Localization/src/ResourceManagerStringLocalizerFactory.cs index db4457d93c57..209de4e2065e 100644 --- a/src/Localization/Localization/src/ResourceManagerStringLocalizerFactory.cs +++ b/src/Localization/Localization/src/ResourceManagerStringLocalizerFactory.cs @@ -6,6 +6,7 @@ using System.IO; using System.Reflection; using System.Resources; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -36,15 +37,8 @@ public ResourceManagerStringLocalizerFactory( IOptions localizationOptions, ILoggerFactory loggerFactory) { - if (localizationOptions == null) - { - throw new ArgumentNullException(nameof(localizationOptions)); - } - - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullThrowHelper.ThrowIfNull(localizationOptions); + ArgumentNullThrowHelper.ThrowIfNull(loggerFactory); _resourcesRelativePath = localizationOptions.Value.ResourcesPath ?? string.Empty; _loggerFactory = loggerFactory; @@ -63,10 +57,7 @@ public ResourceManagerStringLocalizerFactory( /// The prefix for resource lookup. protected virtual string GetResourcePrefix(TypeInfo typeInfo) { - if (typeInfo == null) - { - throw new ArgumentNullException(nameof(typeInfo)); - } + ArgumentNullThrowHelper.ThrowIfNull(typeInfo); return GetResourcePrefix(typeInfo, GetRootNamespace(typeInfo.Assembly), GetResourcePath(typeInfo.Assembly)); } @@ -84,10 +75,7 @@ protected virtual string GetResourcePrefix(TypeInfo typeInfo) /// protected virtual string GetResourcePrefix(TypeInfo typeInfo, string? baseNamespace, string? resourcesRelativePath) { - if (typeInfo == null) - { - throw new ArgumentNullException(nameof(typeInfo)); - } + ArgumentNullThrowHelper.ThrowIfNull(typeInfo); if (string.IsNullOrEmpty(baseNamespace)) { @@ -148,10 +136,7 @@ protected virtual string GetResourcePrefix(string baseResourceName, string baseN /// The . public IStringLocalizer Create(Type resourceSource) { - if (resourceSource == null) - { - throw new ArgumentNullException(nameof(resourceSource)); - } + ArgumentNullThrowHelper.ThrowIfNull(resourceSource); // Get without Add to prevent unnecessary lambda allocation if (!_localizerCache.TryGetValue(resourceSource.AssemblyQualifiedName!, out var localizer)) @@ -161,7 +146,7 @@ public IStringLocalizer Create(Type resourceSource) var assembly = typeInfo.Assembly; localizer = CreateResourceManagerStringLocalizer(assembly, baseName); - + _localizerCache[resourceSource.AssemblyQualifiedName!] = localizer; } @@ -176,15 +161,8 @@ public IStringLocalizer Create(Type resourceSource) /// The . public IStringLocalizer Create(string baseName, string location) { - if (baseName == null) - { - throw new ArgumentNullException(nameof(baseName)); - } - - if (location == null) - { - throw new ArgumentNullException(nameof(location)); - } + ArgumentNullThrowHelper.ThrowIfNull(baseName); + ArgumentNullThrowHelper.ThrowIfNull(location); return _localizerCache.GetOrAdd($"B={baseName},L={location}", _ => { diff --git a/src/Shared/ThrowHelpers/ArgumentOutOfRangeThrowHelper.cs b/src/Shared/ThrowHelpers/ArgumentOutOfRangeThrowHelper.cs index f66ae7d6c410..906653264575 100644 --- a/src/Shared/ThrowHelpers/ArgumentOutOfRangeThrowHelper.cs +++ b/src/Shared/ThrowHelpers/ArgumentOutOfRangeThrowHelper.cs @@ -83,6 +83,21 @@ public static void ThrowIfNegative(int value, [CallerArgumentExpression(nameof(v #endif } + /// Throws an if is negative. + /// The argument to validate as non-negative. + /// The name of the parameter with which corresponds. + public static void ThrowIfNegative(long value, [CallerArgumentExpression(nameof(value))] string? paramName = null) + { +#if !NET7_0_OR_GREATER + if (value < 0) + { + ThrowNegative(paramName, value); + } +#else + ArgumentOutOfRangeException.ThrowIfNegative(value, paramName); +#endif + } + /// Throws an if is negative or zero. /// The argument to validate as non-zero or non-negative. /// The name of the parameter with which corresponds. diff --git a/src/Shared/ThrowHelpers/ObjectDisposedThrowHelper.cs b/src/Shared/ThrowHelpers/ObjectDisposedThrowHelper.cs new file mode 100644 index 000000000000..edce2edce00c --- /dev/null +++ b/src/Shared/ThrowHelpers/ObjectDisposedThrowHelper.cs @@ -0,0 +1,59 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace Microsoft.AspNetCore.Shared; + +#nullable enable + +internal static partial class ObjectDisposedThrowHelper +{ + /// Throws an if the specified is . + /// The condition to evaluate. + /// The object whose type's full name should be included in any resulting . + /// The is . + public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance) + { +#if !NET7_0_OR_GREATER + if (condition) + { + ThrowObjectDisposedException(instance); + } +#else + ObjectDisposedException.ThrowIf(condition, instance); +#endif + } + + /// Throws an if the specified is . + /// The condition to evaluate. + /// The type whose full name should be included in any resulting . + /// The is . + public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type) + { +#if !NET7_0_OR_GREATER + if (condition) + { + ThrowObjectDisposedException(type); + } +#else + ObjectDisposedException.ThrowIf(condition, type); +#endif + } + +#if !NET7_0_OR_GREATER + [DoesNotReturn] + private static void ThrowObjectDisposedException(object? instance) + { + throw new ObjectDisposedException(instance?.GetType().FullName); + } + + [DoesNotReturn] + private static void ThrowObjectDisposedException(Type? type) + { + throw new ObjectDisposedException(type?.FullName); + } +#endif +} diff --git a/src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs b/src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs index ae2216913683..f4bc0bb96526 100644 --- a/src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs +++ b/src/SignalR/clients/csharp/Client.Core/src/HubConnection.cs @@ -18,6 +18,7 @@ using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Connections.Features; using Microsoft.AspNetCore.Internal; +using Microsoft.AspNetCore.Shared; using Microsoft.AspNetCore.SignalR.Client.Internal; using Microsoft.AspNetCore.SignalR.Internal; using Microsoft.AspNetCore.SignalR.Protocol; @@ -1145,10 +1146,7 @@ private void DispatchInvocationCompletion(CompletionMessage completion, Invocati private void CheckDisposed() { - if (_disposed) - { - throw new ObjectDisposedException(nameof(HubConnection)); - } + ObjectDisposedThrowHelper.ThrowIf(_disposed, this); } private async Task HandshakeAsync(ConnectionState startingConnectionState, CancellationToken cancellationToken) diff --git a/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.InvokeAsync.cs b/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.InvokeAsync.cs index 414fa9353e29..859f8c3c9798 100644 --- a/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.InvokeAsync.cs +++ b/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.InvokeAsync.cs @@ -5,6 +5,7 @@ using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.SignalR.Client; @@ -221,10 +222,7 @@ public static Task InvokeAsync(this HubConnection hubConnection, string methodNa /// A that represents the asynchronous invoke. public static Task InvokeCoreAsync(this HubConnection hubConnection, string methodName, object?[] args, CancellationToken cancellationToken = default) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.InvokeCoreAsync(methodName, typeof(object), args, cancellationToken); } diff --git a/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.InvokeAsyncGeneric.cs b/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.InvokeAsyncGeneric.cs index ba69faaae2d1..4def1b390694 100644 --- a/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.InvokeAsyncGeneric.cs +++ b/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.InvokeAsyncGeneric.cs @@ -5,6 +5,7 @@ using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.SignalR.Client; @@ -269,10 +270,7 @@ public static Task InvokeAsync(this HubConnection hubConnectio /// public static async Task InvokeCoreAsync(this HubConnection hubConnection, string methodName, object?[] args, CancellationToken cancellationToken = default) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return (TResult)(await hubConnection.InvokeCoreAsync(methodName, typeof(TResult), args, cancellationToken).ConfigureAwait(false))!; } diff --git a/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.OnResult.cs b/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.OnResult.cs index d8167d9707ff..ad0832586606 100644 --- a/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.OnResult.cs +++ b/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.OnResult.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.SignalR.Client; public static partial class HubConnectionExtensions @@ -49,10 +50,7 @@ public static IDisposable On(this HubConnection hubConnection, string m /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func> handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, Type.EmptyTypes, args => handler()); } @@ -68,10 +66,7 @@ public static IDisposable On(this HubConnection hubConnection, string m /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, Type.EmptyTypes, args => handler()); } @@ -88,10 +83,7 @@ public static IDisposable On(this HubConnection hubConnection, string m /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1) }, @@ -111,10 +103,7 @@ public static IDisposable On(this HubConnection hubConnection, stri /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2) }, @@ -135,10 +124,7 @@ public static IDisposable On(this HubConnection hubConnection, /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3) }, @@ -160,10 +146,7 @@ public static IDisposable On(this HubConnection hubConnecti /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }, @@ -186,10 +169,7 @@ public static IDisposable On(this HubConnection hubConn /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }, @@ -213,10 +193,7 @@ public static IDisposable On(this HubConnection hub /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6) }, @@ -241,10 +218,7 @@ public static IDisposable On(this HubConnection /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7) }, @@ -270,10 +244,7 @@ public static IDisposable On(this HubConnec /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8) }, @@ -292,10 +263,7 @@ public static IDisposable On(this HubCo /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func> handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1) }, @@ -315,10 +283,7 @@ public static IDisposable On(this HubConnection hubConnection, stri /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func> handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2) }, @@ -339,10 +304,7 @@ public static IDisposable On(this HubConnection hubConnection, /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func> handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3) }, @@ -364,10 +326,7 @@ public static IDisposable On(this HubConnection hubConnecti /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func> handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }, @@ -390,10 +349,7 @@ public static IDisposable On(this HubConnection hubConn /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func> handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }, @@ -417,10 +373,7 @@ public static IDisposable On(this HubConnection hub /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func> handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6) }, @@ -445,10 +398,7 @@ public static IDisposable On(this HubConnection /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func> handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7) }, @@ -474,10 +424,7 @@ public static IDisposable On(this HubConnec /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func> handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8) }, diff --git a/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.StreamAsChannelAsync.cs b/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.StreamAsChannelAsync.cs index 02e4155ffb9a..0d513a31edce 100644 --- a/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.StreamAsChannelAsync.cs +++ b/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.StreamAsChannelAsync.cs @@ -6,6 +6,7 @@ using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.SignalR.Client; @@ -270,10 +271,7 @@ public static Task> StreamAsChannelAsync(this Hu /// public static async Task> StreamAsChannelCoreAsync(this HubConnection hubConnection, string methodName, object?[] args, CancellationToken cancellationToken = default) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); var inputChannel = await hubConnection.StreamAsChannelCoreAsync(methodName, typeof(TResult), args, cancellationToken).ConfigureAwait(false); var outputChannel = Channel.CreateUnbounded(); diff --git a/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.cs b/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.cs index ea131eff6b35..f8cbb39c00f5 100644 --- a/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.cs +++ b/src/SignalR/clients/csharp/Client.Core/src/HubConnectionExtensions.cs @@ -3,6 +3,7 @@ using System; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.SignalR.Client; @@ -30,10 +31,7 @@ private static IDisposable On(this HubConnection hubConnection, string methodNam /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Action handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, Type.EmptyTypes, args => handler()); } @@ -48,10 +46,7 @@ public static IDisposable On(this HubConnection hubConnection, string methodName /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Action handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1) }, @@ -69,10 +64,7 @@ public static IDisposable On(this HubConnection hubConnection, string method /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Action handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2) }, @@ -91,10 +83,7 @@ public static IDisposable On(this HubConnection hubConnection, string me /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Action handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3) }, @@ -114,10 +103,7 @@ public static IDisposable On(this HubConnection hubConnection, strin /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Action handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }, @@ -138,10 +124,7 @@ public static IDisposable On(this HubConnection hubConnection, s /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Action handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }, @@ -163,10 +146,7 @@ public static IDisposable On(this HubConnection hubConnectio /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Action handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6) }, @@ -189,10 +169,7 @@ public static IDisposable On(this HubConnection hubConne /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Action handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7) }, @@ -216,10 +193,7 @@ public static IDisposable On(this HubConnection hubC /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Action handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8) }, @@ -252,10 +226,7 @@ public static IDisposable On(this HubConnection hubConnection, string methodName /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, Type.EmptyTypes, args => handler()); } @@ -270,10 +241,7 @@ public static IDisposable On(this HubConnection hubConnection, string methodName /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1) }, @@ -291,10 +259,7 @@ public static IDisposable On(this HubConnection hubConnection, string method /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2) }, @@ -313,10 +278,7 @@ public static IDisposable On(this HubConnection hubConnection, string me /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3) }, @@ -336,10 +298,7 @@ public static IDisposable On(this HubConnection hubConnection, strin /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }, @@ -360,10 +319,7 @@ public static IDisposable On(this HubConnection hubConnection, s /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }, @@ -385,10 +341,7 @@ public static IDisposable On(this HubConnection hubConnectio /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6) }, @@ -411,10 +364,7 @@ public static IDisposable On(this HubConnection hubConne /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7) }, @@ -438,10 +388,7 @@ public static IDisposable On(this HubConnection hubC /// A subscription that can be disposed to unsubscribe from the hub method. public static IDisposable On(this HubConnection hubConnection, string methodName, Func handler) { - if (hubConnection == null) - { - throw new ArgumentNullException(nameof(hubConnection)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnection); return hubConnection.On(methodName, new[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6), typeof(T7), typeof(T8) }, diff --git a/src/SignalR/clients/csharp/Client.Core/src/Microsoft.AspNetCore.SignalR.Client.Core.csproj b/src/SignalR/clients/csharp/Client.Core/src/Microsoft.AspNetCore.SignalR.Client.Core.csproj index d65aa9f8f44b..65cf5d649c19 100644 --- a/src/SignalR/clients/csharp/Client.Core/src/Microsoft.AspNetCore.SignalR.Client.Core.csproj +++ b/src/SignalR/clients/csharp/Client.Core/src/Microsoft.AspNetCore.SignalR.Client.Core.csproj @@ -16,6 +16,7 @@ + diff --git a/src/SignalR/clients/csharp/Client/src/HubConnectionBuilderHttpExtensions.cs b/src/SignalR/clients/csharp/Client/src/HubConnectionBuilderHttpExtensions.cs index 768975f7ea28..eda739d1776e 100644 --- a/src/SignalR/clients/csharp/Client/src/HubConnectionBuilderHttpExtensions.cs +++ b/src/SignalR/clients/csharp/Client/src/HubConnectionBuilderHttpExtensions.cs @@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Http.Connections; using Microsoft.AspNetCore.Http.Connections.Client; +using Microsoft.AspNetCore.Shared; using Microsoft.AspNetCore.SignalR.Protocol; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; @@ -124,10 +125,7 @@ public static IHubConnectionBuilder WithUrl(this IHubConnectionBuilder hubConnec private static IHubConnectionBuilder WithUrlCore(this IHubConnectionBuilder hubConnectionBuilder, Uri url, HttpTransportType? transports, Action? configureHttpConnection) { - if (hubConnectionBuilder == null) - { - throw new ArgumentNullException(nameof(hubConnectionBuilder)); - } + ArgumentNullThrowHelper.ThrowIfNull(hubConnectionBuilder); hubConnectionBuilder.Services.Configure(o => { diff --git a/src/SignalR/clients/csharp/Client/src/Microsoft.AspNetCore.SignalR.Client.csproj b/src/SignalR/clients/csharp/Client/src/Microsoft.AspNetCore.SignalR.Client.csproj index 6a0d74552b3b..edeac1edd808 100644 --- a/src/SignalR/clients/csharp/Client/src/Microsoft.AspNetCore.SignalR.Client.csproj +++ b/src/SignalR/clients/csharp/Client/src/Microsoft.AspNetCore.SignalR.Client.csproj @@ -18,6 +18,8 @@ + + diff --git a/src/SignalR/clients/csharp/Client/test/UnitTests/HttpConnectionTests.ConnectionLifecycle.cs b/src/SignalR/clients/csharp/Client/test/UnitTests/HttpConnectionTests.ConnectionLifecycle.cs index fc108fb98a7c..eb9feb7ecb3d 100644 --- a/src/SignalR/clients/csharp/Client/test/UnitTests/HttpConnectionTests.ConnectionLifecycle.cs +++ b/src/SignalR/clients/csharp/Client/test/UnitTests/HttpConnectionTests.ConnectionLifecycle.cs @@ -69,7 +69,7 @@ await WithConnectionAsync( await Assert.ThrowsAsync( async () => await connection.StartAsync()).DefaultTimeout(); - Assert.Equal(nameof(HttpConnection), exception.ObjectName); + Assert.Equal(typeof(HttpConnection).FullName, exception.ObjectName); }); } } @@ -536,7 +536,7 @@ private static async Task AssertDisposedAsync(HttpConnection connection) { var exception = await Assert.ThrowsAsync(() => connection.StartAsync()); - Assert.Equal(nameof(HttpConnection), exception.ObjectName); + Assert.Equal(typeof(HttpConnection).FullName, exception.ObjectName); } } } diff --git a/src/SignalR/clients/csharp/Client/test/UnitTests/HttpConnectionTests.Transport.cs b/src/SignalR/clients/csharp/Client/test/UnitTests/HttpConnectionTests.Transport.cs index ae7906c45966..bbeb744b85f7 100644 --- a/src/SignalR/clients/csharp/Client/test/UnitTests/HttpConnectionTests.Transport.cs +++ b/src/SignalR/clients/csharp/Client/test/UnitTests/HttpConnectionTests.Transport.cs @@ -276,7 +276,7 @@ public Task TransportPipeCannotBeAccessedAfterConnectionIsDisposed() var exception = await Assert.ThrowsAsync( () => connection.Transport.Output.WriteAsync(new byte[0]).DefaultTimeout()); - Assert.Equal(nameof(HttpConnection), exception.ObjectName); + Assert.Equal(typeof(HttpConnection).FullName, exception.ObjectName); }); } diff --git a/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnection.cs b/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnection.cs index d430cc2dda9c..48bbd64fde64 100644 --- a/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnection.cs +++ b/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnection.cs @@ -15,6 +15,7 @@ using Microsoft.AspNetCore.Connections.Features; using Microsoft.AspNetCore.Http.Connections.Client.Internal; using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -121,10 +122,7 @@ public HttpConnection(Uri url, HttpTransportType transports, ILoggerFactory? log private static HttpConnectionOptions CreateHttpOptions(Uri url, HttpTransportType transports) { - if (url == null) - { - throw new ArgumentNullException(nameof(url)); - } + ArgumentNullThrowHelper.ThrowIfNull(url); return new HttpConnectionOptions { Url = url, Transports = transports }; } @@ -135,10 +133,7 @@ private static HttpConnectionOptions CreateHttpOptions(Uri url, HttpTransportTyp /// The logger factory. public HttpConnection(HttpConnectionOptions httpConnectionOptions, ILoggerFactory? loggerFactory) { - if (httpConnectionOptions == null) - { - throw new ArgumentNullException(nameof(httpConnectionOptions)); - } + ArgumentNullThrowHelper.ThrowIfNull(httpConnectionOptions); if (httpConnectionOptions.Url == null) { @@ -665,10 +660,7 @@ private HttpClient CreateHttpClient() private void CheckDisposed() { - if (_disposed) - { - throw new ObjectDisposedException(nameof(HttpConnection)); - } + ObjectDisposedThrowHelper.ThrowIf(_disposed, this); } private static bool IsWebSocketsSupported() diff --git a/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnectionFactory.cs b/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnectionFactory.cs index 9d3cd003d393..03b52fa385a4 100644 --- a/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnectionFactory.cs +++ b/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnectionFactory.cs @@ -6,6 +6,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -26,10 +27,7 @@ public class HttpConnectionFactory : IConnectionFactory /// The logger factory. public HttpConnectionFactory(IOptions options, ILoggerFactory loggerFactory) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullThrowHelper.ThrowIfNull(options); _httpConnectionOptions = options.Value; _loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory)); @@ -45,10 +43,7 @@ public HttpConnectionFactory(IOptions options, ILoggerFac /// public async ValueTask ConnectAsync(EndPoint endPoint, CancellationToken cancellationToken = default) { - if (endPoint == null) - { - throw new ArgumentNullException(nameof(endPoint)); - } + ArgumentNullThrowHelper.ThrowIfNull(endPoint); if (!(endPoint is UriEndPoint uriEndPoint)) { diff --git a/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnectionOptions.cs b/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnectionOptions.cs index c81d15186c6b..443dc2307786 100644 --- a/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnectionOptions.cs +++ b/src/SignalR/clients/csharp/Http.Connections.Client/src/HttpConnectionOptions.cs @@ -12,6 +12,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; +using Microsoft.AspNetCore.Shared; namespace Microsoft.AspNetCore.Http.Connections.Client; @@ -92,10 +93,7 @@ public long TransportMaxBufferSize get => _transportMaxBufferSize; set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeThrowHelper.ThrowIfNegative(value); _transportMaxBufferSize = value; } @@ -115,10 +113,7 @@ public long ApplicationMaxBufferSize get => _applicationMaxBufferSize; set { - if (value < 0) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } + ArgumentOutOfRangeThrowHelper.ThrowIfNegative(value); _applicationMaxBufferSize = value; } diff --git a/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/LoggingHttpMessageHandler.cs b/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/LoggingHttpMessageHandler.cs index 5be883dfdc70..76f8a1f5d7e9 100644 --- a/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/LoggingHttpMessageHandler.cs +++ b/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/LoggingHttpMessageHandler.cs @@ -6,6 +6,7 @@ using System.Net.Http; using System.Threading; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Http.Connections.Client.Internal; @@ -16,10 +17,7 @@ internal sealed partial class LoggingHttpMessageHandler : DelegatingHandler public LoggingHttpMessageHandler(HttpMessageHandler inner, ILoggerFactory loggerFactory) : base(inner) { - if (loggerFactory == null) - { - throw new ArgumentNullException(nameof(loggerFactory)); - } + ArgumentNullThrowHelper.ThrowIfNull(loggerFactory); _logger = loggerFactory.CreateLogger(); } diff --git a/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/ServerSentEventsTransport.cs b/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/ServerSentEventsTransport.cs index 1efb5f7349db..8371665d6618 100644 --- a/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/ServerSentEventsTransport.cs +++ b/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/ServerSentEventsTransport.cs @@ -10,6 +10,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -36,10 +37,7 @@ internal sealed partial class ServerSentEventsTransport : ITransport public ServerSentEventsTransport(HttpClient httpClient, HttpConnectionOptions? httpConnectionOptions = null, ILoggerFactory? loggerFactory = null) { - if (httpClient == null) - { - throw new ArgumentNullException(nameof(httpClient)); - } + ArgumentNullThrowHelper.ThrowIfNull(httpClient); _httpClient = httpClient; _logger = (loggerFactory ?? NullLoggerFactory.Instance).CreateLogger(); diff --git a/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/WebSocketsTransport.cs b/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/WebSocketsTransport.cs index d3932d83456e..9c935457ae91 100644 --- a/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/WebSocketsTransport.cs +++ b/src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/WebSocketsTransport.cs @@ -13,6 +13,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -221,10 +222,7 @@ static bool IsX509CertificateCollectionEqual(X509CertificateCollection? left, X5 public async Task StartAsync(Uri url, TransferFormat transferFormat, CancellationToken cancellationToken = default) { - if (url == null) - { - throw new ArgumentNullException(nameof(url)); - } + ArgumentNullThrowHelper.ThrowIfNull(url); if (transferFormat != TransferFormat.Binary && transferFormat != TransferFormat.Text) { diff --git a/src/SignalR/clients/csharp/Http.Connections.Client/src/Microsoft.AspNetCore.Http.Connections.Client.csproj b/src/SignalR/clients/csharp/Http.Connections.Client/src/Microsoft.AspNetCore.Http.Connections.Client.csproj index 81fb6436b2dc..e79a1fd7bdba 100644 --- a/src/SignalR/clients/csharp/Http.Connections.Client/src/Microsoft.AspNetCore.Http.Connections.Client.csproj +++ b/src/SignalR/clients/csharp/Http.Connections.Client/src/Microsoft.AspNetCore.Http.Connections.Client.csproj @@ -14,6 +14,10 @@ + + + + diff --git a/src/SignalR/common/Protocols.MessagePack/src/Microsoft.AspNetCore.SignalR.Protocols.MessagePack.csproj b/src/SignalR/common/Protocols.MessagePack/src/Microsoft.AspNetCore.SignalR.Protocols.MessagePack.csproj index 7d3882c020b3..b90702bc6c8b 100644 --- a/src/SignalR/common/Protocols.MessagePack/src/Microsoft.AspNetCore.SignalR.Protocols.MessagePack.csproj +++ b/src/SignalR/common/Protocols.MessagePack/src/Microsoft.AspNetCore.SignalR.Protocols.MessagePack.csproj @@ -13,6 +13,8 @@ + + diff --git a/src/SignalR/common/Protocols.MessagePack/src/Protocol/MessagePackHubProtocol.cs b/src/SignalR/common/Protocols.MessagePack/src/Protocol/MessagePackHubProtocol.cs index 5e825ceee2e6..ff6095f0bcc1 100644 --- a/src/SignalR/common/Protocols.MessagePack/src/Protocol/MessagePackHubProtocol.cs +++ b/src/SignalR/common/Protocols.MessagePack/src/Protocol/MessagePackHubProtocol.cs @@ -9,6 +9,7 @@ using MessagePack.Formatters; using MessagePack.Resolvers; using Microsoft.AspNetCore.Connections; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.SignalR.Protocol; @@ -44,10 +45,7 @@ public MessagePackHubProtocol() /// The options used to initialize the protocol. public MessagePackHubProtocol(IOptions options) { - if (options is null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullThrowHelper.ThrowIfNull(options); _worker = new DefaultMessagePackHubProtocolWorker(options.Value.SerializerOptions); } diff --git a/src/SignalR/common/Shared/TimerAwaitable.cs b/src/SignalR/common/Shared/TimerAwaitable.cs index 035a75bca948..05b7085f834e 100644 --- a/src/SignalR/common/Shared/TimerAwaitable.cs +++ b/src/SignalR/common/Shared/TimerAwaitable.cs @@ -5,6 +5,7 @@ using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; +using Microsoft.AspNetCore.Shared; using Microsoft.Extensions.Internal; namespace Microsoft.AspNetCore.Internal; @@ -95,10 +96,7 @@ public void Stop() lock (_lockObj) { // Stop should be used to trigger the call to end the loop which disposes - if (_disposed) - { - throw new ObjectDisposedException(GetType().FullName); - } + ObjectDisposedThrowHelper.ThrowIf(_disposed, this); _running = false; }