diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 18b3998447..9271d4ee81 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -3,7 +3,7 @@ "isRoot": true, "tools": { "jetbrains.resharper.globaltools": { - "version": "2024.2.7", + "version": "2024.3.3", "commands": [ "jb" ], @@ -17,21 +17,21 @@ "rollForward": false }, "dotnet-reportgenerator-globaltool": { - "version": "5.3.11", + "version": "5.4.2", "commands": [ "reportgenerator" ], "rollForward": false }, "docfx": { - "version": "2.77.0", + "version": "2.78.2", "commands": [ "docfx" ], "rollForward": false }, "microsoft.openapi.kiota": { - "version": "1.19.1", + "version": "1.21.0", "commands": [ "kiota" ], diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8f8e5d2437..318240aed7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -46,8 +46,8 @@ jobs: uses: actions/setup-dotnet@v4 with: dotnet-version: | - 6.0.x 8.0.x + 9.0.x - name: Show installed versions shell: pwsh run: | @@ -164,8 +164,8 @@ jobs: uses: actions/setup-dotnet@v4 with: dotnet-version: | - 6.0.x 8.0.x + 9.0.x - name: Git checkout uses: actions/checkout@v4 - name: Restore tools @@ -219,8 +219,8 @@ jobs: uses: actions/setup-dotnet@v4 with: dotnet-version: | - 6.0.x 8.0.x + 9.0.x - name: Git checkout uses: actions/checkout@v4 with: diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 55d430a67c..3bdc622297 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -27,8 +27,8 @@ jobs: uses: actions/setup-dotnet@v4 with: dotnet-version: | - 6.0.x 8.0.x + 9.0.x - name: Git checkout uses: actions/checkout@v4 - name: Initialize CodeQL diff --git a/Build.ps1 b/Build.ps1 index 3abc926e6a..0b2bbb40f1 100644 --- a/Build.ps1 +++ b/Build.ps1 @@ -19,7 +19,7 @@ VerifySuccessExitCode dotnet build --configuration Release /p:VersionSuffix=$versionSuffix VerifySuccessExitCode -dotnet test --no-build --configuration Release --collect:"XPlat Code Coverage" +dotnet test --no-build --configuration Release --verbosity quiet --collect:"XPlat Code Coverage" VerifySuccessExitCode dotnet reportgenerator -reports:**\coverage.cobertura.xml -targetdir:artifacts\coverage -filefilters:-*.g.cs diff --git a/Directory.Build.props b/Directory.Build.props index dc48433409..eeaaba8d16 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -24,6 +24,9 @@ --> IDE0028;IDE0300;IDE0301;IDE0302;IDE0303;IDE0304;IDE0305 $(NoWarn);$(UseCollectionExpressionRules) + + + $(NoWarn);NETSDK1215 @@ -49,13 +52,8 @@ $(NoWarn);CA1062 - - - $(NoWarn);SYSLIB1006 - - - + diff --git a/JsonApiDotNetCore.sln.DotSettings b/JsonApiDotNetCore.sln.DotSettings index 7cbbf82351..0d32615a65 100644 --- a/JsonApiDotNetCore.sln.DotSettings +++ b/JsonApiDotNetCore.sln.DotSettings @@ -1,21 +1,11 @@  - // Use the following placeholders: -// $EXPR$ -- source expression -// $NAME$ -- source name (string literal or 'nameof' expression) -// $MESSAGE$ -- string literal in the form of "$NAME$ != null" -JsonApiDotNetCore.ArgumentGuard.NotNull($EXPR$); - 199 - 5000 - 99 - 100 - 200 - 1000 - 500 + 5000 + 2000 3000 - 50 False True 71287D6F-6C3B-44B4-9FCA-E78FE3F02289/f:SchemaGenerator.cs + 83FF097C-C8C6-477B-9FAB-DF99B84978B5/f:ReadOnlySet.cs swagger.g.json swagger.json SOLUTION @@ -607,7 +597,7 @@ JsonApiDotNetCore.ArgumentGuard.NotNull($EXPR$); True True True - Replace argument null check using throw expression with Guard clause + Replace argument null check using throw expression with ArgumentNullException.ThrowIfNull True True False @@ -626,13 +616,12 @@ JsonApiDotNetCore.ArgumentGuard.NotNull($EXPR$); True CSHARP False - Replace argument null check with Guard clause - JsonApiDotNetCore.ArgumentGuard.NotNull($argument$); + System.ArgumentNullException.ThrowIfNull($argument$); $left$ = $right$; $left$ = $right$ ?? throw new ArgumentNullException(nameof($argument$)); WARNING True - Replace argument == null check with Guard clause + Replace argument == null check with ArgumentNullException.ThrowIfNull True True False @@ -641,8 +630,7 @@ $left$ = $right$; True CSHARP False - Replace argument null check with Guard clause - JsonApiDotNetCore.ArgumentGuard.NotNull($argument$); + System.ArgumentNullException.ThrowIfNull($argument$); if ($argument$ == null) throw new ArgumentNullException(nameof($argument$)); WARNING True @@ -654,12 +642,11 @@ $left$ = $right$; True CSHARP False - Replace collection null/empty check with extension method $collection$.IsNullOrEmpty() $collection$ == null || !$collection$.Any() WARNING True - Replace argument is null check with Guard clause + Replace argument is null check with ArgumentNullException.ThrowIfNull True True False @@ -668,7 +655,7 @@ $left$ = $right$; True CSHARP False - JsonApiDotNetCore.ArgumentGuard.NotNull($argument$); + System.ArgumentNullException.ThrowIfNull($argument$); if ($argument$ is null) throw new ArgumentNullException(nameof($argument$)); WARNING True diff --git a/README.md b/README.md index 3354eac45b..8bd84b3d9c 100644 --- a/README.md +++ b/README.md @@ -87,13 +87,9 @@ See also our [versioning policy](./VERSIONING_POLICY.md). | | | 7 | 7 | | | | 8 | 8, 9 | | | | 9 | 9 | -| master | Preview | 6 | 6, 7 | -| | | 7 | 7 | -| | | 8 | 8, 9 | +| master | Preview | 8 | 8, 9 | | | | 9 | 9 | -| openapi | Experimental | 6 | 6, 7 | -| | | 7 | 7 | -| | | 8 | 8, 9 | +| openapi | Experimental | 8 | 8, 9 | | | | 9 | 9 | ## Contributing diff --git a/benchmarks/Benchmarks.csproj b/benchmarks/Benchmarks.csproj index 9dbb9ba093..90d53461d2 100644 --- a/benchmarks/Benchmarks.csproj +++ b/benchmarks/Benchmarks.csproj @@ -1,7 +1,7 @@ Exe - net8.0 + net9.0 true diff --git a/package-versions.props b/package-versions.props index a6eb42633a..1700f2b66d 100644 --- a/package-versions.props +++ b/package-versions.props @@ -4,49 +4,49 @@ 4.1.0 0.4.1 2.14.1 - 6.8.1 + 7.2.0 13.0.3 - 8.0.* 0.14.* 1.0.* 35.6.* - 4.11.* + 4.12.* 6.0.* 2.1.* - 6.12.* + 7.0.* 2.4.* 2.0.* 1.* - 8.0.* - 14.1.* + 9.0.* + 9.0.* + 14.2.* 13.0.* 8.0.* - 6.*-* - 17.11.* + 7.*-* + 9.0.* + 17.12.* 2.9.* 2.8.* - + - 8.0.0 + N/A - 8.0.* - 8.0.* - $(AspNetCoreVersion) + 9.0.* + 9.0.* + 9.0.0-* - + - 6.0.0 + 8.0.0 - 6.0.* - 2.1.* - 7.0.* - 8.0.* + 8.0.* + 8.0.* + $(EntityFrameworkCoreVersion) diff --git a/src/Examples/DapperExample/AtomicOperations/AmbientTransaction.cs b/src/Examples/DapperExample/AtomicOperations/AmbientTransaction.cs index c442861bc4..11d052da66 100644 --- a/src/Examples/DapperExample/AtomicOperations/AmbientTransaction.cs +++ b/src/Examples/DapperExample/AtomicOperations/AmbientTransaction.cs @@ -1,5 +1,4 @@ using System.Data.Common; -using JsonApiDotNetCore; using JsonApiDotNetCore.AtomicOperations; namespace DapperExample.AtomicOperations; @@ -18,8 +17,8 @@ internal sealed class AmbientTransaction : IOperationsTransaction public AmbientTransaction(AmbientTransactionFactory owner, DbTransaction current, Guid transactionId) { - ArgumentGuard.NotNull(owner); - ArgumentGuard.NotNull(current); + ArgumentNullException.ThrowIfNull(owner); + ArgumentNullException.ThrowIfNull(current); _owner = owner; Current = current; diff --git a/src/Examples/DapperExample/AtomicOperations/AmbientTransactionFactory.cs b/src/Examples/DapperExample/AtomicOperations/AmbientTransactionFactory.cs index d10959b79a..82790819fe 100644 --- a/src/Examples/DapperExample/AtomicOperations/AmbientTransactionFactory.cs +++ b/src/Examples/DapperExample/AtomicOperations/AmbientTransactionFactory.cs @@ -1,6 +1,5 @@ using System.Data.Common; using DapperExample.TranslationToSql.DataModel; -using JsonApiDotNetCore; using JsonApiDotNetCore.AtomicOperations; using JsonApiDotNetCore.Configuration; @@ -18,8 +17,8 @@ public sealed class AmbientTransactionFactory : IOperationsTransactionFactory public AmbientTransactionFactory(IJsonApiOptions options, IDataModelService dataModelService) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(dataModelService); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(dataModelService); _options = options; _dataModelService = dataModelService; @@ -64,7 +63,7 @@ async Task IOperationsTransactionFactory.BeginTransactio internal void Detach(AmbientTransaction ambientTransaction) { - ArgumentGuard.NotNull(ambientTransaction); + ArgumentNullException.ThrowIfNull(ambientTransaction); if (AmbientTransaction != null && AmbientTransaction == ambientTransaction) { diff --git a/src/Examples/DapperExample/DapperExample.csproj b/src/Examples/DapperExample/DapperExample.csproj index f49c3e4b40..ed7bd358eb 100644 --- a/src/Examples/DapperExample/DapperExample.csproj +++ b/src/Examples/DapperExample/DapperExample.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net9.0;net8.0 @@ -16,6 +16,6 @@ - + diff --git a/src/Examples/DapperExample/Data/AppDbContext.cs b/src/Examples/DapperExample/Data/AppDbContext.cs index ee18bab08e..31f09b277c 100644 --- a/src/Examples/DapperExample/Data/AppDbContext.cs +++ b/src/Examples/DapperExample/Data/AppDbContext.cs @@ -1,6 +1,5 @@ using DapperExample.Models; using JetBrains.Annotations; -using JsonApiDotNetCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; @@ -23,7 +22,7 @@ public sealed class AppDbContext : DbContext public AppDbContext(DbContextOptions options, IConfiguration configuration) : base(options) { - ArgumentGuard.NotNull(configuration); + ArgumentNullException.ThrowIfNull(configuration); _configuration = configuration; } diff --git a/src/Examples/DapperExample/Definitions/TodoItemDefinition.cs b/src/Examples/DapperExample/Definitions/TodoItemDefinition.cs index dc7c1802c8..f20268fb7d 100644 --- a/src/Examples/DapperExample/Definitions/TodoItemDefinition.cs +++ b/src/Examples/DapperExample/Definitions/TodoItemDefinition.cs @@ -1,7 +1,6 @@ using System.ComponentModel; using DapperExample.Models; using JetBrains.Annotations; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Middleware; using JsonApiDotNetCore.Queries.Expressions; @@ -12,14 +11,14 @@ namespace DapperExample.Definitions; [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] public sealed class TodoItemDefinition : JsonApiResourceDefinition { - private readonly IClock _clock; + private readonly TimeProvider _timeProvider; - public TodoItemDefinition(IResourceGraph resourceGraph, IClock clock) + public TodoItemDefinition(IResourceGraph resourceGraph, TimeProvider timeProvider) : base(resourceGraph) { - ArgumentGuard.NotNull(clock); + ArgumentNullException.ThrowIfNull(timeProvider); - _clock = clock; + _timeProvider = timeProvider; } public override SortExpression OnApplySort(SortExpression? existingSort) @@ -39,11 +38,11 @@ public override Task OnWritingAsync(TodoItem resource, WriteOperationKind writeO { if (writeOperation == WriteOperationKind.CreateResource) { - resource.CreatedAt = _clock.UtcNow; + resource.CreatedAt = _timeProvider.GetUtcNow(); } else if (writeOperation == WriteOperationKind.UpdateResource) { - resource.LastModifiedAt = _clock.UtcNow; + resource.LastModifiedAt = _timeProvider.GetUtcNow(); } return Task.CompletedTask; diff --git a/src/Examples/DapperExample/FromEntitiesNavigationResolver.cs b/src/Examples/DapperExample/FromEntitiesNavigationResolver.cs index 8ab88473c1..4ae5f05dcc 100644 --- a/src/Examples/DapperExample/FromEntitiesNavigationResolver.cs +++ b/src/Examples/DapperExample/FromEntitiesNavigationResolver.cs @@ -1,6 +1,5 @@ using DapperExample.Data; using DapperExample.TranslationToSql.DataModel; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Repositories; using Microsoft.EntityFrameworkCore; @@ -18,9 +17,9 @@ internal sealed class FromEntitiesNavigationResolver : IInverseNavigationResolve public FromEntitiesNavigationResolver(IResourceGraph resourceGraph, FromEntitiesDataModelService dataModelService, AppDbContext appDbContext) { - ArgumentGuard.NotNull(resourceGraph); - ArgumentGuard.NotNull(dataModelService); - ArgumentGuard.NotNull(appDbContext); + ArgumentNullException.ThrowIfNull(resourceGraph); + ArgumentNullException.ThrowIfNull(dataModelService); + ArgumentNullException.ThrowIfNull(appDbContext); _defaultResolver = new InverseNavigationResolver(resourceGraph, new[] { diff --git a/src/Examples/DapperExample/IClock.cs b/src/Examples/DapperExample/IClock.cs deleted file mode 100644 index 0319c42480..0000000000 --- a/src/Examples/DapperExample/IClock.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace DapperExample; - -public interface IClock -{ - DateTimeOffset UtcNow { get; } -} diff --git a/src/Examples/DapperExample/Program.cs b/src/Examples/DapperExample/Program.cs index f7bf198af9..6e84497d02 100644 --- a/src/Examples/DapperExample/Program.cs +++ b/src/Examples/DapperExample/Program.cs @@ -11,13 +11,12 @@ using JsonApiDotNetCore.Repositories; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; -using Microsoft.Extensions.DependencyInjection.Extensions; WebApplicationBuilder builder = WebApplication.CreateBuilder(args); // Add services to the container. -builder.Services.TryAddSingleton(); +builder.Services.AddSingleton(); DatabaseProvider databaseProvider = GetDatabaseProvider(builder.Configuration); string? connectionString = builder.Configuration.GetConnectionString($"DapperExample{databaseProvider}"); @@ -31,8 +30,13 @@ } case DatabaseProvider.MySql: { - builder.Services.AddMySql(connectionString, ServerVersion.AutoDetect(connectionString), - optionsAction: options => SetDbContextDebugOptions(options)); +#if NET8_0 + ServerVersion serverVersion = ServerVersion.AutoDetect(connectionString); +#else + ServerVersion serverVersion = await ServerVersion.AutoDetectAsync(connectionString); +#endif + + builder.Services.AddMySql(connectionString, serverVersion, optionsAction: options => SetDbContextDebugOptions(options)); break; } diff --git a/src/Examples/DapperExample/Repositories/DapperFacade.cs b/src/Examples/DapperExample/Repositories/DapperFacade.cs index feb0a88e06..e7190ec0de 100644 --- a/src/Examples/DapperExample/Repositories/DapperFacade.cs +++ b/src/Examples/DapperExample/Repositories/DapperFacade.cs @@ -17,14 +17,14 @@ internal sealed class DapperFacade public DapperFacade(IDataModelService dataModelService) { - ArgumentGuard.NotNull(dataModelService); + ArgumentNullException.ThrowIfNull(dataModelService); _dataModelService = dataModelService; } public CommandDefinition GetSqlCommand(SqlTreeNode node, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(node); + ArgumentNullException.ThrowIfNull(node); var queryBuilder = new SqlQueryBuilder(_dataModelService.DatabaseProvider); string statement = queryBuilder.GetCommand(node); @@ -36,7 +36,7 @@ public CommandDefinition GetSqlCommand(SqlTreeNode node, CancellationToken cance public IReadOnlyCollection BuildSqlCommandsForOneToOneRelationshipsChangedToNotNull(ResourceChangeDetector changeDetector, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(changeDetector); + ArgumentNullException.ThrowIfNull(changeDetector); List sqlCommands = []; @@ -79,7 +79,7 @@ public IReadOnlyCollection BuildSqlCommandsForOneToOneRelatio public IReadOnlyCollection BuildSqlCommandsForChangedRelationshipsHavingForeignKeyAtRightSide(ResourceChangeDetector changeDetector, TId leftId, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(changeDetector); + ArgumentNullException.ThrowIfNull(changeDetector); List sqlCommands = []; @@ -126,7 +126,7 @@ public IReadOnlyCollection BuildSqlCommandsForChangedRelation public CommandDefinition BuildSqlCommandForRemoveFromToMany(RelationshipForeignKey foreignKey, object[] rightResourceIdValues, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(foreignKey); + ArgumentNullException.ThrowIfNull(foreignKey); ArgumentGuard.NotNullNorEmpty(rightResourceIdValues); if (!foreignKey.IsNullable) @@ -149,8 +149,8 @@ public CommandDefinition BuildSqlCommandForRemoveFromToMany(RelationshipForeignK public CommandDefinition BuildSqlCommandForAddToToMany(RelationshipForeignKey foreignKey, object leftId, object[] rightResourceIdValues, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(foreignKey); - ArgumentGuard.NotNull(leftId); + ArgumentNullException.ThrowIfNull(foreignKey); + ArgumentNullException.ThrowIfNull(leftId); ArgumentGuard.NotNullNorEmpty(rightResourceIdValues); var columnsToUpdate = new Dictionary @@ -165,7 +165,7 @@ public CommandDefinition BuildSqlCommandForAddToToMany(RelationshipForeignKey fo public CommandDefinition BuildSqlCommandForCreate(ResourceChangeDetector changeDetector, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(changeDetector); + ArgumentNullException.ThrowIfNull(changeDetector); IReadOnlyDictionary columnsToSet = changeDetector.GetChangedColumnValues(); @@ -176,7 +176,7 @@ public CommandDefinition BuildSqlCommandForCreate(ResourceChangeDetector changeD public CommandDefinition? BuildSqlCommandForUpdate(ResourceChangeDetector changeDetector, TId leftId, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(changeDetector); + ArgumentNullException.ThrowIfNull(changeDetector); IReadOnlyDictionary columnsToUpdate = changeDetector.GetChangedColumnValues(); diff --git a/src/Examples/DapperExample/Repositories/DapperRepository.cs b/src/Examples/DapperExample/Repositories/DapperRepository.cs index 7a46e69a53..716db19519 100644 --- a/src/Examples/DapperExample/Repositories/DapperRepository.cs +++ b/src/Examples/DapperExample/Repositories/DapperRepository.cs @@ -114,14 +114,14 @@ public DapperRepository(ITargetedFields targetedFields, IResourceGraph resourceG IResourceDefinitionAccessor resourceDefinitionAccessor, AmbientTransactionFactory transactionFactory, IDataModelService dataModelService, SqlCaptureStore captureStore, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(targetedFields); - ArgumentGuard.NotNull(resourceGraph); - ArgumentGuard.NotNull(resourceFactory); - ArgumentGuard.NotNull(resourceDefinitionAccessor); - ArgumentGuard.NotNull(transactionFactory); - ArgumentGuard.NotNull(dataModelService); - ArgumentGuard.NotNull(captureStore); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(targetedFields); + ArgumentNullException.ThrowIfNull(resourceGraph); + ArgumentNullException.ThrowIfNull(resourceFactory); + ArgumentNullException.ThrowIfNull(resourceDefinitionAccessor); + ArgumentNullException.ThrowIfNull(transactionFactory); + ArgumentNullException.ThrowIfNull(dataModelService); + ArgumentNullException.ThrowIfNull(captureStore); + ArgumentNullException.ThrowIfNull(loggerFactory); _targetedFields = targetedFields; _resourceGraph = resourceGraph; @@ -138,7 +138,7 @@ public DapperRepository(ITargetedFields targetedFields, IResourceGraph resourceG /// public async Task> GetAsync(QueryLayer queryLayer, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(queryLayer); + ArgumentNullException.ThrowIfNull(queryLayer); var mapper = new ResultSetMapper(queryLayer.Include); @@ -180,7 +180,7 @@ public async Task CountAsync(FilterExpression? filter, CancellationToken ca /// public Task GetForCreateAsync(Type resourceClrType, [DisallowNull] TId id, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(resourceClrType); + ArgumentNullException.ThrowIfNull(resourceClrType); var resource = (TResource)_resourceFactory.CreateInstance(resourceClrType); resource.Id = id; @@ -191,8 +191,8 @@ public Task GetForCreateAsync(Type resourceClrType, [DisallowNull] TI /// public async Task CreateAsync(TResource resourceFromRequest, TResource resourceForDatabase, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(resourceFromRequest); - ArgumentGuard.NotNull(resourceForDatabase); + ArgumentNullException.ThrowIfNull(resourceFromRequest); + ArgumentNullException.ThrowIfNull(resourceForDatabase); var changeDetector = new ResourceChangeDetector(ResourceType, _dataModelService); @@ -283,7 +283,7 @@ await _resourceDefinitionAccessor.OnSetToManyRelationshipAsync(leftResource, has /// public async Task GetForUpdateAsync(QueryLayer queryLayer, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(queryLayer); + ArgumentNullException.ThrowIfNull(queryLayer); IReadOnlyCollection resources = await GetAsync(queryLayer, cancellationToken); return resources.FirstOrDefault(); @@ -292,8 +292,8 @@ await _resourceDefinitionAccessor.OnSetToManyRelationshipAsync(leftResource, has /// public async Task UpdateAsync(TResource resourceFromRequest, TResource resourceFromDatabase, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(resourceFromRequest); - ArgumentGuard.NotNull(resourceFromDatabase); + ArgumentNullException.ThrowIfNull(resourceFromRequest); + ArgumentNullException.ThrowIfNull(resourceFromDatabase); var changeDetector = new ResourceChangeDetector(ResourceType, _dataModelService); changeDetector.CaptureCurrentValues(resourceFromDatabase); @@ -384,7 +384,7 @@ await ExecuteInTransactionAsync(async transaction => /// public async Task SetRelationshipAsync(TResource leftResource, object? rightValue, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(leftResource); + ArgumentNullException.ThrowIfNull(leftResource); RelationshipAttribute relationship = _targetedFields.Relationships.Single(); @@ -455,7 +455,7 @@ await ExecuteInTransactionAsync(async transaction => public async Task AddToToManyRelationshipAsync(TResource? leftResource, [DisallowNull] TId leftId, ISet rightResourceIds, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(rightResourceIds); + ArgumentNullException.ThrowIfNull(rightResourceIds); var relationship = (HasManyAttribute)_targetedFields.Relationships.Single(); @@ -495,8 +495,8 @@ await ExecuteInTransactionAsync(async transaction => /// public async Task RemoveFromToManyRelationshipAsync(TResource leftResource, ISet rightResourceIds, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(leftResource); - ArgumentGuard.NotNull(rightResourceIds); + ArgumentNullException.ThrowIfNull(leftResource); + ArgumentNullException.ThrowIfNull(rightResourceIds); var relationship = (HasManyAttribute)_targetedFields.Relationships.Single(); diff --git a/src/Examples/DapperExample/Repositories/ResourceChangeDetector.cs b/src/Examples/DapperExample/Repositories/ResourceChangeDetector.cs index 73213445e2..58f7579254 100644 --- a/src/Examples/DapperExample/Repositories/ResourceChangeDetector.cs +++ b/src/Examples/DapperExample/Repositories/ResourceChangeDetector.cs @@ -24,8 +24,8 @@ internal sealed class ResourceChangeDetector public ResourceChangeDetector(ResourceType resourceType, IDataModelService dataModelService) { - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNull(dataModelService); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentNullException.ThrowIfNull(dataModelService); ResourceType = resourceType; _dataModelService = dataModelService; @@ -33,7 +33,7 @@ public ResourceChangeDetector(ResourceType resourceType, IDataModelService dataM public void CaptureCurrentValues(IIdentifiable resource) { - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); AssertSameType(ResourceType, resource); _currentColumnValues = CaptureColumnValues(resource); @@ -42,7 +42,7 @@ public void CaptureCurrentValues(IIdentifiable resource) public void CaptureNewValues(IIdentifiable resource) { - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); AssertSameType(ResourceType, resource); _newColumnValues = CaptureColumnValues(resource); diff --git a/src/Examples/DapperExample/Repositories/ResultSetMapper.cs b/src/Examples/DapperExample/Repositories/ResultSetMapper.cs index 1b20f74dd9..89a7890fd0 100644 --- a/src/Examples/DapperExample/Repositories/ResultSetMapper.cs +++ b/src/Examples/DapperExample/Repositories/ResultSetMapper.cs @@ -3,9 +3,6 @@ using JsonApiDotNetCore.Queries.Expressions; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; -#if NET6_0 -using JsonApiDotNetCore; -#endif namespace DapperExample.Repositories; diff --git a/src/Examples/DapperExample/SystemClock.cs b/src/Examples/DapperExample/SystemClock.cs deleted file mode 100644 index 3fed87c586..0000000000 --- a/src/Examples/DapperExample/SystemClock.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace DapperExample; - -public sealed class SystemClock : IClock -{ - public DateTimeOffset UtcNow => DateTimeOffset.UtcNow; -} diff --git a/src/Examples/DapperExample/TranslationToSql/Builders/DeleteOneToOneStatementBuilder.cs b/src/Examples/DapperExample/TranslationToSql/Builders/DeleteOneToOneStatementBuilder.cs index 24be003a0a..afd955dc62 100644 --- a/src/Examples/DapperExample/TranslationToSql/Builders/DeleteOneToOneStatementBuilder.cs +++ b/src/Examples/DapperExample/TranslationToSql/Builders/DeleteOneToOneStatementBuilder.cs @@ -1,6 +1,5 @@ using DapperExample.TranslationToSql.DataModel; using DapperExample.TranslationToSql.TreeNodes; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Queries.Expressions; @@ -11,8 +10,8 @@ internal sealed class DeleteOneToOneStatementBuilder(IDataModelService dataModel { public DeleteNode Build(ResourceType resourceType, string whereColumnName, object? whereValue) { - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNullNorEmpty(whereColumnName); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentException.ThrowIfNullOrEmpty(whereColumnName); ResetState(); diff --git a/src/Examples/DapperExample/TranslationToSql/Builders/DeleteResourceStatementBuilder.cs b/src/Examples/DapperExample/TranslationToSql/Builders/DeleteResourceStatementBuilder.cs index 2e4779e334..b3afe4a2a4 100644 --- a/src/Examples/DapperExample/TranslationToSql/Builders/DeleteResourceStatementBuilder.cs +++ b/src/Examples/DapperExample/TranslationToSql/Builders/DeleteResourceStatementBuilder.cs @@ -12,7 +12,7 @@ internal sealed class DeleteResourceStatementBuilder(IDataModelService dataModel { public DeleteNode Build(ResourceType resourceType, params object[] idValues) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); ArgumentGuard.NotNullNorEmpty(idValues); ResetState(); diff --git a/src/Examples/DapperExample/TranslationToSql/Builders/InsertStatementBuilder.cs b/src/Examples/DapperExample/TranslationToSql/Builders/InsertStatementBuilder.cs index 7a12ec5acd..2f71cee112 100644 --- a/src/Examples/DapperExample/TranslationToSql/Builders/InsertStatementBuilder.cs +++ b/src/Examples/DapperExample/TranslationToSql/Builders/InsertStatementBuilder.cs @@ -1,7 +1,6 @@ using System.Collections.ObjectModel; using DapperExample.TranslationToSql.DataModel; using DapperExample.TranslationToSql.TreeNodes; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Resources; @@ -12,8 +11,8 @@ internal sealed class InsertStatementBuilder(IDataModelService dataModelService) { public InsertNode Build(ResourceType resourceType, IReadOnlyDictionary columnsToSet) { - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNull(columnsToSet); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentNullException.ThrowIfNull(columnsToSet); ResetState(); diff --git a/src/Examples/DapperExample/TranslationToSql/Builders/SelectStatementBuilder.cs b/src/Examples/DapperExample/TranslationToSql/Builders/SelectStatementBuilder.cs index 95a2681a80..23a2b7d2d0 100644 --- a/src/Examples/DapperExample/TranslationToSql/Builders/SelectStatementBuilder.cs +++ b/src/Examples/DapperExample/TranslationToSql/Builders/SelectStatementBuilder.cs @@ -4,7 +4,6 @@ using DapperExample.TranslationToSql.Generators; using DapperExample.TranslationToSql.Transformations; using DapperExample.TranslationToSql.TreeNodes; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Errors; using JsonApiDotNetCore.Queries; @@ -50,7 +49,7 @@ private SelectStatementBuilder(QueryState queryState) public SelectNode Build(QueryLayer queryLayer, SelectShape selectShape) { - ArgumentGuard.NotNull(queryLayer); + ArgumentNullException.ThrowIfNull(queryLayer); // Convert queryLayer.Include into multiple levels of queryLayer.Selection. var includeConverter = new QueryLayerIncludeConverter(queryLayer); @@ -701,7 +700,7 @@ private sealed class NullableAttributeFinder : QueryExpressionRewriter public NullableAttributeFinder(IDataModelService dataModelService) { - ArgumentGuard.NotNull(dataModelService); + ArgumentNullException.ThrowIfNull(dataModelService); _dataModelService = dataModelService; } @@ -758,10 +757,10 @@ private sealed class QueryState public QueryState(IDataModelService dataModelService, TableAliasGenerator tableAliasGenerator, ParameterGenerator parameterGenerator, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(dataModelService); - ArgumentGuard.NotNull(tableAliasGenerator); - ArgumentGuard.NotNull(parameterGenerator); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(dataModelService); + ArgumentNullException.ThrowIfNull(tableAliasGenerator); + ArgumentNullException.ThrowIfNull(parameterGenerator); + ArgumentNullException.ThrowIfNull(loggerFactory); DataModelService = dataModelService; TableAliasGenerator = tableAliasGenerator; diff --git a/src/Examples/DapperExample/TranslationToSql/Builders/SqlQueryBuilder.cs b/src/Examples/DapperExample/TranslationToSql/Builders/SqlQueryBuilder.cs index e8cb8f894a..d94eca2f0d 100644 --- a/src/Examples/DapperExample/TranslationToSql/Builders/SqlQueryBuilder.cs +++ b/src/Examples/DapperExample/TranslationToSql/Builders/SqlQueryBuilder.cs @@ -1,6 +1,5 @@ using System.Text; using DapperExample.TranslationToSql.TreeNodes; -using JsonApiDotNetCore; using JsonApiDotNetCore.Queries.Expressions; namespace DapperExample.TranslationToSql.Builders; @@ -37,7 +36,7 @@ internal sealed class SqlQueryBuilder(DatabaseProvider databaseProvider) : SqlTr public string GetCommand(SqlTreeNode node) { - ArgumentGuard.NotNull(node); + ArgumentNullException.ThrowIfNull(node); ResetState(); diff --git a/src/Examples/DapperExample/TranslationToSql/Builders/StatementBuilder.cs b/src/Examples/DapperExample/TranslationToSql/Builders/StatementBuilder.cs index 06ebc1867f..de35ea5ba9 100644 --- a/src/Examples/DapperExample/TranslationToSql/Builders/StatementBuilder.cs +++ b/src/Examples/DapperExample/TranslationToSql/Builders/StatementBuilder.cs @@ -1,7 +1,6 @@ using DapperExample.TranslationToSql.DataModel; using DapperExample.TranslationToSql.Generators; using DapperExample.TranslationToSql.TreeNodes; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Resources.Annotations; @@ -15,7 +14,7 @@ internal abstract class StatementBuilder protected StatementBuilder(IDataModelService dataModelService) { - ArgumentGuard.NotNull(dataModelService); + ArgumentNullException.ThrowIfNull(dataModelService); _dataModelService = dataModelService; } diff --git a/src/Examples/DapperExample/TranslationToSql/Builders/UpdateClearOneToOneStatementBuilder.cs b/src/Examples/DapperExample/TranslationToSql/Builders/UpdateClearOneToOneStatementBuilder.cs index 6a8c33a4e0..610ae9830d 100644 --- a/src/Examples/DapperExample/TranslationToSql/Builders/UpdateClearOneToOneStatementBuilder.cs +++ b/src/Examples/DapperExample/TranslationToSql/Builders/UpdateClearOneToOneStatementBuilder.cs @@ -1,6 +1,5 @@ using DapperExample.TranslationToSql.DataModel; using DapperExample.TranslationToSql.TreeNodes; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Queries.Expressions; @@ -11,9 +10,9 @@ internal sealed class UpdateClearOneToOneStatementBuilder(IDataModelService data { public UpdateNode Build(ResourceType resourceType, string setColumnName, string whereColumnName, object? whereValue) { - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNullNorEmpty(setColumnName); - ArgumentGuard.NotNullNorEmpty(whereColumnName); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentException.ThrowIfNullOrEmpty(setColumnName); + ArgumentException.ThrowIfNullOrEmpty(whereColumnName); ResetState(); diff --git a/src/Examples/DapperExample/TranslationToSql/Builders/UpdateResourceStatementBuilder.cs b/src/Examples/DapperExample/TranslationToSql/Builders/UpdateResourceStatementBuilder.cs index a745747a61..619dba7797 100644 --- a/src/Examples/DapperExample/TranslationToSql/Builders/UpdateResourceStatementBuilder.cs +++ b/src/Examples/DapperExample/TranslationToSql/Builders/UpdateResourceStatementBuilder.cs @@ -12,7 +12,7 @@ internal sealed class UpdateResourceStatementBuilder(IDataModelService dataModel { public UpdateNode Build(ResourceType resourceType, IReadOnlyDictionary columnsToUpdate, params object[] idValues) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); ArgumentGuard.NotNullNorEmpty(columnsToUpdate); ArgumentGuard.NotNullNorEmpty(idValues); diff --git a/src/Examples/DapperExample/TranslationToSql/DataModel/BaseDataModelService.cs b/src/Examples/DapperExample/TranslationToSql/DataModel/BaseDataModelService.cs index 235e3e72d5..3c752ffcbd 100644 --- a/src/Examples/DapperExample/TranslationToSql/DataModel/BaseDataModelService.cs +++ b/src/Examples/DapperExample/TranslationToSql/DataModel/BaseDataModelService.cs @@ -5,7 +5,6 @@ using System.Reflection; using Dapper; using DapperExample.TranslationToSql.TreeNodes; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; @@ -25,7 +24,7 @@ public abstract class BaseDataModelService : IDataModelService protected BaseDataModelService(IResourceGraph resourceGraph) { - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(resourceGraph); ResourceGraph = resourceGraph; } @@ -114,10 +113,10 @@ private static bool IsMapped(PropertyInfo property) public object? GetColumnValue(ResourceType resourceType, IIdentifiable resource, string columnName) { - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentNullException.ThrowIfNull(resource); AssertSameType(resourceType, resource); - ArgumentGuard.NotNullNorEmpty(columnName); + ArgumentException.ThrowIfNullOrEmpty(columnName); IReadOnlyDictionary columnMappings = GetColumnMappings(resourceType); diff --git a/src/Examples/DapperExample/TranslationToSql/DataModel/RelationshipForeignKey.cs b/src/Examples/DapperExample/TranslationToSql/DataModel/RelationshipForeignKey.cs index 6f5572001a..94633a9c36 100644 --- a/src/Examples/DapperExample/TranslationToSql/DataModel/RelationshipForeignKey.cs +++ b/src/Examples/DapperExample/TranslationToSql/DataModel/RelationshipForeignKey.cs @@ -2,7 +2,6 @@ using DapperExample.TranslationToSql.Builders; using Humanizer; using JetBrains.Annotations; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Resources.Annotations; @@ -38,8 +37,8 @@ public sealed class RelationshipForeignKey public RelationshipForeignKey(DatabaseProvider databaseProvider, RelationshipAttribute relationship, bool isAtLeftSide, string columnName, bool isNullable) { - ArgumentGuard.NotNull(relationship); - ArgumentGuard.NotNullNorEmpty(columnName); + ArgumentNullException.ThrowIfNull(relationship); + ArgumentException.ThrowIfNullOrEmpty(columnName); _databaseProvider = databaseProvider; Relationship = relationship; diff --git a/src/Examples/DapperExample/TranslationToSql/Generators/UniqueNameGenerator.cs b/src/Examples/DapperExample/TranslationToSql/Generators/UniqueNameGenerator.cs index 3ea42ab529..5254f4a024 100644 --- a/src/Examples/DapperExample/TranslationToSql/Generators/UniqueNameGenerator.cs +++ b/src/Examples/DapperExample/TranslationToSql/Generators/UniqueNameGenerator.cs @@ -1,5 +1,3 @@ -using JsonApiDotNetCore; - namespace DapperExample.TranslationToSql.Generators; internal abstract class UniqueNameGenerator @@ -9,7 +7,7 @@ internal abstract class UniqueNameGenerator protected UniqueNameGenerator(string prefix) { - ArgumentGuard.NotNullNorEmpty(prefix); + ArgumentException.ThrowIfNullOrEmpty(prefix); _prefix = prefix; } diff --git a/src/Examples/DapperExample/TranslationToSql/SqlCommand.cs b/src/Examples/DapperExample/TranslationToSql/SqlCommand.cs index 37ed2d3ea5..735da0a55f 100644 --- a/src/Examples/DapperExample/TranslationToSql/SqlCommand.cs +++ b/src/Examples/DapperExample/TranslationToSql/SqlCommand.cs @@ -1,5 +1,4 @@ using JetBrains.Annotations; -using JsonApiDotNetCore; namespace DapperExample.TranslationToSql; @@ -14,8 +13,8 @@ public sealed class SqlCommand internal SqlCommand(string statement, IDictionary parameters) { - ArgumentGuard.NotNull(statement); - ArgumentGuard.NotNull(parameters); + ArgumentNullException.ThrowIfNull(statement); + ArgumentNullException.ThrowIfNull(parameters); Statement = statement; Parameters = parameters; diff --git a/src/Examples/DapperExample/TranslationToSql/Transformations/ColumnSelectorUsageCollector.cs b/src/Examples/DapperExample/TranslationToSql/Transformations/ColumnSelectorUsageCollector.cs index d218093936..e7c7799700 100644 --- a/src/Examples/DapperExample/TranslationToSql/Transformations/ColumnSelectorUsageCollector.cs +++ b/src/Examples/DapperExample/TranslationToSql/Transformations/ColumnSelectorUsageCollector.cs @@ -1,5 +1,4 @@ using DapperExample.TranslationToSql.TreeNodes; -using JsonApiDotNetCore; namespace DapperExample.TranslationToSql.Transformations; @@ -15,14 +14,14 @@ internal sealed partial class ColumnSelectorUsageCollector : SqlTreeNodeVisitor< public ColumnSelectorUsageCollector(ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(loggerFactory); _logger = loggerFactory.CreateLogger(); } public void Collect(SelectNode select) { - ArgumentGuard.NotNull(select); + ArgumentNullException.ThrowIfNull(select); LogStarted(); diff --git a/src/Examples/DapperExample/TranslationToSql/Transformations/StaleColumnReferenceRewriter.cs b/src/Examples/DapperExample/TranslationToSql/Transformations/StaleColumnReferenceRewriter.cs index 6f42345ee1..e364203684 100644 --- a/src/Examples/DapperExample/TranslationToSql/Transformations/StaleColumnReferenceRewriter.cs +++ b/src/Examples/DapperExample/TranslationToSql/Transformations/StaleColumnReferenceRewriter.cs @@ -1,7 +1,6 @@ using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using DapperExample.TranslationToSql.TreeNodes; -using JsonApiDotNetCore; namespace DapperExample.TranslationToSql.Transformations; @@ -37,8 +36,8 @@ internal sealed partial class StaleColumnReferenceRewriter : SqlTreeNodeVisitor< public StaleColumnReferenceRewriter(IReadOnlyDictionary oldToNewTableAliasMap, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(oldToNewTableAliasMap); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(oldToNewTableAliasMap); + ArgumentNullException.ThrowIfNull(loggerFactory); _oldToNewTableAliasMap = oldToNewTableAliasMap; _logger = loggerFactory.CreateLogger(); diff --git a/src/Examples/DapperExample/TranslationToSql/Transformations/UnusedSelectorsRewriter.cs b/src/Examples/DapperExample/TranslationToSql/Transformations/UnusedSelectorsRewriter.cs index 08f09da99a..fe0f326209 100644 --- a/src/Examples/DapperExample/TranslationToSql/Transformations/UnusedSelectorsRewriter.cs +++ b/src/Examples/DapperExample/TranslationToSql/Transformations/UnusedSelectorsRewriter.cs @@ -1,7 +1,6 @@ using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using DapperExample.TranslationToSql.TreeNodes; -using JsonApiDotNetCore; namespace DapperExample.TranslationToSql.Transformations; @@ -36,7 +35,7 @@ internal sealed partial class UnusedSelectorsRewriter : SqlTreeNodeVisitor(); @@ -44,7 +43,7 @@ public UnusedSelectorsRewriter(ILoggerFactory loggerFactory) public SelectNode RemoveUnusedSelectorsInSubQueries(SelectNode select) { - ArgumentGuard.NotNull(select); + ArgumentNullException.ThrowIfNull(select); _rootSelect = select; diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/ColumnAssignmentNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/ColumnAssignmentNode.cs index 1884dc8dbf..3578ea9a55 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/ColumnAssignmentNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/ColumnAssignmentNode.cs @@ -1,5 +1,3 @@ -using JsonApiDotNetCore; - namespace DapperExample.TranslationToSql.TreeNodes; /// @@ -17,8 +15,8 @@ internal sealed class ColumnAssignmentNode : SqlTreeNode public ColumnAssignmentNode(ColumnNode column, SqlValueNode value) { - ArgumentGuard.NotNull(column); - ArgumentGuard.NotNull(value); + ArgumentNullException.ThrowIfNull(column); + ArgumentNullException.ThrowIfNull(value); Column = column; Value = value; diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/ColumnInSelectNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/ColumnInSelectNode.cs index 88625104d2..14d82bb1d3 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/ColumnInSelectNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/ColumnInSelectNode.cs @@ -1,5 +1,3 @@ -using JsonApiDotNetCore; - namespace DapperExample.TranslationToSql.TreeNodes; /// @@ -19,7 +17,7 @@ internal sealed class ColumnInSelectNode(ColumnSelectorNode selector, string? ta private static string GetColumnName(ColumnSelectorNode selector) { - ArgumentGuard.NotNull(selector); + ArgumentNullException.ThrowIfNull(selector); return selector.Identity; } diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/ColumnNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/ColumnNode.cs index e4fbcf14e6..da348882a9 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/ColumnNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/ColumnNode.cs @@ -1,5 +1,3 @@ -using JsonApiDotNetCore; - namespace DapperExample.TranslationToSql.TreeNodes; /// @@ -13,7 +11,7 @@ internal abstract class ColumnNode : SqlValueNode protected ColumnNode(string name, ColumnType type, string? tableAlias) { - ArgumentGuard.NotNullNorEmpty(name); + ArgumentException.ThrowIfNullOrEmpty(name); Name = name; Type = type; diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/ColumnSelectorNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/ColumnSelectorNode.cs index ab2ab1031f..6c8bb9e36a 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/ColumnSelectorNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/ColumnSelectorNode.cs @@ -1,5 +1,3 @@ -using JsonApiDotNetCore; - namespace DapperExample.TranslationToSql.TreeNodes; /// @@ -19,7 +17,7 @@ internal sealed class ColumnSelectorNode : SelectorNode public ColumnSelectorNode(ColumnNode column, string? alias) : base(alias) { - ArgumentGuard.NotNull(column); + ArgumentNullException.ThrowIfNull(column); Column = column; } diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/ComparisonNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/ComparisonNode.cs index dbf61d5451..7264189a6d 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/ComparisonNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/ComparisonNode.cs @@ -1,4 +1,3 @@ -using JsonApiDotNetCore; using JsonApiDotNetCore.Queries.Expressions; namespace DapperExample.TranslationToSql.TreeNodes; @@ -16,8 +15,8 @@ internal sealed class ComparisonNode : FilterNode public ComparisonNode(ComparisonOperator @operator, SqlValueNode left, SqlValueNode right) { - ArgumentGuard.NotNull(left); - ArgumentGuard.NotNull(right); + ArgumentNullException.ThrowIfNull(left); + ArgumentNullException.ThrowIfNull(right); Operator = @operator; Left = left; diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/CountNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/CountNode.cs index 07182d036f..9133969961 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/CountNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/CountNode.cs @@ -1,5 +1,3 @@ -using JsonApiDotNetCore; - namespace DapperExample.TranslationToSql.TreeNodes; /// @@ -16,7 +14,7 @@ internal sealed class CountNode : SqlValueNode public CountNode(SelectNode subSelect) { - ArgumentGuard.NotNull(subSelect); + ArgumentNullException.ThrowIfNull(subSelect); SubSelect = subSelect; } diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/DeleteNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/DeleteNode.cs index aa3968f872..512e0e7321 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/DeleteNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/DeleteNode.cs @@ -1,5 +1,3 @@ -using JsonApiDotNetCore; - namespace DapperExample.TranslationToSql.TreeNodes; /// @@ -14,8 +12,8 @@ internal sealed class DeleteNode : SqlTreeNode public DeleteNode(TableNode table, WhereNode where) { - ArgumentGuard.NotNull(table); - ArgumentGuard.NotNull(where); + ArgumentNullException.ThrowIfNull(table); + ArgumentNullException.ThrowIfNull(where); Table = table; Where = where; diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/ExistsNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/ExistsNode.cs index b73882122c..96087886f9 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/ExistsNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/ExistsNode.cs @@ -1,5 +1,3 @@ -using JsonApiDotNetCore; - namespace DapperExample.TranslationToSql.TreeNodes; /// @@ -16,7 +14,7 @@ internal sealed class ExistsNode : FilterNode public ExistsNode(SelectNode subSelect) { - ArgumentGuard.NotNull(subSelect); + ArgumentNullException.ThrowIfNull(subSelect); SubSelect = subSelect; } diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/InNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/InNode.cs index 26d3c2ec47..114a141eaa 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/InNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/InNode.cs @@ -14,7 +14,7 @@ internal sealed class InNode : FilterNode public InNode(ColumnNode column, IReadOnlyList values) { - ArgumentGuard.NotNull(column); + ArgumentNullException.ThrowIfNull(column); ArgumentGuard.NotNullNorEmpty(values); Column = column; diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/InsertNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/InsertNode.cs index 8ed6770136..f85857f677 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/InsertNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/InsertNode.cs @@ -14,7 +14,7 @@ internal sealed class InsertNode : SqlTreeNode public InsertNode(TableNode table, IReadOnlyCollection assignments) { - ArgumentGuard.NotNull(table); + ArgumentNullException.ThrowIfNull(table); ArgumentGuard.NotNullNorEmpty(assignments); Table = table; diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/JoinNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/JoinNode.cs index 6ed2e4c73c..48140a0c04 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/JoinNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/JoinNode.cs @@ -1,5 +1,3 @@ -using JsonApiDotNetCore; - namespace DapperExample.TranslationToSql.TreeNodes; /// @@ -16,8 +14,8 @@ internal sealed class JoinNode : TableAccessorNode public JoinNode(JoinType joinType, TableSourceNode source, ColumnNode outerColumn, ColumnNode innerColumn) : base(source) { - ArgumentGuard.NotNull(outerColumn); - ArgumentGuard.NotNull(innerColumn); + ArgumentNullException.ThrowIfNull(outerColumn); + ArgumentNullException.ThrowIfNull(innerColumn); JoinType = joinType; OuterColumn = outerColumn; diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/LikeNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/LikeNode.cs index 034e5c012e..f713e687fc 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/LikeNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/LikeNode.cs @@ -1,4 +1,3 @@ -using JsonApiDotNetCore; using JsonApiDotNetCore.Queries.Expressions; namespace DapperExample.TranslationToSql.TreeNodes; @@ -16,8 +15,8 @@ internal sealed class LikeNode : FilterNode public LikeNode(ColumnNode column, TextMatchKind matchKind, string text) { - ArgumentGuard.NotNull(column); - ArgumentGuard.NotNull(text); + ArgumentNullException.ThrowIfNull(column); + ArgumentNullException.ThrowIfNull(text); Column = column; MatchKind = matchKind; diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/LogicalNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/LogicalNode.cs index a01306d061..ebf0554167 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/LogicalNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/LogicalNode.cs @@ -1,4 +1,3 @@ -using JsonApiDotNetCore; using JsonApiDotNetCore.Queries.Expressions; namespace DapperExample.TranslationToSql.TreeNodes; @@ -20,7 +19,7 @@ public LogicalNode(LogicalOperator @operator, params FilterNode[] terms) public LogicalNode(LogicalOperator @operator, IReadOnlyList terms) { - ArgumentGuard.NotNull(terms); + ArgumentNullException.ThrowIfNull(terms); if (terms.Count < 2) { diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/NotNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/NotNode.cs index 38c5d80f26..f1f2e9ed22 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/NotNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/NotNode.cs @@ -1,5 +1,3 @@ -using JsonApiDotNetCore; - namespace DapperExample.TranslationToSql.TreeNodes; /// @@ -13,7 +11,7 @@ internal sealed class NotNode : FilterNode public NotNode(FilterNode child) { - ArgumentGuard.NotNull(child); + ArgumentNullException.ThrowIfNull(child); Child = child; } diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/OrderByColumnNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/OrderByColumnNode.cs index 372b1e86ff..a62094ae5b 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/OrderByColumnNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/OrderByColumnNode.cs @@ -1,5 +1,3 @@ -using JsonApiDotNetCore; - namespace DapperExample.TranslationToSql.TreeNodes; /// @@ -17,7 +15,7 @@ internal sealed class OrderByColumnNode : OrderByTermNode public OrderByColumnNode(ColumnNode column, bool isAscending) : base(isAscending) { - ArgumentGuard.NotNull(column); + ArgumentNullException.ThrowIfNull(column); Column = column; } diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/OrderByCountNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/OrderByCountNode.cs index 3d8f8c240a..c044d98ba9 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/OrderByCountNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/OrderByCountNode.cs @@ -1,5 +1,3 @@ -using JsonApiDotNetCore; - namespace DapperExample.TranslationToSql.TreeNodes; /// @@ -17,7 +15,7 @@ internal sealed class OrderByCountNode : OrderByTermNode public OrderByCountNode(CountNode count, bool isAscending) : base(isAscending) { - ArgumentGuard.NotNull(count); + ArgumentNullException.ThrowIfNull(count); Count = count; } diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/ParameterNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/ParameterNode.cs index a9feaa7836..6e206fa04d 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/ParameterNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/ParameterNode.cs @@ -1,5 +1,3 @@ -using JsonApiDotNetCore; - namespace DapperExample.TranslationToSql.TreeNodes; /// @@ -16,7 +14,7 @@ internal sealed class ParameterNode : SqlValueNode public ParameterNode(string name, object? value) { - ArgumentGuard.NotNullNorEmpty(name); + ArgumentException.ThrowIfNullOrEmpty(name); if (!name.StartsWith('@') || name.Length < 2) { diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/TableAccessorNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/TableAccessorNode.cs index 4096789919..2822749230 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/TableAccessorNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/TableAccessorNode.cs @@ -1,5 +1,3 @@ -using JsonApiDotNetCore; - namespace DapperExample.TranslationToSql.TreeNodes; /// @@ -11,7 +9,7 @@ internal abstract class TableAccessorNode : SqlTreeNode protected TableAccessorNode(TableSourceNode source) { - ArgumentGuard.NotNull(source); + ArgumentNullException.ThrowIfNull(source); Source = source; } diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/TableNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/TableNode.cs index 6abb913418..9fca1971cb 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/TableNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/TableNode.cs @@ -1,5 +1,4 @@ using Humanizer; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Resources.Annotations; @@ -26,8 +25,8 @@ internal sealed class TableNode : TableSourceNode public TableNode(ResourceType resourceType, IReadOnlyDictionary columnMappings, string? alias) : base(alias) { - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNull(columnMappings); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentNullException.ThrowIfNull(columnMappings); _resourceType = resourceType; _columnMappings = columnMappings; diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/UpdateNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/UpdateNode.cs index 3aa5dbdf73..7f9b1b79a4 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/UpdateNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/UpdateNode.cs @@ -15,9 +15,9 @@ internal sealed class UpdateNode : SqlTreeNode public UpdateNode(TableNode table, IReadOnlyCollection assignments, WhereNode where) { - ArgumentGuard.NotNull(table); + ArgumentNullException.ThrowIfNull(table); ArgumentGuard.NotNullNorEmpty(assignments); - ArgumentGuard.NotNull(where); + ArgumentNullException.ThrowIfNull(where); Table = table; Assignments = assignments; diff --git a/src/Examples/DapperExample/TranslationToSql/TreeNodes/WhereNode.cs b/src/Examples/DapperExample/TranslationToSql/TreeNodes/WhereNode.cs index d8d72601c5..4e8c4d54e8 100644 --- a/src/Examples/DapperExample/TranslationToSql/TreeNodes/WhereNode.cs +++ b/src/Examples/DapperExample/TranslationToSql/TreeNodes/WhereNode.cs @@ -1,5 +1,3 @@ -using JsonApiDotNetCore; - namespace DapperExample.TranslationToSql.TreeNodes; /// @@ -13,7 +11,7 @@ internal sealed class WhereNode : SqlTreeNode public WhereNode(FilterNode filter) { - ArgumentGuard.NotNull(filter); + ArgumentNullException.ThrowIfNull(filter); Filter = filter; } diff --git a/src/Examples/DatabasePerTenantExample/DatabasePerTenantExample.csproj b/src/Examples/DatabasePerTenantExample/DatabasePerTenantExample.csproj index 0ccb4bbc5f..3edc993428 100644 --- a/src/Examples/DatabasePerTenantExample/DatabasePerTenantExample.csproj +++ b/src/Examples/DatabasePerTenantExample/DatabasePerTenantExample.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net9.0;net8.0 diff --git a/src/Examples/GettingStarted/GettingStarted.csproj b/src/Examples/GettingStarted/GettingStarted.csproj index 1f4645f323..611aeb37a5 100644 --- a/src/Examples/GettingStarted/GettingStarted.csproj +++ b/src/Examples/GettingStarted/GettingStarted.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net9.0;net8.0 diff --git a/src/Examples/JsonApiDotNetCoreExample/Definitions/TodoItemDefinition.cs b/src/Examples/JsonApiDotNetCoreExample/Definitions/TodoItemDefinition.cs index cd85ccd696..06036968d0 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Definitions/TodoItemDefinition.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Definitions/TodoItemDefinition.cs @@ -5,28 +5,14 @@ using JsonApiDotNetCore.Queries.Expressions; using JsonApiDotNetCore.Resources; using JsonApiDotNetCoreExample.Models; -#if NET6_0 -using Microsoft.AspNetCore.Authentication; -#endif namespace JsonApiDotNetCoreExample.Definitions; [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] -public sealed class TodoItemDefinition( - IResourceGraph resourceGraph, -#if NET6_0 - ISystemClock systemClock -#else - TimeProvider timeProvider -#endif -) +public sealed class TodoItemDefinition(IResourceGraph resourceGraph, TimeProvider timeProvider) : JsonApiResourceDefinition(resourceGraph) { -#if NET6_0 - private readonly Func _getUtcNow = () => systemClock.UtcNow; -#else - private readonly Func _getUtcNow = timeProvider.GetUtcNow; -#endif + private readonly TimeProvider _timeProvider = timeProvider; public override SortExpression OnApplySort(SortExpression? existingSort) { @@ -45,11 +31,11 @@ public override Task OnWritingAsync(TodoItem resource, WriteOperationKind writeO { if (writeOperation == WriteOperationKind.CreateResource) { - resource.CreatedAt = _getUtcNow(); + resource.CreatedAt = _timeProvider.GetUtcNow(); } else if (writeOperation == WriteOperationKind.UpdateResource) { - resource.LastModifiedAt = _getUtcNow(); + resource.LastModifiedAt = _timeProvider.GetUtcNow(); } return Task.CompletedTask; diff --git a/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj b/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj index e55c2ae00d..bf0dce1b3c 100644 --- a/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj +++ b/src/Examples/JsonApiDotNetCoreExample/JsonApiDotNetCoreExample.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net9.0;net8.0 true GeneratedSwagger @@ -16,7 +16,7 @@ - + diff --git a/src/Examples/JsonApiDotNetCoreExample/Program.cs b/src/Examples/JsonApiDotNetCoreExample/Program.cs index 54fa5899a3..b8b33505cf 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Program.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Program.cs @@ -9,9 +9,6 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.DependencyInjection.Extensions; -#if NET6_0 -using Microsoft.AspNetCore.Authentication; -#endif [assembly: ExcludeFromCodeCoverage] @@ -52,11 +49,7 @@ static void ConfigureServices(WebApplicationBuilder builder) { using IDisposable _ = CodeTimingSessionManager.Current.Measure("Configure services"); -#if NET6_0 - builder.Services.TryAddSingleton(); -#else builder.Services.TryAddSingleton(TimeProvider.System); -#endif builder.Services.AddDbContext(options => { diff --git a/src/Examples/MultiDbContextExample/MultiDbContextExample.csproj b/src/Examples/MultiDbContextExample/MultiDbContextExample.csproj index 1f4645f323..611aeb37a5 100644 --- a/src/Examples/MultiDbContextExample/MultiDbContextExample.csproj +++ b/src/Examples/MultiDbContextExample/MultiDbContextExample.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net9.0;net8.0 diff --git a/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj b/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj index c5b18320f0..15a485c08f 100644 --- a/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj +++ b/src/Examples/NoEntityFrameworkExample/NoEntityFrameworkExample.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net9.0;net8.0 diff --git a/src/Examples/NoEntityFrameworkExample/Repositories/InMemoryResourceRepository.cs b/src/Examples/NoEntityFrameworkExample/Repositories/InMemoryResourceRepository.cs index 9eba0b8326..4feb370858 100644 --- a/src/Examples/NoEntityFrameworkExample/Repositories/InMemoryResourceRepository.cs +++ b/src/Examples/NoEntityFrameworkExample/Repositories/InMemoryResourceRepository.cs @@ -32,11 +32,7 @@ public Task> GetAsync(QueryLayer queryLayer, Canc IEnumerable dataSource = GetDataSource(); IEnumerable resources = _queryLayerToLinqConverter.ApplyQueryLayer(queryLayer, dataSource); -#if NET6_0 - return Task.FromResult>(Array.AsReadOnly(resources.ToArray())); -#else return Task.FromResult>(resources.ToArray().AsReadOnly()); -#endif } /// diff --git a/src/Examples/NoEntityFrameworkExample/Services/InMemoryResourceService.cs b/src/Examples/NoEntityFrameworkExample/Services/InMemoryResourceService.cs index e55b9340b6..0dcc5d9905 100644 --- a/src/Examples/NoEntityFrameworkExample/Services/InMemoryResourceService.cs +++ b/src/Examples/NoEntityFrameworkExample/Services/InMemoryResourceService.cs @@ -65,11 +65,7 @@ public Task> GetAsync(CancellationToken cancellat _paginationContext.IsPageFull = true; } -#if NET6_0 - return Task.FromResult>(Array.AsReadOnly(resources)); -#else return Task.FromResult>(resources.AsReadOnly()); -#endif } private void LogFiltersInTopScope() diff --git a/src/Examples/OpenApiKiotaClientExample/OpenApiKiotaClientExample.csproj b/src/Examples/OpenApiKiotaClientExample/OpenApiKiotaClientExample.csproj index 78dda553e9..d1d0dae36a 100644 --- a/src/Examples/OpenApiKiotaClientExample/OpenApiKiotaClientExample.csproj +++ b/src/Examples/OpenApiKiotaClientExample/OpenApiKiotaClientExample.csproj @@ -1,6 +1,6 @@ - net8.0 + net9.0 @@ -20,6 +20,10 @@ + + + + diff --git a/src/Examples/OpenApiNSwagClientExample/OpenApiNSwagClientExample.csproj b/src/Examples/OpenApiNSwagClientExample/OpenApiNSwagClientExample.csproj index 8485aa8c4e..c30833a39a 100644 --- a/src/Examples/OpenApiNSwagClientExample/OpenApiNSwagClientExample.csproj +++ b/src/Examples/OpenApiNSwagClientExample/OpenApiNSwagClientExample.csproj @@ -1,7 +1,7 @@ - net8.0 + net9.0 diff --git a/src/Examples/ReportsExample/ReportsExample.csproj b/src/Examples/ReportsExample/ReportsExample.csproj index bff4909317..6ade1386be 100644 --- a/src/Examples/ReportsExample/ReportsExample.csproj +++ b/src/Examples/ReportsExample/ReportsExample.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net9.0;net8.0 diff --git a/src/JsonApiDotNetCore.Annotations/ArgumentGuard.cs b/src/JsonApiDotNetCore.Annotations/ArgumentGuard.cs index e01b80d776..1eea1c3841 100644 --- a/src/JsonApiDotNetCore.Annotations/ArgumentGuard.cs +++ b/src/JsonApiDotNetCore.Annotations/ArgumentGuard.cs @@ -9,13 +9,6 @@ namespace JsonApiDotNetCore; internal static class ArgumentGuard { - [AssertionMethod] - public static void NotNull([NoEnumeration] [SysNotNull] T? value, [CallerArgumentExpression(nameof(value))] string? parameterName = null) - where T : class - { - ArgumentNullException.ThrowIfNull(value, parameterName); - } - [AssertionMethod] public static void NotNullNorEmpty([SysNotNull] IEnumerable? value, [CallerArgumentExpression(nameof(value))] string? parameterName = null) { @@ -26,34 +19,4 @@ public static void NotNullNorEmpty([SysNotNull] IEnumerable? value, [Calle throw new ArgumentException("Collection cannot be null or empty.", parameterName); } } - - [AssertionMethod] - public static void NotNullNorEmpty([SysNotNull] string? value, [CallerArgumentExpression(nameof(value))] string? parameterName = null) - { -#if !NET6_0 - ArgumentException.ThrowIfNullOrEmpty(value, parameterName); -#else - ArgumentNullException.ThrowIfNull(value, parameterName); - - if (value.Length == 0) - { - throw new ArgumentException("String cannot be null or empty.", parameterName); - } -#endif - } - - [AssertionMethod] - public static void NotNullNorWhitespace([SysNotNull] string? value, [CallerArgumentExpression(nameof(value))] string? parameterName = null) - { -#if !NET6_0 - ArgumentException.ThrowIfNullOrWhiteSpace(value, parameterName); -#else - ArgumentNullException.ThrowIfNull(value, parameterName); - - if (string.IsNullOrWhiteSpace(value)) - { - throw new ArgumentException("String cannot be null, empty, or whitespace.", parameterName); - } -#endif - } } diff --git a/src/JsonApiDotNetCore.Annotations/CollectionConverter.cs b/src/JsonApiDotNetCore.Annotations/CollectionConverter.cs index f055c6548f..cbf834b630 100644 --- a/src/JsonApiDotNetCore.Annotations/CollectionConverter.cs +++ b/src/JsonApiDotNetCore.Annotations/CollectionConverter.cs @@ -36,8 +36,8 @@ private CollectionConverter() /// public IEnumerable CopyToTypedCollection(IEnumerable source, Type collectionType) { - ArgumentGuard.NotNull(source); - ArgumentGuard.NotNull(collectionType); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(collectionType); Type concreteCollectionType = ToConcreteCollectionType(collectionType); dynamic concreteCollectionInstance = Activator.CreateInstance(concreteCollectionType)!; @@ -125,7 +125,7 @@ public IReadOnlyCollection ExtractResources(object? value) /// public bool TypeCanContainHashSet(Type collectionType) { - ArgumentGuard.NotNull(collectionType); + ArgumentNullException.ThrowIfNull(collectionType); if (collectionType.IsGenericType) { diff --git a/src/JsonApiDotNetCore.Annotations/Configuration/ResourceType.cs b/src/JsonApiDotNetCore.Annotations/Configuration/ResourceType.cs index 07817698e0..3cda945d74 100644 --- a/src/JsonApiDotNetCore.Annotations/Configuration/ResourceType.cs +++ b/src/JsonApiDotNetCore.Annotations/Configuration/ResourceType.cs @@ -111,9 +111,9 @@ public ResourceType(string publicName, ClientIdGenerationMode? clientIdGeneratio IReadOnlyCollection? eagerLoads, LinkTypes topLevelLinks = LinkTypes.NotConfigured, LinkTypes resourceLinks = LinkTypes.NotConfigured, LinkTypes relationshipLinks = LinkTypes.NotConfigured) { - ArgumentGuard.NotNullNorWhitespace(publicName); - ArgumentGuard.NotNull(clrType); - ArgumentGuard.NotNull(identityClrType); + ArgumentException.ThrowIfNullOrWhiteSpace(publicName); + ArgumentNullException.ThrowIfNull(clrType); + ArgumentNullException.ThrowIfNull(identityClrType); PublicName = publicName; ClientIdGeneration = clientIdGeneration; @@ -165,7 +165,7 @@ public AttrAttribute GetAttributeByPublicName(string publicName) public AttrAttribute? FindAttributeByPublicName(string publicName) { - ArgumentGuard.NotNull(publicName); + ArgumentNullException.ThrowIfNull(publicName); return _fieldsByPublicName.TryGetValue(publicName, out ResourceFieldAttribute? field) && field is AttrAttribute attribute ? attribute : null; } @@ -179,7 +179,7 @@ public AttrAttribute GetAttributeByPropertyName(string propertyName) public AttrAttribute? FindAttributeByPropertyName(string propertyName) { - ArgumentGuard.NotNull(propertyName); + ArgumentNullException.ThrowIfNull(propertyName); return _fieldsByPropertyName.TryGetValue(propertyName, out ResourceFieldAttribute? field) && field is AttrAttribute attribute ? attribute : null; } @@ -192,7 +192,7 @@ public RelationshipAttribute GetRelationshipByPublicName(string publicName) public RelationshipAttribute? FindRelationshipByPublicName(string publicName) { - ArgumentGuard.NotNull(publicName); + ArgumentNullException.ThrowIfNull(publicName); return _fieldsByPublicName.TryGetValue(publicName, out ResourceFieldAttribute? field) && field is RelationshipAttribute relationship ? relationship @@ -209,7 +209,7 @@ public RelationshipAttribute GetRelationshipByPropertyName(string propertyName) public RelationshipAttribute? FindRelationshipByPropertyName(string propertyName) { - ArgumentGuard.NotNull(propertyName); + ArgumentNullException.ThrowIfNull(propertyName); return _fieldsByPropertyName.TryGetValue(propertyName, out ResourceFieldAttribute? field) && field is RelationshipAttribute relationship ? relationship @@ -229,7 +229,7 @@ public IReadOnlySet GetAllConcreteDerivedTypes() /// public ResourceType GetTypeOrDerived(Type clrType) { - ArgumentGuard.NotNull(clrType); + ArgumentNullException.ThrowIfNull(clrType); ResourceType? derivedType = FindTypeOrDerived(this, clrType); diff --git a/src/JsonApiDotNetCore.Annotations/JsonApiDotNetCore.Annotations.csproj b/src/JsonApiDotNetCore.Annotations/JsonApiDotNetCore.Annotations.csproj index 04238621da..09968a0922 100644 --- a/src/JsonApiDotNetCore.Annotations/JsonApiDotNetCore.Annotations.csproj +++ b/src/JsonApiDotNetCore.Annotations/JsonApiDotNetCore.Annotations.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0;netstandard1.0 + net8.0;netstandard1.0 true true JsonApiDotNetCore diff --git a/src/JsonApiDotNetCore.Annotations/PolyfillCollectionExtensions.cs b/src/JsonApiDotNetCore.Annotations/PolyfillCollectionExtensions.cs index 72578e5db2..efc51f4f17 100644 --- a/src/JsonApiDotNetCore.Annotations/PolyfillCollectionExtensions.cs +++ b/src/JsonApiDotNetCore.Annotations/PolyfillCollectionExtensions.cs @@ -1,10 +1,4 @@ -#if NET6_0 using System.Collections.ObjectModel; -#endif - -#if NET6_0 -#pragma warning disable AV1130 // Return type in method signature should be an interface to an unchangeable collection -#endif namespace JsonApiDotNetCore; @@ -13,22 +7,6 @@ internal static class PolyfillCollectionExtensions { public static IReadOnlySet AsReadOnly(this HashSet source) { - // We can't use ReadOnlySet yet, which is being introduced in .NET 9. - return source; - } - -#if NET6_0 - public static ReadOnlyDictionary AsReadOnly(this IDictionary source) - where TKey : notnull - { - // The AsReadOnly() extension method is unavailable in .NET 6. - return new ReadOnlyDictionary(source); - } - - public static ReadOnlyCollection AsReadOnly(this T[] source) - { - // The AsReadOnly() extension method is unavailable in .NET 6. - return Array.AsReadOnly(source); + return new ReadOnlySet(source); } -#endif } diff --git a/src/JsonApiDotNetCore.Annotations/ReadOnlySet.cs b/src/JsonApiDotNetCore.Annotations/ReadOnlySet.cs new file mode 100644 index 0000000000..9917af9ec7 --- /dev/null +++ b/src/JsonApiDotNetCore.Annotations/ReadOnlySet.cs @@ -0,0 +1,171 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if NET8_0 +#pragma warning disable + +// ReadOnlySet was introduced in .NET 9. +// This file was copied from https://github.com/dotnet/runtime/blob/release/9.0/src/libraries/System.Collections/src/System/Collections/Generic/ReadOnlySet.cs +// and made internal to enable usage on lower .NET versions. + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace System.Collections.ObjectModel; + +/// Represents a read-only, generic set of values. +/// The type of values in the set. +[DebuggerDisplay("Count = {Count}")] +[ExcludeFromCodeCoverage] +internal class ReadOnlySet : IReadOnlySet, ISet, ICollection +{ + /// The wrapped set. + private readonly ISet _set; + + /// Initializes a new instance of the class that is a wrapper around the specified set. + /// The set to wrap. + public ReadOnlySet(ISet set) + { + ArgumentNullException.ThrowIfNull(set); + _set = set; + } + + /// Gets an empty . + public static ReadOnlySet Empty { get; } = new ReadOnlySet(new HashSet()); + + /// Gets the set that is wrapped by this object. + protected ISet Set => _set; + + /// + public int Count => _set.Count; + + /// + public IEnumerator GetEnumerator() => + _set.Count == 0 ? ((IEnumerable)Array.Empty()).GetEnumerator() : + _set.GetEnumerator(); + + /// + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + + /// + public bool Contains(T item) => _set.Contains(item); + + /// + public bool IsProperSubsetOf(IEnumerable other) => _set.IsProperSubsetOf(other); + + /// + public bool IsProperSupersetOf(IEnumerable other) => _set.IsProperSupersetOf(other); + + /// + public bool IsSubsetOf(IEnumerable other) => _set.IsSubsetOf(other); + + /// + public bool IsSupersetOf(IEnumerable other) => _set.IsSupersetOf(other); + + /// + public bool Overlaps(IEnumerable other) => _set.Overlaps(other); + + /// + public bool SetEquals(IEnumerable other) => _set.SetEquals(other); + + /// + void ICollection.CopyTo(T[] array, int arrayIndex) => _set.CopyTo(array, arrayIndex); + + /// + void ICollection.CopyTo(Array array, int index) => CollectionHelpers.CopyTo(_set, array, index); + + /// + bool ICollection.IsReadOnly => true; + + /// + bool ICollection.IsSynchronized => false; + + /// + object ICollection.SyncRoot => _set is ICollection c ? c.SyncRoot : this; + + /// + bool ISet.Add(T item) => throw new NotSupportedException(); + + /// + void ISet.ExceptWith(IEnumerable other) => throw new NotSupportedException(); + + /// + void ISet.IntersectWith(IEnumerable other) => throw new NotSupportedException(); + + /// + void ISet.SymmetricExceptWith(IEnumerable other) => throw new NotSupportedException(); + + /// + void ISet.UnionWith(IEnumerable other) => throw new NotSupportedException(); + + /// + void ICollection.Add(T item) => throw new NotSupportedException(); + + /// + void ICollection.Clear() => throw new NotSupportedException(); + + /// + bool ICollection.Remove(T item) => throw new NotSupportedException(); + + private static class CollectionHelpers + { + private static void ValidateCopyToArguments(int sourceCount, Array array, int index) + { + ArgumentNullException.ThrowIfNull(array); + + if (array.Rank != 1) + { + throw new ArgumentException("Only single dimensional arrays are supported for the requested action.", nameof(array)); + } + + if (array.GetLowerBound(0) != 0) + { + throw new ArgumentException("The lower bound of target array must be zero.", nameof(array)); + } + + ArgumentOutOfRangeException.ThrowIfNegative(index); + ArgumentOutOfRangeException.ThrowIfGreaterThan(index, array.Length); + + if (array.Length - index < sourceCount) + { + throw new ArgumentException("Destination array is not long enough to copy all the items in the collection. Check array index and length."); + } + } + + internal static void CopyTo(ICollection collection, Array array, int index) + { + ValidateCopyToArguments(collection.Count, array, index); + + if (collection is ICollection nonGenericCollection) + { + // Easy out if the ICollection implements the non-generic ICollection + nonGenericCollection.CopyTo(array, index); + } + else if (array is T[] items) + { + collection.CopyTo(items, index); + } + else + { + // We can't cast array of value type to object[], so we don't support widening of primitive types here. + if (array is not object?[] objects) + { + throw new ArgumentException("Target array type is not compatible with the type of items in the collection.", nameof(array)); + } + + try + { + foreach (T item in collection) + { + objects[index++] = item; + } + } + catch (ArrayTypeMismatchException) + { + throw new ArgumentException("Target array type is not compatible with the type of items in the collection.", nameof(array)); + } + } + } + } +} +#endif diff --git a/src/JsonApiDotNetCore.Annotations/Resources/Annotations/HasManyAttribute.cs b/src/JsonApiDotNetCore.Annotations/Resources/Annotations/HasManyAttribute.cs index 274a6bb16f..a906f4a667 100644 --- a/src/JsonApiDotNetCore.Annotations/Resources/Annotations/HasManyAttribute.cs +++ b/src/JsonApiDotNetCore.Annotations/Resources/Annotations/HasManyAttribute.cs @@ -69,7 +69,7 @@ private bool EvaluateIsManyToMany() /// public override void SetValue(object resource, object? newValue) { - ArgumentGuard.NotNull(newValue); + ArgumentNullException.ThrowIfNull(newValue); AssertIsIdentifiableCollection(newValue); base.SetValue(resource, newValue); @@ -99,8 +99,8 @@ private void AssertIsIdentifiableCollection(object newValue) /// public void AddValue(object resource, IIdentifiable resourceToAdd) { - ArgumentGuard.NotNull(resource); - ArgumentGuard.NotNull(resourceToAdd); + ArgumentNullException.ThrowIfNull(resource); + ArgumentNullException.ThrowIfNull(resourceToAdd); object? rightValue = GetValue(resource); List rightResources = CollectionConverter.Instance.ExtractResources(rightValue).ToList(); diff --git a/src/JsonApiDotNetCore.Annotations/Resources/Annotations/RelationshipAttribute.cs b/src/JsonApiDotNetCore.Annotations/Resources/Annotations/RelationshipAttribute.cs index 72bdecf7b0..21d5bfab1d 100644 --- a/src/JsonApiDotNetCore.Annotations/Resources/Annotations/RelationshipAttribute.cs +++ b/src/JsonApiDotNetCore.Annotations/Resources/Annotations/RelationshipAttribute.cs @@ -59,7 +59,7 @@ public ResourceType RightType get => _rightType!; internal set { - ArgumentGuard.NotNull(value); + ArgumentNullException.ThrowIfNull(value); _rightType = value; } } diff --git a/src/JsonApiDotNetCore.Annotations/Resources/Annotations/ResourceFieldAttribute.cs b/src/JsonApiDotNetCore.Annotations/Resources/Annotations/ResourceFieldAttribute.cs index 3b55c4b644..593b0a905d 100644 --- a/src/JsonApiDotNetCore.Annotations/Resources/Annotations/ResourceFieldAttribute.cs +++ b/src/JsonApiDotNetCore.Annotations/Resources/Annotations/ResourceFieldAttribute.cs @@ -43,7 +43,7 @@ public PropertyInfo Property get => _property!; internal set { - ArgumentGuard.NotNull(value); + ArgumentNullException.ThrowIfNull(value); _property = value; } } @@ -56,7 +56,7 @@ public ResourceType Type get => _type!; internal set { - ArgumentGuard.NotNull(value); + ArgumentNullException.ThrowIfNull(value); _type = value; } } @@ -67,7 +67,7 @@ internal set /// public object? GetValue(object resource) { - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); AssertIsIdentifiable(resource); if (Property.GetMethod == null) @@ -93,7 +93,7 @@ internal set /// public virtual void SetValue(object resource, object? newValue) { - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); AssertIsIdentifiable(resource); if (Property.SetMethod == null) diff --git a/src/JsonApiDotNetCore.Annotations/Resources/RuntimeTypeConverter.cs b/src/JsonApiDotNetCore.Annotations/Resources/RuntimeTypeConverter.cs index a811dd0646..74a4eb877c 100644 --- a/src/JsonApiDotNetCore.Annotations/Resources/RuntimeTypeConverter.cs +++ b/src/JsonApiDotNetCore.Annotations/Resources/RuntimeTypeConverter.cs @@ -33,7 +33,7 @@ public static class RuntimeTypeConverter /// public static object? ConvertType(object? value, Type type) { - ArgumentGuard.NotNull(type); + ArgumentNullException.ThrowIfNull(type); // Earlier versions of JsonApiDotNetCore failed to pass CultureInfo.InvariantCulture in the parsing below, which resulted in the 'current' // culture being used. Unlike parsing JSON request/response bodies, this effectively meant that query strings were parsed based on the @@ -140,7 +140,7 @@ public static class RuntimeTypeConverter /// public static bool CanContainNull(Type type) { - ArgumentGuard.NotNull(type); + ArgumentNullException.ThrowIfNull(type); return !type.IsValueType || Nullable.GetUnderlyingType(type) != null; } @@ -153,7 +153,7 @@ public static bool CanContainNull(Type type) /// public static object? GetDefaultValue(Type type) { - ArgumentGuard.NotNull(type); + ArgumentNullException.ThrowIfNull(type); return type.IsValueType ? DefaultTypeCache.GetOrAdd(type, Activator.CreateInstance) : null; } diff --git a/src/JsonApiDotNetCore.Annotations/TypeExtensions.cs b/src/JsonApiDotNetCore.Annotations/TypeExtensions.cs index 785dff030a..89b8158554 100644 --- a/src/JsonApiDotNetCore.Annotations/TypeExtensions.cs +++ b/src/JsonApiDotNetCore.Annotations/TypeExtensions.cs @@ -15,7 +15,7 @@ public static bool IsOrImplementsInterface(this Type? source) /// private static bool IsOrImplementsInterface(this Type? source, Type interfaceType) { - ArgumentGuard.NotNull(interfaceType); + ArgumentNullException.ThrowIfNull(interfaceType); if (source == null) { @@ -41,7 +41,7 @@ private static bool AreTypesEqual(Type left, Type right, bool isLeftGeneric) /// public static string GetFriendlyTypeName(this Type type) { - ArgumentGuard.NotNull(type); + ArgumentNullException.ThrowIfNull(type); // Based on https://stackoverflow.com/questions/2581642/how-do-i-get-the-type-name-of-a-generic-type-argument. diff --git a/src/JsonApiDotNetCore.OpenApi.Client.Kiota/JsonApiDotNetCore.OpenApi.Client.Kiota.csproj b/src/JsonApiDotNetCore.OpenApi.Client.Kiota/JsonApiDotNetCore.OpenApi.Client.Kiota.csproj index a5aaa7ec53..da24a35ecb 100644 --- a/src/JsonApiDotNetCore.OpenApi.Client.Kiota/JsonApiDotNetCore.OpenApi.Client.Kiota.csproj +++ b/src/JsonApiDotNetCore.OpenApi.Client.Kiota/JsonApiDotNetCore.OpenApi.Client.Kiota.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net8.0 true true false diff --git a/src/JsonApiDotNetCore.OpenApi.Client.NSwag/ApiResponse.cs b/src/JsonApiDotNetCore.OpenApi.Client.NSwag/ApiResponse.cs index 40c24b9b1b..74ee77127f 100644 --- a/src/JsonApiDotNetCore.OpenApi.Client.NSwag/ApiResponse.cs +++ b/src/JsonApiDotNetCore.OpenApi.Client.NSwag/ApiResponse.cs @@ -12,7 +12,7 @@ public class ApiResponse(int statusCode, IReadOnlyDictionary TranslateAsync(Func> operation) where TResponse : class { - ArgumentGuard.NotNull(operation); + ArgumentNullException.ThrowIfNull(operation); try { @@ -27,7 +27,7 @@ public class ApiResponse(int statusCode, IReadOnlyDictionary operation) { - ArgumentGuard.NotNull(operation); + ArgumentNullException.ThrowIfNull(operation); try { @@ -42,7 +42,7 @@ public static async Task TranslateAsync(Func operation) public static async Task> TranslateAsync(Func>> operation) where TResult : class { - ArgumentGuard.NotNull(operation); + ArgumentNullException.ThrowIfNull(operation); try { @@ -57,7 +57,7 @@ public static async Task TranslateAsync(Func operation) public static async Task TranslateAsync(Func> operation) { - ArgumentGuard.NotNull(operation); + ArgumentNullException.ThrowIfNull(operation); try { diff --git a/src/JsonApiDotNetCore.OpenApi.Client.NSwag/ArgumentGuard.cs b/src/JsonApiDotNetCore.OpenApi.Client.NSwag/ArgumentGuard.cs deleted file mode 100644 index 4a2836353b..0000000000 --- a/src/JsonApiDotNetCore.OpenApi.Client.NSwag/ArgumentGuard.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Runtime.CompilerServices; -using JetBrains.Annotations; -using SysNotNull = System.Diagnostics.CodeAnalysis.NotNullAttribute; - -#pragma warning disable AV1008 // Class should not be static -#pragma warning disable format - -namespace JsonApiDotNetCore.OpenApi.Client.NSwag; - -internal static class ArgumentGuard -{ - [AssertionMethod] - public static void NotNull([NoEnumeration] [SysNotNull] T? value, [CallerArgumentExpression(nameof(value))] string? parameterName = null) - where T : class - { - ArgumentNullException.ThrowIfNull(value, parameterName); - } -} diff --git a/src/JsonApiDotNetCore.OpenApi.Client.NSwag/JsonApiClient.cs b/src/JsonApiDotNetCore.OpenApi.Client.NSwag/JsonApiClient.cs index 01da85e838..2c1603bbdb 100644 --- a/src/JsonApiDotNetCore.OpenApi.Client.NSwag/JsonApiClient.cs +++ b/src/JsonApiDotNetCore.OpenApi.Client.NSwag/JsonApiClient.cs @@ -17,7 +17,7 @@ public abstract class JsonApiClient : IJsonApiClient /// protected void SetSerializerSettingsForJsonApi(JsonSerializerSettings settings) { - ArgumentGuard.NotNull(settings); + ArgumentNullException.ThrowIfNull(settings); settings.Converters.Add(_documentJsonConverter); } @@ -27,8 +27,8 @@ public IDisposable WithPartialAttributeSerialization>[] alwaysIncludedAttributeSelectors) where TRequestDocument : class { - ArgumentGuard.NotNull(requestDocument); - ArgumentGuard.NotNull(alwaysIncludedAttributeSelectors); + ArgumentNullException.ThrowIfNull(requestDocument); + ArgumentNullException.ThrowIfNull(alwaysIncludedAttributeSelectors); HashSet attributeNames = []; @@ -79,8 +79,8 @@ private sealed class DocumentRegistrationScope : IDisposable public DocumentRegistrationScope(DocumentJsonConverter documentJsonConverter, object document) { - ArgumentGuard.NotNull(documentJsonConverter); - ArgumentGuard.NotNull(document); + ArgumentNullException.ThrowIfNull(documentJsonConverter); + ArgumentNullException.ThrowIfNull(document); _documentJsonConverter = documentJsonConverter; _document = document; @@ -102,8 +102,8 @@ private sealed class AlwaysIncludedAttributes public AlwaysIncludedAttributes(HashSet propertyNames, Type attributesObjectType) { - ArgumentGuard.NotNull(propertyNames); - ArgumentGuard.NotNull(attributesObjectType); + ArgumentNullException.ThrowIfNull(propertyNames); + ArgumentNullException.ThrowIfNull(attributesObjectType); _propertyNames = propertyNames; _attributesObjectType = attributesObjectType; @@ -162,7 +162,7 @@ public void UnRegisterDocument(object document) public override bool CanConvert(Type objectType) { - ArgumentGuard.NotNull(objectType); + ArgumentNullException.ThrowIfNull(objectType); if (_isSerializing) { @@ -180,8 +180,8 @@ public override object ReadJson(JsonReader reader, Type objectType, object? exis public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { - ArgumentGuard.NotNull(writer); - ArgumentGuard.NotNull(serializer); + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(serializer); if (value != null) { @@ -216,14 +216,14 @@ private sealed class AttributesJsonConverter : JsonConverter public AttributesJsonConverter(AlwaysIncludedAttributes alwaysIncludedAttributes) { - ArgumentGuard.NotNull(alwaysIncludedAttributes); + ArgumentNullException.ThrowIfNull(alwaysIncludedAttributes); _alwaysIncludedAttributes = alwaysIncludedAttributes; } public override bool CanConvert(Type objectType) { - ArgumentGuard.NotNull(objectType); + ArgumentNullException.ThrowIfNull(objectType); if (_isSerializing) { @@ -241,8 +241,8 @@ public override object ReadJson(JsonReader reader, Type objectType, object? exis public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { - ArgumentGuard.NotNull(writer); - ArgumentGuard.NotNull(serializer); + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(serializer); if (value != null) { @@ -322,7 +322,7 @@ private sealed class JsonApiAttributeContractResolver : DefaultContractResolver public JsonApiAttributeContractResolver(AlwaysIncludedAttributes alwaysIncludedAttributes) { - ArgumentGuard.NotNull(alwaysIncludedAttributes); + ArgumentNullException.ThrowIfNull(alwaysIncludedAttributes); _alwaysIncludedAttributes = alwaysIncludedAttributes; } diff --git a/src/JsonApiDotNetCore.OpenApi.Client.NSwag/JsonApiDotNetCore.OpenApi.Client.NSwag.csproj b/src/JsonApiDotNetCore.OpenApi.Client.NSwag/JsonApiDotNetCore.OpenApi.Client.NSwag.csproj index 912bea71d1..51d55de3f4 100644 --- a/src/JsonApiDotNetCore.OpenApi.Client.NSwag/JsonApiDotNetCore.OpenApi.Client.NSwag.csproj +++ b/src/JsonApiDotNetCore.OpenApi.Client.NSwag/JsonApiDotNetCore.OpenApi.Client.NSwag.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net8.0 true true false diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ActionDescriptorExtensions.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ActionDescriptorExtensions.cs index d796fba3dc..1892aca576 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ActionDescriptorExtensions.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ActionDescriptorExtensions.cs @@ -10,7 +10,7 @@ internal static class ActionDescriptorExtensions { public static MethodInfo GetActionMethod(this ActionDescriptor descriptor) { - ArgumentGuard.NotNull(descriptor); + ArgumentNullException.ThrowIfNull(descriptor); return ((ControllerActionDescriptor)descriptor).MethodInfo; } @@ -18,14 +18,14 @@ public static MethodInfo GetActionMethod(this ActionDescriptor descriptor) public static TFilterMetaData? GetFilterMetadata(this ActionDescriptor descriptor) where TFilterMetaData : IFilterMetadata { - ArgumentGuard.NotNull(descriptor); + ArgumentNullException.ThrowIfNull(descriptor); return descriptor.FilterDescriptors.Select(filterDescriptor => filterDescriptor.Filter).OfType().FirstOrDefault(); } public static ControllerParameterDescriptor? GetBodyParameterDescriptor(this ActionDescriptor descriptor) { - ArgumentGuard.NotNull(descriptor); + ArgumentNullException.ThrowIfNull(descriptor); return (ControllerParameterDescriptor?)descriptor.Parameters.FirstOrDefault(parameterDescriptor => parameterDescriptor.BindingInfo?.BindingSource == BindingSource.Body); diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ConfigureMvcOptions.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ConfigureMvcOptions.cs index b9e44aa7b5..9409e7824c 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ConfigureMvcOptions.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ConfigureMvcOptions.cs @@ -14,9 +14,9 @@ internal sealed class ConfigureMvcOptions : IConfigureOptions public ConfigureMvcOptions(IJsonApiRoutingConvention jsonApiRoutingConvention, OpenApiEndpointConvention openApiEndpointConvention, JsonApiRequestFormatMetadataProvider jsonApiRequestFormatMetadataProvider) { - ArgumentGuard.NotNull(jsonApiRoutingConvention); - ArgumentGuard.NotNull(openApiEndpointConvention); - ArgumentGuard.NotNull(jsonApiRequestFormatMetadataProvider); + ArgumentNullException.ThrowIfNull(jsonApiRoutingConvention); + ArgumentNullException.ThrowIfNull(openApiEndpointConvention); + ArgumentNullException.ThrowIfNull(jsonApiRequestFormatMetadataProvider); _jsonApiRoutingConvention = jsonApiRoutingConvention; _openApiEndpointConvention = openApiEndpointConvention; diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ConfigureSwaggerGenOptions.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ConfigureSwaggerGenOptions.cs index 3c8cc4e82c..de34115b65 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ConfigureSwaggerGenOptions.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ConfigureSwaggerGenOptions.cs @@ -32,10 +32,10 @@ internal sealed class ConfigureSwaggerGenOptions : IConfigureOptions public IReadOnlySet GetReachableRelatedTypes(ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); HashSet resourceTypesFound = []; AddTypesFromRelationships(resourceType.Relationships, resourceTypesFound); diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiActionDescriptorCollectionProvider.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiActionDescriptorCollectionProvider.cs index 486d261490..c145067bb3 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiActionDescriptorCollectionProvider.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiActionDescriptorCollectionProvider.cs @@ -32,8 +32,8 @@ internal sealed class JsonApiActionDescriptorCollectionProvider : IActionDescrip public JsonApiActionDescriptorCollectionProvider(IActionDescriptorCollectionProvider defaultProvider, JsonApiEndpointMetadataProvider jsonApiEndpointMetadataProvider) { - ArgumentGuard.NotNull(defaultProvider); - ArgumentGuard.NotNull(jsonApiEndpointMetadataProvider); + ArgumentNullException.ThrowIfNull(defaultProvider); + ArgumentNullException.ThrowIfNull(jsonApiEndpointMetadataProvider); _defaultProvider = defaultProvider; _jsonApiEndpointMetadataProvider = jsonApiEndpointMetadataProvider; diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiDotNetCore.OpenApi.Swashbuckle.csproj b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiDotNetCore.OpenApi.Swashbuckle.csproj index dd2c3d7d17..4fadf7b272 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiDotNetCore.OpenApi.Swashbuckle.csproj +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiDotNetCore.OpenApi.Swashbuckle.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net8.0 true true false diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/EndpointResolver.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/EndpointResolver.cs index 6107956d78..e4c074f081 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/EndpointResolver.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/EndpointResolver.cs @@ -15,7 +15,7 @@ private EndpointResolver() public JsonApiEndpoints GetEndpoint(MethodInfo controllerAction) { - ArgumentGuard.NotNull(controllerAction); + ArgumentNullException.ThrowIfNull(controllerAction); if (!IsJsonApiController(controllerAction)) { diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/JsonApiEndpointMetadataProvider.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/JsonApiEndpointMetadataProvider.cs index 1c22b1505e..85ae85482d 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/JsonApiEndpointMetadataProvider.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/JsonApiEndpointMetadataProvider.cs @@ -18,8 +18,8 @@ internal sealed class JsonApiEndpointMetadataProvider public JsonApiEndpointMetadataProvider(IControllerResourceMapping controllerResourceMapping, NonPrimaryDocumentTypeFactory nonPrimaryDocumentTypeFactory) { - ArgumentGuard.NotNull(controllerResourceMapping); - ArgumentGuard.NotNull(nonPrimaryDocumentTypeFactory); + ArgumentNullException.ThrowIfNull(controllerResourceMapping); + ArgumentNullException.ThrowIfNull(nonPrimaryDocumentTypeFactory); _controllerResourceMapping = controllerResourceMapping; _nonPrimaryDocumentTypeFactory = nonPrimaryDocumentTypeFactory; @@ -27,7 +27,7 @@ public JsonApiEndpointMetadataProvider(IControllerResourceMapping controllerReso public JsonApiEndpointMetadataContainer Get(MethodInfo controllerAction) { - ArgumentGuard.NotNull(controllerAction); + ArgumentNullException.ThrowIfNull(controllerAction); if (EndpointResolver.Instance.IsAtomicOperationsController(controllerAction)) { diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/NonPrimaryDocumentTypeFactory.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/NonPrimaryDocumentTypeFactory.cs index 9a297f2846..ee155142dc 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/NonPrimaryDocumentTypeFactory.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/NonPrimaryDocumentTypeFactory.cs @@ -19,28 +19,28 @@ internal sealed class NonPrimaryDocumentTypeFactory public NonPrimaryDocumentTypeFactory(ResourceFieldValidationMetadataProvider resourceFieldValidationMetadataProvider) { - ArgumentGuard.NotNull(resourceFieldValidationMetadataProvider); + ArgumentNullException.ThrowIfNull(resourceFieldValidationMetadataProvider); _resourceFieldValidationMetadataProvider = resourceFieldValidationMetadataProvider; } public Type GetForSecondaryResponse(RelationshipAttribute relationship) { - ArgumentGuard.NotNull(relationship); + ArgumentNullException.ThrowIfNull(relationship); return Get(relationship, SecondaryResponseDocumentOpenTypes); } public Type GetForRelationshipRequest(RelationshipAttribute relationship) { - ArgumentGuard.NotNull(relationship); + ArgumentNullException.ThrowIfNull(relationship); return Get(relationship, RelationshipRequestDocumentOpenTypes); } public Type GetForRelationshipResponse(RelationshipAttribute relationship) { - ArgumentGuard.NotNull(relationship); + ArgumentNullException.ThrowIfNull(relationship); return Get(relationship, RelationshipResponseDocumentOpenTypes); } @@ -68,9 +68,9 @@ private sealed class DocumentOpenTypes public DocumentOpenTypes(Type manyDataOpenType, Type nullableSingleDataOpenType, Type singleDataOpenType) { - ArgumentGuard.NotNull(manyDataOpenType); - ArgumentGuard.NotNull(nullableSingleDataOpenType); - ArgumentGuard.NotNull(singleDataOpenType); + ArgumentNullException.ThrowIfNull(manyDataOpenType); + ArgumentNullException.ThrowIfNull(nullableSingleDataOpenType); + ArgumentNullException.ThrowIfNull(singleDataOpenType); ManyDataOpenType = manyDataOpenType; NullableSingleDataOpenType = nullableSingleDataOpenType; diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/NonPrimaryEndpointMetadata.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/NonPrimaryEndpointMetadata.cs index e1e284c0a8..ed43dc4da8 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/NonPrimaryEndpointMetadata.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/NonPrimaryEndpointMetadata.cs @@ -6,7 +6,7 @@ internal abstract class NonPrimaryEndpointMetadata protected NonPrimaryEndpointMetadata(IDictionary documentTypesByRelationshipName) { - ArgumentGuard.NotNull(documentTypesByRelationshipName); + ArgumentNullException.ThrowIfNull(documentTypesByRelationshipName); DocumentTypesByRelationshipName = documentTypesByRelationshipName; } diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/PrimaryRequestMetadata.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/PrimaryRequestMetadata.cs index c66dc8546c..7c224417f1 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/PrimaryRequestMetadata.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/PrimaryRequestMetadata.cs @@ -6,7 +6,7 @@ internal sealed class PrimaryRequestMetadata : IJsonApiRequestMetadata public PrimaryRequestMetadata(Type documentType) { - ArgumentGuard.NotNull(documentType); + ArgumentNullException.ThrowIfNull(documentType); DocumentType = documentType; } diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/PrimaryResponseMetadata.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/PrimaryResponseMetadata.cs index 514082154d..2d2590be7d 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/PrimaryResponseMetadata.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/PrimaryResponseMetadata.cs @@ -6,7 +6,7 @@ internal sealed class PrimaryResponseMetadata : IJsonApiResponseMetadata public PrimaryResponseMetadata(Type documentType) { - ArgumentGuard.NotNull(documentType); + ArgumentNullException.ThrowIfNull(documentType); DocumentType = documentType; } diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/RelationshipTypeFactory.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/RelationshipTypeFactory.cs index 0040021cdb..0841645f93 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/RelationshipTypeFactory.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiMetadata/RelationshipTypeFactory.cs @@ -11,8 +11,8 @@ internal sealed class RelationshipTypeFactory public RelationshipTypeFactory(NonPrimaryDocumentTypeFactory nonPrimaryDocumentTypeFactory, ResourceFieldValidationMetadataProvider resourceFieldValidationMetadataProvider) { - ArgumentGuard.NotNull(nonPrimaryDocumentTypeFactory); - ArgumentGuard.NotNull(resourceFieldValidationMetadataProvider); + ArgumentNullException.ThrowIfNull(nonPrimaryDocumentTypeFactory); + ArgumentNullException.ThrowIfNull(resourceFieldValidationMetadataProvider); _nonPrimaryDocumentTypeFactory = nonPrimaryDocumentTypeFactory; _resourceFieldValidationMetadataProvider = resourceFieldValidationMetadataProvider; @@ -20,14 +20,14 @@ public RelationshipTypeFactory(NonPrimaryDocumentTypeFactory nonPrimaryDocumentT public Type GetForRequest(RelationshipAttribute relationship) { - ArgumentGuard.NotNull(relationship); + ArgumentNullException.ThrowIfNull(relationship); return _nonPrimaryDocumentTypeFactory.GetForRelationshipRequest(relationship); } public Type GetForResponse(RelationshipAttribute relationship) { - ArgumentGuard.NotNull(relationship); + ArgumentNullException.ThrowIfNull(relationship); // @formatter:nested_ternary_style expanded diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiRequestFormatMetadataProvider.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiRequestFormatMetadataProvider.cs index 56e43f7352..08e2844f83 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiRequestFormatMetadataProvider.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiRequestFormatMetadataProvider.cs @@ -24,8 +24,8 @@ public Task ReadAsync(InputFormatterContext context) /// public IReadOnlyList GetSupportedContentTypes(string contentType, Type objectType) { - ArgumentGuard.NotNullNorEmpty(contentType); - ArgumentGuard.NotNull(objectType); + ArgumentException.ThrowIfNullOrEmpty(contentType); + ArgumentNullException.ThrowIfNull(objectType); if (JsonApiSchemaFacts.IsRequestBodySchemaType(objectType) && MediaTypeHeaderValue.TryParse(contentType, out MediaTypeHeaderValue? headerValue) && headerValue.MediaType.Equals(DefaultMediaType, StringComparison.OrdinalIgnoreCase)) diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiSchemaIdSelector.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiSchemaIdSelector.cs index 9ad0623d9f..6790f94f0f 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiSchemaIdSelector.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/JsonApiSchemaIdSelector.cs @@ -69,8 +69,8 @@ internal sealed class JsonApiSchemaIdSelector public JsonApiSchemaIdSelector(IJsonApiOptions options, IResourceGraph resourceGraph) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(resourceGraph); _options = options; _resourceGraph = resourceGraph; @@ -78,7 +78,7 @@ public JsonApiSchemaIdSelector(IJsonApiOptions options, IResourceGraph resourceG public string GetSchemaId(Type type) { - ArgumentGuard.NotNull(type); + ArgumentNullException.ThrowIfNull(type); ResourceType? resourceType = _resourceGraph.FindResourceType(type); @@ -152,14 +152,14 @@ public string GetAtomicOperationCodeSchemaId(AtomicOperationCode operationCode) public string GetAtomicOperationDiscriminatorValue(AtomicOperationCode operationCode, ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); return ApplySchemaTemplate(ResourceAtomicOperationDiscriminatorValueTemplate, resourceType, null, operationCode); } public string GetAtomicOperationDiscriminatorValue(AtomicOperationCode operationCode, RelationshipAttribute relationship) { - ArgumentGuard.NotNull(relationship); + ArgumentNullException.ThrowIfNull(relationship); string schemaIdTemplate = operationCode switch { @@ -173,7 +173,7 @@ public string GetAtomicOperationDiscriminatorValue(AtomicOperationCode operation public string GetRelationshipAtomicOperationSchemaId(RelationshipAttribute relationship, AtomicOperationCode operationCode) { - ArgumentGuard.NotNull(relationship); + ArgumentNullException.ThrowIfNull(relationship); string schemaIdTemplate = operationCode switch { @@ -187,14 +187,14 @@ public string GetRelationshipAtomicOperationSchemaId(RelationshipAttribute relat public string GetRelationshipIdentifierSchemaId(RelationshipAttribute relationship) { - ArgumentGuard.NotNull(relationship); + ArgumentNullException.ThrowIfNull(relationship); return ApplySchemaTemplate(RelationshipIdentifierSchemaIdTemplate, relationship.LeftType, relationship.PublicName, null); } public string GetRelationshipNameSchemaId(RelationshipAttribute relationship) { - ArgumentGuard.NotNull(relationship); + ArgumentNullException.ThrowIfNull(relationship); return ApplySchemaTemplate(RelationshipNameSchemaIdTemplate, relationship.LeftType, relationship.PublicName, null); } diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ObjectExtensions.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ObjectExtensions.cs index 24a65e8afa..accd03d7c4 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ObjectExtensions.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ObjectExtensions.cs @@ -11,7 +11,7 @@ internal static class ObjectExtensions public static T MemberwiseClone(this T source) where T : class { - ArgumentGuard.NotNull(source); + ArgumentNullException.ThrowIfNull(source); return (T)MemberwiseCloneMethod.Value.Invoke(source, null)!; } diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/OpenApiDescriptionLinkProvider.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/OpenApiDescriptionLinkProvider.cs index 8b92f120b6..278c2154a9 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/OpenApiDescriptionLinkProvider.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/OpenApiDescriptionLinkProvider.cs @@ -16,8 +16,8 @@ internal sealed class OpenApiDescriptionLinkProvider : IDocumentDescriptionLinkP public OpenApiDescriptionLinkProvider(IOptionsMonitor swaggerGeneratorOptionsMonitor, IOptionsMonitor swaggerOptionsMonitor) { - ArgumentGuard.NotNull(swaggerGeneratorOptionsMonitor); - ArgumentGuard.NotNull(swaggerOptionsMonitor); + ArgumentNullException.ThrowIfNull(swaggerGeneratorOptionsMonitor); + ArgumentNullException.ThrowIfNull(swaggerOptionsMonitor); _swaggerGeneratorOptionsMonitor = swaggerGeneratorOptionsMonitor; _swaggerOptionsMonitor = swaggerOptionsMonitor; diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/OpenApiEndpointConvention.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/OpenApiEndpointConvention.cs index 6f202daca8..745c435ee5 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/OpenApiEndpointConvention.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/OpenApiEndpointConvention.cs @@ -21,8 +21,8 @@ internal sealed class OpenApiEndpointConvention : IActionModelConvention public OpenApiEndpointConvention(IControllerResourceMapping controllerResourceMapping, IJsonApiOptions options) { - ArgumentGuard.NotNull(controllerResourceMapping); - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(controllerResourceMapping); + ArgumentNullException.ThrowIfNull(options); _controllerResourceMapping = controllerResourceMapping; _options = options; @@ -30,7 +30,7 @@ public OpenApiEndpointConvention(IControllerResourceMapping controllerResourceMa public void Apply(ActionModel action) { - ArgumentGuard.NotNull(action); + ArgumentNullException.ThrowIfNull(action); JsonApiEndpointWrapper endpoint = JsonApiEndpointWrapper.FromActionModel(action); diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/OpenApiOperationIdSelector.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/OpenApiOperationIdSelector.cs index bb7e770ff8..9c5552350a 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/OpenApiOperationIdSelector.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/OpenApiOperationIdSelector.cs @@ -42,8 +42,8 @@ internal sealed class OpenApiOperationIdSelector public OpenApiOperationIdSelector(IControllerResourceMapping controllerResourceMapping, IJsonApiOptions options) { - ArgumentGuard.NotNull(controllerResourceMapping); - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(controllerResourceMapping); + ArgumentNullException.ThrowIfNull(options); _controllerResourceMapping = controllerResourceMapping; _options = options; @@ -51,7 +51,7 @@ public OpenApiOperationIdSelector(IControllerResourceMapping controllerResourceM public string GetOpenApiOperationId(ApiDescription endpoint) { - ArgumentGuard.NotNull(endpoint); + ArgumentNullException.ThrowIfNull(endpoint); MethodInfo actionMethod = endpoint.ActionDescriptor.GetActionMethod(); ResourceType? primaryResourceType = _controllerResourceMapping.GetResourceTypeForController(actionMethod.ReflectedType); diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/OpenApiSchemaExtensions.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/OpenApiSchemaExtensions.cs index 06550080a9..967ab69188 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/OpenApiSchemaExtensions.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/OpenApiSchemaExtensions.cs @@ -6,8 +6,8 @@ internal static class OpenApiSchemaExtensions { public static void ReorderProperties(this OpenApiSchema fullSchema, IEnumerable propertyNamesInOrder) { - ArgumentGuard.NotNull(fullSchema); - ArgumentGuard.NotNull(propertyNamesInOrder); + ArgumentNullException.ThrowIfNull(fullSchema); + ArgumentNullException.ThrowIfNull(propertyNamesInOrder); var propertiesInOrder = new Dictionary(); @@ -29,7 +29,7 @@ public static void ReorderProperties(this OpenApiSchema fullSchema, IEnumerable< public static OpenApiSchema WrapInExtendedSchema(this OpenApiSchema source) { - ArgumentGuard.NotNull(source); + ArgumentNullException.ThrowIfNull(source); return new OpenApiSchema { @@ -39,7 +39,7 @@ public static OpenApiSchema WrapInExtendedSchema(this OpenApiSchema source) public static OpenApiSchema UnwrapLastExtendedSchema(this OpenApiSchema source) { - ArgumentGuard.NotNull(source); + ArgumentNullException.ThrowIfNull(source); if (source.AllOf is { Count: > 0 }) { diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ParameterInfoWrapper.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ParameterInfoWrapper.cs index d00c51c94d..a785de0452 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ParameterInfoWrapper.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ParameterInfoWrapper.cs @@ -23,8 +23,8 @@ internal sealed class ParameterInfoWrapper : ParameterInfo public ParameterInfoWrapper(ParameterInfo innerParameter, Type overriddenParameterType, string? overriddenName) { - ArgumentGuard.NotNull(innerParameter); - ArgumentGuard.NotNull(overriddenParameterType); + ArgumentNullException.ThrowIfNull(innerParameter); + ArgumentNullException.ThrowIfNull(overriddenParameterType); _innerParameter = innerParameter; ParameterType = overriddenParameterType; diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ResourceFieldValidationMetadataProvider.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ResourceFieldValidationMetadataProvider.cs index 0b4cdf142b..f0ce60c730 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ResourceFieldValidationMetadataProvider.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ResourceFieldValidationMetadataProvider.cs @@ -14,8 +14,8 @@ internal sealed class ResourceFieldValidationMetadataProvider public ResourceFieldValidationMetadataProvider(IJsonApiOptions options, IModelMetadataProvider modelMetadataProvider) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(modelMetadataProvider); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(modelMetadataProvider); _options = options; _modelMetadataProvider = modelMetadataProvider; @@ -23,7 +23,7 @@ public ResourceFieldValidationMetadataProvider(IJsonApiOptions options, IModelMe public bool IsNullable(ResourceFieldAttribute field) { - ArgumentGuard.NotNull(field); + ArgumentNullException.ThrowIfNull(field); if (field is HasManyAttribute) { @@ -44,7 +44,7 @@ public bool IsNullable(ResourceFieldAttribute field) public bool IsRequired(ResourceFieldAttribute field) { - ArgumentGuard.NotNull(field); + ArgumentNullException.ThrowIfNull(field); bool hasRequiredAttribute = field.Property.HasAttribute(); diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Bodies/AtomicOperationsBodySchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Bodies/AtomicOperationsBodySchemaGenerator.cs index 6c34e4a0fe..288df2a007 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Bodies/AtomicOperationsBodySchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Bodies/AtomicOperationsBodySchemaGenerator.cs @@ -35,16 +35,16 @@ public AtomicOperationsBodySchemaGenerator(SchemaGenerator defaultSchemaGenerato IResourceGraph resourceGraph) : base(metaSchemaGenerator, linksVisibilitySchemaGenerator, options) { - ArgumentGuard.NotNull(defaultSchemaGenerator); - ArgumentGuard.NotNull(atomicOperationCodeSchemaGenerator); - ArgumentGuard.NotNull(resourceIdentifierSchemaGenerator); - ArgumentGuard.NotNull(relationshipIdentifierSchemaGenerator); - ArgumentGuard.NotNull(abstractAtomicOperationSchemaGenerator); - ArgumentGuard.NotNull(dataContainerSchemaGenerator); - ArgumentGuard.NotNull(atomicOperationFilter); - ArgumentGuard.NotNull(schemaIdSelector); - ArgumentGuard.NotNull(resourceFieldValidationMetadataProvider); - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(defaultSchemaGenerator); + ArgumentNullException.ThrowIfNull(atomicOperationCodeSchemaGenerator); + ArgumentNullException.ThrowIfNull(resourceIdentifierSchemaGenerator); + ArgumentNullException.ThrowIfNull(relationshipIdentifierSchemaGenerator); + ArgumentNullException.ThrowIfNull(abstractAtomicOperationSchemaGenerator); + ArgumentNullException.ThrowIfNull(dataContainerSchemaGenerator); + ArgumentNullException.ThrowIfNull(atomicOperationFilter); + ArgumentNullException.ThrowIfNull(schemaIdSelector); + ArgumentNullException.ThrowIfNull(resourceFieldValidationMetadataProvider); + ArgumentNullException.ThrowIfNull(resourceGraph); _defaultSchemaGenerator = defaultSchemaGenerator; _atomicOperationCodeSchemaGenerator = atomicOperationCodeSchemaGenerator; diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Bodies/BodySchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Bodies/BodySchemaGenerator.cs index dfbbc4538c..237d8f5e2f 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Bodies/BodySchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Bodies/BodySchemaGenerator.cs @@ -17,9 +17,9 @@ internal abstract class BodySchemaGenerator protected BodySchemaGenerator(MetaSchemaGenerator metaSchemaGenerator, LinksVisibilitySchemaGenerator linksVisibilitySchemaGenerator, IJsonApiOptions options) { - ArgumentGuard.NotNull(metaSchemaGenerator); - ArgumentGuard.NotNull(linksVisibilitySchemaGenerator); - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(metaSchemaGenerator); + ArgumentNullException.ThrowIfNull(linksVisibilitySchemaGenerator); + ArgumentNullException.ThrowIfNull(options); _metaSchemaGenerator = metaSchemaGenerator; _linksVisibilitySchemaGenerator = linksVisibilitySchemaGenerator; @@ -30,8 +30,8 @@ protected BodySchemaGenerator(MetaSchemaGenerator metaSchemaGenerator, LinksVisi public OpenApiSchema GenerateSchema(Type bodyType, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(bodyType); - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(bodyType); + ArgumentNullException.ThrowIfNull(schemaRepository); if (schemaRepository.TryLookupByType(bodyType, out OpenApiSchema? referenceSchema)) { diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Bodies/ErrorResponseBodySchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Bodies/ErrorResponseBodySchemaGenerator.cs index a655dd3de4..5e61048daa 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Bodies/ErrorResponseBodySchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Bodies/ErrorResponseBodySchemaGenerator.cs @@ -19,7 +19,7 @@ public ErrorResponseBodySchemaGenerator(SchemaGenerator defaultSchemaGenerator, LinksVisibilitySchemaGenerator linksVisibilitySchemaGenerator, IJsonApiOptions options) : base(metaSchemaGenerator, linksVisibilitySchemaGenerator, options) { - ArgumentGuard.NotNull(defaultSchemaGenerator); + ArgumentNullException.ThrowIfNull(defaultSchemaGenerator); _defaultSchemaGenerator = defaultSchemaGenerator; _metaSchemaGenerator = metaSchemaGenerator; diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Bodies/ResourceOrRelationshipBodySchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Bodies/ResourceOrRelationshipBodySchemaGenerator.cs index 0d33be7c33..99e013b852 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Bodies/ResourceOrRelationshipBodySchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Bodies/ResourceOrRelationshipBodySchemaGenerator.cs @@ -42,9 +42,9 @@ public ResourceOrRelationshipBodySchemaGenerator(SchemaGenerator defaultSchemaGe IResourceGraph resourceGraph) : base(metaSchemaGenerator, linksVisibilitySchemaGenerator, options) { - ArgumentGuard.NotNull(defaultSchemaGenerator); - ArgumentGuard.NotNull(dataContainerSchemaGenerator); - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(defaultSchemaGenerator); + ArgumentNullException.ThrowIfNull(dataContainerSchemaGenerator); + ArgumentNullException.ThrowIfNull(resourceGraph); _defaultSchemaGenerator = defaultSchemaGenerator; _dataContainerSchemaGenerator = dataContainerSchemaGenerator; @@ -59,8 +59,8 @@ public override bool CanGenerate(Type modelType) protected override OpenApiSchema GenerateBodySchema(Type bodyType, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(bodyType); - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(bodyType); + ArgumentNullException.ThrowIfNull(schemaRepository); if (schemaRepository.TryLookupByType(bodyType, out OpenApiSchema? referenceSchemaForBody)) { diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/AbstractAtomicOperationSchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/AbstractAtomicOperationSchemaGenerator.cs index 2fde578bfc..6ba9a3868c 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/AbstractAtomicOperationSchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/AbstractAtomicOperationSchemaGenerator.cs @@ -17,8 +17,8 @@ internal sealed class AbstractAtomicOperationSchemaGenerator public AbstractAtomicOperationSchemaGenerator(MetaSchemaGenerator metaSchemaGenerator, JsonApiSchemaIdSelector schemaIdSelector) { - ArgumentGuard.NotNull(metaSchemaGenerator); - ArgumentGuard.NotNull(schemaIdSelector); + ArgumentNullException.ThrowIfNull(metaSchemaGenerator); + ArgumentNullException.ThrowIfNull(schemaIdSelector); _metaSchemaGenerator = metaSchemaGenerator; _schemaIdSelector = schemaIdSelector; @@ -26,7 +26,7 @@ public AbstractAtomicOperationSchemaGenerator(MetaSchemaGenerator metaSchemaGene public OpenApiSchema GenerateSchema(SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(schemaRepository); if (schemaRepository.TryLookupByType(AtomicOperationAbstractType, out OpenApiSchema? referenceSchema)) { @@ -69,8 +69,8 @@ public OpenApiSchema GenerateSchema(SchemaRepository schemaRepository) public void MapDiscriminator(OpenApiSchema referenceSchemaForOperation, string discriminatorValue, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(referenceSchemaForOperation); - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(referenceSchemaForOperation); + ArgumentNullException.ThrowIfNull(schemaRepository); if (!schemaRepository.TryLookupByType(AtomicOperationAbstractType, out OpenApiSchema? referenceSchemaForAbstractOperation)) { diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/AbstractResourceDataSchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/AbstractResourceDataSchemaGenerator.cs index 537606a024..24aae5bf80 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/AbstractResourceDataSchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/AbstractResourceDataSchemaGenerator.cs @@ -17,9 +17,9 @@ internal sealed class AbstractResourceDataSchemaGenerator public AbstractResourceDataSchemaGenerator(MetaSchemaGenerator metaSchemaGenerator, JsonApiSchemaIdSelector schemaIdSelector, IResourceGraph resourceGraph) { - ArgumentGuard.NotNull(metaSchemaGenerator); - ArgumentGuard.NotNull(schemaIdSelector); - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(metaSchemaGenerator); + ArgumentNullException.ThrowIfNull(schemaIdSelector); + ArgumentNullException.ThrowIfNull(resourceGraph); _metaSchemaGenerator = metaSchemaGenerator; _schemaIdSelector = schemaIdSelector; @@ -28,7 +28,7 @@ public AbstractResourceDataSchemaGenerator(MetaSchemaGenerator metaSchemaGenerat public OpenApiSchema GenerateSchema(SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(schemaRepository); if (schemaRepository.TryLookupByType(ResourceDataAbstractType, out OpenApiSchema? referenceSchema)) { @@ -87,9 +87,9 @@ private OpenApiSchema GenerateEmptyResourceTypeSchema(SchemaRepository schemaRep public void MapDiscriminator(Type resourceDataConstructedType, OpenApiSchema referenceSchemaForResourceData, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(resourceDataConstructedType); - ArgumentGuard.NotNull(referenceSchemaForResourceData); - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(resourceDataConstructedType); + ArgumentNullException.ThrowIfNull(referenceSchemaForResourceData); + ArgumentNullException.ThrowIfNull(schemaRepository); var resourceSchemaType = ResourceSchemaType.Create(resourceDataConstructedType, _resourceGraph); diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/AtomicOperationCodeSchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/AtomicOperationCodeSchemaGenerator.cs index b36aae77d7..c4b28c1878 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/AtomicOperationCodeSchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/AtomicOperationCodeSchemaGenerator.cs @@ -11,14 +11,14 @@ internal sealed class AtomicOperationCodeSchemaGenerator public AtomicOperationCodeSchemaGenerator(JsonApiSchemaIdSelector schemaIdSelector) { - ArgumentGuard.NotNull(schemaIdSelector); + ArgumentNullException.ThrowIfNull(schemaIdSelector); _schemaIdSelector = schemaIdSelector; } public OpenApiSchema GenerateSchema(AtomicOperationCode operationCode, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(schemaRepository); string schemaId = _schemaIdSelector.GetAtomicOperationCodeSchemaId(operationCode); diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/DataContainerSchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/DataContainerSchemaGenerator.cs index c45ada61a7..419a6a53ca 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/DataContainerSchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/DataContainerSchemaGenerator.cs @@ -20,10 +20,10 @@ internal sealed class DataContainerSchemaGenerator public DataContainerSchemaGenerator(AbstractResourceDataSchemaGenerator abstractResourceDataSchemaGenerator, DataSchemaGenerator dataSchemaGenerator, IncludeDependencyScanner includeDependencyScanner, IResourceGraph resourceGraph) { - ArgumentGuard.NotNull(abstractResourceDataSchemaGenerator); - ArgumentGuard.NotNull(dataSchemaGenerator); - ArgumentGuard.NotNull(includeDependencyScanner); - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(abstractResourceDataSchemaGenerator); + ArgumentNullException.ThrowIfNull(dataSchemaGenerator); + ArgumentNullException.ThrowIfNull(includeDependencyScanner); + ArgumentNullException.ThrowIfNull(resourceGraph); _abstractResourceDataSchemaGenerator = abstractResourceDataSchemaGenerator; _dataSchemaGenerator = dataSchemaGenerator; @@ -33,9 +33,9 @@ public DataContainerSchemaGenerator(AbstractResourceDataSchemaGenerator abstract public OpenApiSchema GenerateSchema(Type dataContainerConstructedType, ResourceType resourceType, bool forRequestSchema, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(dataContainerConstructedType); - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(dataContainerConstructedType); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentNullException.ThrowIfNull(schemaRepository); if (schemaRepository.TryLookupByType(dataContainerConstructedType, out OpenApiSchema referenceSchemaForData)) { diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/DataSchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/DataSchemaGenerator.cs index 63464a77de..a051d3072f 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/DataSchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/DataSchemaGenerator.cs @@ -39,17 +39,17 @@ public DataSchemaGenerator(SchemaGenerator defaultSchemaGenerator, GenerationCac IJsonApiOptions options, IResourceGraph resourceGraph, ResourceFieldValidationMetadataProvider resourceFieldValidationMetadataProvider, RelationshipTypeFactory relationshipTypeFactory, ResourceDocumentationReader resourceDocumentationReader) { - ArgumentGuard.NotNull(defaultSchemaGenerator); - ArgumentGuard.NotNull(generationCacheSchemaGenerator); - ArgumentGuard.NotNull(resourceTypeSchemaGenerator); - ArgumentGuard.NotNull(resourceIdSchemaGenerator); - ArgumentGuard.NotNull(resourceIdentifierSchemaGenerator); - ArgumentGuard.NotNull(linksVisibilitySchemaGenerator); - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(resourceGraph); - ArgumentGuard.NotNull(resourceFieldValidationMetadataProvider); - ArgumentGuard.NotNull(relationshipTypeFactory); - ArgumentGuard.NotNull(resourceDocumentationReader); + ArgumentNullException.ThrowIfNull(defaultSchemaGenerator); + ArgumentNullException.ThrowIfNull(generationCacheSchemaGenerator); + ArgumentNullException.ThrowIfNull(resourceTypeSchemaGenerator); + ArgumentNullException.ThrowIfNull(resourceIdSchemaGenerator); + ArgumentNullException.ThrowIfNull(resourceIdentifierSchemaGenerator); + ArgumentNullException.ThrowIfNull(linksVisibilitySchemaGenerator); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(resourceGraph); + ArgumentNullException.ThrowIfNull(resourceFieldValidationMetadataProvider); + ArgumentNullException.ThrowIfNull(relationshipTypeFactory); + ArgumentNullException.ThrowIfNull(resourceDocumentationReader); _defaultSchemaGenerator = defaultSchemaGenerator; _generationCacheSchemaGenerator = generationCacheSchemaGenerator; @@ -66,8 +66,8 @@ public DataSchemaGenerator(SchemaGenerator defaultSchemaGenerator, GenerationCac public OpenApiSchema GenerateSchema(Type dataSchemaType, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(dataSchemaType); - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(dataSchemaType); + ArgumentNullException.ThrowIfNull(schemaRepository); if (schemaRepository.TryLookupByType(dataSchemaType, out OpenApiSchema referenceSchemaForData)) { diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/LinksVisibilitySchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/LinksVisibilitySchemaGenerator.cs index fa5bca33b7..606a5d1f42 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/LinksVisibilitySchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/LinksVisibilitySchemaGenerator.cs @@ -64,16 +64,16 @@ internal sealed class LinksVisibilitySchemaGenerator public LinksVisibilitySchemaGenerator(IJsonApiOptions options, IResourceGraph resourceGraph) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(resourceGraph); _lazyLinksVisibility = new Lazy(() => new LinksVisibility(options, resourceGraph), LazyThreadSafetyMode.ExecutionAndPublication); } public void UpdateSchemaForTopLevel(Type modelType, OpenApiSchema fullSchemaForLinksContainer, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(modelType); - ArgumentGuard.NotNull(fullSchemaForLinksContainer); + ArgumentNullException.ThrowIfNull(modelType); + ArgumentNullException.ThrowIfNull(fullSchemaForLinksContainer); Type lookupType = modelType.ConstructedToOpenType(); @@ -85,8 +85,8 @@ public void UpdateSchemaForTopLevel(Type modelType, OpenApiSchema fullSchemaForL public void UpdateSchemaForResource(ResourceSchemaType resourceSchemaType, OpenApiSchema fullSchemaForResourceData, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(resourceSchemaType); - ArgumentGuard.NotNull(fullSchemaForResourceData); + ArgumentNullException.ThrowIfNull(resourceSchemaType); + ArgumentNullException.ThrowIfNull(fullSchemaForResourceData); if (LinksInJsonApiSchemaTypes.TryGetValue(resourceSchemaType.SchemaOpenType, out LinkTypes possibleLinkTypes)) { @@ -96,8 +96,8 @@ public void UpdateSchemaForResource(ResourceSchemaType resourceSchemaType, OpenA public void UpdateSchemaForRelationship(Type modelType, OpenApiSchema fullSchemaForRelationship, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(modelType); - ArgumentGuard.NotNull(fullSchemaForRelationship); + ArgumentNullException.ThrowIfNull(modelType); + ArgumentNullException.ThrowIfNull(fullSchemaForRelationship); Type lookupType = modelType.ConstructedToOpenType(); @@ -144,8 +144,8 @@ private sealed class LinksVisibility public LinksVisibility(IJsonApiOptions options, IResourceGraph resourceGraph) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(resourceGraph); var unionTopLevelLinks = LinkTypes.None; var unionResourceLinks = LinkTypes.None; diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/MetaSchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/MetaSchemaGenerator.cs index 7d298d80f9..500250c609 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/MetaSchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/MetaSchemaGenerator.cs @@ -10,14 +10,14 @@ internal sealed class MetaSchemaGenerator public MetaSchemaGenerator(JsonApiSchemaIdSelector schemaIdSelector) { - ArgumentGuard.NotNull(schemaIdSelector); + ArgumentNullException.ThrowIfNull(schemaIdSelector); _schemaIdSelector = schemaIdSelector; } public OpenApiSchema GenerateSchema(SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(schemaRepository); if (schemaRepository.TryLookupByType(typeof(Meta), out OpenApiSchema? referenceSchema)) { diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/RelationshipIdentifierSchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/RelationshipIdentifierSchemaGenerator.cs index f144e92877..303270c305 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/RelationshipIdentifierSchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/RelationshipIdentifierSchemaGenerator.cs @@ -8,16 +8,6 @@ namespace JsonApiDotNetCore.OpenApi.Swashbuckle.SchemaGenerators.Components; internal sealed class RelationshipIdentifierSchemaGenerator { -#if NET6_0 - private static readonly string[] RelationshipIdentifierPropertyNamesInOrder = - [ - JsonApiPropertyName.Type, - JsonApiPropertyName.Id, - JsonApiPropertyName.Lid, - JsonApiPropertyName.Relationship - ]; -#endif - private readonly SchemaGenerator _defaultSchemaGenerator; private readonly ResourceTypeSchemaGenerator _resourceTypeSchemaGenerator; private readonly ResourceIdSchemaGenerator _resourceIdSchemaGenerator; @@ -28,11 +18,11 @@ public RelationshipIdentifierSchemaGenerator(SchemaGenerator defaultSchemaGenera ResourceIdSchemaGenerator resourceIdSchemaGenerator, RelationshipNameSchemaGenerator relationshipNameSchemaGenerator, JsonApiSchemaIdSelector schemaIdSelector) { - ArgumentGuard.NotNull(defaultSchemaGenerator); - ArgumentGuard.NotNull(resourceTypeSchemaGenerator); - ArgumentGuard.NotNull(resourceIdSchemaGenerator); - ArgumentGuard.NotNull(relationshipNameSchemaGenerator); - ArgumentGuard.NotNull(schemaIdSelector); + ArgumentNullException.ThrowIfNull(defaultSchemaGenerator); + ArgumentNullException.ThrowIfNull(resourceTypeSchemaGenerator); + ArgumentNullException.ThrowIfNull(resourceIdSchemaGenerator); + ArgumentNullException.ThrowIfNull(relationshipNameSchemaGenerator); + ArgumentNullException.ThrowIfNull(schemaIdSelector); _defaultSchemaGenerator = defaultSchemaGenerator; _resourceTypeSchemaGenerator = resourceTypeSchemaGenerator; @@ -43,8 +33,8 @@ public RelationshipIdentifierSchemaGenerator(SchemaGenerator defaultSchemaGenera public OpenApiSchema GenerateSchema(RelationshipAttribute relationship, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(relationship); - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(relationship); + ArgumentNullException.ThrowIfNull(schemaRepository); string schemaId = _schemaIdSelector.GetRelationshipIdentifierSchemaId(relationship); @@ -76,10 +66,6 @@ public OpenApiSchema GenerateSchema(RelationshipAttribute relationship, SchemaRe SetResourceId(fullSchemaForIdentifier, relationship.LeftType, schemaRepository); SetRelationship(fullSchemaForIdentifier, relationship, schemaRepository); -#if NET6_0 - fullSchemaForIdentifier.ReorderProperties(RelationshipIdentifierPropertyNamesInOrder); -#endif - schemaRepository.ReplaceSchemaId(relationshipIdentifierConstructedType, schemaId); referenceSchemaForIdentifier.Reference.Id = schemaId; diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/RelationshipNameSchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/RelationshipNameSchemaGenerator.cs index 5844e8184b..f040a4bad8 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/RelationshipNameSchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/RelationshipNameSchemaGenerator.cs @@ -11,15 +11,15 @@ internal sealed class RelationshipNameSchemaGenerator public RelationshipNameSchemaGenerator(JsonApiSchemaIdSelector schemaIdSelector) { - ArgumentGuard.NotNull(schemaIdSelector); + ArgumentNullException.ThrowIfNull(schemaIdSelector); _schemaIdSelector = schemaIdSelector; } public OpenApiSchema GenerateSchema(RelationshipAttribute relationship, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(relationship); - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(relationship); + ArgumentNullException.ThrowIfNull(schemaRepository); string schemaId = _schemaIdSelector.GetRelationshipNameSchemaId(relationship); diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/ResourceIdSchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/ResourceIdSchemaGenerator.cs index 6549f4676e..6a6602088d 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/ResourceIdSchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/ResourceIdSchemaGenerator.cs @@ -10,7 +10,7 @@ internal sealed class ResourceIdSchemaGenerator public ResourceIdSchemaGenerator(SchemaGenerator defaultSchemaGenerator) { - ArgumentGuard.NotNull(defaultSchemaGenerator); + ArgumentNullException.ThrowIfNull(defaultSchemaGenerator); _defaultSchemaGenerator = defaultSchemaGenerator; } @@ -22,8 +22,8 @@ public OpenApiSchema GenerateSchema(ResourceType resourceType, SchemaRepository public OpenApiSchema GenerateSchema(Type resourceIdClrType, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(resourceIdClrType); - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(resourceIdClrType); + ArgumentNullException.ThrowIfNull(schemaRepository); OpenApiSchema idSchema = _defaultSchemaGenerator.GenerateSchema(resourceIdClrType, schemaRepository); idSchema.Type = "string"; diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/ResourceIdentifierSchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/ResourceIdentifierSchemaGenerator.cs index 21db71ee7e..0c60bc9069 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/ResourceIdentifierSchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/ResourceIdentifierSchemaGenerator.cs @@ -15,10 +15,10 @@ internal sealed class ResourceIdentifierSchemaGenerator public ResourceIdentifierSchemaGenerator(SchemaGenerator defaultSchemaGenerator, GenerationCacheSchemaGenerator generationCacheSchemaGenerator, ResourceTypeSchemaGenerator resourceTypeSchemaGenerator, ResourceIdSchemaGenerator resourceIdSchemaGenerator) { - ArgumentGuard.NotNull(defaultSchemaGenerator); - ArgumentGuard.NotNull(generationCacheSchemaGenerator); - ArgumentGuard.NotNull(resourceTypeSchemaGenerator); - ArgumentGuard.NotNull(resourceIdSchemaGenerator); + ArgumentNullException.ThrowIfNull(defaultSchemaGenerator); + ArgumentNullException.ThrowIfNull(generationCacheSchemaGenerator); + ArgumentNullException.ThrowIfNull(resourceTypeSchemaGenerator); + ArgumentNullException.ThrowIfNull(resourceIdSchemaGenerator); _defaultSchemaGenerator = defaultSchemaGenerator; _generationCacheSchemaGenerator = generationCacheSchemaGenerator; @@ -28,8 +28,8 @@ public ResourceIdentifierSchemaGenerator(SchemaGenerator defaultSchemaGenerator, public OpenApiSchema GenerateSchema(ResourceType resourceType, bool forRequestSchema, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentNullException.ThrowIfNull(schemaRepository); Type resourceIdentifierOpenType = forRequestSchema ? typeof(ResourceIdentifierInRequest<>) : typeof(ResourceIdentifierInResponse<>); Type resourceIdentifierConstructedType = resourceIdentifierOpenType.MakeGenericType(resourceType.ClrType); diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/ResourceTypeSchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/ResourceTypeSchemaGenerator.cs index 4f63261a44..6d19280ba2 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/ResourceTypeSchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/Components/ResourceTypeSchemaGenerator.cs @@ -11,15 +11,15 @@ internal sealed class ResourceTypeSchemaGenerator public ResourceTypeSchemaGenerator(JsonApiSchemaIdSelector schemaIdSelector) { - ArgumentGuard.NotNull(schemaIdSelector); + ArgumentNullException.ThrowIfNull(schemaIdSelector); _schemaIdSelector = schemaIdSelector; } public OpenApiSchema GenerateSchema(ResourceType resourceType, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentNullException.ThrowIfNull(schemaRepository); if (schemaRepository.TryLookupByType(resourceType.ClrType, out OpenApiSchema? referenceSchema)) { diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/GenerationCacheSchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/GenerationCacheSchemaGenerator.cs index c4427bfc6a..043eff295b 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/GenerationCacheSchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/GenerationCacheSchemaGenerator.cs @@ -21,8 +21,8 @@ internal sealed class GenerationCacheSchemaGenerator public GenerationCacheSchemaGenerator(IActionDescriptorCollectionProvider defaultProvider, JsonApiEndpointMetadataProvider jsonApiEndpointMetadataProvider) { - ArgumentGuard.NotNull(defaultProvider); - ArgumentGuard.NotNull(jsonApiEndpointMetadataProvider); + ArgumentNullException.ThrowIfNull(defaultProvider); + ArgumentNullException.ThrowIfNull(jsonApiEndpointMetadataProvider); _defaultProvider = defaultProvider; _jsonApiEndpointMetadataProvider = jsonApiEndpointMetadataProvider; @@ -38,7 +38,7 @@ public bool HasAtomicOperationsEndpoint(SchemaRepository schemaRepository) private OpenApiSchema GenerateFullSchema(SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(schemaRepository); if (schemaRepository.Schemas.TryGetValue(SchemaId, out OpenApiSchema? fullSchema)) { diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/JsonApiSchemaGenerator.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/JsonApiSchemaGenerator.cs index 71c3418c37..56a2211166 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/JsonApiSchemaGenerator.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaGenerators/JsonApiSchemaGenerator.cs @@ -15,8 +15,8 @@ internal sealed class JsonApiSchemaGenerator : ISchemaGenerator public JsonApiSchemaGenerator(ResourceIdSchemaGenerator resourceIdSchemaGenerator, IEnumerable bodySchemaGenerators) { - ArgumentGuard.NotNull(resourceIdSchemaGenerator); - ArgumentGuard.NotNull(bodySchemaGenerators); + ArgumentNullException.ThrowIfNull(resourceIdSchemaGenerator); + ArgumentNullException.ThrowIfNull(bodySchemaGenerators); _resourceIdSchemaGenerator = resourceIdSchemaGenerator; _bodySchemaGenerators = bodySchemaGenerators as BodySchemaGenerator[] ?? bodySchemaGenerators.ToArray(); @@ -25,8 +25,8 @@ public JsonApiSchemaGenerator(ResourceIdSchemaGenerator resourceIdSchemaGenerato public OpenApiSchema GenerateSchema(Type modelType, SchemaRepository schemaRepository, MemberInfo? memberInfo = null, ParameterInfo? parameterInfo = null, ApiParameterRouteInfo? routeInfo = null) { - ArgumentGuard.NotNull(modelType); - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(modelType); + ArgumentNullException.ThrowIfNull(schemaRepository); if (parameterInfo is { Name: "id" } && IsJsonApiParameter(parameterInfo)) { diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaRepositoryExtensions.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaRepositoryExtensions.cs index 58f670e532..a51a8d917a 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaRepositoryExtensions.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SchemaRepositoryExtensions.cs @@ -30,9 +30,9 @@ private static FieldInfo GetReservedIdsField() public static void ReplaceSchemaId(this SchemaRepository schemaRepository, Type oldSchemaType, string newSchemaId) { - ArgumentGuard.NotNull(schemaRepository); - ArgumentGuard.NotNull(oldSchemaType); - ArgumentGuard.NotNullNorEmpty(newSchemaId); + ArgumentNullException.ThrowIfNull(schemaRepository); + ArgumentNullException.ThrowIfNull(oldSchemaType); + ArgumentException.ThrowIfNullOrEmpty(newSchemaId); if (schemaRepository.TryLookupByType(oldSchemaType, out OpenApiSchema? referenceSchema)) { diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ServiceCollectionExtensions.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ServiceCollectionExtensions.cs index e6507042f6..173fb9b1d3 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ServiceCollectionExtensions.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/ServiceCollectionExtensions.cs @@ -20,7 +20,7 @@ public static class ServiceCollectionExtensions /// public static void AddOpenApiForJsonApi(this IServiceCollection services, Action? setupSwaggerGenAction = null) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); AddCustomApiExplorer(services); AddCustomSwaggerComponents(services); diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/DocumentationOpenApiOperationFilter.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/DocumentationOpenApiOperationFilter.cs index c987c662c5..415738fc55 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/DocumentationOpenApiOperationFilter.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/DocumentationOpenApiOperationFilter.cs @@ -60,9 +60,9 @@ internal sealed class DocumentationOpenApiOperationFilter : IOperationFilter public DocumentationOpenApiOperationFilter(IJsonApiOptions options, IControllerResourceMapping controllerResourceMapping, ResourceFieldValidationMetadataProvider resourceFieldValidationMetadataProvider) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(controllerResourceMapping); - ArgumentGuard.NotNull(resourceFieldValidationMetadataProvider); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(controllerResourceMapping); + ArgumentNullException.ThrowIfNull(resourceFieldValidationMetadataProvider); _options = options; _controllerResourceMapping = controllerResourceMapping; @@ -71,8 +71,8 @@ public DocumentationOpenApiOperationFilter(IJsonApiOptions options, IControllerR public void Apply(OpenApiOperation operation, OperationFilterContext context) { - ArgumentGuard.NotNull(operation); - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(operation); + ArgumentNullException.ThrowIfNull(context); bool hasHeadVerb = context.ApiDescription.HttpMethod == "HEAD"; diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/EndpointOrderingFilter.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/EndpointOrderingFilter.cs index 48fdcfdbc8..047ba4355a 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/EndpointOrderingFilter.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/EndpointOrderingFilter.cs @@ -6,23 +6,12 @@ namespace JsonApiDotNetCore.OpenApi.Swashbuckle.SwaggerComponents; [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] -#if NET6_0 -internal sealed class EndpointOrderingFilter : IDocumentFilter -#else internal sealed partial class EndpointOrderingFilter : IDocumentFilter -#endif { - private const string PatternText = @".*{id}/(?>relationships\/)?(?\w+)"; - -#if NET6_0 - private const RegexOptions RegexOptionsNet60 = RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture; - private static readonly Regex RelationshipNameInUrlPattern = new(PatternText, RegexOptionsNet60); -#endif - public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { - ArgumentGuard.NotNull(swaggerDoc); - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(swaggerDoc); + ArgumentNullException.ThrowIfNull(context); KeyValuePair[] endpointsInOrder = swaggerDoc.Paths.OrderBy(GetPrimaryResourcePublicName) .ThenBy(GetRelationshipName).ThenBy(IsSecondaryEndpoint).ToArray(); @@ -52,13 +41,6 @@ private static string GetRelationshipName(KeyValuePair return match.Success ? match.Groups["RelationshipName"].Value : string.Empty; } -#if NET6_0 - private static Regex RelationshipNameInUrlRegex() - { - return RelationshipNameInUrlPattern; - } -#else - [GeneratedRegex(PatternText, RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture)] + [GeneratedRegex(@".*{id}/(?>relationships\/)?(?\w+)", RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture)] private static partial Regex RelationshipNameInUrlRegex(); -#endif } diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/JsonApiDataContractResolver.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/JsonApiDataContractResolver.cs index c3218828b3..dcc652c696 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/JsonApiDataContractResolver.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/JsonApiDataContractResolver.cs @@ -16,8 +16,8 @@ internal sealed class JsonApiDataContractResolver : ISerializerDataContractResol public JsonApiDataContractResolver(IJsonApiOptions options, IResourceGraph resourceGraph) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(resourceGraph); _resourceGraph = resourceGraph; _dataContractResolver = new JsonSerializerDataContractResolver(options.SerializerOptions); @@ -25,7 +25,7 @@ public JsonApiDataContractResolver(IJsonApiOptions options, IResourceGraph resou public DataContract GetDataContractForType(Type type) { - ArgumentGuard.NotNull(type); + ArgumentNullException.ThrowIfNull(type); if (type == typeof(IIdentifiable)) { @@ -47,8 +47,6 @@ public DataContract GetDataContractForType(Type type) dataContract = ReplacePropertiesInDataContract(dataContract, replacementProperties); } - dataContract = OrderPropertiesInDataContract(dataContract); - return dataContract; } @@ -58,29 +56,6 @@ private static DataContract ReplacePropertiesInDataContract(DataContract dataCon dataContract.ObjectTypeNameValue); } - private static DataContract OrderPropertiesInDataContract(DataContract dataContract) - { -#if NET6_0 - // From https://learn.microsoft.com/en-us/dotnet/api/system.type.getproperties#system-type-getproperties: - // In .NET 6 and earlier versions, the GetProperties method does not return properties in a particular order, such as alphabetical or declaration - // order. Your code must not depend on the order in which properties are returned, because that order varies. However, starting with .NET 7, the - // ordering is deterministic based upon the metadata ordering in the assembly. - - if (dataContract.ObjectProperties != null) - { - DataProperty[] dataPropertiesInOrder = dataContract.ObjectProperties.OrderBy(dataProperty => dataProperty.MemberInfo.MetadataToken).ToArray(); - - // @formatter:keep_existing_linebreaks true - - return DataContract.ForObject(dataContract.UnderlyingType, dataPropertiesInOrder, dataContract.ObjectExtensionDataType, - dataContract.ObjectTypeNameProperty, dataContract.ObjectTypeNameValue); - - // @formatter:keep_existing_linebreaks restore - } -#endif - return dataContract; - } - private List GetDataPropertiesThatExistInResourceClrType(Type resourceClrType, DataContract dataContract) { ResourceType resourceType = _resourceGraph.GetResourceType(resourceClrType); diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/ResourceDocumentationReader.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/ResourceDocumentationReader.cs index 4afa0373bf..cd2727854c 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/ResourceDocumentationReader.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/ResourceDocumentationReader.cs @@ -14,7 +14,7 @@ internal sealed class ResourceDocumentationReader public string? GetDocumentationForType(ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); XPathNavigator? navigator = GetNavigator(resourceType.ClrType.Assembly); @@ -29,7 +29,7 @@ internal sealed class ResourceDocumentationReader public string? GetDocumentationForAttribute(AttrAttribute attribute) { - ArgumentGuard.NotNull(attribute); + ArgumentNullException.ThrowIfNull(attribute); XPathNavigator? navigator = GetNavigator(attribute.Type.ClrType.Assembly); @@ -44,7 +44,7 @@ internal sealed class ResourceDocumentationReader public string? GetDocumentationForRelationship(RelationshipAttribute relationship) { - ArgumentGuard.NotNull(relationship); + ArgumentNullException.ThrowIfNull(relationship); XPathNavigator? navigator = GetNavigator(relationship.Type.ClrType.Assembly); diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/ResourceFieldSchemaBuilder.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/ResourceFieldSchemaBuilder.cs index 10750d08cd..001d2a9fe2 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/ResourceFieldSchemaBuilder.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/ResourceFieldSchemaBuilder.cs @@ -25,12 +25,12 @@ public ResourceFieldSchemaBuilder(SchemaGenerator defaultSchemaGenerator, Resour LinksVisibilitySchemaGenerator linksVisibilitySchemaGenerator, ResourceFieldValidationMetadataProvider resourceFieldValidationMetadataProvider, RelationshipTypeFactory relationshipTypeFactory, ResourceSchemaType resourceSchemaType) { - ArgumentGuard.NotNull(defaultSchemaGenerator); - ArgumentGuard.NotNull(resourceIdentifierSchemaGenerator); - ArgumentGuard.NotNull(linksVisibilitySchemaGenerator); - ArgumentGuard.NotNull(resourceSchemaType); - ArgumentGuard.NotNull(resourceFieldValidationMetadataProvider); - ArgumentGuard.NotNull(relationshipTypeFactory); + ArgumentNullException.ThrowIfNull(defaultSchemaGenerator); + ArgumentNullException.ThrowIfNull(resourceIdentifierSchemaGenerator); + ArgumentNullException.ThrowIfNull(linksVisibilitySchemaGenerator); + ArgumentNullException.ThrowIfNull(resourceSchemaType); + ArgumentNullException.ThrowIfNull(resourceFieldValidationMetadataProvider); + ArgumentNullException.ThrowIfNull(relationshipTypeFactory); _defaultSchemaGenerator = defaultSchemaGenerator; _resourceIdentifierSchemaGenerator = resourceIdentifierSchemaGenerator; @@ -55,8 +55,8 @@ private IDictionary GetFieldSchemas() public void SetMembersOfAttributes(OpenApiSchema fullSchemaForAttributes, bool forRequestSchema, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(fullSchemaForAttributes); - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(fullSchemaForAttributes); + ArgumentNullException.ThrowIfNull(schemaRepository); AssertHasNoProperties(fullSchemaForAttributes); AttrCapabilities requiredCapability = GetRequiredCapabilityForAttributes(_resourceSchemaType.SchemaOpenType); @@ -150,8 +150,8 @@ private bool IsFieldRequired(ResourceFieldAttribute field) public void SetMembersOfRelationships(OpenApiSchema fullSchemaForRelationships, bool forRequestSchema, SchemaRepository schemaRepository) { - ArgumentGuard.NotNull(fullSchemaForRelationships); - ArgumentGuard.NotNull(schemaRepository); + ArgumentNullException.ThrowIfNull(fullSchemaForRelationships); + ArgumentNullException.ThrowIfNull(schemaRepository); AssertHasNoProperties(fullSchemaForRelationships); foreach (string publicName in _schemasForResourceFields.Keys) diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/ResourceSchemaType.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/ResourceSchemaType.cs index 9580119126..24221d2fde 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/ResourceSchemaType.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/ResourceSchemaType.cs @@ -25,8 +25,8 @@ private ResourceSchemaType(Type schemaOpenType, ResourceType resourceType) public static ResourceSchemaType Create(Type schemaConstructedType, IResourceGraph resourceGraph) { - ArgumentGuard.NotNull(schemaConstructedType); - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(schemaConstructedType); + ArgumentNullException.ThrowIfNull(resourceGraph); Type schemaOpenType = schemaConstructedType.GetGenericTypeDefinition(); Type resourceClrType = schemaConstructedType.GenericTypeArguments[0]; diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/ServerDocumentFilter.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/ServerDocumentFilter.cs index 4dc74e4cd0..723499d39c 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/ServerDocumentFilter.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/ServerDocumentFilter.cs @@ -12,7 +12,7 @@ internal sealed class ServerDocumentFilter : IDocumentFilter public ServerDocumentFilter(IHttpContextAccessor httpContextAccessor) { - ArgumentGuard.NotNull(httpContextAccessor); + ArgumentNullException.ThrowIfNull(httpContextAccessor); _httpContextAccessor = httpContextAccessor; } diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/StringEnumOrderingFilter.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/StringEnumOrderingFilter.cs index 7fb235ce59..022e3ca384 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/StringEnumOrderingFilter.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/SwaggerComponents/StringEnumOrderingFilter.cs @@ -14,8 +14,8 @@ internal sealed class StringEnumOrderingFilter : IDocumentFilter public void Apply(OpenApiDocument document, DocumentFilterContext context) { - ArgumentGuard.NotNull(document); - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(context); var visitor = new OpenApiEnumVisitor(); var walker = new OpenApiWalker(visitor); diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/TypeExtensions.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/TypeExtensions.cs index aaea265368..ebfb000577 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/TypeExtensions.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/TypeExtensions.cs @@ -4,7 +4,7 @@ internal static class TypeExtensions { public static Type ConstructedToOpenType(this Type type) { - ArgumentGuard.NotNull(type); + ArgumentNullException.ThrowIfNull(type); return type.IsConstructedGenericType ? type.GetGenericTypeDefinition() : type; } diff --git a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/UnusedComponentSchemaCleaner.cs b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/UnusedComponentSchemaCleaner.cs index c2e9ba4db1..e0d32bdcf7 100644 --- a/src/JsonApiDotNetCore.OpenApi.Swashbuckle/UnusedComponentSchemaCleaner.cs +++ b/src/JsonApiDotNetCore.OpenApi.Swashbuckle/UnusedComponentSchemaCleaner.cs @@ -14,8 +14,8 @@ internal sealed class UnusedComponentSchemaCleaner : IDocumentFilter { public void Apply(OpenApiDocument document, DocumentFilterContext context) { - ArgumentGuard.NotNull(document); - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(context); bool hasChanges; diff --git a/src/JsonApiDotNetCore/AtomicOperations/DefaultOperationFilter.cs b/src/JsonApiDotNetCore/AtomicOperations/DefaultOperationFilter.cs index 1407674150..fb632dd276 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/DefaultOperationFilter.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/DefaultOperationFilter.cs @@ -12,7 +12,7 @@ public class DefaultOperationFilter : IAtomicOperationFilter /// public virtual bool IsEnabled(ResourceType resourceType, WriteOperationKind writeOperation) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); // To match the behavior of non-operations controllers: // If an operation is enabled on a base type, it is implicitly enabled on all derived types. @@ -34,7 +34,7 @@ public virtual bool IsEnabled(ResourceType resourceType, WriteOperationKind writ protected virtual JsonApiEndpoints? GetJsonApiEndpoints(ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); var resourceAttribute = resourceType.ClrType.GetCustomAttribute(); return resourceAttribute?.GenerateControllerEndpoints; diff --git a/src/JsonApiDotNetCore/AtomicOperations/EntityFrameworkCoreTransaction.cs b/src/JsonApiDotNetCore/AtomicOperations/EntityFrameworkCoreTransaction.cs index f59f86162d..d045bc0814 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/EntityFrameworkCoreTransaction.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/EntityFrameworkCoreTransaction.cs @@ -19,8 +19,8 @@ public sealed class EntityFrameworkCoreTransaction : IOperationsTransaction public EntityFrameworkCoreTransaction(IDbContextTransaction transaction, DbContext dbContext) { - ArgumentGuard.NotNull(transaction); - ArgumentGuard.NotNull(dbContext); + ArgumentNullException.ThrowIfNull(transaction); + ArgumentNullException.ThrowIfNull(dbContext); _transaction = transaction; _dbContext = dbContext; diff --git a/src/JsonApiDotNetCore/AtomicOperations/EntityFrameworkCoreTransactionFactory.cs b/src/JsonApiDotNetCore/AtomicOperations/EntityFrameworkCoreTransactionFactory.cs index 8ef44cb627..2fe6959b1f 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/EntityFrameworkCoreTransactionFactory.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/EntityFrameworkCoreTransactionFactory.cs @@ -15,8 +15,8 @@ public sealed class EntityFrameworkCoreTransactionFactory : IOperationsTransacti public EntityFrameworkCoreTransactionFactory(IDbContextResolver dbContextResolver, IJsonApiOptions options) { - ArgumentGuard.NotNull(dbContextResolver); - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(dbContextResolver); + ArgumentNullException.ThrowIfNull(options); _dbContextResolver = dbContextResolver; _options = options; diff --git a/src/JsonApiDotNetCore/AtomicOperations/LocalIdTracker.cs b/src/JsonApiDotNetCore/AtomicOperations/LocalIdTracker.cs index 5d22198a72..bb058475e3 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/LocalIdTracker.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/LocalIdTracker.cs @@ -17,8 +17,8 @@ public void Reset() /// public void Declare(string localId, ResourceType resourceType) { - ArgumentGuard.NotNullNorEmpty(localId); - ArgumentGuard.NotNull(resourceType); + ArgumentException.ThrowIfNullOrEmpty(localId); + ArgumentNullException.ThrowIfNull(resourceType); AssertIsNotDeclared(localId); @@ -36,9 +36,9 @@ private void AssertIsNotDeclared(string localId) /// public void Assign(string localId, ResourceType resourceType, string stringId) { - ArgumentGuard.NotNullNorEmpty(localId); - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNullNorEmpty(stringId); + ArgumentException.ThrowIfNullOrEmpty(localId); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentException.ThrowIfNullOrEmpty(stringId); AssertIsDeclared(localId); @@ -57,8 +57,8 @@ public void Assign(string localId, ResourceType resourceType, string stringId) /// public string GetValue(string localId, ResourceType resourceType) { - ArgumentGuard.NotNullNorEmpty(localId); - ArgumentGuard.NotNull(resourceType); + ArgumentException.ThrowIfNullOrEmpty(localId); + ArgumentNullException.ThrowIfNull(resourceType); AssertIsDeclared(localId); diff --git a/src/JsonApiDotNetCore/AtomicOperations/LocalIdValidator.cs b/src/JsonApiDotNetCore/AtomicOperations/LocalIdValidator.cs index fb75fe3c7f..92d9bd8319 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/LocalIdValidator.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/LocalIdValidator.cs @@ -18,8 +18,8 @@ public sealed class LocalIdValidator public LocalIdValidator(ILocalIdTracker localIdTracker, IResourceGraph resourceGraph) { - ArgumentGuard.NotNull(localIdTracker); - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(localIdTracker); + ArgumentNullException.ThrowIfNull(resourceGraph); _localIdTracker = localIdTracker; _resourceGraph = resourceGraph; @@ -27,7 +27,7 @@ public LocalIdValidator(ILocalIdTracker localIdTracker, IResourceGraph resourceG public void Validate(IEnumerable operations) { - ArgumentGuard.NotNull(operations); + ArgumentNullException.ThrowIfNull(operations); _localIdTracker.Reset(); diff --git a/src/JsonApiDotNetCore/AtomicOperations/OperationProcessorAccessor.cs b/src/JsonApiDotNetCore/AtomicOperations/OperationProcessorAccessor.cs index 927bbf92d3..a6dc2051ec 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/OperationProcessorAccessor.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/OperationProcessorAccessor.cs @@ -15,7 +15,7 @@ public class OperationProcessorAccessor : IOperationProcessorAccessor public OperationProcessorAccessor(IServiceProvider serviceProvider) { - ArgumentGuard.NotNull(serviceProvider); + ArgumentNullException.ThrowIfNull(serviceProvider); _serviceProvider = serviceProvider; } @@ -23,7 +23,7 @@ public OperationProcessorAccessor(IServiceProvider serviceProvider) /// public Task ProcessAsync(OperationContainer operation, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(operation); + ArgumentNullException.ThrowIfNull(operation); IOperationProcessor processor = ResolveProcessor(operation); return processor.ProcessAsync(operation, cancellationToken); @@ -31,7 +31,7 @@ public OperationProcessorAccessor(IServiceProvider serviceProvider) protected virtual IOperationProcessor ResolveProcessor(OperationContainer operation) { - ArgumentGuard.NotNull(operation); + ArgumentNullException.ThrowIfNull(operation); Type processorInterface = GetProcessorInterface(operation.Request.WriteOperation!.Value); ResourceType resourceType = operation.Request.PrimaryResourceType!; diff --git a/src/JsonApiDotNetCore/AtomicOperations/OperationsProcessor.cs b/src/JsonApiDotNetCore/AtomicOperations/OperationsProcessor.cs index ff7a48dc32..f3d0b22256 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/OperationsProcessor.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/OperationsProcessor.cs @@ -25,13 +25,13 @@ public OperationsProcessor(IOperationProcessorAccessor operationProcessorAccesso ILocalIdTracker localIdTracker, IResourceGraph resourceGraph, IJsonApiRequest request, ITargetedFields targetedFields, ISparseFieldSetCache sparseFieldSetCache) { - ArgumentGuard.NotNull(operationProcessorAccessor); - ArgumentGuard.NotNull(operationsTransactionFactory); - ArgumentGuard.NotNull(localIdTracker); - ArgumentGuard.NotNull(resourceGraph); - ArgumentGuard.NotNull(request); - ArgumentGuard.NotNull(targetedFields); - ArgumentGuard.NotNull(sparseFieldSetCache); + ArgumentNullException.ThrowIfNull(operationProcessorAccessor); + ArgumentNullException.ThrowIfNull(operationsTransactionFactory); + ArgumentNullException.ThrowIfNull(localIdTracker); + ArgumentNullException.ThrowIfNull(resourceGraph); + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(targetedFields); + ArgumentNullException.ThrowIfNull(sparseFieldSetCache); _operationProcessorAccessor = operationProcessorAccessor; _operationsTransactionFactory = operationsTransactionFactory; @@ -46,7 +46,7 @@ public OperationsProcessor(IOperationProcessorAccessor operationProcessorAccesso /// public virtual async Task> ProcessAsync(IList operations, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(operations); + ArgumentNullException.ThrowIfNull(operations); _localIdValidator.Validate(operations); _localIdTracker.Reset(); @@ -101,7 +101,7 @@ public OperationsProcessor(IOperationProcessorAccessor operationProcessorAccesso protected virtual async Task ProcessOperationAsync(OperationContainer operation, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(operation); + ArgumentNullException.ThrowIfNull(operation); cancellationToken.ThrowIfCancellationRequested(); @@ -115,7 +115,7 @@ public OperationsProcessor(IOperationProcessorAccessor operationProcessorAccesso protected void TrackLocalIdsForOperation(OperationContainer operation) { - ArgumentGuard.NotNull(operation); + ArgumentNullException.ThrowIfNull(operation); if (operation.Request.WriteOperation == WriteOperationKind.CreateResource) { diff --git a/src/JsonApiDotNetCore/AtomicOperations/Processors/AddToRelationshipProcessor.cs b/src/JsonApiDotNetCore/AtomicOperations/Processors/AddToRelationshipProcessor.cs index fa835910ef..e84756120a 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/Processors/AddToRelationshipProcessor.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/Processors/AddToRelationshipProcessor.cs @@ -13,7 +13,7 @@ public class AddToRelationshipProcessor : IAddToRelationshipProc public AddToRelationshipProcessor(IAddToRelationshipService service) { - ArgumentGuard.NotNull(service); + ArgumentNullException.ThrowIfNull(service); _service = service; } @@ -21,7 +21,7 @@ public AddToRelationshipProcessor(IAddToRelationshipService serv /// public virtual async Task ProcessAsync(OperationContainer operation, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(operation); + ArgumentNullException.ThrowIfNull(operation); var leftId = (TId)operation.Resource.GetTypedId(); ISet rightResourceIds = operation.GetSecondaryResources(); diff --git a/src/JsonApiDotNetCore/AtomicOperations/Processors/CreateProcessor.cs b/src/JsonApiDotNetCore/AtomicOperations/Processors/CreateProcessor.cs index e4ccd7b69d..c7bf3c9b77 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/Processors/CreateProcessor.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/Processors/CreateProcessor.cs @@ -14,8 +14,8 @@ public class CreateProcessor : ICreateProcessor public CreateProcessor(ICreateService service, ILocalIdTracker localIdTracker) { - ArgumentGuard.NotNull(service); - ArgumentGuard.NotNull(localIdTracker); + ArgumentNullException.ThrowIfNull(service); + ArgumentNullException.ThrowIfNull(localIdTracker); _service = service; _localIdTracker = localIdTracker; @@ -24,7 +24,7 @@ public CreateProcessor(ICreateService service, ILocalIdTracker l /// public virtual async Task ProcessAsync(OperationContainer operation, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(operation); + ArgumentNullException.ThrowIfNull(operation); TResource? newResource = await _service.CreateAsync((TResource)operation.Resource, cancellationToken); diff --git a/src/JsonApiDotNetCore/AtomicOperations/Processors/DeleteProcessor.cs b/src/JsonApiDotNetCore/AtomicOperations/Processors/DeleteProcessor.cs index d758e065bc..5709188a8c 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/Processors/DeleteProcessor.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/Processors/DeleteProcessor.cs @@ -13,7 +13,7 @@ public class DeleteProcessor : IDeleteProcessor public DeleteProcessor(IDeleteService service) { - ArgumentGuard.NotNull(service); + ArgumentNullException.ThrowIfNull(service); _service = service; } @@ -21,7 +21,7 @@ public DeleteProcessor(IDeleteService service) /// public virtual async Task ProcessAsync(OperationContainer operation, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(operation); + ArgumentNullException.ThrowIfNull(operation); var id = (TId)operation.Resource.GetTypedId(); await _service.DeleteAsync(id!, cancellationToken); diff --git a/src/JsonApiDotNetCore/AtomicOperations/Processors/RemoveFromRelationshipProcessor.cs b/src/JsonApiDotNetCore/AtomicOperations/Processors/RemoveFromRelationshipProcessor.cs index 6222a01fd8..81c4eb93ee 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/Processors/RemoveFromRelationshipProcessor.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/Processors/RemoveFromRelationshipProcessor.cs @@ -13,7 +13,7 @@ public class RemoveFromRelationshipProcessor : IRemoveFromRelati public RemoveFromRelationshipProcessor(IRemoveFromRelationshipService service) { - ArgumentGuard.NotNull(service); + ArgumentNullException.ThrowIfNull(service); _service = service; } @@ -21,7 +21,7 @@ public RemoveFromRelationshipProcessor(IRemoveFromRelationshipService public virtual async Task ProcessAsync(OperationContainer operation, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(operation); + ArgumentNullException.ThrowIfNull(operation); var leftId = (TId)operation.Resource.GetTypedId(); ISet rightResourceIds = operation.GetSecondaryResources(); diff --git a/src/JsonApiDotNetCore/AtomicOperations/Processors/SetRelationshipProcessor.cs b/src/JsonApiDotNetCore/AtomicOperations/Processors/SetRelationshipProcessor.cs index abc40c4812..913068a26c 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/Processors/SetRelationshipProcessor.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/Processors/SetRelationshipProcessor.cs @@ -14,7 +14,7 @@ public class SetRelationshipProcessor : ISetRelationshipProcesso public SetRelationshipProcessor(ISetRelationshipService service) { - ArgumentGuard.NotNull(service); + ArgumentNullException.ThrowIfNull(service); _service = service; } @@ -22,7 +22,7 @@ public SetRelationshipProcessor(ISetRelationshipService service) /// public virtual async Task ProcessAsync(OperationContainer operation, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(operation); + ArgumentNullException.ThrowIfNull(operation); var leftId = (TId)operation.Resource.GetTypedId(); object? rightValue = GetRelationshipRightValue(operation); diff --git a/src/JsonApiDotNetCore/AtomicOperations/Processors/UpdateProcessor.cs b/src/JsonApiDotNetCore/AtomicOperations/Processors/UpdateProcessor.cs index 32fe2a1eb5..cf66c70462 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/Processors/UpdateProcessor.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/Processors/UpdateProcessor.cs @@ -13,7 +13,7 @@ public class UpdateProcessor : IUpdateProcessor public UpdateProcessor(IUpdateService service) { - ArgumentGuard.NotNull(service); + ArgumentNullException.ThrowIfNull(service); _service = service; } @@ -21,7 +21,7 @@ public UpdateProcessor(IUpdateService service) /// public virtual async Task ProcessAsync(OperationContainer operation, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(operation); + ArgumentNullException.ThrowIfNull(operation); var resource = (TResource)operation.Resource; TResource? updated = await _service.UpdateAsync(resource.Id!, resource, cancellationToken); diff --git a/src/JsonApiDotNetCore/AtomicOperations/RevertRequestStateOnDispose.cs b/src/JsonApiDotNetCore/AtomicOperations/RevertRequestStateOnDispose.cs index 824e69de74..82b0641c34 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/RevertRequestStateOnDispose.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/RevertRequestStateOnDispose.cs @@ -16,7 +16,7 @@ internal sealed class RevertRequestStateOnDispose : IDisposable public RevertRequestStateOnDispose(IJsonApiRequest request, ITargetedFields? targetedFields) { - ArgumentGuard.NotNull(request); + ArgumentNullException.ThrowIfNull(request); _sourceRequest = request; _backupRequest.CopyFrom(request); diff --git a/src/JsonApiDotNetCore/CollectionExtensions.cs b/src/JsonApiDotNetCore/CollectionExtensions.cs index 05ed03f328..ca46953bfc 100644 --- a/src/JsonApiDotNetCore/CollectionExtensions.cs +++ b/src/JsonApiDotNetCore/CollectionExtensions.cs @@ -18,7 +18,7 @@ public static bool IsNullOrEmpty([NotNullWhen(false)] this IEnumerable? so public static int FindIndex(this IReadOnlyList source, T item) { - ArgumentGuard.NotNull(source); + ArgumentNullException.ThrowIfNull(source); for (int index = 0; index < source.Count; index++) { @@ -33,8 +33,8 @@ public static int FindIndex(this IReadOnlyList source, T item) public static int FindIndex(this IReadOnlyList source, Predicate match) { - ArgumentGuard.NotNull(source); - ArgumentGuard.NotNull(match); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(match); for (int index = 0; index < source.Count; index++) { diff --git a/src/JsonApiDotNetCore/Configuration/ApplicationBuilderExtensions.cs b/src/JsonApiDotNetCore/Configuration/ApplicationBuilderExtensions.cs index 8ed4e42a42..349cb20dd9 100644 --- a/src/JsonApiDotNetCore/Configuration/ApplicationBuilderExtensions.cs +++ b/src/JsonApiDotNetCore/Configuration/ApplicationBuilderExtensions.cs @@ -22,7 +22,7 @@ public static class ApplicationBuilderExtensions /// public static void UseJsonApi(this IApplicationBuilder builder) { - ArgumentGuard.NotNull(builder); + ArgumentNullException.ThrowIfNull(builder); using (IServiceScope scope = builder.ApplicationServices.CreateScope()) { diff --git a/src/JsonApiDotNetCore/Configuration/DefaultJsonApiApplicationBuilderEvents.cs b/src/JsonApiDotNetCore/Configuration/DefaultJsonApiApplicationBuilderEvents.cs index dbab4e076b..c1bea78418 100644 --- a/src/JsonApiDotNetCore/Configuration/DefaultJsonApiApplicationBuilderEvents.cs +++ b/src/JsonApiDotNetCore/Configuration/DefaultJsonApiApplicationBuilderEvents.cs @@ -8,7 +8,7 @@ internal sealed class DefaultJsonApiApplicationBuilderEvents : IJsonApiApplicati public DefaultJsonApiApplicationBuilderEvents(IJsonApiOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); _options = options; } diff --git a/src/JsonApiDotNetCore/Configuration/InjectablesAssemblyScanner.cs b/src/JsonApiDotNetCore/Configuration/InjectablesAssemblyScanner.cs index 9985533776..3ac71053b0 100644 --- a/src/JsonApiDotNetCore/Configuration/InjectablesAssemblyScanner.cs +++ b/src/JsonApiDotNetCore/Configuration/InjectablesAssemblyScanner.cs @@ -46,8 +46,8 @@ internal sealed class InjectablesAssemblyScanner public InjectablesAssemblyScanner(ResourceDescriptorAssemblyCache assemblyCache, IServiceCollection services) { - ArgumentGuard.NotNull(assemblyCache); - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(assemblyCache); + ArgumentNullException.ThrowIfNull(services); _assemblyCache = assemblyCache; _services = services; diff --git a/src/JsonApiDotNetCore/Configuration/InverseNavigationResolver.cs b/src/JsonApiDotNetCore/Configuration/InverseNavigationResolver.cs index 270444928e..4527afdcbe 100644 --- a/src/JsonApiDotNetCore/Configuration/InverseNavigationResolver.cs +++ b/src/JsonApiDotNetCore/Configuration/InverseNavigationResolver.cs @@ -15,8 +15,8 @@ public sealed class InverseNavigationResolver : IInverseNavigationResolver public InverseNavigationResolver(IResourceGraph resourceGraph, IEnumerable dbContextResolvers) { - ArgumentGuard.NotNull(resourceGraph); - ArgumentGuard.NotNull(dbContextResolvers); + ArgumentNullException.ThrowIfNull(resourceGraph); + ArgumentNullException.ThrowIfNull(dbContextResolvers); _resourceGraph = resourceGraph; _dbContextResolvers = dbContextResolvers as IDbContextResolver[] ?? dbContextResolvers.ToArray(); diff --git a/src/JsonApiDotNetCore/Configuration/JsonApiApplicationBuilder.cs b/src/JsonApiDotNetCore/Configuration/JsonApiApplicationBuilder.cs index 8dc8f47b77..65646b7697 100644 --- a/src/JsonApiDotNetCore/Configuration/JsonApiApplicationBuilder.cs +++ b/src/JsonApiDotNetCore/Configuration/JsonApiApplicationBuilder.cs @@ -36,8 +36,8 @@ internal sealed class JsonApiApplicationBuilder : IJsonApiApplicationBuilder public JsonApiApplicationBuilder(IServiceCollection services, IMvcCoreBuilder mvcBuilder) { - ArgumentGuard.NotNull(services); - ArgumentGuard.NotNull(mvcBuilder); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(mvcBuilder); _services = services; _mvcBuilder = mvcBuilder; @@ -68,7 +68,7 @@ public void ConfigureAutoDiscovery(Action? configureAuto /// public void ConfigureResourceGraph(ICollection dbContextTypes, Action? configureResourceGraph) { - ArgumentGuard.NotNull(dbContextTypes); + ArgumentNullException.ThrowIfNull(dbContextTypes); _services.TryAddSingleton(serviceProvider => { @@ -135,7 +135,7 @@ public void DiscoverInjectables() /// public void ConfigureServiceContainer(ICollection dbContextTypes) { - ArgumentGuard.NotNull(dbContextTypes); + ArgumentNullException.ThrowIfNull(dbContextTypes); if (dbContextTypes.Count > 0) { diff --git a/src/JsonApiDotNetCore/Configuration/JsonApiModelMetadataProvider.cs b/src/JsonApiDotNetCore/Configuration/JsonApiModelMetadataProvider.cs index 2aaa218be7..5e1941a165 100644 --- a/src/JsonApiDotNetCore/Configuration/JsonApiModelMetadataProvider.cs +++ b/src/JsonApiDotNetCore/Configuration/JsonApiModelMetadataProvider.cs @@ -31,7 +31,7 @@ public JsonApiModelMetadataProvider(ICompositeMetadataDetailsProvider detailsPro /// protected override ModelMetadata CreateModelMetadata(DefaultMetadataDetails entry) { - ArgumentGuard.NotNull(entry); + ArgumentNullException.ThrowIfNull(entry); var metadata = (DefaultModelMetadata)base.CreateModelMetadata(entry); metadata.ValidationMetadata.PropertyValidationFilter = _jsonApiValidationFilter; diff --git a/src/JsonApiDotNetCore/Configuration/JsonApiOptions.cs b/src/JsonApiDotNetCore/Configuration/JsonApiOptions.cs index 084070b27c..182c51431b 100644 --- a/src/JsonApiDotNetCore/Configuration/JsonApiOptions.cs +++ b/src/JsonApiDotNetCore/Configuration/JsonApiOptions.cs @@ -144,7 +144,7 @@ public JsonApiOptions() /// public void IncludeExtensions(params JsonApiMediaTypeExtension[] extensionsToAdd) { - ArgumentGuard.NotNull(extensionsToAdd); + ArgumentNullException.ThrowIfNull(extensionsToAdd); if (!Extensions.IsSupersetOf(extensionsToAdd)) { diff --git a/src/JsonApiDotNetCore/Configuration/JsonApiValidationFilter.cs b/src/JsonApiDotNetCore/Configuration/JsonApiValidationFilter.cs index 3fd29a9c65..30b850e8b8 100644 --- a/src/JsonApiDotNetCore/Configuration/JsonApiValidationFilter.cs +++ b/src/JsonApiDotNetCore/Configuration/JsonApiValidationFilter.cs @@ -16,7 +16,7 @@ internal sealed class JsonApiValidationFilter : IPropertyValidationFilter public JsonApiValidationFilter(IHttpContextAccessor httpContextAccessor) { - ArgumentGuard.NotNull(httpContextAccessor); + ArgumentNullException.ThrowIfNull(httpContextAccessor); _httpContextAccessor = httpContextAccessor; } diff --git a/src/JsonApiDotNetCore/Configuration/PageNumber.cs b/src/JsonApiDotNetCore/Configuration/PageNumber.cs index 44732fc404..f4af725a3d 100644 --- a/src/JsonApiDotNetCore/Configuration/PageNumber.cs +++ b/src/JsonApiDotNetCore/Configuration/PageNumber.cs @@ -11,14 +11,7 @@ public sealed class PageNumber : IEquatable public PageNumber(int oneBasedValue) { -#if NET6_0 - if (oneBasedValue < 1) - { - throw new ArgumentOutOfRangeException(nameof(oneBasedValue)); - } -#else ArgumentOutOfRangeException.ThrowIfLessThan(oneBasedValue, 1); -#endif OneBasedValue = oneBasedValue; } diff --git a/src/JsonApiDotNetCore/Configuration/PageSize.cs b/src/JsonApiDotNetCore/Configuration/PageSize.cs index 46beb1419f..4581992597 100644 --- a/src/JsonApiDotNetCore/Configuration/PageSize.cs +++ b/src/JsonApiDotNetCore/Configuration/PageSize.cs @@ -9,14 +9,7 @@ public sealed class PageSize : IEquatable public PageSize(int value) { -#if NET6_0 - if (value < 1) - { - throw new ArgumentOutOfRangeException(nameof(value)); - } -#else ArgumentOutOfRangeException.ThrowIfLessThan(value, 1); -#endif Value = value; } diff --git a/src/JsonApiDotNetCore/Configuration/ResourceDescriptor.cs b/src/JsonApiDotNetCore/Configuration/ResourceDescriptor.cs index 885f67567c..9c0ce2cf30 100644 --- a/src/JsonApiDotNetCore/Configuration/ResourceDescriptor.cs +++ b/src/JsonApiDotNetCore/Configuration/ResourceDescriptor.cs @@ -7,8 +7,8 @@ internal sealed class ResourceDescriptor public ResourceDescriptor(Type resourceClrType, Type idClrType) { - ArgumentGuard.NotNull(resourceClrType); - ArgumentGuard.NotNull(idClrType); + ArgumentNullException.ThrowIfNull(resourceClrType); + ArgumentNullException.ThrowIfNull(idClrType); ResourceClrType = resourceClrType; IdClrType = idClrType; diff --git a/src/JsonApiDotNetCore/Configuration/ResourceGraph.cs b/src/JsonApiDotNetCore/Configuration/ResourceGraph.cs index b0eddedc91..a4ffd082d3 100644 --- a/src/JsonApiDotNetCore/Configuration/ResourceGraph.cs +++ b/src/JsonApiDotNetCore/Configuration/ResourceGraph.cs @@ -19,7 +19,7 @@ public sealed class ResourceGraph : IResourceGraph public ResourceGraph(IReadOnlySet resourceTypeSet) { - ArgumentGuard.NotNull(resourceTypeSet); + ArgumentNullException.ThrowIfNull(resourceTypeSet); _resourceTypeSet = resourceTypeSet; @@ -52,7 +52,7 @@ public ResourceType GetResourceType(string publicName) /// public ResourceType? FindResourceType(string publicName) { - ArgumentGuard.NotNull(publicName); + ArgumentNullException.ThrowIfNull(publicName); return _resourceTypesByPublicName.GetValueOrDefault(publicName); } @@ -73,7 +73,7 @@ public ResourceType GetResourceType(Type resourceClrType) /// public ResourceType? FindResourceType(Type resourceClrType) { - ArgumentGuard.NotNull(resourceClrType); + ArgumentNullException.ThrowIfNull(resourceClrType); Type typeToFind = IsLazyLoadingProxyForResourceType(resourceClrType) ? resourceClrType.BaseType! : resourceClrType; return _resourceTypesByClrType.GetValueOrDefault(typeToFind); @@ -95,7 +95,7 @@ public ResourceType GetResourceType() public IReadOnlyCollection GetFields(Expression> selector) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(selector); + ArgumentNullException.ThrowIfNull(selector); return FilterFields(selector); } @@ -104,7 +104,7 @@ public IReadOnlyCollection GetFields(Expressi public IReadOnlyCollection GetAttributes(Expression> selector) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(selector); + ArgumentNullException.ThrowIfNull(selector); return FilterFields(selector); } @@ -113,7 +113,7 @@ public IReadOnlyCollection GetAttributes(Expression GetRelationships(Expression> selector) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(selector); + ArgumentNullException.ThrowIfNull(selector); return FilterFields(selector); } diff --git a/src/JsonApiDotNetCore/Configuration/ResourceGraphBuilder.cs b/src/JsonApiDotNetCore/Configuration/ResourceGraphBuilder.cs index 159ce5be69..5233db578f 100644 --- a/src/JsonApiDotNetCore/Configuration/ResourceGraphBuilder.cs +++ b/src/JsonApiDotNetCore/Configuration/ResourceGraphBuilder.cs @@ -23,8 +23,8 @@ public partial class ResourceGraphBuilder public ResourceGraphBuilder(IJsonApiOptions options, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(loggerFactory); _options = options; _logger = loggerFactory.CreateLogger(); @@ -149,7 +149,7 @@ private static void ValidateRelationshipsInDerivedType(ResourceType resourceType public ResourceGraphBuilder Add(DbContext dbContext) { - ArgumentGuard.NotNull(dbContext); + ArgumentNullException.ThrowIfNull(dbContext); foreach (IEntityType entityType in dbContext.Model.GetEntityTypes()) { @@ -205,7 +205,7 @@ public ResourceGraphBuilder Add(string? publicName = null) public ResourceGraphBuilder Add(Type resourceClrType, Type? idClrType = null, string? publicName = null) #pragma warning restore AV1553 // Do not use optional parameters with default value null for strings, collections or tasks { - ArgumentGuard.NotNull(resourceClrType); + ArgumentNullException.ThrowIfNull(resourceClrType); if (_resourceTypesByClrType.ContainsKey(resourceClrType)) { diff --git a/src/JsonApiDotNetCore/Configuration/ResourceNameFormatter.cs b/src/JsonApiDotNetCore/Configuration/ResourceNameFormatter.cs index 6a5a09dcaf..0531c25ca9 100644 --- a/src/JsonApiDotNetCore/Configuration/ResourceNameFormatter.cs +++ b/src/JsonApiDotNetCore/Configuration/ResourceNameFormatter.cs @@ -14,7 +14,7 @@ internal sealed class ResourceNameFormatter(JsonNamingPolicy? namingPolicy) /// public string FormatResourceName(Type resourceClrType) { - ArgumentGuard.NotNull(resourceClrType); + ArgumentNullException.ThrowIfNull(resourceClrType); var resourceAttribute = resourceClrType.GetCustomAttribute(true); diff --git a/src/JsonApiDotNetCore/Configuration/ResourcesAssemblyScanner.cs b/src/JsonApiDotNetCore/Configuration/ResourcesAssemblyScanner.cs index cdfdc4446c..f2dcf827d3 100644 --- a/src/JsonApiDotNetCore/Configuration/ResourcesAssemblyScanner.cs +++ b/src/JsonApiDotNetCore/Configuration/ResourcesAssemblyScanner.cs @@ -12,8 +12,8 @@ internal sealed class ResourcesAssemblyScanner public ResourcesAssemblyScanner(ResourceDescriptorAssemblyCache assemblyCache, ResourceGraphBuilder resourceGraphBuilder) { - ArgumentGuard.NotNull(assemblyCache); - ArgumentGuard.NotNull(resourceGraphBuilder); + ArgumentNullException.ThrowIfNull(assemblyCache); + ArgumentNullException.ThrowIfNull(resourceGraphBuilder); _assemblyCache = assemblyCache; _resourceGraphBuilder = resourceGraphBuilder; diff --git a/src/JsonApiDotNetCore/Configuration/ServiceCollectionExtensions.cs b/src/JsonApiDotNetCore/Configuration/ServiceCollectionExtensions.cs index 5ad4474d95..65bf465ce3 100644 --- a/src/JsonApiDotNetCore/Configuration/ServiceCollectionExtensions.cs +++ b/src/JsonApiDotNetCore/Configuration/ServiceCollectionExtensions.cs @@ -22,7 +22,7 @@ public static IServiceCollection AddJsonApi(this IServiceCollection services, Ac ICollection? dbContextTypes = null) #pragma warning restore AV1553 // Do not use optional parameters with default value null for strings, collections or tasks { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); SetupApplicationBuilder(services, options, discovery, resources, mvcBuilder, dbContextTypes ?? Array.Empty()); @@ -59,7 +59,7 @@ private static void SetupApplicationBuilder(IServiceCollection services, Action< /// public static IServiceCollection AddResourceService(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); RegisterTypeForUnboundInterfaces(services, typeof(TService), InjectablesAssemblyScanner.ServiceUnboundInterfaces); @@ -72,7 +72,7 @@ public static IServiceCollection AddResourceService(this IServiceColle /// public static IServiceCollection AddResourceRepository(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); RegisterTypeForUnboundInterfaces(services, typeof(TRepository), InjectablesAssemblyScanner.RepositoryUnboundInterfaces); @@ -85,7 +85,7 @@ public static IServiceCollection AddResourceRepository(this IServic /// public static IServiceCollection AddResourceDefinition(this IServiceCollection services) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); RegisterTypeForUnboundInterfaces(services, typeof(TResourceDefinition), InjectablesAssemblyScanner.ResourceDefinitionUnboundInterfaces); diff --git a/src/JsonApiDotNetCore/Configuration/ServiceDiscoveryFacade.cs b/src/JsonApiDotNetCore/Configuration/ServiceDiscoveryFacade.cs index 615ef244fc..d28b8381c6 100644 --- a/src/JsonApiDotNetCore/Configuration/ServiceDiscoveryFacade.cs +++ b/src/JsonApiDotNetCore/Configuration/ServiceDiscoveryFacade.cs @@ -13,7 +13,7 @@ public sealed class ServiceDiscoveryFacade internal ServiceDiscoveryFacade(ResourceDescriptorAssemblyCache assemblyCache) { - ArgumentGuard.NotNull(assemblyCache); + ArgumentNullException.ThrowIfNull(assemblyCache); _assemblyCache = assemblyCache; } @@ -31,7 +31,7 @@ public ServiceDiscoveryFacade AddCurrentAssembly() /// public ServiceDiscoveryFacade AddAssembly(Assembly assembly) { - ArgumentGuard.NotNull(assembly); + ArgumentNullException.ThrowIfNull(assembly); _assemblyCache.RegisterAssembly(assembly); return this; diff --git a/src/JsonApiDotNetCore/Configuration/TypeLocator.cs b/src/JsonApiDotNetCore/Configuration/TypeLocator.cs index bce31946f1..6b8c545744 100644 --- a/src/JsonApiDotNetCore/Configuration/TypeLocator.cs +++ b/src/JsonApiDotNetCore/Configuration/TypeLocator.cs @@ -66,9 +66,9 @@ internal sealed class TypeLocator public (Type implementationType, Type serviceInterface)? GetContainerRegistrationFromAssembly(Assembly assembly, Type unboundInterface, params Type[] interfaceTypeArguments) { - ArgumentGuard.NotNull(assembly); - ArgumentGuard.NotNull(unboundInterface); - ArgumentGuard.NotNull(interfaceTypeArguments); + ArgumentNullException.ThrowIfNull(assembly); + ArgumentNullException.ThrowIfNull(unboundInterface); + ArgumentNullException.ThrowIfNull(interfaceTypeArguments); if (!unboundInterface.IsInterface || !unboundInterface.IsGenericType || unboundInterface != unboundInterface.GetGenericTypeDefinition()) { @@ -126,8 +126,8 @@ private static (Type implementationType, Type serviceInterface)? GetContainerReg /// public IEnumerable GetDerivedTypes(Assembly assembly, Type baseType) { - ArgumentGuard.NotNull(assembly); - ArgumentGuard.NotNull(baseType); + ArgumentNullException.ThrowIfNull(assembly); + ArgumentNullException.ThrowIfNull(baseType); foreach (Type type in assembly.GetTypes()) { diff --git a/src/JsonApiDotNetCore/Controllers/Annotations/DisableQueryStringAttribute.cs b/src/JsonApiDotNetCore/Controllers/Annotations/DisableQueryStringAttribute.cs index b659fdc370..d90d67118e 100644 --- a/src/JsonApiDotNetCore/Controllers/Annotations/DisableQueryStringAttribute.cs +++ b/src/JsonApiDotNetCore/Controllers/Annotations/DisableQueryStringAttribute.cs @@ -46,7 +46,7 @@ public DisableQueryStringAttribute(JsonApiQueryStringParameters parameters) /// public DisableQueryStringAttribute(string parameterNames) { - ArgumentGuard.NotNullNorEmpty(parameterNames); + ArgumentException.ThrowIfNullOrEmpty(parameterNames); ParameterNames = parameterNames.Split(",").ToHashSet().AsReadOnly(); } diff --git a/src/JsonApiDotNetCore/Controllers/BaseJsonApiController.cs b/src/JsonApiDotNetCore/Controllers/BaseJsonApiController.cs index d293a98701..acd6528500 100644 --- a/src/JsonApiDotNetCore/Controllers/BaseJsonApiController.cs +++ b/src/JsonApiDotNetCore/Controllers/BaseJsonApiController.cs @@ -66,9 +66,9 @@ protected BaseJsonApiController(IJsonApiOptions options, IResourceGraph resource IUpdateService? update = null, ISetRelationshipService? setRelationship = null, IDeleteService? delete = null, IRemoveFromRelationshipService? removeFromRelationship = null) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(resourceGraph); - ArgumentGuard.NotNull(loggerFactory); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(resourceGraph); + ArgumentNullException.ThrowIfNull(loggerFactory); _options = options; _resourceGraph = resourceGraph; @@ -143,7 +143,7 @@ public virtual async Task GetSecondaryAsync([DisallowNull] TId id relationshipName }); - ArgumentGuard.NotNull(relationshipName); + ArgumentNullException.ThrowIfNull(relationshipName); if (_getSecondary == null) { @@ -173,7 +173,7 @@ public virtual async Task GetRelationshipAsync([DisallowNull] TId relationshipName }); - ArgumentGuard.NotNull(relationshipName); + ArgumentNullException.ThrowIfNull(relationshipName); if (_getRelationship == null) { @@ -197,7 +197,7 @@ public virtual async Task PostAsync([FromBody] TResource resource resource }); - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); if (_create == null) { @@ -259,8 +259,8 @@ public virtual async Task PostRelationshipAsync([DisallowNull] TI rightResourceIds }); - ArgumentGuard.NotNull(relationshipName); - ArgumentGuard.NotNull(rightResourceIds); + ArgumentNullException.ThrowIfNull(relationshipName); + ArgumentNullException.ThrowIfNull(rightResourceIds); if (_addToRelationship == null) { @@ -286,7 +286,7 @@ public virtual async Task PatchAsync([DisallowNull] TId id, [From resource }); - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); if (_update == null) { @@ -334,7 +334,7 @@ public virtual async Task PatchRelationshipAsync([DisallowNull] T rightValue }); - ArgumentGuard.NotNull(relationshipName); + ArgumentNullException.ThrowIfNull(relationshipName); if (_setRelationship == null) { @@ -395,8 +395,8 @@ public virtual async Task DeleteRelationshipAsync([DisallowNull] rightResourceIds }); - ArgumentGuard.NotNull(relationshipName); - ArgumentGuard.NotNull(rightResourceIds); + ArgumentNullException.ThrowIfNull(relationshipName); + ArgumentNullException.ThrowIfNull(rightResourceIds); if (_removeFromRelationship == null) { diff --git a/src/JsonApiDotNetCore/Controllers/BaseJsonApiOperationsController.cs b/src/JsonApiDotNetCore/Controllers/BaseJsonApiOperationsController.cs index 3c8ebac01a..6c6703c132 100644 --- a/src/JsonApiDotNetCore/Controllers/BaseJsonApiOperationsController.cs +++ b/src/JsonApiDotNetCore/Controllers/BaseJsonApiOperationsController.cs @@ -30,13 +30,13 @@ public abstract class BaseJsonApiOperationsController : CoreJsonApiController protected BaseJsonApiOperationsController(IJsonApiOptions options, IResourceGraph resourceGraph, ILoggerFactory loggerFactory, IOperationsProcessor processor, IJsonApiRequest request, ITargetedFields targetedFields, IAtomicOperationFilter operationFilter) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(resourceGraph); - ArgumentGuard.NotNull(loggerFactory); - ArgumentGuard.NotNull(processor); - ArgumentGuard.NotNull(request); - ArgumentGuard.NotNull(targetedFields); - ArgumentGuard.NotNull(operationFilter); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(resourceGraph); + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(processor); + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(targetedFields); + ArgumentNullException.ThrowIfNull(operationFilter); _options = options; _resourceGraph = resourceGraph; @@ -114,7 +114,7 @@ public virtual async Task PostOperationsAsync([FromBody] IList PostOperationsAsync([FromBody] IList operations) { - ArgumentGuard.NotNull(operations); + ArgumentNullException.ThrowIfNull(operations); List errors = []; @@ -193,7 +193,7 @@ private static string GetOperationCodeText(WriteOperationKind writeOperation) protected virtual void ValidateModelState(IList operations) { - ArgumentGuard.NotNull(operations); + ArgumentNullException.ThrowIfNull(operations); // We must validate the resource inside each operation manually, because they are typed as IIdentifiable. // Instead of validating IIdentifiable we need to validate the resource runtime-type. diff --git a/src/JsonApiDotNetCore/Controllers/CoreJsonApiController.cs b/src/JsonApiDotNetCore/Controllers/CoreJsonApiController.cs index 332a9bf255..f81ec9d071 100644 --- a/src/JsonApiDotNetCore/Controllers/CoreJsonApiController.cs +++ b/src/JsonApiDotNetCore/Controllers/CoreJsonApiController.cs @@ -11,7 +11,7 @@ public abstract class CoreJsonApiController : ControllerBase { protected IActionResult Error(ErrorObject error) { - ArgumentGuard.NotNull(error); + ArgumentNullException.ThrowIfNull(error); return new ObjectResult(error) { diff --git a/src/JsonApiDotNetCore/Diagnostics/AspNetCodeTimerSession.cs b/src/JsonApiDotNetCore/Diagnostics/AspNetCodeTimerSession.cs index a42d734580..9b58dc43e7 100644 --- a/src/JsonApiDotNetCore/Diagnostics/AspNetCodeTimerSession.cs +++ b/src/JsonApiDotNetCore/Diagnostics/AspNetCodeTimerSession.cs @@ -37,14 +37,14 @@ public ICodeTimer CodeTimer public AspNetCodeTimerSession(IHttpContextAccessor httpContextAccessor) { - ArgumentGuard.NotNull(httpContextAccessor); + ArgumentNullException.ThrowIfNull(httpContextAccessor); _httpContextAccessor = httpContextAccessor; } public AspNetCodeTimerSession(HttpContext httpContext) { - ArgumentGuard.NotNull(httpContext); + ArgumentNullException.ThrowIfNull(httpContext); _httpContext = httpContext; } diff --git a/src/JsonApiDotNetCore/Diagnostics/CodeTimingSessionManager.cs b/src/JsonApiDotNetCore/Diagnostics/CodeTimingSessionManager.cs index f44cfe2c75..adf642c3b8 100644 --- a/src/JsonApiDotNetCore/Diagnostics/CodeTimingSessionManager.cs +++ b/src/JsonApiDotNetCore/Diagnostics/CodeTimingSessionManager.cs @@ -68,7 +68,7 @@ private static void AssertHasActiveSession() public static void Capture(ICodeTimerSession session) { - ArgumentGuard.NotNull(session); + ArgumentNullException.ThrowIfNull(session); AssertNoActiveSession(); diff --git a/src/JsonApiDotNetCore/Diagnostics/DefaultCodeTimerSession.cs b/src/JsonApiDotNetCore/Diagnostics/DefaultCodeTimerSession.cs index 5737dbe3f2..6ee970711a 100644 --- a/src/JsonApiDotNetCore/Diagnostics/DefaultCodeTimerSession.cs +++ b/src/JsonApiDotNetCore/Diagnostics/DefaultCodeTimerSession.cs @@ -2,7 +2,7 @@ namespace JsonApiDotNetCore.Diagnostics; /// /// General code timing session management. Can be used with async/wait, but it cannot distinguish between concurrently running threads, so you'll need -/// to pass an instance through the entire call chain in that case. +/// to pass a instance through the entire call chain in that case. /// public sealed class DefaultCodeTimerSession : ICodeTimerSession { @@ -27,14 +27,7 @@ public DefaultCodeTimerSession() private void AssertNotDisposed() { -#if NET6_0 - if (_codeTimerInContext.Value == null) - { - throw new ObjectDisposedException(nameof(DefaultCodeTimerSession)); - } -#else ObjectDisposedException.ThrowIf(_codeTimerInContext.Value == null, this); -#endif } public void Dispose() diff --git a/src/JsonApiDotNetCore/Errors/InvalidModelStateException.cs b/src/JsonApiDotNetCore/Errors/InvalidModelStateException.cs index ccf23e1eb5..fc85156e57 100644 --- a/src/JsonApiDotNetCore/Errors/InvalidModelStateException.cs +++ b/src/JsonApiDotNetCore/Errors/InvalidModelStateException.cs @@ -23,9 +23,9 @@ public sealed class InvalidModelStateException( private static List FromModelStateDictionary(IReadOnlyDictionary modelState, Type modelType, IResourceGraph resourceGraph, bool includeExceptionStackTraceInErrors, Func? getCollectionElementTypeCallback) { - ArgumentGuard.NotNull(modelState); - ArgumentGuard.NotNull(modelType); - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(modelState); + ArgumentNullException.ThrowIfNull(modelType); + ArgumentNullException.ThrowIfNull(resourceGraph); List errorObjects = []; @@ -231,8 +231,8 @@ private abstract class ModelStateKeySegment protected ModelStateKeySegment(Type modelType, bool isInComplexType, string nextKey, string? sourcePointer, ModelStateKeySegment? parent, Func? getCollectionElementTypeCallback) { - ArgumentGuard.NotNull(modelType); - ArgumentGuard.NotNull(nextKey); + ArgumentNullException.ThrowIfNull(modelType); + ArgumentNullException.ThrowIfNull(nextKey); ModelType = modelType; IsInComplexType = isInComplexType; @@ -244,15 +244,15 @@ protected ModelStateKeySegment(Type modelType, bool isInComplexType, string next public ModelStateKeySegment? GetNextSegment(Type modelType, bool isInComplexType, string? sourcePointer) { - ArgumentGuard.NotNull(modelType); + ArgumentNullException.ThrowIfNull(modelType); return _nextKey.Length == 0 ? null : CreateSegment(modelType, _nextKey, isInComplexType, this, sourcePointer, GetCollectionElementTypeCallback); } public static ModelStateKeySegment Create(Type modelType, string key, Func? getCollectionElementTypeCallback) { - ArgumentGuard.NotNull(modelType); - ArgumentGuard.NotNull(key); + ArgumentNullException.ThrowIfNull(modelType); + ArgumentNullException.ThrowIfNull(key); return CreateSegment(modelType, key, false, null, null, getCollectionElementTypeCallback); } @@ -355,14 +355,14 @@ public PropertySegment(string propertyName, Type modelType, bool isInComplexType Func? getCollectionElementTypeCallback) : base(modelType, isInComplexType, nextKey, sourcePointer, parent, getCollectionElementTypeCallback) { - ArgumentGuard.NotNull(propertyName); + ArgumentNullException.ThrowIfNull(propertyName); PropertyName = propertyName; } public static string GetPublicNameForProperty(PropertyInfo property) { - ArgumentGuard.NotNull(property); + ArgumentNullException.ThrowIfNull(property); var jsonNameAttribute = property.GetCustomAttribute(true); return jsonNameAttribute?.Name ?? property.Name; diff --git a/src/JsonApiDotNetCore/Errors/JsonApiException.cs b/src/JsonApiDotNetCore/Errors/JsonApiException.cs index 1f15a127b4..b44b18d5a8 100644 --- a/src/JsonApiDotNetCore/Errors/JsonApiException.cs +++ b/src/JsonApiDotNetCore/Errors/JsonApiException.cs @@ -25,7 +25,7 @@ public class JsonApiException : Exception public JsonApiException(ErrorObject error, Exception? innerException = null) : base(null, innerException) { - ArgumentGuard.NotNull(error); + ArgumentNullException.ThrowIfNull(error); Errors = [error]; } diff --git a/src/JsonApiDotNetCore/Errors/MissingResourceInRelationship.cs b/src/JsonApiDotNetCore/Errors/MissingResourceInRelationship.cs index c2afd80cbf..de38f61fcd 100644 --- a/src/JsonApiDotNetCore/Errors/MissingResourceInRelationship.cs +++ b/src/JsonApiDotNetCore/Errors/MissingResourceInRelationship.cs @@ -11,9 +11,9 @@ public sealed class MissingResourceInRelationship public MissingResourceInRelationship(string relationshipName, string resourceType, string resourceId) { - ArgumentGuard.NotNull(relationshipName); - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNull(resourceId); + ArgumentNullException.ThrowIfNull(relationshipName); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceId); RelationshipName = relationshipName; ResourceType = resourceType; diff --git a/src/JsonApiDotNetCore/Errors/UnsuccessfulActionResultException.cs b/src/JsonApiDotNetCore/Errors/UnsuccessfulActionResultException.cs index 16f79db822..9e8083f7dc 100644 --- a/src/JsonApiDotNetCore/Errors/UnsuccessfulActionResultException.cs +++ b/src/JsonApiDotNetCore/Errors/UnsuccessfulActionResultException.cs @@ -27,7 +27,7 @@ public UnsuccessfulActionResultException(ProblemDetails problemDetails) private static IEnumerable ToErrorObjects(ProblemDetails problemDetails) { - ArgumentGuard.NotNull(problemDetails); + ArgumentNullException.ThrowIfNull(problemDetails); HttpStatusCode status = problemDetails.Status != null ? (HttpStatusCode)problemDetails.Status.Value : HttpStatusCode.InternalServerError; diff --git a/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj b/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj index 0f395511a7..b30f89cb9f 100644 --- a/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj +++ b/src/JsonApiDotNetCore/JsonApiDotNetCore.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net8.0 true true diff --git a/src/JsonApiDotNetCore/Middleware/AsyncConvertEmptyActionResultFilter.cs b/src/JsonApiDotNetCore/Middleware/AsyncConvertEmptyActionResultFilter.cs index a895c20ba4..440d3e69ea 100644 --- a/src/JsonApiDotNetCore/Middleware/AsyncConvertEmptyActionResultFilter.cs +++ b/src/JsonApiDotNetCore/Middleware/AsyncConvertEmptyActionResultFilter.cs @@ -10,8 +10,8 @@ public sealed class AsyncConvertEmptyActionResultFilter : IAsyncConvertEmptyActi /// public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { - ArgumentGuard.NotNull(context); - ArgumentGuard.NotNull(next); + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(next); if (context.HttpContext.IsJsonApiRequest()) { diff --git a/src/JsonApiDotNetCore/Middleware/AsyncJsonApiExceptionFilter.cs b/src/JsonApiDotNetCore/Middleware/AsyncJsonApiExceptionFilter.cs index 45a0b96891..915747de8b 100644 --- a/src/JsonApiDotNetCore/Middleware/AsyncJsonApiExceptionFilter.cs +++ b/src/JsonApiDotNetCore/Middleware/AsyncJsonApiExceptionFilter.cs @@ -13,7 +13,7 @@ public sealed class AsyncJsonApiExceptionFilter : IAsyncJsonApiExceptionFilter public AsyncJsonApiExceptionFilter(IExceptionHandler exceptionHandler) { - ArgumentGuard.NotNull(exceptionHandler); + ArgumentNullException.ThrowIfNull(exceptionHandler); _exceptionHandler = exceptionHandler; } @@ -21,7 +21,7 @@ public AsyncJsonApiExceptionFilter(IExceptionHandler exceptionHandler) /// public Task OnExceptionAsync(ExceptionContext context) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); if (context.HttpContext.IsJsonApiRequest()) { diff --git a/src/JsonApiDotNetCore/Middleware/AsyncQueryStringActionFilter.cs b/src/JsonApiDotNetCore/Middleware/AsyncQueryStringActionFilter.cs index 6c394a531f..e832b4693a 100644 --- a/src/JsonApiDotNetCore/Middleware/AsyncQueryStringActionFilter.cs +++ b/src/JsonApiDotNetCore/Middleware/AsyncQueryStringActionFilter.cs @@ -12,7 +12,7 @@ public sealed class AsyncQueryStringActionFilter : IAsyncQueryStringActionFilter public AsyncQueryStringActionFilter(IQueryStringReader queryStringReader) { - ArgumentGuard.NotNull(queryStringReader); + ArgumentNullException.ThrowIfNull(queryStringReader); _queryStringReader = queryStringReader; } @@ -20,8 +20,8 @@ public AsyncQueryStringActionFilter(IQueryStringReader queryStringReader) /// public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { - ArgumentGuard.NotNull(context); - ArgumentGuard.NotNull(next); + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(next); if (context.HttpContext.IsJsonApiRequest()) { diff --git a/src/JsonApiDotNetCore/Middleware/ExceptionHandler.cs b/src/JsonApiDotNetCore/Middleware/ExceptionHandler.cs index 0712f659ac..44e1b384ef 100644 --- a/src/JsonApiDotNetCore/Middleware/ExceptionHandler.cs +++ b/src/JsonApiDotNetCore/Middleware/ExceptionHandler.cs @@ -17,8 +17,8 @@ public partial class ExceptionHandler : IExceptionHandler public ExceptionHandler(ILoggerFactory loggerFactory, IJsonApiOptions options) { - ArgumentGuard.NotNull(loggerFactory); - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(options); _options = options; _logger = loggerFactory.CreateLogger(); @@ -26,7 +26,7 @@ public ExceptionHandler(ILoggerFactory loggerFactory, IJsonApiOptions options) public IReadOnlyList HandleException(Exception exception) { - ArgumentGuard.NotNull(exception); + ArgumentNullException.ThrowIfNull(exception); Exception demystified = exception.Demystify(); @@ -45,7 +45,7 @@ private void LogException(Exception exception) protected virtual LogLevel GetLogLevel(Exception exception) { - ArgumentGuard.NotNull(exception); + ArgumentNullException.ThrowIfNull(exception); if (exception is OperationCanceledException) { @@ -62,14 +62,14 @@ protected virtual LogLevel GetLogLevel(Exception exception) protected virtual string GetLogMessage(Exception exception) { - ArgumentGuard.NotNull(exception); + ArgumentNullException.ThrowIfNull(exception); return exception is JsonApiException jsonApiException ? jsonApiException.GetSummary() : exception.Message; } protected virtual IReadOnlyList CreateErrorResponse(Exception exception) { - ArgumentGuard.NotNull(exception); + ArgumentNullException.ThrowIfNull(exception); IReadOnlyList errors = exception switch { diff --git a/src/JsonApiDotNetCore/Middleware/HttpContextExtensions.cs b/src/JsonApiDotNetCore/Middleware/HttpContextExtensions.cs index a675aeeaff..85de6e92fb 100644 --- a/src/JsonApiDotNetCore/Middleware/HttpContextExtensions.cs +++ b/src/JsonApiDotNetCore/Middleware/HttpContextExtensions.cs @@ -13,7 +13,7 @@ public static class HttpContextExtensions /// public static bool IsJsonApiRequest(this HttpContext httpContext) { - ArgumentGuard.NotNull(httpContext); + ArgumentNullException.ThrowIfNull(httpContext); string? value = httpContext.Items[IsJsonApiRequestKey] as string; return value == bool.TrueString; @@ -21,7 +21,7 @@ public static bool IsJsonApiRequest(this HttpContext httpContext) internal static void RegisterJsonApiRequest(this HttpContext httpContext) { - ArgumentGuard.NotNull(httpContext); + ArgumentNullException.ThrowIfNull(httpContext); httpContext.Items[IsJsonApiRequestKey] = bool.TrueString; } diff --git a/src/JsonApiDotNetCore/Middleware/HttpMethodAttributeExtensions.cs b/src/JsonApiDotNetCore/Middleware/HttpMethodAttributeExtensions.cs index e00cdd326d..b85e2f53ae 100644 --- a/src/JsonApiDotNetCore/Middleware/HttpMethodAttributeExtensions.cs +++ b/src/JsonApiDotNetCore/Middleware/HttpMethodAttributeExtensions.cs @@ -13,7 +13,7 @@ internal static class HttpMethodAttributeExtensions public static JsonApiEndpoints GetJsonApiEndpoint(this IEnumerable httpMethods) { - ArgumentGuard.NotNull(httpMethods); + ArgumentNullException.ThrowIfNull(httpMethods); HttpMethodAttribute[] nonHeadAttributes = httpMethods.Where(attribute => attribute is not HttpHeadAttribute).ToArray(); diff --git a/src/JsonApiDotNetCore/Middleware/JsonApiContentNegotiator.cs b/src/JsonApiDotNetCore/Middleware/JsonApiContentNegotiator.cs index 9cc366b282..a9806129f8 100644 --- a/src/JsonApiDotNetCore/Middleware/JsonApiContentNegotiator.cs +++ b/src/JsonApiDotNetCore/Middleware/JsonApiContentNegotiator.cs @@ -30,8 +30,8 @@ private HttpContext HttpContext public JsonApiContentNegotiator(IJsonApiOptions options, IHttpContextAccessor httpContextAccessor) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(httpContextAccessor); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(httpContextAccessor); _options = options; _httpContextAccessor = httpContextAccessor; diff --git a/src/JsonApiDotNetCore/Middleware/JsonApiInputFormatter.cs b/src/JsonApiDotNetCore/Middleware/JsonApiInputFormatter.cs index 9988d0dcaf..008d5fd6dd 100644 --- a/src/JsonApiDotNetCore/Middleware/JsonApiInputFormatter.cs +++ b/src/JsonApiDotNetCore/Middleware/JsonApiInputFormatter.cs @@ -10,7 +10,7 @@ public sealed class JsonApiInputFormatter : IJsonApiInputFormatter /// public bool CanRead(InputFormatterContext context) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); return context.HttpContext.IsJsonApiRequest(); } @@ -18,7 +18,7 @@ public bool CanRead(InputFormatterContext context) /// public async Task ReadAsync(InputFormatterContext context) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); var reader = context.HttpContext.RequestServices.GetRequiredService(); diff --git a/src/JsonApiDotNetCore/Middleware/JsonApiMediaType.cs b/src/JsonApiDotNetCore/Middleware/JsonApiMediaType.cs index 57e5c40e5e..d9661abffd 100644 --- a/src/JsonApiDotNetCore/Middleware/JsonApiMediaType.cs +++ b/src/JsonApiDotNetCore/Middleware/JsonApiMediaType.cs @@ -33,14 +33,14 @@ public sealed class JsonApiMediaType : IEquatable public JsonApiMediaType(IReadOnlySet extensions) { - ArgumentGuard.NotNull(extensions); + ArgumentNullException.ThrowIfNull(extensions); Extensions = extensions; } public JsonApiMediaType(IEnumerable extensions) { - ArgumentGuard.NotNull(extensions); + ArgumentNullException.ThrowIfNull(extensions); Extensions = extensions.ToHashSet().AsReadOnly(); } diff --git a/src/JsonApiDotNetCore/Middleware/JsonApiMediaTypeExtension.cs b/src/JsonApiDotNetCore/Middleware/JsonApiMediaTypeExtension.cs index 0e07eb40e0..f35a613dc1 100644 --- a/src/JsonApiDotNetCore/Middleware/JsonApiMediaTypeExtension.cs +++ b/src/JsonApiDotNetCore/Middleware/JsonApiMediaTypeExtension.cs @@ -15,7 +15,7 @@ public sealed class JsonApiMediaTypeExtension : IEquatable logger) { - ArgumentGuard.NotNull(httpContextAccessor); - ArgumentGuard.NotNull(controllerResourceMapping); - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(contentNegotiator); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(httpContextAccessor); + ArgumentNullException.ThrowIfNull(controllerResourceMapping); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(contentNegotiator); + ArgumentNullException.ThrowIfNull(logger); _next = next; _controllerResourceMapping = controllerResourceMapping; @@ -50,8 +50,8 @@ public JsonApiMiddleware(RequestDelegate? next, IHttpContextAccessor httpContext public async Task InvokeAsync(HttpContext httpContext, IJsonApiRequest request) { - ArgumentGuard.NotNull(httpContext); - ArgumentGuard.NotNull(request); + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentNullException.ThrowIfNull(request); using (CodeTimingSessionManager.Current.Measure("JSON:API middleware")) { diff --git a/src/JsonApiDotNetCore/Middleware/JsonApiOutputFormatter.cs b/src/JsonApiDotNetCore/Middleware/JsonApiOutputFormatter.cs index 80d7863251..1f6de39b8b 100644 --- a/src/JsonApiDotNetCore/Middleware/JsonApiOutputFormatter.cs +++ b/src/JsonApiDotNetCore/Middleware/JsonApiOutputFormatter.cs @@ -10,7 +10,7 @@ public sealed class JsonApiOutputFormatter : IJsonApiOutputFormatter /// public bool CanWriteResult(OutputFormatterCanWriteContext context) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); return context.HttpContext.IsJsonApiRequest(); } @@ -18,7 +18,7 @@ public bool CanWriteResult(OutputFormatterCanWriteContext context) /// public async Task WriteAsync(OutputFormatterWriteContext context) { - ArgumentGuard.NotNull(context); + ArgumentNullException.ThrowIfNull(context); var writer = context.HttpContext.RequestServices.GetRequiredService(); await writer.WriteAsync(context.Object, context.HttpContext); diff --git a/src/JsonApiDotNetCore/Middleware/JsonApiRequest.cs b/src/JsonApiDotNetCore/Middleware/JsonApiRequest.cs index bba58aaab5..4f382ec329 100644 --- a/src/JsonApiDotNetCore/Middleware/JsonApiRequest.cs +++ b/src/JsonApiDotNetCore/Middleware/JsonApiRequest.cs @@ -43,7 +43,7 @@ public sealed class JsonApiRequest : IJsonApiRequest /// public void CopyFrom(IJsonApiRequest other) { - ArgumentGuard.NotNull(other); + ArgumentNullException.ThrowIfNull(other); Kind = other.Kind; PrimaryId = other.PrimaryId; diff --git a/src/JsonApiDotNetCore/Middleware/JsonApiRoutingConvention.cs b/src/JsonApiDotNetCore/Middleware/JsonApiRoutingConvention.cs index 8403109d19..027775df29 100644 --- a/src/JsonApiDotNetCore/Middleware/JsonApiRoutingConvention.cs +++ b/src/JsonApiDotNetCore/Middleware/JsonApiRoutingConvention.cs @@ -41,10 +41,10 @@ public sealed partial class JsonApiRoutingConvention : IJsonApiRoutingConvention public JsonApiRoutingConvention(IJsonApiOptions options, IResourceGraph resourceGraph, IJsonApiEndpointFilter jsonApiEndpointFilter, ILogger logger) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(resourceGraph); - ArgumentGuard.NotNull(jsonApiEndpointFilter); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(resourceGraph); + ArgumentNullException.ThrowIfNull(jsonApiEndpointFilter); + ArgumentNullException.ThrowIfNull(logger); _options = options; _resourceGraph = resourceGraph; @@ -69,7 +69,7 @@ public JsonApiRoutingConvention(IJsonApiOptions options, IResourceGraph resource /// public void Apply(ApplicationModel application) { - ArgumentGuard.NotNull(application); + ArgumentNullException.ThrowIfNull(application); foreach (ControllerModel controller in application.Controllers) { diff --git a/src/JsonApiDotNetCore/Queries/EvaluatedIncludeCache.cs b/src/JsonApiDotNetCore/Queries/EvaluatedIncludeCache.cs index ea54da96af..72a311d246 100644 --- a/src/JsonApiDotNetCore/Queries/EvaluatedIncludeCache.cs +++ b/src/JsonApiDotNetCore/Queries/EvaluatedIncludeCache.cs @@ -11,7 +11,7 @@ internal sealed class EvaluatedIncludeCache : IEvaluatedIncludeCache public EvaluatedIncludeCache(IEnumerable constraintProviders) { - ArgumentGuard.NotNull(constraintProviders); + ArgumentNullException.ThrowIfNull(constraintProviders); _constraintProviders = constraintProviders as IQueryConstraintProvider[] ?? constraintProviders.ToArray(); } @@ -19,7 +19,7 @@ public EvaluatedIncludeCache(IEnumerable constraintPro /// public void Set(IncludeExpression include) { - ArgumentGuard.NotNull(include); + ArgumentNullException.ThrowIfNull(include); _include = include; _isAssigned = true; diff --git a/src/JsonApiDotNetCore/Queries/ExpressionInScope.cs b/src/JsonApiDotNetCore/Queries/ExpressionInScope.cs index 6ac6f75059..4cab3e203b 100644 --- a/src/JsonApiDotNetCore/Queries/ExpressionInScope.cs +++ b/src/JsonApiDotNetCore/Queries/ExpressionInScope.cs @@ -15,7 +15,7 @@ public class ExpressionInScope public ExpressionInScope(ResourceFieldChainExpression? scope, QueryExpression expression) { - ArgumentGuard.NotNull(expression); + ArgumentNullException.ThrowIfNull(expression); Scope = scope; Expression = expression; diff --git a/src/JsonApiDotNetCore/Queries/Expressions/AnyExpression.cs b/src/JsonApiDotNetCore/Queries/Expressions/AnyExpression.cs index dfa7536b03..306a98d1aa 100644 --- a/src/JsonApiDotNetCore/Queries/Expressions/AnyExpression.cs +++ b/src/JsonApiDotNetCore/Queries/Expressions/AnyExpression.cs @@ -28,7 +28,7 @@ public class AnyExpression : FilterExpression public AnyExpression(ResourceFieldChainExpression targetAttribute, IImmutableSet constants) { - ArgumentGuard.NotNull(targetAttribute); + ArgumentNullException.ThrowIfNull(targetAttribute); ArgumentGuard.NotNullNorEmpty(constants); TargetAttribute = targetAttribute; diff --git a/src/JsonApiDotNetCore/Queries/Expressions/ComparisonExpression.cs b/src/JsonApiDotNetCore/Queries/Expressions/ComparisonExpression.cs index 9259560776..b768f556ce 100644 --- a/src/JsonApiDotNetCore/Queries/Expressions/ComparisonExpression.cs +++ b/src/JsonApiDotNetCore/Queries/Expressions/ComparisonExpression.cs @@ -40,8 +40,8 @@ public class ComparisonExpression : FilterExpression public ComparisonExpression(ComparisonOperator @operator, QueryExpression left, QueryExpression right) { - ArgumentGuard.NotNull(left); - ArgumentGuard.NotNull(right); + ArgumentNullException.ThrowIfNull(left); + ArgumentNullException.ThrowIfNull(right); Operator = @operator; Left = left; diff --git a/src/JsonApiDotNetCore/Queries/Expressions/CountExpression.cs b/src/JsonApiDotNetCore/Queries/Expressions/CountExpression.cs index 960cf6371b..f79c49af1b 100644 --- a/src/JsonApiDotNetCore/Queries/Expressions/CountExpression.cs +++ b/src/JsonApiDotNetCore/Queries/Expressions/CountExpression.cs @@ -26,7 +26,7 @@ public class CountExpression : FunctionExpression public CountExpression(ResourceFieldChainExpression targetCollection) { - ArgumentGuard.NotNull(targetCollection); + ArgumentNullException.ThrowIfNull(targetCollection); TargetCollection = targetCollection; } diff --git a/src/JsonApiDotNetCore/Queries/Expressions/HasExpression.cs b/src/JsonApiDotNetCore/Queries/Expressions/HasExpression.cs index 709fd60916..5c40039d4e 100644 --- a/src/JsonApiDotNetCore/Queries/Expressions/HasExpression.cs +++ b/src/JsonApiDotNetCore/Queries/Expressions/HasExpression.cs @@ -32,7 +32,7 @@ public class HasExpression : FilterExpression public HasExpression(ResourceFieldChainExpression targetCollection, FilterExpression? filter) { - ArgumentGuard.NotNull(targetCollection); + ArgumentNullException.ThrowIfNull(targetCollection); TargetCollection = targetCollection; Filter = filter; diff --git a/src/JsonApiDotNetCore/Queries/Expressions/IncludeChainConverter.cs b/src/JsonApiDotNetCore/Queries/Expressions/IncludeChainConverter.cs index 5915886e72..c729c692b9 100644 --- a/src/JsonApiDotNetCore/Queries/Expressions/IncludeChainConverter.cs +++ b/src/JsonApiDotNetCore/Queries/Expressions/IncludeChainConverter.cs @@ -29,7 +29,7 @@ internal sealed class IncludeChainConverter /// public IReadOnlyCollection GetRelationshipChains(IncludeExpression include) { - ArgumentGuard.NotNull(include); + ArgumentNullException.ThrowIfNull(include); if (include.Elements.Count == 0) { diff --git a/src/JsonApiDotNetCore/Queries/Expressions/IncludeElementExpression.cs b/src/JsonApiDotNetCore/Queries/Expressions/IncludeElementExpression.cs index b67ece4379..9e98deefe3 100644 --- a/src/JsonApiDotNetCore/Queries/Expressions/IncludeElementExpression.cs +++ b/src/JsonApiDotNetCore/Queries/Expressions/IncludeElementExpression.cs @@ -32,8 +32,8 @@ public IncludeElementExpression(RelationshipAttribute relationship) public IncludeElementExpression(RelationshipAttribute relationship, IImmutableSet children) { - ArgumentGuard.NotNull(relationship); - ArgumentGuard.NotNull(children); + ArgumentNullException.ThrowIfNull(relationship); + ArgumentNullException.ThrowIfNull(children); Relationship = relationship; Children = children; diff --git a/src/JsonApiDotNetCore/Queries/Expressions/IsTypeExpression.cs b/src/JsonApiDotNetCore/Queries/Expressions/IsTypeExpression.cs index c916aff3bc..e2f68ee8ec 100644 --- a/src/JsonApiDotNetCore/Queries/Expressions/IsTypeExpression.cs +++ b/src/JsonApiDotNetCore/Queries/Expressions/IsTypeExpression.cs @@ -41,7 +41,7 @@ public class IsTypeExpression : FilterExpression public IsTypeExpression(ResourceFieldChainExpression? targetToOneRelationship, ResourceType derivedType, FilterExpression? child) { - ArgumentGuard.NotNull(derivedType); + ArgumentNullException.ThrowIfNull(derivedType); TargetToOneRelationship = targetToOneRelationship; DerivedType = derivedType; diff --git a/src/JsonApiDotNetCore/Queries/Expressions/LiteralConstantExpression.cs b/src/JsonApiDotNetCore/Queries/Expressions/LiteralConstantExpression.cs index 1592aadcfd..50c3b2cd54 100644 --- a/src/JsonApiDotNetCore/Queries/Expressions/LiteralConstantExpression.cs +++ b/src/JsonApiDotNetCore/Queries/Expressions/LiteralConstantExpression.cs @@ -24,8 +24,8 @@ public LiteralConstantExpression(object typedValue) public LiteralConstantExpression(object typedValue, string stringValue) { - ArgumentGuard.NotNull(typedValue); - ArgumentGuard.NotNull(stringValue); + ArgumentNullException.ThrowIfNull(typedValue); + ArgumentNullException.ThrowIfNull(stringValue); TypedValue = typedValue; _stringValue = stringValue; @@ -33,7 +33,7 @@ public LiteralConstantExpression(object typedValue, string stringValue) private static string? GetStringValue(object typedValue) { - ArgumentGuard.NotNull(typedValue); + ArgumentNullException.ThrowIfNull(typedValue); return typedValue is IFormattable cultureAwareValue ? cultureAwareValue.ToString(null, CultureInfo.InvariantCulture) : typedValue.ToString(); } diff --git a/src/JsonApiDotNetCore/Queries/Expressions/LogicalExpression.cs b/src/JsonApiDotNetCore/Queries/Expressions/LogicalExpression.cs index f1a9ba8c1c..416303b06b 100644 --- a/src/JsonApiDotNetCore/Queries/Expressions/LogicalExpression.cs +++ b/src/JsonApiDotNetCore/Queries/Expressions/LogicalExpression.cs @@ -37,7 +37,7 @@ public LogicalExpression(LogicalOperator @operator, params FilterExpression[] te public LogicalExpression(LogicalOperator @operator, IImmutableList terms) { - ArgumentGuard.NotNull(terms); + ArgumentNullException.ThrowIfNull(terms); if (terms.Count < 2) { @@ -50,7 +50,7 @@ public LogicalExpression(LogicalOperator @operator, IImmutableList> fieldSelector, IResourceGraph resourceGraph) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(fieldSelector); - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(fieldSelector); + ArgumentNullException.ThrowIfNull(resourceGraph); SparseFieldSetExpression? newSparseFieldSet = sparseFieldSet; @@ -42,8 +42,8 @@ public static class SparseFieldSetExpressionExtensions Expression> fieldSelector, IResourceGraph resourceGraph) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(fieldSelector); - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(fieldSelector); + ArgumentNullException.ThrowIfNull(resourceGraph); SparseFieldSetExpression? newSparseFieldSet = sparseFieldSet; diff --git a/src/JsonApiDotNetCore/Queries/FieldSelection.cs b/src/JsonApiDotNetCore/Queries/FieldSelection.cs index 53cf38268e..b929db2c80 100644 --- a/src/JsonApiDotNetCore/Queries/FieldSelection.cs +++ b/src/JsonApiDotNetCore/Queries/FieldSelection.cs @@ -23,7 +23,7 @@ public IReadOnlySet GetResourceTypes() public FieldSelectors GetOrCreateSelectors(ResourceType resourceType) #pragma warning restore AV1130 // Return type in method signature should be an interface to an unchangeable collection { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); if (!ContainsKey(resourceType)) { diff --git a/src/JsonApiDotNetCore/Queries/FieldSelectors.cs b/src/JsonApiDotNetCore/Queries/FieldSelectors.cs index 63415cfffc..d9ab815638 100644 --- a/src/JsonApiDotNetCore/Queries/FieldSelectors.cs +++ b/src/JsonApiDotNetCore/Queries/FieldSelectors.cs @@ -30,21 +30,21 @@ public bool ContainsOnlyRelationships public bool ContainsField(ResourceFieldAttribute field) { - ArgumentGuard.NotNull(field); + ArgumentNullException.ThrowIfNull(field); return ContainsKey(field); } public void IncludeAttribute(AttrAttribute attribute) { - ArgumentGuard.NotNull(attribute); + ArgumentNullException.ThrowIfNull(attribute); this[attribute] = null; } public void IncludeAttributes(IEnumerable attributes) { - ArgumentGuard.NotNull(attributes); + ArgumentNullException.ThrowIfNull(attributes); foreach (AttrAttribute attribute in attributes) { @@ -54,8 +54,8 @@ public void IncludeAttributes(IEnumerable attributes) public void IncludeRelationship(RelationshipAttribute relationship, QueryLayer queryLayer) { - ArgumentGuard.NotNull(relationship); - ArgumentGuard.NotNull(queryLayer); + ArgumentNullException.ThrowIfNull(relationship); + ArgumentNullException.ThrowIfNull(queryLayer); this[relationship] = queryLayer; } diff --git a/src/JsonApiDotNetCore/Queries/Parsing/FilterParser.cs b/src/JsonApiDotNetCore/Queries/Parsing/FilterParser.cs index fd300c0431..f89bf3dc39 100644 --- a/src/JsonApiDotNetCore/Queries/Parsing/FilterParser.cs +++ b/src/JsonApiDotNetCore/Queries/Parsing/FilterParser.cs @@ -54,7 +54,7 @@ protected ResourceType ResourceTypeInScope public FilterParser(IResourceFactory resourceFactory) { - ArgumentGuard.NotNull(resourceFactory); + ArgumentNullException.ThrowIfNull(resourceFactory); _resourceFactory = resourceFactory; } @@ -62,7 +62,7 @@ public FilterParser(IResourceFactory resourceFactory) /// public FilterExpression Parse(string source, ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); Tokenize(source); @@ -83,7 +83,7 @@ public FilterExpression Parse(string source, ResourceType resourceType) protected virtual bool IsFunction(string name) { - ArgumentGuard.NotNullNorEmpty(name); + ArgumentException.ThrowIfNullOrEmpty(name); return name == Keywords.Count || FilterKeywords.Contains(name); } @@ -179,7 +179,7 @@ protected virtual NotExpression ParseNot() protected virtual LogicalExpression ParseLogical(string operatorName) { - ArgumentGuard.NotNullNorEmpty(operatorName); + ArgumentException.ThrowIfNullOrEmpty(operatorName); EatText(operatorName); EatSingleCharacterToken(TokenKind.OpenParen); @@ -210,7 +210,7 @@ protected virtual LogicalExpression ParseLogical(string operatorName) protected virtual ComparisonExpression ParseComparison(string operatorName) { - ArgumentGuard.NotNullNorEmpty(operatorName); + ArgumentException.ThrowIfNullOrEmpty(operatorName); var comparisonOperator = Enum.Parse(operatorName.Pascalize()); @@ -315,7 +315,7 @@ private QueryExpression ParseTypedComparisonRightTerm(Type leftType, ConstantVal protected virtual MatchTextExpression ParseTextMatch(string operatorName) { - ArgumentGuard.NotNullNorEmpty(operatorName); + ArgumentException.ThrowIfNullOrEmpty(operatorName); EatText(operatorName); EatSingleCharacterToken(TokenKind.OpenParen); @@ -522,7 +522,7 @@ private NullConstantExpression ParseNull() protected virtual ConstantValueConverter GetConstantValueConverterForType(Type destinationType) { - ArgumentGuard.NotNull(destinationType); + ArgumentNullException.ThrowIfNull(destinationType); return (stringValue, position) => { @@ -566,7 +566,7 @@ private object DeObfuscateStringId(ResourceType resourceType, string stringId) protected override void ValidateField(ResourceFieldAttribute field, int position) { - ArgumentGuard.NotNull(field); + ArgumentNullException.ThrowIfNull(field); if (field.IsFilterBlocked()) { @@ -580,7 +580,7 @@ protected override void ValidateField(ResourceFieldAttribute field, int position /// protected IDisposable InScopeOfResourceType(ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); _resourceTypeStack.Push(resourceType); return new PopResourceTypeOnDispose(_resourceTypeStack); diff --git a/src/JsonApiDotNetCore/Queries/Parsing/IncludeParser.cs b/src/JsonApiDotNetCore/Queries/Parsing/IncludeParser.cs index 6afa8a0698..eb328f3183 100644 --- a/src/JsonApiDotNetCore/Queries/Parsing/IncludeParser.cs +++ b/src/JsonApiDotNetCore/Queries/Parsing/IncludeParser.cs @@ -17,7 +17,7 @@ public class IncludeParser : QueryExpressionParser, IIncludeParser public IncludeParser(IJsonApiOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); _options = options; } @@ -25,7 +25,7 @@ public IncludeParser(IJsonApiOptions options) /// public IncludeExpression Parse(string source, ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); Tokenize(source); @@ -39,8 +39,8 @@ public IncludeExpression Parse(string source, ResourceType resourceType) protected virtual IncludeExpression ParseInclude(string source, ResourceType resourceType) { - ArgumentGuard.NotNull(source); - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(resourceType); var treeRoot = IncludeTreeNode.CreateRoot(resourceType); bool isAtStart = true; @@ -307,7 +307,7 @@ private sealed class HiddenRootRelationshipAttribute : RelationshipAttribute { public HiddenRootRelationshipAttribute(ResourceType rightType) { - ArgumentGuard.NotNull(rightType); + ArgumentNullException.ThrowIfNull(rightType); RightType = rightType; PublicName = "<>"; diff --git a/src/JsonApiDotNetCore/Queries/Parsing/PaginationParser.cs b/src/JsonApiDotNetCore/Queries/Parsing/PaginationParser.cs index fff06ed3ec..669fba7b9c 100644 --- a/src/JsonApiDotNetCore/Queries/Parsing/PaginationParser.cs +++ b/src/JsonApiDotNetCore/Queries/Parsing/PaginationParser.cs @@ -13,7 +13,7 @@ public class PaginationParser : QueryExpressionParser, IPaginationParser /// public PaginationQueryStringValueExpression Parse(string source, ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); Tokenize(source); @@ -26,7 +26,7 @@ public PaginationQueryStringValueExpression Parse(string source, ResourceType re protected virtual PaginationQueryStringValueExpression ParsePagination(ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); ImmutableArray.Builder elementsBuilder = ImmutableArray.CreateBuilder(); @@ -47,7 +47,7 @@ protected virtual PaginationQueryStringValueExpression ParsePagination(ResourceT protected virtual PaginationElementQueryStringValueExpression ParsePaginationElement(ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); int position = GetNextTokenPositionOrEnd(); int? number = TryParseNumber(); diff --git a/src/JsonApiDotNetCore/Queries/Parsing/QueryExpressionParser.cs b/src/JsonApiDotNetCore/Queries/Parsing/QueryExpressionParser.cs index fc93c3fb81..772be38530 100644 --- a/src/JsonApiDotNetCore/Queries/Parsing/QueryExpressionParser.cs +++ b/src/JsonApiDotNetCore/Queries/Parsing/QueryExpressionParser.cs @@ -43,7 +43,7 @@ protected virtual void ValidateField(ResourceFieldAttribute field, int position) /// protected virtual void Tokenize(string source) { - ArgumentGuard.NotNull(source); + ArgumentNullException.ThrowIfNull(source); var tokenizer = new QueryTokenizer(source); TokenStack = new Stack(tokenizer.EnumerateTokens().Reverse()); @@ -56,8 +56,8 @@ protected virtual void Tokenize(string source) protected ResourceFieldChainExpression ParseFieldChain(FieldChainPattern pattern, FieldChainPatternMatchOptions options, ResourceType resourceType, string? alternativeErrorMessage) { - ArgumentGuard.NotNull(pattern); - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(pattern); + ArgumentNullException.ThrowIfNull(resourceType); int startPosition = GetNextTokenPositionOrEnd(); @@ -120,7 +120,7 @@ private string EatFieldChain(string? alternativeErrorMessage) /// protected void EatText(string text) { - ArgumentGuard.NotNull(text); + ArgumentNullException.ThrowIfNull(text); if (!TokenStack.TryPop(out Token? token) || token.Kind != TokenKind.Text || token.Value != text) { @@ -162,7 +162,7 @@ protected int GetNextTokenPositionOrEnd() /// protected int GetRelativePositionOfLastFieldInChain(ResourceFieldChainExpression fieldChain) { - ArgumentGuard.NotNull(fieldChain); + ArgumentNullException.ThrowIfNull(fieldChain); int position = 0; diff --git a/src/JsonApiDotNetCore/Queries/Parsing/QueryParseException.cs b/src/JsonApiDotNetCore/Queries/Parsing/QueryParseException.cs index 8136fb476e..4f63f45e24 100644 --- a/src/JsonApiDotNetCore/Queries/Parsing/QueryParseException.cs +++ b/src/JsonApiDotNetCore/Queries/Parsing/QueryParseException.cs @@ -28,7 +28,7 @@ public QueryParseException(string message, int position, Exception innerExceptio public string GetMessageWithPosition(string sourceText) { - ArgumentGuard.NotNull(sourceText); + ArgumentNullException.ThrowIfNull(sourceText); if (Position < 0) { diff --git a/src/JsonApiDotNetCore/Queries/Parsing/QueryStringParameterScopeParser.cs b/src/JsonApiDotNetCore/Queries/Parsing/QueryStringParameterScopeParser.cs index 8b7b80f70c..dfb98dc612 100644 --- a/src/JsonApiDotNetCore/Queries/Parsing/QueryStringParameterScopeParser.cs +++ b/src/JsonApiDotNetCore/Queries/Parsing/QueryStringParameterScopeParser.cs @@ -12,8 +12,8 @@ public class QueryStringParameterScopeParser : QueryExpressionParser, IQueryStri /// public QueryStringParameterScopeExpression Parse(string source, ResourceType resourceType, FieldChainPattern pattern, FieldChainPatternMatchOptions options) { - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNull(pattern); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentNullException.ThrowIfNull(pattern); Tokenize(source); @@ -27,8 +27,8 @@ public QueryStringParameterScopeExpression Parse(string source, ResourceType res protected virtual QueryStringParameterScopeExpression ParseQueryStringParameterScope(ResourceType resourceType, FieldChainPattern pattern, FieldChainPatternMatchOptions options) { - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNull(pattern); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentNullException.ThrowIfNull(pattern); int position = GetNextTokenPositionOrEnd(); diff --git a/src/JsonApiDotNetCore/Queries/Parsing/QueryTokenizer.cs b/src/JsonApiDotNetCore/Queries/Parsing/QueryTokenizer.cs index c73a8042d1..0c5f634375 100644 --- a/src/JsonApiDotNetCore/Queries/Parsing/QueryTokenizer.cs +++ b/src/JsonApiDotNetCore/Queries/Parsing/QueryTokenizer.cs @@ -26,7 +26,7 @@ public sealed class QueryTokenizer public QueryTokenizer(string source) { - ArgumentGuard.NotNull(source); + ArgumentNullException.ThrowIfNull(source); _source = source; } diff --git a/src/JsonApiDotNetCore/Queries/Parsing/SortParser.cs b/src/JsonApiDotNetCore/Queries/Parsing/SortParser.cs index db622873d2..e8df9b4a88 100644 --- a/src/JsonApiDotNetCore/Queries/Parsing/SortParser.cs +++ b/src/JsonApiDotNetCore/Queries/Parsing/SortParser.cs @@ -14,7 +14,7 @@ public class SortParser : QueryExpressionParser, ISortParser /// public SortExpression Parse(string source, ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); Tokenize(source); @@ -27,7 +27,7 @@ public SortExpression Parse(string source, ResourceType resourceType) protected virtual SortExpression ParseSort(ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); SortElementExpression firstElement = ParseSortElement(resourceType); @@ -47,7 +47,7 @@ protected virtual SortExpression ParseSort(ResourceType resourceType) protected virtual SortElementExpression ParseSortElement(ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); bool isAscending = true; @@ -99,14 +99,14 @@ protected virtual SortElementExpression ParseSortElement(ResourceType resourceTy protected virtual bool IsFunction(string name) { - ArgumentGuard.NotNullNorEmpty(name); + ArgumentException.ThrowIfNullOrEmpty(name); return name == Keywords.Count; } protected virtual FunctionExpression ParseFunction(ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); if (TokenStack.TryPeek(out Token? nextToken) && nextToken.Kind == TokenKind.Text) { @@ -138,7 +138,7 @@ private CountExpression ParseCount(ResourceType resourceType) protected override void ValidateField(ResourceFieldAttribute field, int position) { - ArgumentGuard.NotNull(field); + ArgumentNullException.ThrowIfNull(field); if (field is AttrAttribute attribute && !attribute.Capabilities.HasFlag(AttrCapabilities.AllowSort)) { diff --git a/src/JsonApiDotNetCore/Queries/Parsing/SparseFieldSetParser.cs b/src/JsonApiDotNetCore/Queries/Parsing/SparseFieldSetParser.cs index d4ac0ff921..9bf6a89daa 100644 --- a/src/JsonApiDotNetCore/Queries/Parsing/SparseFieldSetParser.cs +++ b/src/JsonApiDotNetCore/Queries/Parsing/SparseFieldSetParser.cs @@ -14,7 +14,7 @@ public class SparseFieldSetParser : QueryExpressionParser, ISparseFieldSetParser /// public SparseFieldSetExpression? Parse(string source, ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); Tokenize(source); @@ -27,7 +27,7 @@ public class SparseFieldSetParser : QueryExpressionParser, ISparseFieldSetParser protected virtual SparseFieldSetExpression? ParseSparseFieldSet(ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); ImmutableHashSet.Builder fieldSetBuilder = ImmutableHashSet.CreateBuilder(); @@ -50,7 +50,7 @@ public class SparseFieldSetParser : QueryExpressionParser, ISparseFieldSetParser protected override void ValidateField(ResourceFieldAttribute field, int position) { - ArgumentGuard.NotNull(field); + ArgumentNullException.ThrowIfNull(field); if (field.IsViewBlocked()) { diff --git a/src/JsonApiDotNetCore/Queries/Parsing/SparseFieldTypeParser.cs b/src/JsonApiDotNetCore/Queries/Parsing/SparseFieldTypeParser.cs index e24ce9f90e..00c5c6a525 100644 --- a/src/JsonApiDotNetCore/Queries/Parsing/SparseFieldTypeParser.cs +++ b/src/JsonApiDotNetCore/Queries/Parsing/SparseFieldTypeParser.cs @@ -11,7 +11,7 @@ public class SparseFieldTypeParser : QueryExpressionParser, ISparseFieldTypePars public SparseFieldTypeParser(IResourceGraph resourceGraph) { - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(resourceGraph); _resourceGraph = resourceGraph; } diff --git a/src/JsonApiDotNetCore/Queries/QueryLayer.cs b/src/JsonApiDotNetCore/Queries/QueryLayer.cs index e30de0ef03..1ff8e34dcf 100644 --- a/src/JsonApiDotNetCore/Queries/QueryLayer.cs +++ b/src/JsonApiDotNetCore/Queries/QueryLayer.cs @@ -21,7 +21,7 @@ public sealed class QueryLayer public QueryLayer(ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); ResourceType = resourceType; } diff --git a/src/JsonApiDotNetCore/Queries/QueryLayerComposer.cs b/src/JsonApiDotNetCore/Queries/QueryLayerComposer.cs index 1804027de4..141800cdfd 100644 --- a/src/JsonApiDotNetCore/Queries/QueryLayerComposer.cs +++ b/src/JsonApiDotNetCore/Queries/QueryLayerComposer.cs @@ -26,13 +26,13 @@ public QueryLayerComposer(IEnumerable constraintProvid IJsonApiOptions options, IPaginationContext paginationContext, ITargetedFields targetedFields, IEvaluatedIncludeCache evaluatedIncludeCache, ISparseFieldSetCache sparseFieldSetCache) { - ArgumentGuard.NotNull(constraintProviders); - ArgumentGuard.NotNull(resourceDefinitionAccessor); - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(paginationContext); - ArgumentGuard.NotNull(targetedFields); - ArgumentGuard.NotNull(evaluatedIncludeCache); - ArgumentGuard.NotNull(sparseFieldSetCache); + ArgumentNullException.ThrowIfNull(constraintProviders); + ArgumentNullException.ThrowIfNull(resourceDefinitionAccessor); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(paginationContext); + ArgumentNullException.ThrowIfNull(targetedFields); + ArgumentNullException.ThrowIfNull(evaluatedIncludeCache); + ArgumentNullException.ThrowIfNull(sparseFieldSetCache); _constraintProviders = constraintProviders as IQueryConstraintProvider[] ?? constraintProviders.ToArray(); _resourceDefinitionAccessor = resourceDefinitionAccessor; @@ -66,7 +66,7 @@ public QueryLayerComposer(IEnumerable constraintProvid /// public FilterExpression? GetSecondaryFilterFromConstraints([DisallowNull] TId primaryId, HasManyAttribute hasManyRelationship) { - ArgumentGuard.NotNull(hasManyRelationship); + ArgumentNullException.ThrowIfNull(hasManyRelationship); if (hasManyRelationship.InverseNavigationProperty == null) { @@ -133,13 +133,9 @@ private static HasExpression GetInverseHasManyRelationshipFilter([DisallowN /// public QueryLayer ComposeFromConstraints(ResourceType requestResourceType) { - ArgumentGuard.NotNull(requestResourceType); + ArgumentNullException.ThrowIfNull(requestResourceType); -#if NET6_0 - ImmutableArray constraints = _constraintProviders.SelectMany(provider => provider.GetConstraints()).ToImmutableArray(); -#else ImmutableArray constraints = [.. _constraintProviders.SelectMany(provider => provider.GetConstraints())]; -#endif QueryLayer topLayer = ComposeTopLayer(constraints, requestResourceType); topLayer.Include = ComposeChildren(topLayer, constraints); @@ -273,7 +269,7 @@ private static ImmutableHashSet ApplyIncludeElementUpd /// public QueryLayer ComposeForGetById([DisallowNull] TId id, ResourceType primaryResourceType, TopFieldSelection fieldSelection) { - ArgumentGuard.NotNull(primaryResourceType); + ArgumentNullException.ThrowIfNull(primaryResourceType); AttrAttribute idAttribute = GetIdAttribute(primaryResourceType); @@ -301,7 +297,7 @@ public QueryLayer ComposeForGetById([DisallowNull] TId id, ResourceType pri /// public QueryLayer ComposeSecondaryLayerForRelationship(ResourceType secondaryResourceType) { - ArgumentGuard.NotNull(secondaryResourceType); + ArgumentNullException.ThrowIfNull(secondaryResourceType); QueryLayer secondaryLayer = ComposeFromConstraints(secondaryResourceType); secondaryLayer.Selection = GetSelectionForRelationship(secondaryResourceType); @@ -325,9 +321,9 @@ private FieldSelection GetSelectionForRelationship(ResourceType secondaryResourc public QueryLayer WrapLayerForSecondaryEndpoint(QueryLayer secondaryLayer, ResourceType primaryResourceType, [DisallowNull] TId primaryId, RelationshipAttribute relationship) { - ArgumentGuard.NotNull(secondaryLayer); - ArgumentGuard.NotNull(primaryResourceType); - ArgumentGuard.NotNull(relationship); + ArgumentNullException.ThrowIfNull(secondaryLayer); + ArgumentNullException.ThrowIfNull(primaryResourceType); + ArgumentNullException.ThrowIfNull(relationship); IncludeExpression? innerInclude = secondaryLayer.Include; secondaryLayer.Include = null; @@ -387,7 +383,7 @@ private IncludeExpression RewriteIncludeForSecondaryEndpoint(IncludeExpression? /// public QueryLayer ComposeForUpdate([DisallowNull] TId id, ResourceType primaryResourceType) { - ArgumentGuard.NotNull(primaryResourceType); + ArgumentNullException.ThrowIfNull(primaryResourceType); ImmutableHashSet includeElements = _targetedFields.Relationships .Select(relationship => new IncludeElementExpression(relationship)).ToImmutableHashSet(); @@ -407,7 +403,7 @@ public QueryLayer ComposeForUpdate([DisallowNull] TId id, ResourceType prim /// public IEnumerable<(QueryLayer, RelationshipAttribute)> ComposeForGetTargetedSecondaryResourceIds(IIdentifiable primaryResource) { - ArgumentGuard.NotNull(primaryResource); + ArgumentNullException.ThrowIfNull(primaryResource); foreach (RelationshipAttribute relationship in _targetedFields.Relationships) { @@ -425,8 +421,8 @@ public QueryLayer ComposeForUpdate([DisallowNull] TId id, ResourceType prim /// public QueryLayer ComposeForGetRelationshipRightIds(RelationshipAttribute relationship, ICollection rightResourceIds) { - ArgumentGuard.NotNull(relationship); - ArgumentGuard.NotNull(rightResourceIds); + ArgumentNullException.ThrowIfNull(relationship); + ArgumentNullException.ThrowIfNull(rightResourceIds); AttrAttribute rightIdAttribute = GetIdAttribute(relationship.RightType); @@ -450,8 +446,8 @@ public QueryLayer ComposeForGetRelationshipRightIds(RelationshipAttribute relati /// public QueryLayer ComposeForHasMany(HasManyAttribute hasManyRelationship, [DisallowNull] TId leftId, ICollection rightResourceIds) { - ArgumentGuard.NotNull(hasManyRelationship); - ArgumentGuard.NotNull(rightResourceIds); + ArgumentNullException.ThrowIfNull(hasManyRelationship); + ArgumentNullException.ThrowIfNull(rightResourceIds); AttrAttribute leftIdAttribute = GetIdAttribute(hasManyRelationship.LeftType); AttrAttribute rightIdAttribute = GetIdAttribute(hasManyRelationship.RightType); @@ -486,16 +482,16 @@ public QueryLayer ComposeForHasMany(HasManyAttribute hasManyRelationship, [ protected virtual IImmutableSet GetIncludeElements(IImmutableSet includeElements, ResourceType resourceType) { - ArgumentGuard.NotNull(includeElements); - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(includeElements); + ArgumentNullException.ThrowIfNull(resourceType); return _resourceDefinitionAccessor.OnApplyIncludes(resourceType, includeElements); } protected virtual FilterExpression? GetFilter(IReadOnlyCollection expressionsInScope, ResourceType resourceType) { - ArgumentGuard.NotNull(expressionsInScope); - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(expressionsInScope); + ArgumentNullException.ThrowIfNull(resourceType); FilterExpression[] filters = expressionsInScope.OfType().ToArray(); FilterExpression? filter = LogicalExpression.Compose(LogicalOperator.And, filters); @@ -505,8 +501,8 @@ protected virtual IImmutableSet GetIncludeElements(IIm protected virtual SortExpression GetSort(IReadOnlyCollection expressionsInScope, ResourceType resourceType) { - ArgumentGuard.NotNull(expressionsInScope); - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(expressionsInScope); + ArgumentNullException.ThrowIfNull(resourceType); SortExpression? sort = expressionsInScope.OfType().FirstOrDefault(); @@ -524,8 +520,8 @@ protected virtual SortExpression GetSort(IReadOnlyCollection ex protected virtual PaginationExpression GetPagination(IReadOnlyCollection expressionsInScope, ResourceType resourceType) { - ArgumentGuard.NotNull(expressionsInScope); - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(expressionsInScope); + ArgumentNullException.ThrowIfNull(resourceType); PaginationExpression? pagination = expressionsInScope.OfType().FirstOrDefault(); @@ -540,7 +536,7 @@ protected virtual PaginationExpression GetPagination(IReadOnlyCollection public LambdaScope CreateScope(Type elementType, Expression? accessorExpression = null) { - ArgumentGuard.NotNull(elementType); + ArgumentNullException.ThrowIfNull(elementType); string parameterName = elementType.Name.Camelize(); parameterName = EnsureUniqueName(parameterName); @@ -48,7 +48,7 @@ private string EnsureUniqueName(string name) internal void Release(LambdaScope lambdaScope) { - ArgumentGuard.NotNull(lambdaScope); + ArgumentNullException.ThrowIfNull(lambdaScope); _namesInScope.Remove(lambdaScope.Parameter.Name!); } diff --git a/src/JsonApiDotNetCore/Queries/QueryableBuilding/OrderClauseBuilder.cs b/src/JsonApiDotNetCore/Queries/QueryableBuilding/OrderClauseBuilder.cs index ab37d2aff1..6528d63ff8 100644 --- a/src/JsonApiDotNetCore/Queries/QueryableBuilding/OrderClauseBuilder.cs +++ b/src/JsonApiDotNetCore/Queries/QueryableBuilding/OrderClauseBuilder.cs @@ -10,7 +10,7 @@ public class OrderClauseBuilder : QueryClauseBuilder, IOrderClauseBuilder { public virtual Expression ApplyOrderBy(SortExpression expression, QueryClauseBuilderContext context) { - ArgumentGuard.NotNull(expression); + ArgumentNullException.ThrowIfNull(expression); return Visit(expression, context); } diff --git a/src/JsonApiDotNetCore/Queries/QueryableBuilding/QueryClauseBuilderContext.cs b/src/JsonApiDotNetCore/Queries/QueryableBuilding/QueryClauseBuilderContext.cs index b218b09ca6..6344b91cb8 100644 --- a/src/JsonApiDotNetCore/Queries/QueryableBuilding/QueryClauseBuilderContext.cs +++ b/src/JsonApiDotNetCore/Queries/QueryableBuilding/QueryClauseBuilderContext.cs @@ -54,13 +54,13 @@ public sealed class QueryClauseBuilderContext public QueryClauseBuilderContext(Expression source, ResourceType resourceType, Type extensionType, IReadOnlyModel entityModel, LambdaScopeFactory lambdaScopeFactory, LambdaScope lambdaScope, IQueryableBuilder queryableBuilder, object? state) { - ArgumentGuard.NotNull(source); - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNull(extensionType); - ArgumentGuard.NotNull(entityModel); - ArgumentGuard.NotNull(lambdaScopeFactory); - ArgumentGuard.NotNull(lambdaScope); - ArgumentGuard.NotNull(queryableBuilder); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentNullException.ThrowIfNull(extensionType); + ArgumentNullException.ThrowIfNull(entityModel); + ArgumentNullException.ThrowIfNull(lambdaScopeFactory); + ArgumentNullException.ThrowIfNull(lambdaScope); + ArgumentNullException.ThrowIfNull(queryableBuilder); AssertSameType(source.Type, resourceType); Source = source; @@ -86,14 +86,14 @@ private static void AssertSameType(Type sourceType, ResourceType resourceType) public QueryClauseBuilderContext WithSource(Expression source) { - ArgumentGuard.NotNull(source); + ArgumentNullException.ThrowIfNull(source); return new QueryClauseBuilderContext(source, ResourceType, ExtensionType, EntityModel, LambdaScopeFactory, LambdaScope, QueryableBuilder, State); } public QueryClauseBuilderContext WithLambdaScope(LambdaScope lambdaScope) { - ArgumentGuard.NotNull(lambdaScope); + ArgumentNullException.ThrowIfNull(lambdaScope); return new QueryClauseBuilderContext(Source, ResourceType, ExtensionType, EntityModel, LambdaScopeFactory, lambdaScope, QueryableBuilder, State); } diff --git a/src/JsonApiDotNetCore/Queries/QueryableBuilding/QueryLayerIncludeConverter.cs b/src/JsonApiDotNetCore/Queries/QueryableBuilding/QueryLayerIncludeConverter.cs index 9c4351f0f7..5d4eec3e31 100644 --- a/src/JsonApiDotNetCore/Queries/QueryableBuilding/QueryLayerIncludeConverter.cs +++ b/src/JsonApiDotNetCore/Queries/QueryableBuilding/QueryLayerIncludeConverter.cs @@ -12,7 +12,7 @@ public sealed class QueryLayerIncludeConverter : QueryExpressionVisitor constraintProviders, IResourceDefinitionAccessor resourceDefinitionAccessor) { - ArgumentGuard.NotNull(constraintProviders); - ArgumentGuard.NotNull(resourceDefinitionAccessor); + ArgumentNullException.ThrowIfNull(constraintProviders); + ArgumentNullException.ThrowIfNull(resourceDefinitionAccessor); _resourceDefinitionAccessor = resourceDefinitionAccessor; _lazySourceTable = new Lazy>>(() => BuildSourceTable(constraintProviders)); @@ -71,7 +71,7 @@ private static void AddSparseFieldsToSet(IImmutableSet s /// public IImmutableSet GetSparseFieldSetForQuery(ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); if (!_visitedTable.TryGetValue(resourceType, out IImmutableSet? outputFields)) { @@ -92,7 +92,7 @@ public IImmutableSet GetSparseFieldSetForQuery(ResourceT /// public IImmutableSet GetIdAttributeSetForRelationshipQuery(ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); AttrAttribute idAttribute = resourceType.GetAttributeByPropertyName(nameof(Identifiable.Id)); var inputExpression = new SparseFieldSetExpression(ImmutableHashSet.Create(idAttribute)); @@ -111,7 +111,7 @@ public IImmutableSet GetIdAttributeSetForRelationshipQuery(Resour /// public IImmutableSet GetSparseFieldSetForSerializer(ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); if (!_visitedTable.TryGetValue(resourceType, out IImmutableSet? outputFields)) { diff --git a/src/JsonApiDotNetCore/Queries/SystemExpressionBuilder.cs b/src/JsonApiDotNetCore/Queries/SystemExpressionBuilder.cs index f625ee9b4f..72a30a060a 100644 --- a/src/JsonApiDotNetCore/Queries/SystemExpressionBuilder.cs +++ b/src/JsonApiDotNetCore/Queries/SystemExpressionBuilder.cs @@ -20,7 +20,7 @@ internal static class SystemExpressionBuilder public static Expression CloseOver(object value) { - ArgumentGuard.NotNull(value); + ArgumentNullException.ThrowIfNull(value); MethodInfo closeOverClosedMethod = CloseOverOpenMethod.MakeGenericMethod(value.GetType()); return (Expression)closeOverClosedMethod.Invoke(null, [value])!; diff --git a/src/JsonApiDotNetCore/QueryStrings/FieldChains/FieldChainParser.cs b/src/JsonApiDotNetCore/QueryStrings/FieldChains/FieldChainParser.cs index 448b802cec..0bbea6b63f 100644 --- a/src/JsonApiDotNetCore/QueryStrings/FieldChains/FieldChainParser.cs +++ b/src/JsonApiDotNetCore/QueryStrings/FieldChains/FieldChainParser.cs @@ -7,7 +7,7 @@ internal sealed class FieldChainParser { public IEnumerable Parse(string source) { - ArgumentGuard.NotNull(source); + ArgumentNullException.ThrowIfNull(source); if (source.Length > 0) { diff --git a/src/JsonApiDotNetCore/QueryStrings/FieldChains/FieldChainPattern.cs b/src/JsonApiDotNetCore/QueryStrings/FieldChains/FieldChainPattern.cs index fb63c6a03d..e3c15ebdbe 100644 --- a/src/JsonApiDotNetCore/QueryStrings/FieldChains/FieldChainPattern.cs +++ b/src/JsonApiDotNetCore/QueryStrings/FieldChains/FieldChainPattern.cs @@ -144,8 +144,8 @@ public static FieldChainPattern Parse(string pattern) public PatternMatchResult Match(string fieldChain, ResourceType resourceType, FieldChainPatternMatchOptions options = FieldChainPatternMatchOptions.None, ILoggerFactory? loggerFactory = null) { - ArgumentGuard.NotNull(fieldChain); - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(fieldChain); + ArgumentNullException.ThrowIfNull(resourceType); ILogger logger = loggerFactory == null ? NullLogger.Instance : loggerFactory.CreateLogger(); var matcher = new PatternMatcher(this, options, logger); diff --git a/src/JsonApiDotNetCore/QueryStrings/FieldChains/MatchState.cs b/src/JsonApiDotNetCore/QueryStrings/FieldChains/MatchState.cs index fa05753ae8..678850e4c4 100644 --- a/src/JsonApiDotNetCore/QueryStrings/FieldChains/MatchState.cs +++ b/src/JsonApiDotNetCore/QueryStrings/FieldChains/MatchState.cs @@ -53,9 +53,9 @@ private MatchState(FieldChainPattern? pattern, ResourceType? resourceType, IImmu public static MatchState Create(FieldChainPattern pattern, string fieldChainText, ResourceType resourceType) { - ArgumentGuard.NotNull(pattern); - ArgumentGuard.NotNull(fieldChainText); - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(pattern); + ArgumentNullException.ThrowIfNull(fieldChainText); + ArgumentNullException.ThrowIfNull(resourceType); try { @@ -77,7 +77,7 @@ public static MatchState Create(FieldChainPattern pattern, string fieldChainText /// public MatchState SuccessMoveForwardOneField(ResourceFieldAttribute matchedValue) { - ArgumentGuard.NotNull(matchedValue); + ArgumentNullException.ThrowIfNull(matchedValue); AssertIsSuccess(this); IImmutableList fieldsMatched = FieldsMatched.Add(matchedValue); diff --git a/src/JsonApiDotNetCore/QueryStrings/FieldChains/MatchTraceScope.cs b/src/JsonApiDotNetCore/QueryStrings/FieldChains/MatchTraceScope.cs index a4cf569173..5f3dd5f713 100644 --- a/src/JsonApiDotNetCore/QueryStrings/FieldChains/MatchTraceScope.cs +++ b/src/JsonApiDotNetCore/QueryStrings/FieldChains/MatchTraceScope.cs @@ -23,8 +23,8 @@ private MatchTraceScope(FieldChainPattern? pattern, bool isEnabled, ILogger logg public static MatchTraceScope CreateRoot(MatchState startState, ILogger logger) { - ArgumentGuard.NotNull(startState); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(startState); + ArgumentNullException.ThrowIfNull(logger); bool isEnabled = logger.IsEnabled(LogLevel.Trace); var scope = new MatchTraceScope(startState.Pattern, isEnabled, logger, 0); @@ -40,7 +40,7 @@ public static MatchTraceScope CreateRoot(MatchState startState, ILogger logger) public MatchTraceScope CreateChild(MatchState startState) { - ArgumentGuard.NotNull(startState); + ArgumentNullException.ThrowIfNull(startState); int indentDepth = _indentDepth + 1; FieldChainPattern? patternSegment = startState.Pattern?.WithoutNext(); @@ -57,7 +57,7 @@ public MatchTraceScope CreateChild(MatchState startState) public void LogMatchResult(MatchState resultState) { - ArgumentGuard.NotNull(resultState); + ArgumentNullException.ThrowIfNull(resultState); if (_isEnabled) { @@ -85,7 +85,7 @@ public void LogMatchResult(MatchState resultState) public void LogBacktrackTo(MatchState backtrackState) { - ArgumentGuard.NotNull(backtrackState); + ArgumentNullException.ThrowIfNull(backtrackState); if (_isEnabled) { @@ -97,7 +97,7 @@ public void LogBacktrackTo(MatchState backtrackState) public void SetResult(MatchState endState) { - ArgumentGuard.NotNull(endState); + ArgumentNullException.ThrowIfNull(endState); _endState = endState; } diff --git a/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternDescriptionFormatter.cs b/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternDescriptionFormatter.cs index 841dbb2050..bdd29e3200 100644 --- a/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternDescriptionFormatter.cs +++ b/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternDescriptionFormatter.cs @@ -11,7 +11,7 @@ internal sealed class PatternDescriptionFormatter public PatternDescriptionFormatter(FieldChainPattern pattern) { - ArgumentGuard.NotNull(pattern); + ArgumentNullException.ThrowIfNull(pattern); _pattern = pattern; } diff --git a/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternMatchResult.cs b/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternMatchResult.cs index f32ff953f4..6b9a1d1075 100644 --- a/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternMatchResult.cs +++ b/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternMatchResult.cs @@ -49,14 +49,14 @@ private PatternMatchResult(bool isSuccess, IReadOnlyList internal static PatternMatchResult CreateForSuccess(IReadOnlyList fieldChain) { - ArgumentGuard.NotNull(fieldChain); + ArgumentNullException.ThrowIfNull(fieldChain); return new PatternMatchResult(true, fieldChain, string.Empty, -1, false); } internal static PatternMatchResult CreateForFailure(MatchError error) { - ArgumentGuard.NotNull(error); + ArgumentNullException.ThrowIfNull(error); return new PatternMatchResult(false, Array.Empty(), error.Message, error.Position, error.IsFieldChainError); } diff --git a/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternMatcher.cs b/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternMatcher.cs index d05f4e3d12..9a86542533 100644 --- a/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternMatcher.cs +++ b/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternMatcher.cs @@ -15,8 +15,8 @@ internal sealed class PatternMatcher public PatternMatcher(FieldChainPattern pattern, FieldChainPatternMatchOptions options, ILogger logger) { - ArgumentGuard.NotNull(pattern); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(pattern); + ArgumentNullException.ThrowIfNull(logger); _pattern = pattern; _logger = logger; @@ -25,8 +25,8 @@ public PatternMatcher(FieldChainPattern pattern, FieldChainPatternMatchOptions o public PatternMatchResult Match(string fieldChain, ResourceType resourceType) { - ArgumentGuard.NotNull(fieldChain); - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(fieldChain); + ArgumentNullException.ThrowIfNull(resourceType); var startState = MatchState.Create(_pattern, fieldChain, resourceType); diff --git a/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternParser.cs b/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternParser.cs index cc0fa0a69e..c6e05fdd4f 100644 --- a/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternParser.cs +++ b/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternParser.cs @@ -41,7 +41,7 @@ internal sealed class PatternParser public FieldChainPattern Parse(string source) { - ArgumentGuard.NotNull(source); + ArgumentNullException.ThrowIfNull(source); _source = source; EnqueueTokens(); diff --git a/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternTextFormatter.cs b/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternTextFormatter.cs index 6e12ad8481..2fec95b900 100644 --- a/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternTextFormatter.cs +++ b/src/JsonApiDotNetCore/QueryStrings/FieldChains/PatternTextFormatter.cs @@ -11,7 +11,7 @@ internal sealed class PatternTextFormatter public PatternTextFormatter(FieldChainPattern pattern) { - ArgumentGuard.NotNull(pattern); + ArgumentNullException.ThrowIfNull(pattern); _pattern = pattern; } diff --git a/src/JsonApiDotNetCore/QueryStrings/FilterQueryStringParameterReader.cs b/src/JsonApiDotNetCore/QueryStrings/FilterQueryStringParameterReader.cs index 052e4ac93e..6b85273ddb 100644 --- a/src/JsonApiDotNetCore/QueryStrings/FilterQueryStringParameterReader.cs +++ b/src/JsonApiDotNetCore/QueryStrings/FilterQueryStringParameterReader.cs @@ -30,9 +30,9 @@ public FilterQueryStringParameterReader(IQueryStringParameterScopeParser scopePa IResourceGraph resourceGraph, IJsonApiOptions options) : base(request, resourceGraph) { - ArgumentGuard.NotNull(scopeParser); - ArgumentGuard.NotNull(filterParser); - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(scopeParser); + ArgumentNullException.ThrowIfNull(filterParser); + ArgumentNullException.ThrowIfNull(options); _options = options; _scopeParser = scopeParser; @@ -42,7 +42,7 @@ public FilterQueryStringParameterReader(IQueryStringParameterScopeParser scopePa /// public virtual bool IsEnabled(DisableQueryStringAttribute disableQueryStringAttribute) { - ArgumentGuard.NotNull(disableQueryStringAttribute); + ArgumentNullException.ThrowIfNull(disableQueryStringAttribute); return !IsAtomicOperationsRequest && !disableQueryStringAttribute.ContainsParameter(JsonApiQueryStringParameters.Filter); } @@ -50,7 +50,7 @@ public virtual bool IsEnabled(DisableQueryStringAttribute disableQueryStringAttr /// public virtual bool CanRead(string parameterName) { - ArgumentGuard.NotNullNorEmpty(parameterName); + ArgumentException.ThrowIfNullOrEmpty(parameterName); bool isNested = parameterName.StartsWith("filter[", StringComparison.Ordinal) && parameterName.EndsWith(']'); return parameterName == "filter" || isNested; diff --git a/src/JsonApiDotNetCore/QueryStrings/IncludeQueryStringParameterReader.cs b/src/JsonApiDotNetCore/QueryStrings/IncludeQueryStringParameterReader.cs index 7b3739da8e..55ef25779f 100644 --- a/src/JsonApiDotNetCore/QueryStrings/IncludeQueryStringParameterReader.cs +++ b/src/JsonApiDotNetCore/QueryStrings/IncludeQueryStringParameterReader.cs @@ -23,7 +23,7 @@ public class IncludeQueryStringParameterReader : QueryStringParameterReader, IIn public IncludeQueryStringParameterReader(IIncludeParser includeParser, IJsonApiRequest request, IResourceGraph resourceGraph) : base(request, resourceGraph) { - ArgumentGuard.NotNull(includeParser); + ArgumentNullException.ThrowIfNull(includeParser); _includeParser = includeParser; } @@ -31,7 +31,7 @@ public IncludeQueryStringParameterReader(IIncludeParser includeParser, IJsonApiR /// public virtual bool IsEnabled(DisableQueryStringAttribute disableQueryStringAttribute) { - ArgumentGuard.NotNull(disableQueryStringAttribute); + ArgumentNullException.ThrowIfNull(disableQueryStringAttribute); return !IsAtomicOperationsRequest && !disableQueryStringAttribute.ContainsParameter(JsonApiQueryStringParameters.Include); } @@ -39,7 +39,7 @@ public virtual bool IsEnabled(DisableQueryStringAttribute disableQueryStringAttr /// public virtual bool CanRead(string parameterName) { - ArgumentGuard.NotNullNorEmpty(parameterName); + ArgumentException.ThrowIfNullOrEmpty(parameterName); return parameterName == "include"; } diff --git a/src/JsonApiDotNetCore/QueryStrings/LegacyFilterNotationConverter.cs b/src/JsonApiDotNetCore/QueryStrings/LegacyFilterNotationConverter.cs index 0480158133..eff147e3d4 100644 --- a/src/JsonApiDotNetCore/QueryStrings/LegacyFilterNotationConverter.cs +++ b/src/JsonApiDotNetCore/QueryStrings/LegacyFilterNotationConverter.cs @@ -22,7 +22,7 @@ public sealed class LegacyFilterNotationConverter public IEnumerable ExtractConditions(string parameterValue) { - ArgumentGuard.NotNullNorEmpty(parameterValue); + ArgumentException.ThrowIfNullOrEmpty(parameterValue); if (parameterValue.StartsWith(ParameterValuePrefix.Expression, StringComparison.Ordinal) || parameterValue.StartsWith(ParameterValuePrefix.In, StringComparison.Ordinal) || @@ -41,8 +41,8 @@ public IEnumerable ExtractConditions(string parameterValue) public (string parameterName, string parameterValue) Convert(string parameterName, string parameterValue) { - ArgumentGuard.NotNullNorEmpty(parameterName); - ArgumentGuard.NotNullNorEmpty(parameterValue); + ArgumentException.ThrowIfNullOrEmpty(parameterName); + ArgumentException.ThrowIfNullOrEmpty(parameterValue); if (parameterValue.StartsWith(ParameterValuePrefix.Expression, StringComparison.Ordinal)) { diff --git a/src/JsonApiDotNetCore/QueryStrings/PaginationQueryStringParameterReader.cs b/src/JsonApiDotNetCore/QueryStrings/PaginationQueryStringParameterReader.cs index 6484253574..353204eee2 100644 --- a/src/JsonApiDotNetCore/QueryStrings/PaginationQueryStringParameterReader.cs +++ b/src/JsonApiDotNetCore/QueryStrings/PaginationQueryStringParameterReader.cs @@ -31,8 +31,8 @@ public PaginationQueryStringParameterReader(IPaginationParser paginationParser, IJsonApiOptions options) : base(request, resourceGraph) { - ArgumentGuard.NotNull(paginationParser); - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(paginationParser); + ArgumentNullException.ThrowIfNull(options); _options = options; _paginationParser = paginationParser; @@ -41,7 +41,7 @@ public PaginationQueryStringParameterReader(IPaginationParser paginationParser, /// public virtual bool IsEnabled(DisableQueryStringAttribute disableQueryStringAttribute) { - ArgumentGuard.NotNull(disableQueryStringAttribute); + ArgumentNullException.ThrowIfNull(disableQueryStringAttribute); return !IsAtomicOperationsRequest && !disableQueryStringAttribute.ContainsParameter(JsonApiQueryStringParameters.Page); } @@ -49,7 +49,7 @@ public virtual bool IsEnabled(DisableQueryStringAttribute disableQueryStringAttr /// public virtual bool CanRead(string parameterName) { - ArgumentGuard.NotNullNorEmpty(parameterName); + ArgumentException.ThrowIfNullOrEmpty(parameterName); return parameterName is PageSizeParameterName or PageNumberParameterName; } @@ -95,7 +95,7 @@ private PaginationQueryStringValueExpression GetPageConstraint(string parameterV protected virtual void ValidatePageSize(PaginationQueryStringValueExpression constraint) { - ArgumentGuard.NotNull(constraint); + ArgumentNullException.ThrowIfNull(constraint); foreach (PaginationElementQueryStringValueExpression element in constraint.Elements) { @@ -121,7 +121,7 @@ protected virtual void ValidatePageSize(PaginationQueryStringValueExpression con protected virtual void ValidatePageNumber(PaginationQueryStringValueExpression constraint) { - ArgumentGuard.NotNull(constraint); + ArgumentNullException.ThrowIfNull(constraint); foreach (PaginationElementQueryStringValueExpression element in constraint.Elements) { diff --git a/src/JsonApiDotNetCore/QueryStrings/QueryStringParameterReader.cs b/src/JsonApiDotNetCore/QueryStrings/QueryStringParameterReader.cs index d3f5277881..1b59eed083 100644 --- a/src/JsonApiDotNetCore/QueryStrings/QueryStringParameterReader.cs +++ b/src/JsonApiDotNetCore/QueryStrings/QueryStringParameterReader.cs @@ -16,8 +16,8 @@ public abstract class QueryStringParameterReader protected QueryStringParameterReader(IJsonApiRequest request, IResourceGraph resourceGraph) { - ArgumentGuard.NotNull(request); - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(resourceGraph); _resourceGraph = resourceGraph; _isCollectionRequest = request.IsCollection; diff --git a/src/JsonApiDotNetCore/QueryStrings/QueryStringReader.cs b/src/JsonApiDotNetCore/QueryStrings/QueryStringReader.cs index fd19e78236..89337708e7 100644 --- a/src/JsonApiDotNetCore/QueryStrings/QueryStringReader.cs +++ b/src/JsonApiDotNetCore/QueryStrings/QueryStringReader.cs @@ -18,10 +18,10 @@ public sealed partial class QueryStringReader : IQueryStringReader public QueryStringReader(IJsonApiOptions options, IRequestQueryStringAccessor queryStringAccessor, IEnumerable parameterReaders, ILoggerFactory loggerFactory) { - ArgumentGuard.NotNull(loggerFactory); - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(queryStringAccessor); - ArgumentGuard.NotNull(parameterReaders); + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(queryStringAccessor); + ArgumentNullException.ThrowIfNull(parameterReaders); _options = options; _queryStringAccessor = queryStringAccessor; diff --git a/src/JsonApiDotNetCore/QueryStrings/RequestQueryStringAccessor.cs b/src/JsonApiDotNetCore/QueryStrings/RequestQueryStringAccessor.cs index 00c0bfb69f..92b9a0a60a 100644 --- a/src/JsonApiDotNetCore/QueryStrings/RequestQueryStringAccessor.cs +++ b/src/JsonApiDotNetCore/QueryStrings/RequestQueryStringAccessor.cs @@ -22,7 +22,7 @@ public IQueryCollection Query public RequestQueryStringAccessor(IHttpContextAccessor httpContextAccessor) { - ArgumentGuard.NotNull(httpContextAccessor); + ArgumentNullException.ThrowIfNull(httpContextAccessor); _httpContextAccessor = httpContextAccessor; } diff --git a/src/JsonApiDotNetCore/QueryStrings/ResourceDefinitionQueryableParameterReader.cs b/src/JsonApiDotNetCore/QueryStrings/ResourceDefinitionQueryableParameterReader.cs index 54ed090d78..fb52e5775d 100644 --- a/src/JsonApiDotNetCore/QueryStrings/ResourceDefinitionQueryableParameterReader.cs +++ b/src/JsonApiDotNetCore/QueryStrings/ResourceDefinitionQueryableParameterReader.cs @@ -21,8 +21,8 @@ public class ResourceDefinitionQueryableParameterReader : IResourceDefinitionQue public ResourceDefinitionQueryableParameterReader(IJsonApiRequest request, IResourceDefinitionAccessor resourceDefinitionAccessor) { - ArgumentGuard.NotNull(request); - ArgumentGuard.NotNull(resourceDefinitionAccessor); + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(resourceDefinitionAccessor); _request = request; _resourceDefinitionAccessor = resourceDefinitionAccessor; @@ -37,7 +37,7 @@ public virtual bool IsEnabled(DisableQueryStringAttribute disableQueryStringAttr /// public virtual bool CanRead(string parameterName) { - ArgumentGuard.NotNullNorEmpty(parameterName); + ArgumentException.ThrowIfNullOrEmpty(parameterName); if (_request.Kind == EndpointKind.AtomicOperations) { diff --git a/src/JsonApiDotNetCore/QueryStrings/SortQueryStringParameterReader.cs b/src/JsonApiDotNetCore/QueryStrings/SortQueryStringParameterReader.cs index 98d11b2344..203ee70235 100644 --- a/src/JsonApiDotNetCore/QueryStrings/SortQueryStringParameterReader.cs +++ b/src/JsonApiDotNetCore/QueryStrings/SortQueryStringParameterReader.cs @@ -25,8 +25,8 @@ public SortQueryStringParameterReader(IQueryStringParameterScopeParser scopePars IResourceGraph resourceGraph) : base(request, resourceGraph) { - ArgumentGuard.NotNull(scopeParser); - ArgumentGuard.NotNull(sortParser); + ArgumentNullException.ThrowIfNull(scopeParser); + ArgumentNullException.ThrowIfNull(sortParser); _scopeParser = scopeParser; _sortParser = sortParser; @@ -35,7 +35,7 @@ public SortQueryStringParameterReader(IQueryStringParameterScopeParser scopePars /// public virtual bool IsEnabled(DisableQueryStringAttribute disableQueryStringAttribute) { - ArgumentGuard.NotNull(disableQueryStringAttribute); + ArgumentNullException.ThrowIfNull(disableQueryStringAttribute); return !IsAtomicOperationsRequest && !disableQueryStringAttribute.ContainsParameter(JsonApiQueryStringParameters.Sort); } @@ -43,7 +43,7 @@ public virtual bool IsEnabled(DisableQueryStringAttribute disableQueryStringAttr /// public virtual bool CanRead(string parameterName) { - ArgumentGuard.NotNullNorEmpty(parameterName); + ArgumentException.ThrowIfNullOrEmpty(parameterName); bool isNested = parameterName.StartsWith("sort[", StringComparison.Ordinal) && parameterName.EndsWith(']'); return parameterName == "sort" || isNested; diff --git a/src/JsonApiDotNetCore/QueryStrings/SparseFieldSetQueryStringParameterReader.cs b/src/JsonApiDotNetCore/QueryStrings/SparseFieldSetQueryStringParameterReader.cs index ad2d728fa8..308fe44588 100644 --- a/src/JsonApiDotNetCore/QueryStrings/SparseFieldSetQueryStringParameterReader.cs +++ b/src/JsonApiDotNetCore/QueryStrings/SparseFieldSetQueryStringParameterReader.cs @@ -30,8 +30,8 @@ public SparseFieldSetQueryStringParameterReader(ISparseFieldTypeParser scopePars IResourceGraph resourceGraph) : base(request, resourceGraph) { - ArgumentGuard.NotNull(scopeParser); - ArgumentGuard.NotNull(sparseFieldSetParser); + ArgumentNullException.ThrowIfNull(scopeParser); + ArgumentNullException.ThrowIfNull(sparseFieldSetParser); _scopeParser = scopeParser; _sparseFieldSetParser = sparseFieldSetParser; @@ -40,7 +40,7 @@ public SparseFieldSetQueryStringParameterReader(ISparseFieldTypeParser scopePars /// public virtual bool IsEnabled(DisableQueryStringAttribute disableQueryStringAttribute) { - ArgumentGuard.NotNull(disableQueryStringAttribute); + ArgumentNullException.ThrowIfNull(disableQueryStringAttribute); return !IsAtomicOperationsRequest && !disableQueryStringAttribute.ContainsParameter(JsonApiQueryStringParameters.Fields); } @@ -48,7 +48,7 @@ public virtual bool IsEnabled(DisableQueryStringAttribute disableQueryStringAttr /// public virtual bool CanRead(string parameterName) { - ArgumentGuard.NotNullNorEmpty(parameterName); + ArgumentException.ThrowIfNullOrEmpty(parameterName); return parameterName.StartsWith("fields[", StringComparison.Ordinal) && parameterName.EndsWith(']'); } diff --git a/src/JsonApiDotNetCore/Repositories/DbContextExtensions.cs b/src/JsonApiDotNetCore/Repositories/DbContextExtensions.cs index f78841defc..0e7089acec 100644 --- a/src/JsonApiDotNetCore/Repositories/DbContextExtensions.cs +++ b/src/JsonApiDotNetCore/Repositories/DbContextExtensions.cs @@ -13,8 +13,8 @@ public static class DbContextExtensions /// public static IIdentifiable GetTrackedOrAttach(this DbContext dbContext, IIdentifiable resource) { - ArgumentGuard.NotNull(dbContext); - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(dbContext); + ArgumentNullException.ThrowIfNull(resource); var trackedIdentifiable = (IIdentifiable?)dbContext.GetTrackedIdentifiable(resource); @@ -32,8 +32,8 @@ public static IIdentifiable GetTrackedOrAttach(this DbContext dbContext, IIdenti /// public static object? GetTrackedIdentifiable(this DbContext dbContext, IIdentifiable identifiable) { - ArgumentGuard.NotNull(dbContext); - ArgumentGuard.NotNull(identifiable); + ArgumentNullException.ThrowIfNull(dbContext); + ArgumentNullException.ThrowIfNull(identifiable); Type resourceClrType = identifiable.GetClrType(); string? stringId = identifiable.StringId; @@ -53,7 +53,7 @@ private static bool IsResource(EntityEntry entry, Type resourceClrType, string? /// public static void ResetChangeTracker(this DbContext dbContext) { - ArgumentGuard.NotNull(dbContext); + ArgumentNullException.ThrowIfNull(dbContext); dbContext.ChangeTracker.Clear(); } diff --git a/src/JsonApiDotNetCore/Repositories/DbContextResolver.cs b/src/JsonApiDotNetCore/Repositories/DbContextResolver.cs index bc275a96c1..c48169df72 100644 --- a/src/JsonApiDotNetCore/Repositories/DbContextResolver.cs +++ b/src/JsonApiDotNetCore/Repositories/DbContextResolver.cs @@ -15,7 +15,7 @@ public sealed class DbContextResolver : IDbContextResolver public DbContextResolver(TDbContext dbContext) { - ArgumentGuard.NotNull(dbContext); + ArgumentNullException.ThrowIfNull(dbContext); _dbContext = dbContext; } diff --git a/src/JsonApiDotNetCore/Repositories/EntityFrameworkCoreRepository.cs b/src/JsonApiDotNetCore/Repositories/EntityFrameworkCoreRepository.cs index 0dc43487da..214987828a 100644 --- a/src/JsonApiDotNetCore/Repositories/EntityFrameworkCoreRepository.cs +++ b/src/JsonApiDotNetCore/Repositories/EntityFrameworkCoreRepository.cs @@ -46,13 +46,13 @@ public EntityFrameworkCoreRepository(ITargetedFields targetedFields, IDbContextR IResourceFactory resourceFactory, IEnumerable constraintProviders, ILoggerFactory loggerFactory, IResourceDefinitionAccessor resourceDefinitionAccessor) { - ArgumentGuard.NotNull(targetedFields); - ArgumentGuard.NotNull(dbContextResolver); - ArgumentGuard.NotNull(resourceGraph); - ArgumentGuard.NotNull(resourceFactory); - ArgumentGuard.NotNull(constraintProviders); - ArgumentGuard.NotNull(loggerFactory); - ArgumentGuard.NotNull(resourceDefinitionAccessor); + ArgumentNullException.ThrowIfNull(targetedFields); + ArgumentNullException.ThrowIfNull(dbContextResolver); + ArgumentNullException.ThrowIfNull(resourceGraph); + ArgumentNullException.ThrowIfNull(resourceFactory); + ArgumentNullException.ThrowIfNull(constraintProviders); + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(resourceDefinitionAccessor); _targetedFields = targetedFields; _dbContext = dbContextResolver.GetContext(); @@ -71,7 +71,7 @@ public virtual async Task> GetAsync(QueryLayer qu queryLayer }); - ArgumentGuard.NotNull(queryLayer); + ArgumentNullException.ThrowIfNull(queryLayer); using (CodeTimingSessionManager.Current.Measure("Repository - Get resource(s)")) { @@ -113,14 +113,14 @@ public virtual async Task CountAsync(FilterExpression? filter, Cancellation protected virtual IQueryable ApplyQueryLayer(QueryLayer queryLayer) { - ArgumentGuard.NotNull(queryLayer); + ArgumentNullException.ThrowIfNull(queryLayer); _traceWriter.LogMethodStart(new { queryLayer }); - ArgumentGuard.NotNull(queryLayer); + ArgumentNullException.ThrowIfNull(queryLayer); using (CodeTimingSessionManager.Current.Measure("Convert QueryLayer to System.Expression")) { @@ -189,7 +189,7 @@ public virtual Task GetForCreateAsync(Type resourceClrType, [Disallow id }); - ArgumentGuard.NotNull(resourceClrType); + ArgumentNullException.ThrowIfNull(resourceClrType); var resource = (TResource)_resourceFactory.CreateInstance(resourceClrType); resource.Id = id; @@ -206,8 +206,8 @@ public virtual async Task CreateAsync(TResource resourceFromRequest, TResource r resourceForDatabase }); - ArgumentGuard.NotNull(resourceFromRequest); - ArgumentGuard.NotNull(resourceForDatabase); + ArgumentNullException.ThrowIfNull(resourceFromRequest); + ArgumentNullException.ThrowIfNull(resourceForDatabase); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Repository - Create resource"); @@ -268,7 +268,7 @@ await _resourceDefinitionAccessor.OnSetToManyRelationshipAsync(leftResource, has queryLayer }); - ArgumentGuard.NotNull(queryLayer); + ArgumentNullException.ThrowIfNull(queryLayer); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Repository - Get resource for update"); @@ -285,8 +285,8 @@ public virtual async Task UpdateAsync(TResource resourceFromRequest, TResource r resourceFromDatabase }); - ArgumentGuard.NotNull(resourceFromRequest); - ArgumentGuard.NotNull(resourceFromDatabase); + ArgumentNullException.ThrowIfNull(resourceFromRequest); + ArgumentNullException.ThrowIfNull(resourceFromDatabase); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Repository - Update resource"); @@ -318,7 +318,7 @@ public virtual async Task UpdateAsync(TResource resourceFromRequest, TResource r protected void AssertIsNotClearingRequiredToOneRelationship(RelationshipAttribute relationship, object? rightValue) { - ArgumentGuard.NotNull(relationship); + ArgumentNullException.ThrowIfNull(relationship); if (relationship is HasOneAttribute) { @@ -415,7 +415,7 @@ public virtual async Task SetRelationshipAsync(TResource leftResource, object? r rightValue }); - ArgumentGuard.NotNull(leftResource); + ArgumentNullException.ThrowIfNull(leftResource); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Repository - Set relationship"); @@ -446,7 +446,7 @@ public virtual async Task AddToToManyRelationshipAsync(TResource? leftResource, rightResourceIds }); - ArgumentGuard.NotNull(rightResourceIds); + ArgumentNullException.ThrowIfNull(rightResourceIds); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Repository - Add to to-many relationship"); @@ -510,8 +510,8 @@ public virtual async Task RemoveFromToManyRelationshipAsync(TResource leftResour rightResourceIds }); - ArgumentGuard.NotNull(leftResource); - ArgumentGuard.NotNull(rightResourceIds); + ArgumentNullException.ThrowIfNull(leftResource); + ArgumentNullException.ThrowIfNull(rightResourceIds); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Repository - Remove from to-many relationship"); @@ -600,8 +600,8 @@ private void MarkManyToManyRelationshipAsLoaded(EntityEntry leftEntry protected async Task UpdateRelationshipAsync(RelationshipAttribute relationship, TResource leftResource, object? valueToAssign, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(relationship); - ArgumentGuard.NotNull(leftResource); + ArgumentNullException.ThrowIfNull(relationship); + ArgumentNullException.ThrowIfNull(leftResource); object? trackedValueToAssign = EnsureRelationshipValueToAssignIsTracked(valueToAssign, relationship.Property.PropertyType); diff --git a/src/JsonApiDotNetCore/Repositories/ResourceRepositoryAccessor.cs b/src/JsonApiDotNetCore/Repositories/ResourceRepositoryAccessor.cs index 827c2259fd..4e3b5163a3 100644 --- a/src/JsonApiDotNetCore/Repositories/ResourceRepositoryAccessor.cs +++ b/src/JsonApiDotNetCore/Repositories/ResourceRepositoryAccessor.cs @@ -20,9 +20,9 @@ public class ResourceRepositoryAccessor : IResourceRepositoryAccessor public ResourceRepositoryAccessor(IServiceProvider serviceProvider, IResourceGraph resourceGraph, IJsonApiRequest request) { - ArgumentGuard.NotNull(serviceProvider); - ArgumentGuard.NotNull(resourceGraph); - ArgumentGuard.NotNull(request); + ArgumentNullException.ThrowIfNull(serviceProvider); + ArgumentNullException.ThrowIfNull(resourceGraph); + ArgumentNullException.ThrowIfNull(request); _serviceProvider = serviceProvider; _resourceGraph = resourceGraph; @@ -32,7 +32,7 @@ public ResourceRepositoryAccessor(IServiceProvider serviceProvider, IResourceGra /// public ResourceType LookupResourceType(Type resourceClrType) { - ArgumentGuard.NotNull(resourceClrType); + ArgumentNullException.ThrowIfNull(resourceClrType); return _resourceGraph.GetResourceType(resourceClrType); } @@ -41,7 +41,7 @@ public ResourceType LookupResourceType(Type resourceClrType) public async Task> GetAsync(QueryLayer queryLayer, CancellationToken cancellationToken) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(queryLayer); + ArgumentNullException.ThrowIfNull(queryLayer); dynamic repository = ResolveReadRepository(typeof(TResource)); return (IReadOnlyCollection)await repository.GetAsync(queryLayer, cancellationToken); @@ -50,8 +50,8 @@ public async Task> GetAsync(QueryLayer /// public async Task> GetAsync(ResourceType resourceType, QueryLayer queryLayer, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNull(queryLayer); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentNullException.ThrowIfNull(queryLayer); dynamic repository = ResolveReadRepository(resourceType); return (IReadOnlyCollection)await repository.GetAsync(queryLayer, cancellationToken); @@ -60,7 +60,7 @@ public async Task> GetAsync(ResourceType reso /// public async Task CountAsync(ResourceType resourceType, FilterExpression? filter, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); dynamic repository = ResolveReadRepository(resourceType); return (int)await repository.CountAsync(filter, cancellationToken); @@ -70,7 +70,7 @@ public async Task CountAsync(ResourceType resourceType, FilterExpression? f public async Task GetForCreateAsync(Type resourceClrType, [DisallowNull] TId id, CancellationToken cancellationToken) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(resourceClrType); + ArgumentNullException.ThrowIfNull(resourceClrType); dynamic repository = GetWriteRepository(typeof(TResource)); return await repository.GetForCreateAsync(resourceClrType, id, cancellationToken); @@ -80,8 +80,8 @@ public async Task GetForCreateAsync(Type resourceClrT public async Task CreateAsync(TResource resourceFromRequest, TResource resourceForDatabase, CancellationToken cancellationToken) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(resourceFromRequest); - ArgumentGuard.NotNull(resourceForDatabase); + ArgumentNullException.ThrowIfNull(resourceFromRequest); + ArgumentNullException.ThrowIfNull(resourceForDatabase); dynamic repository = GetWriteRepository(typeof(TResource)); await repository.CreateAsync(resourceFromRequest, resourceForDatabase, cancellationToken); @@ -91,7 +91,7 @@ public async Task CreateAsync(TResource resourceFromRequest, TResourc public async Task GetForUpdateAsync(QueryLayer queryLayer, CancellationToken cancellationToken) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(queryLayer); + ArgumentNullException.ThrowIfNull(queryLayer); dynamic repository = GetWriteRepository(typeof(TResource)); return await repository.GetForUpdateAsync(queryLayer, cancellationToken); @@ -101,8 +101,8 @@ public async Task CreateAsync(TResource resourceFromRequest, TResourc public async Task UpdateAsync(TResource resourceFromRequest, TResource resourceFromDatabase, CancellationToken cancellationToken) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(resourceFromRequest); - ArgumentGuard.NotNull(resourceFromDatabase); + ArgumentNullException.ThrowIfNull(resourceFromRequest); + ArgumentNullException.ThrowIfNull(resourceFromDatabase); dynamic repository = GetWriteRepository(typeof(TResource)); await repository.UpdateAsync(resourceFromRequest, resourceFromDatabase, cancellationToken); @@ -120,7 +120,7 @@ public async Task DeleteAsync(TResource? resourceFromDatabase, [ public async Task SetRelationshipAsync(TResource leftResource, object? rightValue, CancellationToken cancellationToken) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(leftResource); + ArgumentNullException.ThrowIfNull(leftResource); dynamic repository = GetWriteRepository(typeof(TResource)); await repository.SetRelationshipAsync(leftResource, rightValue, cancellationToken); @@ -131,7 +131,7 @@ public async Task AddToToManyRelationshipAsync(TResource? leftRe CancellationToken cancellationToken) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(rightResourceIds); + ArgumentNullException.ThrowIfNull(rightResourceIds); dynamic repository = GetWriteRepository(typeof(TResource)); await repository.AddToToManyRelationshipAsync(leftResource, leftId, rightResourceIds, cancellationToken); @@ -142,8 +142,8 @@ public async Task RemoveFromToManyRelationshipAsync(TResource leftRes CancellationToken cancellationToken) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(leftResource); - ArgumentGuard.NotNull(rightResourceIds); + ArgumentNullException.ThrowIfNull(leftResource); + ArgumentNullException.ThrowIfNull(rightResourceIds); dynamic repository = GetWriteRepository(typeof(TResource)); await repository.RemoveFromToManyRelationshipAsync(leftResource, rightResourceIds, cancellationToken); @@ -151,7 +151,7 @@ public async Task RemoveFromToManyRelationshipAsync(TResource leftRes protected object ResolveReadRepository(Type resourceClrType) { - ArgumentGuard.NotNull(resourceClrType); + ArgumentNullException.ThrowIfNull(resourceClrType); ResourceType resourceType = _resourceGraph.GetResourceType(resourceClrType); return ResolveReadRepository(resourceType); @@ -159,7 +159,7 @@ protected object ResolveReadRepository(Type resourceClrType) protected virtual object ResolveReadRepository(ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); Type repositoryType = typeof(IResourceReadRepository<,>).MakeGenericType(resourceType.ClrType, resourceType.IdentityClrType); return _serviceProvider.GetRequiredService(repositoryType); @@ -188,7 +188,7 @@ private object GetWriteRepository(Type resourceClrType) protected virtual object ResolveWriteRepository(Type resourceClrType) { - ArgumentGuard.NotNull(resourceClrType); + ArgumentNullException.ThrowIfNull(resourceClrType); ResourceType resourceType = _resourceGraph.GetResourceType(resourceClrType); diff --git a/src/JsonApiDotNetCore/Resources/AbstractResourceWrapper.cs b/src/JsonApiDotNetCore/Resources/AbstractResourceWrapper.cs index c3a193d3cd..3cf6233cf2 100644 --- a/src/JsonApiDotNetCore/Resources/AbstractResourceWrapper.cs +++ b/src/JsonApiDotNetCore/Resources/AbstractResourceWrapper.cs @@ -8,7 +8,7 @@ internal sealed class AbstractResourceWrapper : Identifiable, IAbstrac public AbstractResourceWrapper(Type abstractType) { - ArgumentGuard.NotNull(abstractType); + ArgumentNullException.ThrowIfNull(abstractType); AbstractType = abstractType; } diff --git a/src/JsonApiDotNetCore/Resources/IdentifiableExtensions.cs b/src/JsonApiDotNetCore/Resources/IdentifiableExtensions.cs index 91905e4df3..d4e3c156cb 100644 --- a/src/JsonApiDotNetCore/Resources/IdentifiableExtensions.cs +++ b/src/JsonApiDotNetCore/Resources/IdentifiableExtensions.cs @@ -8,7 +8,7 @@ internal static class IdentifiableExtensions public static object GetTypedId(this IIdentifiable identifiable) { - ArgumentGuard.NotNull(identifiable); + ArgumentNullException.ThrowIfNull(identifiable); PropertyInfo? property = identifiable.GetClrType().GetProperty(IdPropertyName); @@ -31,7 +31,7 @@ public static object GetTypedId(this IIdentifiable identifiable) public static Type GetClrType(this IIdentifiable identifiable) { - ArgumentGuard.NotNull(identifiable); + ArgumentNullException.ThrowIfNull(identifiable); return identifiable is IAbstractResourceWrapper abstractResource ? abstractResource.AbstractType : identifiable.GetType(); } diff --git a/src/JsonApiDotNetCore/Resources/JsonApiResourceDefinition.cs b/src/JsonApiDotNetCore/Resources/JsonApiResourceDefinition.cs index f069c155e8..e2a354ca76 100644 --- a/src/JsonApiDotNetCore/Resources/JsonApiResourceDefinition.cs +++ b/src/JsonApiDotNetCore/Resources/JsonApiResourceDefinition.cs @@ -26,7 +26,7 @@ public class JsonApiResourceDefinition : IResourceDefinition(); diff --git a/src/JsonApiDotNetCore/Resources/OperationContainer.cs b/src/JsonApiDotNetCore/Resources/OperationContainer.cs index 2c8ec00d17..dd2cfe2630 100644 --- a/src/JsonApiDotNetCore/Resources/OperationContainer.cs +++ b/src/JsonApiDotNetCore/Resources/OperationContainer.cs @@ -16,9 +16,9 @@ public sealed class OperationContainer public OperationContainer(IIdentifiable resource, ITargetedFields targetedFields, IJsonApiRequest request) { - ArgumentGuard.NotNull(resource); - ArgumentGuard.NotNull(targetedFields); - ArgumentGuard.NotNull(request); + ArgumentNullException.ThrowIfNull(resource); + ArgumentNullException.ThrowIfNull(targetedFields); + ArgumentNullException.ThrowIfNull(request); Resource = resource; TargetedFields = targetedFields; @@ -32,7 +32,7 @@ public void SetTransactionId(string transactionId) public OperationContainer WithResource(IIdentifiable resource) { - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); return new OperationContainer(resource, TargetedFields, Request); } diff --git a/src/JsonApiDotNetCore/Resources/ResourceChangeTracker.cs b/src/JsonApiDotNetCore/Resources/ResourceChangeTracker.cs index 795c33f16b..c17ce60b45 100644 --- a/src/JsonApiDotNetCore/Resources/ResourceChangeTracker.cs +++ b/src/JsonApiDotNetCore/Resources/ResourceChangeTracker.cs @@ -18,8 +18,8 @@ public sealed class ResourceChangeTracker : IResourceChangeTracker public void SetInitiallyStoredAttributeValues(TResource resource) { - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); _initiallyStoredAttributeValues = CreateAttributeDictionary(resource, _request.PrimaryResourceType!.Attributes); } @@ -36,7 +36,7 @@ public void SetInitiallyStoredAttributeValues(TResource resource) /// public void SetRequestAttributeValues(TResource resource) { - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); _requestAttributeValues = CreateAttributeDictionary(resource, _targetedFields.Attributes); } @@ -44,7 +44,7 @@ public void SetRequestAttributeValues(TResource resource) /// public void SetFinallyStoredAttributeValues(TResource resource) { - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); _finallyStoredAttributeValues = CreateAttributeDictionary(resource, _request.PrimaryResourceType!.Attributes); } diff --git a/src/JsonApiDotNetCore/Resources/ResourceDefinitionAccessor.cs b/src/JsonApiDotNetCore/Resources/ResourceDefinitionAccessor.cs index 28079b7e2a..a225766fb5 100644 --- a/src/JsonApiDotNetCore/Resources/ResourceDefinitionAccessor.cs +++ b/src/JsonApiDotNetCore/Resources/ResourceDefinitionAccessor.cs @@ -33,8 +33,8 @@ public bool IsReadOnlyRequest public ResourceDefinitionAccessor(IResourceGraph resourceGraph, IServiceProvider serviceProvider) { - ArgumentGuard.NotNull(resourceGraph); - ArgumentGuard.NotNull(serviceProvider); + ArgumentNullException.ThrowIfNull(resourceGraph); + ArgumentNullException.ThrowIfNull(serviceProvider); _resourceGraph = resourceGraph; _serviceProvider = serviceProvider; @@ -43,7 +43,7 @@ public ResourceDefinitionAccessor(IResourceGraph resourceGraph, IServiceProvider /// public IImmutableSet OnApplyIncludes(ResourceType resourceType, IImmutableSet existingIncludes) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); dynamic resourceDefinition = ResolveResourceDefinition(resourceType); return resourceDefinition.OnApplyIncludes(existingIncludes); @@ -52,7 +52,7 @@ public IImmutableSet OnApplyIncludes(ResourceType reso /// public FilterExpression? OnApplyFilter(ResourceType resourceType, FilterExpression? existingFilter) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); dynamic resourceDefinition = ResolveResourceDefinition(resourceType); return resourceDefinition.OnApplyFilter(existingFilter); @@ -61,7 +61,7 @@ public IImmutableSet OnApplyIncludes(ResourceType reso /// public SortExpression? OnApplySort(ResourceType resourceType, SortExpression? existingSort) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); dynamic resourceDefinition = ResolveResourceDefinition(resourceType); return resourceDefinition.OnApplySort(existingSort); @@ -70,7 +70,7 @@ public IImmutableSet OnApplyIncludes(ResourceType reso /// public PaginationExpression? OnApplyPagination(ResourceType resourceType, PaginationExpression? existingPagination) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); dynamic resourceDefinition = ResolveResourceDefinition(resourceType); return resourceDefinition.OnApplyPagination(existingPagination); @@ -79,7 +79,7 @@ public IImmutableSet OnApplyIncludes(ResourceType reso /// public SparseFieldSetExpression? OnApplySparseFieldSet(ResourceType resourceType, SparseFieldSetExpression? existingSparseFieldSet) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); dynamic resourceDefinition = ResolveResourceDefinition(resourceType); return resourceDefinition.OnApplySparseFieldSet(existingSparseFieldSet); @@ -88,8 +88,8 @@ public IImmutableSet OnApplyIncludes(ResourceType reso /// public object? GetQueryableHandlerForQueryStringParameter(Type resourceClrType, string parameterName) { - ArgumentGuard.NotNull(resourceClrType); - ArgumentGuard.NotNullNorEmpty(parameterName); + ArgumentNullException.ThrowIfNull(resourceClrType); + ArgumentException.ThrowIfNullOrEmpty(parameterName); dynamic resourceDefinition = ResolveResourceDefinition(resourceClrType); dynamic? handlers = resourceDefinition.OnRegisterQueryableHandlersForQueryStringParameters(); @@ -108,7 +108,7 @@ public IImmutableSet OnApplyIncludes(ResourceType reso /// public IDictionary? GetMeta(ResourceType resourceType, IIdentifiable resourceInstance) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); dynamic resourceDefinition = ResolveResourceDefinition(resourceType); return resourceDefinition.GetMeta((dynamic)resourceInstance); @@ -118,7 +118,7 @@ public IImmutableSet OnApplyIncludes(ResourceType reso public async Task OnPrepareWriteAsync(TResource resource, WriteOperationKind writeOperation, CancellationToken cancellationToken) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); dynamic resourceDefinition = ResolveResourceDefinition(resource.GetClrType()); await resourceDefinition.OnPrepareWriteAsync((dynamic)resource, writeOperation, cancellationToken); @@ -129,8 +129,8 @@ public async Task OnPrepareWriteAsync(TResource resource, WriteOperat IIdentifiable? rightResourceId, WriteOperationKind writeOperation, CancellationToken cancellationToken) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(leftResource); - ArgumentGuard.NotNull(hasOneRelationship); + ArgumentNullException.ThrowIfNull(leftResource); + ArgumentNullException.ThrowIfNull(hasOneRelationship); dynamic resourceDefinition = ResolveResourceDefinition(leftResource.GetClrType()); @@ -143,9 +143,9 @@ public async Task OnSetToManyRelationshipAsync(TResource leftResource ISet rightResourceIds, WriteOperationKind writeOperation, CancellationToken cancellationToken) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(leftResource); - ArgumentGuard.NotNull(hasManyRelationship); - ArgumentGuard.NotNull(rightResourceIds); + ArgumentNullException.ThrowIfNull(leftResource); + ArgumentNullException.ThrowIfNull(hasManyRelationship); + ArgumentNullException.ThrowIfNull(rightResourceIds); dynamic resourceDefinition = ResolveResourceDefinition(leftResource.GetClrType()); await resourceDefinition.OnSetToManyRelationshipAsync((dynamic)leftResource, hasManyRelationship, rightResourceIds, writeOperation, cancellationToken); @@ -156,8 +156,8 @@ public async Task OnAddToRelationshipAsync(TResource leftResource, Ha CancellationToken cancellationToken) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(hasManyRelationship); - ArgumentGuard.NotNull(rightResourceIds); + ArgumentNullException.ThrowIfNull(hasManyRelationship); + ArgumentNullException.ThrowIfNull(rightResourceIds); dynamic resourceDefinition = ResolveResourceDefinition(leftResource.GetClrType()); await resourceDefinition.OnAddToRelationshipAsync((dynamic)leftResource, hasManyRelationship, rightResourceIds, cancellationToken); @@ -168,9 +168,9 @@ public async Task OnRemoveFromRelationshipAsync(TResource leftResourc ISet rightResourceIds, CancellationToken cancellationToken) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(leftResource); - ArgumentGuard.NotNull(hasManyRelationship); - ArgumentGuard.NotNull(rightResourceIds); + ArgumentNullException.ThrowIfNull(leftResource); + ArgumentNullException.ThrowIfNull(hasManyRelationship); + ArgumentNullException.ThrowIfNull(rightResourceIds); dynamic resourceDefinition = ResolveResourceDefinition(leftResource.GetClrType()); await resourceDefinition.OnRemoveFromRelationshipAsync((dynamic)leftResource, hasManyRelationship, rightResourceIds, cancellationToken); @@ -180,7 +180,7 @@ public async Task OnRemoveFromRelationshipAsync(TResource leftResourc public async Task OnWritingAsync(TResource resource, WriteOperationKind writeOperation, CancellationToken cancellationToken) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); dynamic resourceDefinition = ResolveResourceDefinition(resource.GetClrType()); await resourceDefinition.OnWritingAsync((dynamic)resource, writeOperation, cancellationToken); @@ -190,7 +190,7 @@ public async Task OnWritingAsync(TResource resource, WriteOperationKi public async Task OnWriteSucceededAsync(TResource resource, WriteOperationKind writeOperation, CancellationToken cancellationToken) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); dynamic resourceDefinition = ResolveResourceDefinition(resource.GetClrType()); await resourceDefinition.OnWriteSucceededAsync((dynamic)resource, writeOperation, cancellationToken); @@ -199,7 +199,7 @@ public async Task OnWriteSucceededAsync(TResource resource, WriteOper /// public void OnDeserialize(IIdentifiable resource) { - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); dynamic resourceDefinition = ResolveResourceDefinition(resource.GetClrType()); resourceDefinition.OnDeserialize((dynamic)resource); @@ -208,7 +208,7 @@ public void OnDeserialize(IIdentifiable resource) /// public void OnSerialize(IIdentifiable resource) { - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); dynamic resourceDefinition = ResolveResourceDefinition(resource.GetClrType()); resourceDefinition.OnSerialize((dynamic)resource); @@ -216,7 +216,7 @@ public void OnSerialize(IIdentifiable resource) protected object ResolveResourceDefinition(Type resourceClrType) { - ArgumentGuard.NotNull(resourceClrType); + ArgumentNullException.ThrowIfNull(resourceClrType); ResourceType resourceType = _resourceGraph.GetResourceType(resourceClrType); return ResolveResourceDefinition(resourceType); @@ -224,7 +224,7 @@ protected object ResolveResourceDefinition(Type resourceClrType) protected virtual object ResolveResourceDefinition(ResourceType resourceType) { - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resourceType); Type resourceDefinitionType = typeof(IResourceDefinition<,>).MakeGenericType(resourceType.ClrType, resourceType.IdentityClrType); return _serviceProvider.GetRequiredService(resourceDefinitionType); diff --git a/src/JsonApiDotNetCore/Resources/ResourceFactory.cs b/src/JsonApiDotNetCore/Resources/ResourceFactory.cs index 9b02953c84..5a18763939 100644 --- a/src/JsonApiDotNetCore/Resources/ResourceFactory.cs +++ b/src/JsonApiDotNetCore/Resources/ResourceFactory.cs @@ -15,7 +15,7 @@ internal sealed class ResourceFactory : IResourceFactory public ResourceFactory(IServiceProvider serviceProvider) { - ArgumentGuard.NotNull(serviceProvider); + ArgumentNullException.ThrowIfNull(serviceProvider); _serviceProvider = serviceProvider; } @@ -23,7 +23,7 @@ public ResourceFactory(IServiceProvider serviceProvider) /// public IIdentifiable CreateInstance(Type resourceClrType) { - ArgumentGuard.NotNull(resourceClrType); + ArgumentNullException.ThrowIfNull(resourceClrType); if (!resourceClrType.IsAssignableTo(typeof(IIdentifiable))) { @@ -85,7 +85,7 @@ private static IIdentifiable InnerCreateInstance(Type type, IServiceProvider ser /// public NewExpression CreateNewExpression(Type resourceClrType) { - ArgumentGuard.NotNull(resourceClrType); + ArgumentNullException.ThrowIfNull(resourceClrType); if (HasSingleConstructorWithoutParameters(resourceClrType)) { diff --git a/src/JsonApiDotNetCore/Resources/SortExpressionLambdaConverter.cs b/src/JsonApiDotNetCore/Resources/SortExpressionLambdaConverter.cs index 92862d4d99..97e014f344 100644 --- a/src/JsonApiDotNetCore/Resources/SortExpressionLambdaConverter.cs +++ b/src/JsonApiDotNetCore/Resources/SortExpressionLambdaConverter.cs @@ -15,14 +15,14 @@ internal sealed class SortExpressionLambdaConverter public SortExpressionLambdaConverter(IResourceGraph resourceGraph) { - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(resourceGraph); _resourceGraph = resourceGraph; } public SortElementExpression FromLambda(Expression> keySelector, ListSortDirection sortDirection) { - ArgumentGuard.NotNull(keySelector); + ArgumentNullException.ThrowIfNull(keySelector); _fields.Clear(); diff --git a/src/JsonApiDotNetCore/Resources/TargetedFields.cs b/src/JsonApiDotNetCore/Resources/TargetedFields.cs index 3b44c4a261..420058106f 100644 --- a/src/JsonApiDotNetCore/Resources/TargetedFields.cs +++ b/src/JsonApiDotNetCore/Resources/TargetedFields.cs @@ -16,7 +16,7 @@ public sealed class TargetedFields : ITargetedFields /// public void CopyFrom(ITargetedFields other) { - ArgumentGuard.NotNull(other); + ArgumentNullException.ThrowIfNull(other); Clear(); diff --git a/src/JsonApiDotNetCore/Serialization/JsonConverters/JsonObjectConverter.cs b/src/JsonApiDotNetCore/Serialization/JsonConverters/JsonObjectConverter.cs index c470b991d6..054fc28e55 100644 --- a/src/JsonApiDotNetCore/Serialization/JsonConverters/JsonObjectConverter.cs +++ b/src/JsonApiDotNetCore/Serialization/JsonConverters/JsonObjectConverter.cs @@ -7,7 +7,7 @@ public abstract class JsonObjectConverter : JsonConverter { protected static TValue? ReadSubTree(ref Utf8JsonReader reader, JsonSerializerOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); if (typeof(TValue) != typeof(object) && options.GetConverter(typeof(TValue)) is JsonConverter converter) { @@ -19,7 +19,7 @@ public abstract class JsonObjectConverter : JsonConverter protected static void WriteSubTree(Utf8JsonWriter writer, TValue value, JsonSerializerOptions options) { - ArgumentGuard.NotNull(options); + ArgumentNullException.ThrowIfNull(options); if (typeof(TValue) != typeof(object) && options.GetConverter(typeof(TValue)) is JsonConverter converter) { diff --git a/src/JsonApiDotNetCore/Serialization/JsonConverters/ResourceObjectConverter.cs b/src/JsonApiDotNetCore/Serialization/JsonConverters/ResourceObjectConverter.cs index fcb950b39b..369adee7a3 100644 --- a/src/JsonApiDotNetCore/Serialization/JsonConverters/ResourceObjectConverter.cs +++ b/src/JsonApiDotNetCore/Serialization/JsonConverters/ResourceObjectConverter.cs @@ -27,7 +27,7 @@ public class ResourceObjectConverter : JsonObjectConverter public ResourceObjectConverter(IResourceGraph resourceGraph) { - ArgumentGuard.NotNull(resourceGraph); + ArgumentNullException.ThrowIfNull(resourceGraph); _resourceGraph = resourceGraph; } @@ -287,8 +287,8 @@ private protected virtual void ValidateExtensionInRelationships(string extension /// public override void Write(Utf8JsonWriter writer, ResourceObject value, JsonSerializerOptions options) { - ArgumentGuard.NotNull(writer); - ArgumentGuard.NotNull(value); + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(value); writer.WriteStartObject(); diff --git a/src/JsonApiDotNetCore/Serialization/JsonConverters/SingleOrManyDataConverterFactory.cs b/src/JsonApiDotNetCore/Serialization/JsonConverters/SingleOrManyDataConverterFactory.cs index 48d90f9c8f..81ae41a380 100644 --- a/src/JsonApiDotNetCore/Serialization/JsonConverters/SingleOrManyDataConverterFactory.cs +++ b/src/JsonApiDotNetCore/Serialization/JsonConverters/SingleOrManyDataConverterFactory.cs @@ -14,7 +14,7 @@ public sealed class SingleOrManyDataConverterFactory : JsonConverterFactory /// public override bool CanConvert(Type typeToConvert) { - ArgumentGuard.NotNull(typeToConvert); + ArgumentNullException.ThrowIfNull(typeToConvert); return typeToConvert.IsGenericType && typeToConvert.GetGenericTypeDefinition() == typeof(SingleOrManyData<>); } @@ -22,7 +22,7 @@ public override bool CanConvert(Type typeToConvert) /// public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { - ArgumentGuard.NotNull(typeToConvert); + ArgumentNullException.ThrowIfNull(typeToConvert); Type objectType = typeToConvert.GetGenericArguments()[0]; Type converterType = typeof(SingleOrManyDataConverter<>).MakeGenericType(objectType); diff --git a/src/JsonApiDotNetCore/Serialization/JsonConverters/WriteOnlyDocumentConverter.cs b/src/JsonApiDotNetCore/Serialization/JsonConverters/WriteOnlyDocumentConverter.cs index 2195ff2ec8..f459b49c9b 100644 --- a/src/JsonApiDotNetCore/Serialization/JsonConverters/WriteOnlyDocumentConverter.cs +++ b/src/JsonApiDotNetCore/Serialization/JsonConverters/WriteOnlyDocumentConverter.cs @@ -32,8 +32,8 @@ public override Document Read(ref Utf8JsonReader reader, Type typeToConvert, Jso /// public override void Write(Utf8JsonWriter writer, Document value, JsonSerializerOptions options) { - ArgumentGuard.NotNull(writer); - ArgumentGuard.NotNull(value); + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(value); writer.WriteStartObject(); diff --git a/src/JsonApiDotNetCore/Serialization/JsonConverters/WriteOnlyRelationshipObjectConverter.cs b/src/JsonApiDotNetCore/Serialization/JsonConverters/WriteOnlyRelationshipObjectConverter.cs index 30a26c055b..db6b7dc686 100644 --- a/src/JsonApiDotNetCore/Serialization/JsonConverters/WriteOnlyRelationshipObjectConverter.cs +++ b/src/JsonApiDotNetCore/Serialization/JsonConverters/WriteOnlyRelationshipObjectConverter.cs @@ -27,8 +27,8 @@ public override RelationshipObject Read(ref Utf8JsonReader reader, Type typeToCo /// public override void Write(Utf8JsonWriter writer, RelationshipObject value, JsonSerializerOptions options) { - ArgumentGuard.NotNull(writer); - ArgumentGuard.NotNull(value); + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(value); writer.WriteStartObject(); diff --git a/src/JsonApiDotNetCore/Serialization/Request/Adapters/AtomicOperationObjectAdapter.cs b/src/JsonApiDotNetCore/Serialization/Request/Adapters/AtomicOperationObjectAdapter.cs index a9205ce4fa..4339cf6c48 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/Adapters/AtomicOperationObjectAdapter.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/Adapters/AtomicOperationObjectAdapter.cs @@ -17,10 +17,10 @@ public sealed class AtomicOperationObjectAdapter : IAtomicOperationObjectAdapter public AtomicOperationObjectAdapter(IJsonApiOptions options, IAtomicReferenceAdapter atomicReferenceAdapter, IResourceDataInOperationsRequestAdapter resourceDataInOperationsRequestAdapter, IRelationshipDataAdapter relationshipDataAdapter) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(atomicReferenceAdapter); - ArgumentGuard.NotNull(resourceDataInOperationsRequestAdapter); - ArgumentGuard.NotNull(relationshipDataAdapter); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(atomicReferenceAdapter); + ArgumentNullException.ThrowIfNull(resourceDataInOperationsRequestAdapter); + ArgumentNullException.ThrowIfNull(relationshipDataAdapter); _options = options; _atomicReferenceAdapter = atomicReferenceAdapter; @@ -31,8 +31,8 @@ public AtomicOperationObjectAdapter(IJsonApiOptions options, IAtomicReferenceAda /// public OperationContainer Convert(AtomicOperationObject atomicOperationObject, RequestAdapterState state) { - ArgumentGuard.NotNull(atomicOperationObject); - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(atomicOperationObject); + ArgumentNullException.ThrowIfNull(state); AssertNoHref(atomicOperationObject, state); diff --git a/src/JsonApiDotNetCore/Serialization/Request/Adapters/AtomicReferenceAdapter.cs b/src/JsonApiDotNetCore/Serialization/Request/Adapters/AtomicReferenceAdapter.cs index 8e682439aa..0dc72a08fa 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/Adapters/AtomicReferenceAdapter.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/Adapters/AtomicReferenceAdapter.cs @@ -14,9 +14,9 @@ public sealed class AtomicReferenceAdapter(IResourceGraph resourceGraph, IResour /// public AtomicReferenceResult Convert(AtomicReference atomicReference, ResourceIdentityRequirements requirements, RequestAdapterState state) { - ArgumentGuard.NotNull(atomicReference); - ArgumentGuard.NotNull(requirements); - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(atomicReference); + ArgumentNullException.ThrowIfNull(requirements); + ArgumentNullException.ThrowIfNull(state); using IDisposable _ = state.Position.PushElement("ref"); (IIdentifiable resource, ResourceType resourceType) = ConvertResourceIdentity(atomicReference, requirements, state); diff --git a/src/JsonApiDotNetCore/Serialization/Request/Adapters/AtomicReferenceResult.cs b/src/JsonApiDotNetCore/Serialization/Request/Adapters/AtomicReferenceResult.cs index a15ecd8e0c..367d7ec2ea 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/Adapters/AtomicReferenceResult.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/Adapters/AtomicReferenceResult.cs @@ -17,8 +17,8 @@ public sealed class AtomicReferenceResult public AtomicReferenceResult(IIdentifiable resource, ResourceType resourceType, RelationshipAttribute? relationship) { - ArgumentGuard.NotNull(resource); - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resource); + ArgumentNullException.ThrowIfNull(resourceType); Resource = resource; ResourceType = resourceType; diff --git a/src/JsonApiDotNetCore/Serialization/Request/Adapters/BaseAdapter.cs b/src/JsonApiDotNetCore/Serialization/Request/Adapters/BaseAdapter.cs index f7bbcb2121..8969d28fd7 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/Adapters/BaseAdapter.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/Adapters/BaseAdapter.cs @@ -13,7 +13,7 @@ public abstract class BaseAdapter protected static void AssertHasData(SingleOrManyData data, RequestAdapterState state) where T : ResourceIdentifierObject, new() { - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(state); if (!data.IsAssigned) { @@ -25,7 +25,7 @@ protected static void AssertHasData(SingleOrManyData data, RequestAdapterS protected static void AssertDataHasSingleValue(SingleOrManyData data, bool allowNull, RequestAdapterState state) where T : ResourceIdentifierObject, new() { - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(state); if (data.SingleValue == null) { @@ -50,7 +50,7 @@ protected static void AssertDataHasSingleValue(SingleOrManyData data, bool protected static void AssertDataHasManyValue(SingleOrManyData data, RequestAdapterState state) where T : ResourceIdentifierObject, new() { - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(state); if (data.ManyValue == null) { @@ -62,7 +62,7 @@ protected static void AssertDataHasManyValue(SingleOrManyData data, Reques protected static void AssertObjectIsNotNull([SysNotNull] T? value, RequestAdapterState state) where T : class { - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(state); if (value is null) { diff --git a/src/JsonApiDotNetCore/Serialization/Request/Adapters/DocumentAdapter.cs b/src/JsonApiDotNetCore/Serialization/Request/Adapters/DocumentAdapter.cs index ec9842b271..f5b514b202 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/Adapters/DocumentAdapter.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/Adapters/DocumentAdapter.cs @@ -16,10 +16,10 @@ public DocumentAdapter(IJsonApiRequest request, ITargetedFields targetedFields, IDocumentInResourceOrRelationshipRequestAdapter documentInResourceOrRelationshipRequestAdapter, IDocumentInOperationsRequestAdapter documentInOperationsRequestAdapter) { - ArgumentGuard.NotNull(request); - ArgumentGuard.NotNull(targetedFields); - ArgumentGuard.NotNull(documentInResourceOrRelationshipRequestAdapter); - ArgumentGuard.NotNull(documentInOperationsRequestAdapter); + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(targetedFields); + ArgumentNullException.ThrowIfNull(documentInResourceOrRelationshipRequestAdapter); + ArgumentNullException.ThrowIfNull(documentInOperationsRequestAdapter); _request = request; _targetedFields = targetedFields; @@ -30,7 +30,7 @@ public DocumentAdapter(IJsonApiRequest request, ITargetedFields targetedFields, /// public object? Convert(Document document) { - ArgumentGuard.NotNull(document); + ArgumentNullException.ThrowIfNull(document); using var adapterState = new RequestAdapterState(_request, _targetedFields); diff --git a/src/JsonApiDotNetCore/Serialization/Request/Adapters/DocumentInOperationsRequestAdapter.cs b/src/JsonApiDotNetCore/Serialization/Request/Adapters/DocumentInOperationsRequestAdapter.cs index 7187ef0398..9c2aaaaf5e 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/Adapters/DocumentInOperationsRequestAdapter.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/Adapters/DocumentInOperationsRequestAdapter.cs @@ -13,8 +13,8 @@ public sealed class DocumentInOperationsRequestAdapter : BaseAdapter, IDocumentI public DocumentInOperationsRequestAdapter(IJsonApiOptions options, IAtomicOperationObjectAdapter atomicOperationObjectAdapter) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(atomicOperationObjectAdapter); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(atomicOperationObjectAdapter); _options = options; _atomicOperationObjectAdapter = atomicOperationObjectAdapter; @@ -23,8 +23,8 @@ public DocumentInOperationsRequestAdapter(IJsonApiOptions options, IAtomicOperat /// public IList Convert(Document document, RequestAdapterState state) { - ArgumentGuard.NotNull(document); - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(state); AssertHasOperations(document.Operations, state); diff --git a/src/JsonApiDotNetCore/Serialization/Request/Adapters/DocumentInResourceOrRelationshipRequestAdapter.cs b/src/JsonApiDotNetCore/Serialization/Request/Adapters/DocumentInResourceOrRelationshipRequestAdapter.cs index f6acf6212a..48b0c2c5f6 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/Adapters/DocumentInResourceOrRelationshipRequestAdapter.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/Adapters/DocumentInResourceOrRelationshipRequestAdapter.cs @@ -15,9 +15,9 @@ public sealed class DocumentInResourceOrRelationshipRequestAdapter : IDocumentIn public DocumentInResourceOrRelationshipRequestAdapter(IJsonApiOptions options, IResourceDataAdapter resourceDataAdapter, IRelationshipDataAdapter relationshipDataAdapter) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(resourceDataAdapter); - ArgumentGuard.NotNull(relationshipDataAdapter); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(resourceDataAdapter); + ArgumentNullException.ThrowIfNull(relationshipDataAdapter); _options = options; _resourceDataAdapter = resourceDataAdapter; @@ -27,8 +27,8 @@ public DocumentInResourceOrRelationshipRequestAdapter(IJsonApiOptions options, I /// public object? Convert(Document document, RequestAdapterState state) { - ArgumentGuard.NotNull(document); - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(document); + ArgumentNullException.ThrowIfNull(state); state.WritableTargetedFields = new TargetedFields(); diff --git a/src/JsonApiDotNetCore/Serialization/Request/Adapters/RelationshipDataAdapter.cs b/src/JsonApiDotNetCore/Serialization/Request/Adapters/RelationshipDataAdapter.cs index 02b3e80e43..a488e727af 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/Adapters/RelationshipDataAdapter.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/Adapters/RelationshipDataAdapter.cs @@ -13,7 +13,7 @@ public sealed class RelationshipDataAdapter : BaseAdapter, IRelationshipDataAdap public RelationshipDataAdapter(IResourceIdentifierObjectAdapter resourceIdentifierObjectAdapter) { - ArgumentGuard.NotNull(resourceIdentifierObjectAdapter); + ArgumentNullException.ThrowIfNull(resourceIdentifierObjectAdapter); _resourceIdentifierObjectAdapter = resourceIdentifierObjectAdapter; } @@ -60,8 +60,8 @@ private static SingleOrManyData ToIdentifierData(Singl public object? Convert(SingleOrManyData data, RelationshipAttribute relationship, bool useToManyElementType, RequestAdapterState state) { - ArgumentGuard.NotNull(relationship); - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(relationship); + ArgumentNullException.ThrowIfNull(state); AssertHasData(data, state); using IDisposable _ = state.Position.PushElement("data"); diff --git a/src/JsonApiDotNetCore/Serialization/Request/Adapters/RequestAdapterPosition.cs b/src/JsonApiDotNetCore/Serialization/Request/Adapters/RequestAdapterPosition.cs index 4c047afaea..da3ef481b5 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/Adapters/RequestAdapterPosition.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/Adapters/RequestAdapterPosition.cs @@ -21,7 +21,7 @@ public RequestAdapterPosition() public IDisposable PushElement(string name) { - ArgumentGuard.NotNullNorWhitespace(name); + ArgumentException.ThrowIfNullOrWhiteSpace(name); _stack.Push($"/{name}"); return _disposable; diff --git a/src/JsonApiDotNetCore/Serialization/Request/Adapters/RequestAdapterState.cs b/src/JsonApiDotNetCore/Serialization/Request/Adapters/RequestAdapterState.cs index e0c8a0d1c6..089bd48bdf 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/Adapters/RequestAdapterState.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/Adapters/RequestAdapterState.cs @@ -24,8 +24,8 @@ public sealed class RequestAdapterState : IDisposable public RequestAdapterState(IJsonApiRequest request, ITargetedFields targetedFields) { - ArgumentGuard.NotNull(request); - ArgumentGuard.NotNull(targetedFields); + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(targetedFields); InjectableRequest = request; InjectableTargetedFields = targetedFields; diff --git a/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceDataAdapter.cs b/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceDataAdapter.cs index 4717436085..91f745327d 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceDataAdapter.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceDataAdapter.cs @@ -12,8 +12,8 @@ public class ResourceDataAdapter : BaseAdapter, IResourceDataAdapter public ResourceDataAdapter(IResourceDefinitionAccessor resourceDefinitionAccessor, IResourceObjectAdapter resourceObjectAdapter) { - ArgumentGuard.NotNull(resourceDefinitionAccessor); - ArgumentGuard.NotNull(resourceObjectAdapter); + ArgumentNullException.ThrowIfNull(resourceDefinitionAccessor); + ArgumentNullException.ThrowIfNull(resourceObjectAdapter); _resourceDefinitionAccessor = resourceDefinitionAccessor; _resourceObjectAdapter = resourceObjectAdapter; @@ -22,8 +22,8 @@ public ResourceDataAdapter(IResourceDefinitionAccessor resourceDefinitionAccesso /// public IIdentifiable Convert(SingleOrManyData data, ResourceIdentityRequirements requirements, RequestAdapterState state) { - ArgumentGuard.NotNull(requirements); - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(requirements); + ArgumentNullException.ThrowIfNull(state); AssertHasData(data, state); @@ -42,8 +42,8 @@ public IIdentifiable Convert(SingleOrManyData data, ResourceIden protected virtual (IIdentifiable resource, ResourceType resourceType) ConvertResourceObject(SingleOrManyData data, ResourceIdentityRequirements requirements, RequestAdapterState state) { - ArgumentGuard.NotNull(requirements); - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(requirements); + ArgumentNullException.ThrowIfNull(state); return _resourceObjectAdapter.Convert(data.SingleValue!, requirements, state); } diff --git a/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceDataInOperationsRequestAdapter.cs b/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceDataInOperationsRequestAdapter.cs index 004363cd7f..30deb3c9ba 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceDataInOperationsRequestAdapter.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceDataInOperationsRequestAdapter.cs @@ -11,8 +11,8 @@ public sealed class ResourceDataInOperationsRequestAdapter(IResourceDefinitionAc protected override (IIdentifiable resource, ResourceType resourceType) ConvertResourceObject(SingleOrManyData data, ResourceIdentityRequirements requirements, RequestAdapterState state) { - ArgumentGuard.NotNull(requirements); - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(requirements); + ArgumentNullException.ThrowIfNull(state); // This override ensures that we enrich IJsonApiRequest before calling into IResourceDefinition, so it is ready for consumption there. diff --git a/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceIdentifierObjectAdapter.cs b/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceIdentifierObjectAdapter.cs index bc9d380388..05e2bcdafb 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceIdentifierObjectAdapter.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceIdentifierObjectAdapter.cs @@ -11,9 +11,9 @@ public sealed class ResourceIdentifierObjectAdapter(IResourceGraph resourceGraph /// public IIdentifiable Convert(ResourceIdentifierObject resourceIdentifierObject, ResourceIdentityRequirements requirements, RequestAdapterState state) { - ArgumentGuard.NotNull(resourceIdentifierObject); - ArgumentGuard.NotNull(requirements); - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(resourceIdentifierObject); + ArgumentNullException.ThrowIfNull(requirements); + ArgumentNullException.ThrowIfNull(state); (IIdentifiable resource, _) = ConvertResourceIdentity(resourceIdentifierObject, requirements, state); return resource; diff --git a/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceIdentityAdapter.cs b/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceIdentityAdapter.cs index 44e56cce99..d0def4e9cd 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceIdentityAdapter.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceIdentityAdapter.cs @@ -18,8 +18,8 @@ public abstract class ResourceIdentityAdapter : BaseAdapter protected ResourceIdentityAdapter(IResourceGraph resourceGraph, IResourceFactory resourceFactory) { - ArgumentGuard.NotNull(resourceGraph); - ArgumentGuard.NotNull(resourceFactory); + ArgumentNullException.ThrowIfNull(resourceGraph); + ArgumentNullException.ThrowIfNull(resourceFactory); _resourceGraph = resourceGraph; _resourceFactory = resourceFactory; @@ -28,9 +28,9 @@ protected ResourceIdentityAdapter(IResourceGraph resourceGraph, IResourceFactory protected (IIdentifiable resource, ResourceType resourceType) ConvertResourceIdentity(ResourceIdentity identity, ResourceIdentityRequirements requirements, RequestAdapterState state) { - ArgumentGuard.NotNull(identity); - ArgumentGuard.NotNull(requirements); - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(identity); + ArgumentNullException.ThrowIfNull(requirements); + ArgumentNullException.ThrowIfNull(state); ResourceType resourceType = ResolveType(identity, requirements, state); IIdentifiable resource = CreateResource(identity, requirements, resourceType, state); @@ -238,9 +238,9 @@ private void AssignStringId(ResourceIdentity identity, IIdentifiable resource, R protected static void AssertIsKnownRelationship([NotNull] RelationshipAttribute? relationship, string relationshipName, ResourceType resourceType, RequestAdapterState state) { - ArgumentGuard.NotNull(relationshipName); - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(relationshipName); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentNullException.ThrowIfNull(state); if (relationship == null) { @@ -251,8 +251,8 @@ protected static void AssertIsKnownRelationship([NotNull] RelationshipAttribute? protected internal static void AssertToManyInAddOrRemoveRelationship(RelationshipAttribute relationship, RequestAdapterState state) { - ArgumentGuard.NotNull(relationship); - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(relationship); + ArgumentNullException.ThrowIfNull(state); bool requireToManyRelationship = state.Request.WriteOperation is WriteOperationKind.AddToRelationship or WriteOperationKind.RemoveFromRelationship; diff --git a/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceObjectAdapter.cs b/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceObjectAdapter.cs index 1b85b35336..5f9b4dd05c 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceObjectAdapter.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/Adapters/ResourceObjectAdapter.cs @@ -17,8 +17,8 @@ public ResourceObjectAdapter(IResourceGraph resourceGraph, IResourceFactory reso IRelationshipDataAdapter relationshipDataAdapter) : base(resourceGraph, resourceFactory) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(relationshipDataAdapter); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(relationshipDataAdapter); _options = options; _relationshipDataAdapter = relationshipDataAdapter; @@ -28,9 +28,9 @@ public ResourceObjectAdapter(IResourceGraph resourceGraph, IResourceFactory reso public (IIdentifiable resource, ResourceType resourceType) Convert(ResourceObject resourceObject, ResourceIdentityRequirements requirements, RequestAdapterState state) { - ArgumentGuard.NotNull(resourceObject); - ArgumentGuard.NotNull(requirements); - ArgumentGuard.NotNull(state); + ArgumentNullException.ThrowIfNull(resourceObject); + ArgumentNullException.ThrowIfNull(requirements); + ArgumentNullException.ThrowIfNull(state); (IIdentifiable resource, ResourceType resourceType) = ConvertResourceIdentity(resourceObject, requirements, state); diff --git a/src/JsonApiDotNetCore/Serialization/Request/JsonApiReader.cs b/src/JsonApiDotNetCore/Serialization/Request/JsonApiReader.cs index 2d5fd0a66b..f565395969 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/JsonApiReader.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/JsonApiReader.cs @@ -24,9 +24,9 @@ public sealed partial class JsonApiReader : IJsonApiReader public JsonApiReader(IJsonApiOptions options, IDocumentAdapter documentAdapter, ILogger logger) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(documentAdapter); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(documentAdapter); + ArgumentNullException.ThrowIfNull(logger); _options = options; _documentAdapter = documentAdapter; @@ -36,7 +36,7 @@ public JsonApiReader(IJsonApiOptions options, IDocumentAdapter documentAdapter, /// public async Task ReadAsync(HttpRequest httpRequest) { - ArgumentGuard.NotNull(httpRequest); + ArgumentNullException.ThrowIfNull(httpRequest); string requestBody = await ReceiveRequestBodyAsync(httpRequest); diff --git a/src/JsonApiDotNetCore/Serialization/Request/JsonInvalidAttributeInfo.cs b/src/JsonApiDotNetCore/Serialization/Request/JsonInvalidAttributeInfo.cs index 2fcb31daa1..4004e83de9 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/JsonInvalidAttributeInfo.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/JsonInvalidAttributeInfo.cs @@ -16,8 +16,8 @@ internal sealed class JsonInvalidAttributeInfo public JsonInvalidAttributeInfo(string attributeName, Type attributeType, string? jsonValue, JsonValueKind jsonType) { - ArgumentGuard.NotNull(attributeName); - ArgumentGuard.NotNull(attributeType); + ArgumentNullException.ThrowIfNull(attributeName); + ArgumentNullException.ThrowIfNull(attributeType); AttributeName = attributeName; AttributeType = attributeType; diff --git a/src/JsonApiDotNetCore/Serialization/Request/ModelConversionException.cs b/src/JsonApiDotNetCore/Serialization/Request/ModelConversionException.cs index cf2428129d..02db72573d 100644 --- a/src/JsonApiDotNetCore/Serialization/Request/ModelConversionException.cs +++ b/src/JsonApiDotNetCore/Serialization/Request/ModelConversionException.cs @@ -18,7 +18,7 @@ public sealed class ModelConversionException : Exception public ModelConversionException(RequestAdapterPosition position, string? genericMessage, string? specificMessage, HttpStatusCode? statusCode = null) : base(genericMessage) { - ArgumentGuard.NotNull(position); + ArgumentNullException.ThrowIfNull(position); GenericMessage = genericMessage; SpecificMessage = specificMessage; diff --git a/src/JsonApiDotNetCore/Serialization/Response/ETagGenerator.cs b/src/JsonApiDotNetCore/Serialization/Response/ETagGenerator.cs index d5aefb1fee..e88d9c17d4 100644 --- a/src/JsonApiDotNetCore/Serialization/Response/ETagGenerator.cs +++ b/src/JsonApiDotNetCore/Serialization/Response/ETagGenerator.cs @@ -9,7 +9,7 @@ internal sealed class ETagGenerator : IETagGenerator public ETagGenerator(IFingerprintGenerator fingerprintGenerator) { - ArgumentGuard.NotNull(fingerprintGenerator); + ArgumentNullException.ThrowIfNull(fingerprintGenerator); _fingerprintGenerator = fingerprintGenerator; } diff --git a/src/JsonApiDotNetCore/Serialization/Response/FingerprintGenerator.cs b/src/JsonApiDotNetCore/Serialization/Response/FingerprintGenerator.cs index 5baef6c086..61f3349df3 100644 --- a/src/JsonApiDotNetCore/Serialization/Response/FingerprintGenerator.cs +++ b/src/JsonApiDotNetCore/Serialization/Response/FingerprintGenerator.cs @@ -18,7 +18,7 @@ private static uint ToLookupEntry(int index) /// public string Generate(IEnumerable elements) { - ArgumentGuard.NotNull(elements); + ArgumentNullException.ThrowIfNull(elements); using var hasher = IncrementalHash.CreateHash(HashAlgorithmName.MD5); diff --git a/src/JsonApiDotNetCore/Serialization/Response/JsonApiWriter.cs b/src/JsonApiDotNetCore/Serialization/Response/JsonApiWriter.cs index dad82f7c48..67bb61213b 100644 --- a/src/JsonApiDotNetCore/Serialization/Response/JsonApiWriter.cs +++ b/src/JsonApiDotNetCore/Serialization/Response/JsonApiWriter.cs @@ -29,12 +29,12 @@ public sealed partial class JsonApiWriter : IJsonApiWriter public JsonApiWriter(IJsonApiRequest request, IJsonApiOptions options, IResponseModelAdapter responseModelAdapter, IExceptionHandler exceptionHandler, IETagGenerator eTagGenerator, ILogger logger) { - ArgumentGuard.NotNull(request); - ArgumentGuard.NotNull(responseModelAdapter); - ArgumentGuard.NotNull(exceptionHandler); - ArgumentGuard.NotNull(eTagGenerator); - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(logger); + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(responseModelAdapter); + ArgumentNullException.ThrowIfNull(exceptionHandler); + ArgumentNullException.ThrowIfNull(eTagGenerator); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(logger); _request = request; _options = options; @@ -47,7 +47,7 @@ public JsonApiWriter(IJsonApiRequest request, IJsonApiOptions options, IResponse /// public async Task WriteAsync(object? model, HttpContext httpContext) { - ArgumentGuard.NotNull(httpContext); + ArgumentNullException.ThrowIfNull(httpContext); if (model == null && !CanWriteBody((HttpStatusCode)httpContext.Response.StatusCode)) { diff --git a/src/JsonApiDotNetCore/Serialization/Response/LinkBuilder.cs b/src/JsonApiDotNetCore/Serialization/Response/LinkBuilder.cs index 6d85052177..b7f200dd48 100644 --- a/src/JsonApiDotNetCore/Serialization/Response/LinkBuilder.cs +++ b/src/JsonApiDotNetCore/Serialization/Response/LinkBuilder.cs @@ -56,13 +56,13 @@ public LinkBuilder(IJsonApiOptions options, IJsonApiRequest request, IPagination LinkGenerator linkGenerator, IControllerResourceMapping controllerResourceMapping, IPaginationParser paginationParser, IDocumentDescriptionLinkProvider documentDescriptionLinkProvider) { - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(request); - ArgumentGuard.NotNull(paginationContext); - ArgumentGuard.NotNull(linkGenerator); - ArgumentGuard.NotNull(controllerResourceMapping); - ArgumentGuard.NotNull(paginationParser); - ArgumentGuard.NotNull(documentDescriptionLinkProvider); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(paginationContext); + ArgumentNullException.ThrowIfNull(linkGenerator); + ArgumentNullException.ThrowIfNull(controllerResourceMapping); + ArgumentNullException.ThrowIfNull(paginationParser); + ArgumentNullException.ThrowIfNull(documentDescriptionLinkProvider); _options = options; _request = request; @@ -245,8 +245,8 @@ private string GetQueryStringInPaginationLink(int pageOffset, string? pageSizeVa /// public ResourceLinks? GetResourceLinks(ResourceType resourceType, IIdentifiable resource) { - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentNullException.ThrowIfNull(resource); var links = new ResourceLinks(); @@ -283,8 +283,8 @@ private bool ShouldIncludeResourceLink(LinkTypes linkType, ResourceType resource /// public RelationshipLinks? GetRelationshipLinks(RelationshipAttribute relationship, IIdentifiable leftResource) { - ArgumentGuard.NotNull(relationship); - ArgumentGuard.NotNull(leftResource); + ArgumentNullException.ThrowIfNull(relationship); + ArgumentNullException.ThrowIfNull(leftResource); var links = new RelationshipLinks(); @@ -332,8 +332,8 @@ private RouteValueDictionary GetRouteValues(string primaryId, string? relationsh protected virtual string? RenderLinkForAction(string? controllerName, string actionName, IDictionary routeValues) { - ArgumentGuard.NotNull(actionName); - ArgumentGuard.NotNull(routeValues); + ArgumentNullException.ThrowIfNull(actionName); + ArgumentNullException.ThrowIfNull(routeValues); if (controllerName == null) { diff --git a/src/JsonApiDotNetCore/Serialization/Response/MetaBuilder.cs b/src/JsonApiDotNetCore/Serialization/Response/MetaBuilder.cs index cafe2fad52..1c3cc604e3 100644 --- a/src/JsonApiDotNetCore/Serialization/Response/MetaBuilder.cs +++ b/src/JsonApiDotNetCore/Serialization/Response/MetaBuilder.cs @@ -16,9 +16,9 @@ public sealed class MetaBuilder : IMetaBuilder public MetaBuilder(IPaginationContext paginationContext, IJsonApiOptions options, IResponseMeta responseMeta) { - ArgumentGuard.NotNull(paginationContext); - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(responseMeta); + ArgumentNullException.ThrowIfNull(paginationContext); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(responseMeta); _paginationContext = paginationContext; _options = options; @@ -28,7 +28,7 @@ public MetaBuilder(IPaginationContext paginationContext, IJsonApiOptions options /// public void Add(IDictionary values) { - ArgumentGuard.NotNull(values); + ArgumentNullException.ThrowIfNull(values); _meta = values.Keys.Union(_meta.Keys).ToDictionary(key => key, key => values.TryGetValue(key, out object? value) ? value : _meta[key]); } diff --git a/src/JsonApiDotNetCore/Serialization/Response/ResourceObjectTreeNode.cs b/src/JsonApiDotNetCore/Serialization/Response/ResourceObjectTreeNode.cs index e6b61527b2..2ded4ae896 100644 --- a/src/JsonApiDotNetCore/Serialization/Response/ResourceObjectTreeNode.cs +++ b/src/JsonApiDotNetCore/Serialization/Response/ResourceObjectTreeNode.cs @@ -37,9 +37,9 @@ internal sealed class ResourceObjectTreeNode : IEquatable includeElements) { - ArgumentGuard.NotNull(includeElements); + ArgumentNullException.ThrowIfNull(includeElements); ResourceObject? resourceObject = null; @@ -206,8 +206,8 @@ private static ResourceType GetEffectiveResourceType(IIdentifiable resource, Res protected virtual ResourceObject ConvertResource(IIdentifiable resource, ResourceType resourceType, EndpointKind kind) { - ArgumentGuard.NotNull(resource); - ArgumentGuard.NotNull(resourceType); + ArgumentNullException.ThrowIfNull(resource); + ArgumentNullException.ThrowIfNull(resourceType); bool isRelationship = kind == EndpointKind.Relationship; @@ -239,9 +239,9 @@ protected virtual ResourceObject ConvertResource(IIdentifiable resource, Resourc #pragma warning restore AV1130 // Return type in method signature should be an interface to an unchangeable collection IImmutableSet fieldSet) { - ArgumentGuard.NotNull(resource); - ArgumentGuard.NotNull(resourceType); - ArgumentGuard.NotNull(fieldSet); + ArgumentNullException.ThrowIfNull(resource); + ArgumentNullException.ThrowIfNull(resourceType); + ArgumentNullException.ThrowIfNull(fieldSet); var attrMap = new Dictionary(resourceType.Attributes.Count); diff --git a/src/JsonApiDotNetCore/Services/AsyncCollectionExtensions.cs b/src/JsonApiDotNetCore/Services/AsyncCollectionExtensions.cs index 31dc56bbec..83ba8902a2 100644 --- a/src/JsonApiDotNetCore/Services/AsyncCollectionExtensions.cs +++ b/src/JsonApiDotNetCore/Services/AsyncCollectionExtensions.cs @@ -7,8 +7,8 @@ public static class AsyncCollectionExtensions { public static async Task AddRangeAsync(this ICollection source, IAsyncEnumerable elementsToAdd, CancellationToken cancellationToken = default) { - ArgumentGuard.NotNull(source); - ArgumentGuard.NotNull(elementsToAdd); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(elementsToAdd); await foreach (T missingResource in elementsToAdd.WithCancellation(cancellationToken)) { @@ -18,7 +18,7 @@ public static async Task AddRangeAsync(this ICollection source, IAsyncEnum public static async Task> ToListAsync(this IAsyncEnumerable source, CancellationToken cancellationToken = default) { - ArgumentGuard.NotNull(source); + ArgumentNullException.ThrowIfNull(source); List list = []; diff --git a/src/JsonApiDotNetCore/Services/JsonApiResourceService.cs b/src/JsonApiDotNetCore/Services/JsonApiResourceService.cs index 4fa0cdc4f0..de5d3b7b1f 100644 --- a/src/JsonApiDotNetCore/Services/JsonApiResourceService.cs +++ b/src/JsonApiDotNetCore/Services/JsonApiResourceService.cs @@ -34,14 +34,14 @@ public JsonApiResourceService(IResourceRepositoryAccessor repositoryAccessor, IQ IJsonApiOptions options, ILoggerFactory loggerFactory, IJsonApiRequest request, IResourceChangeTracker resourceChangeTracker, IResourceDefinitionAccessor resourceDefinitionAccessor) { - ArgumentGuard.NotNull(repositoryAccessor); - ArgumentGuard.NotNull(queryLayerComposer); - ArgumentGuard.NotNull(paginationContext); - ArgumentGuard.NotNull(options); - ArgumentGuard.NotNull(loggerFactory); - ArgumentGuard.NotNull(request); - ArgumentGuard.NotNull(resourceChangeTracker); - ArgumentGuard.NotNull(resourceDefinitionAccessor); + ArgumentNullException.ThrowIfNull(repositoryAccessor); + ArgumentNullException.ThrowIfNull(queryLayerComposer); + ArgumentNullException.ThrowIfNull(paginationContext); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(loggerFactory); + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(resourceChangeTracker); + ArgumentNullException.ThrowIfNull(resourceDefinitionAccessor); _repositoryAccessor = repositoryAccessor; _queryLayerComposer = queryLayerComposer; @@ -106,7 +106,7 @@ public virtual async Task GetAsync([DisallowNull] TId id, Cancellatio relationshipName }); - ArgumentGuard.NotNull(relationshipName); + ArgumentNullException.ThrowIfNull(relationshipName); AssertPrimaryResourceTypeInJsonApiRequestIsNotNull(_request.PrimaryResourceType); AssertHasRelationship(_request.Relationship, relationshipName); @@ -146,7 +146,7 @@ public virtual async Task GetAsync([DisallowNull] TId id, Cancellatio relationshipName }); - ArgumentGuard.NotNull(relationshipName); + ArgumentNullException.ThrowIfNull(relationshipName); AssertPrimaryResourceTypeInJsonApiRequestIsNotNull(_request.PrimaryResourceType); AssertHasRelationship(_request.Relationship, relationshipName); @@ -196,7 +196,7 @@ private async Task RetrieveResourceCountForNonPrimaryEndpointAsync([DisallowNull resource }); - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Create resource"); @@ -237,7 +237,7 @@ private async Task RetrieveResourceCountForNonPrimaryEndpointAsync([DisallowNull protected async Task AssertPrimaryResourceDoesNotExistAsync(TResource resource, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); if (!Equals(resource.Id, default(TId))) { @@ -252,7 +252,7 @@ protected async Task AssertPrimaryResourceDoesNotExistAsync(TResource resource, protected virtual async Task InitializeResourceAsync(TResource resourceForDatabase, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(resourceForDatabase); + ArgumentNullException.ThrowIfNull(resourceForDatabase); await _resourceDefinitionAccessor.OnPrepareWriteAsync(resourceForDatabase, WriteOperationKind.CreateResource, cancellationToken); } @@ -264,7 +264,7 @@ private async Task AccurizeResourceTypesInHierarchyToAssignInRelationshipsAsync( protected async Task AssertResourcesToAssignInRelationshipsExistAsync(TResource primaryResource, CancellationToken cancellationToken) { - ArgumentGuard.NotNull(primaryResource); + ArgumentNullException.ThrowIfNull(primaryResource); await ValidateResourcesToAssignInRelationshipsExistWithRefreshAsync(primaryResource, false, cancellationToken); } @@ -349,8 +349,8 @@ public virtual async Task AddToToManyRelationshipAsync([DisallowNull] TId leftId rightResourceIds }); - ArgumentGuard.NotNull(relationshipName); - ArgumentGuard.NotNull(rightResourceIds); + ArgumentNullException.ThrowIfNull(relationshipName); + ArgumentNullException.ThrowIfNull(rightResourceIds); AssertHasRelationship(_request.Relationship, relationshipName); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Add to to-many relationship"); @@ -455,7 +455,7 @@ private async Task GetForHasManyUpdateAsync(HasManyAttribute hasManyR resource }); - ArgumentGuard.NotNull(resource); + ArgumentNullException.ThrowIfNull(resource); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Update resource"); @@ -499,7 +499,7 @@ public virtual async Task SetRelationshipAsync([DisallowNull] TId leftId, string rightValue }); - ArgumentGuard.NotNull(relationshipName); + ArgumentNullException.ThrowIfNull(relationshipName); AssertHasRelationship(_request.Relationship, relationshipName); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Set relationship"); @@ -570,8 +570,8 @@ public virtual async Task RemoveFromToManyRelationshipAsync([DisallowNull] TId l rightResourceIds }); - ArgumentGuard.NotNull(relationshipName); - ArgumentGuard.NotNull(rightResourceIds); + ArgumentNullException.ThrowIfNull(relationshipName); + ArgumentNullException.ThrowIfNull(rightResourceIds); AssertHasRelationship(_request.Relationship, relationshipName); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Repository - Remove from to-many relationship"); diff --git a/test/AnnotationTests/AnnotationTests.csproj b/test/AnnotationTests/AnnotationTests.csproj index 081046adb0..885e9f769c 100644 --- a/test/AnnotationTests/AnnotationTests.csproj +++ b/test/AnnotationTests/AnnotationTests.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0;netstandard2.0 + net9.0;net8.0;netstandard2.0 diff --git a/test/DapperTests/DapperTests.csproj b/test/DapperTests/DapperTests.csproj index 45d9c6a88d..7d41d78911 100644 --- a/test/DapperTests/DapperTests.csproj +++ b/test/DapperTests/DapperTests.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net9.0;net8.0 diff --git a/test/DapperTests/IntegrationTests/DapperTestContext.cs b/test/DapperTests/IntegrationTests/DapperTestContext.cs index 9fdc330c74..2156902f98 100644 --- a/test/DapperTests/IntegrationTests/DapperTestContext.cs +++ b/test/DapperTests/IntegrationTests/DapperTestContext.cs @@ -4,8 +4,6 @@ using DapperExample.Models; using DapperExample.Repositories; using DapperExample.TranslationToSql.DataModel; -using FluentAssertions.Common; -using FluentAssertions.Extensions; using JetBrains.Annotations; using JsonApiDotNetCore.Configuration; using Microsoft.AspNetCore.Hosting; @@ -13,10 +11,10 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using TestBuildingBlocks; using Xunit.Abstractions; -using IClock = DapperExample.IClock; namespace DapperTests.IntegrationTests; @@ -29,7 +27,7 @@ public sealed class DapperTestContext : IntegrationTest EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'; """; - public static readonly DateTimeOffset FrozenTime = 29.September(2018).At(16, 41, 56).AsUtc().ToDateTimeOffset(); + public static readonly DateTimeOffset FrozenTime = DefaultDateTimeUtc; private readonly Lazy> _lazyFactory; private ITestOutputHelper? _testOutputHelper; @@ -82,10 +80,7 @@ private WebApplicationFactory CreateFactory() builder.ConfigureServices(services => { - services.AddSingleton(new FrozenClock - { - UtcNow = FrozenTime - }); + services.Replace(ServiceDescriptor.Singleton(new FrozenTimeProvider(FrozenTime))); ServiceDescriptor scopedCaptureStore = services.Single(descriptor => descriptor.ImplementationType == typeof(SqlCaptureStore)); services.Remove(scopedCaptureStore); @@ -122,14 +117,10 @@ public async Task ClearAllTablesAsync(DbContext dbContext) _ => throw new NotSupportedException($"Unsupported database provider '{databaseProvider}'.") }; -#if !NET6_0 #pragma warning disable EF1002 // Risk of vulnerability to SQL injection. -#endif // Justification: Table names cannot be parameterized. await dbContext.Database.ExecuteSqlRawAsync($"DELETE FROM {escapedTableName}"); -#if !NET6_0 #pragma warning restore EF1002 // Risk of vulnerability to SQL injection. -#endif } } } diff --git a/test/DapperTests/IntegrationTests/FrozenClock.cs b/test/DapperTests/IntegrationTests/FrozenClock.cs deleted file mode 100644 index 7edfadce5b..0000000000 --- a/test/DapperTests/IntegrationTests/FrozenClock.cs +++ /dev/null @@ -1,11 +0,0 @@ -using DapperExample; -using JetBrains.Annotations; -using TestBuildingBlocks; - -namespace DapperTests.IntegrationTests; - -[UsedImplicitly(ImplicitUseTargetFlags.Members)] -internal sealed class FrozenClock : IClock -{ - public DateTimeOffset UtcNow { get; set; } = FrozenSystemClock.DefaultDateTimeOffsetUtc; -} diff --git a/test/DapperTests/IntegrationTests/SqlTextAdapter.cs b/test/DapperTests/IntegrationTests/SqlTextAdapter.cs index 3bdeab115f..1d6d45555e 100644 --- a/test/DapperTests/IntegrationTests/SqlTextAdapter.cs +++ b/test/DapperTests/IntegrationTests/SqlTextAdapter.cs @@ -5,11 +5,7 @@ namespace DapperTests.IntegrationTests; internal sealed class SqlTextAdapter(DatabaseProvider databaseProvider) { -#if NET6_0 - private const RegexOptions Options = RegexOptions.Compiled | RegexOptions.CultureInvariant; -#else private const RegexOptions Options = RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.NonBacktracking; -#endif private static readonly Dictionary SqlServerReplacements = new() { diff --git a/test/DiscoveryTests/DiscoveryTests.csproj b/test/DiscoveryTests/DiscoveryTests.csproj index a64d3be689..abeaaa956d 100644 --- a/test/DiscoveryTests/DiscoveryTests.csproj +++ b/test/DiscoveryTests/DiscoveryTests.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net9.0;net8.0 diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Creating/AtomicCreateResourceTests.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Creating/AtomicCreateResourceTests.cs index 247a827a34..2438aca27a 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Creating/AtomicCreateResourceTests.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Creating/AtomicCreateResourceTests.cs @@ -26,8 +26,6 @@ public AtomicCreateResourceTests(IntegrationTestContext(); testContext.UseController(); - testContext.ConfigureServices(services => services.AddSingleton()); - var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService(); options.AllowUnknownFieldsInRequestBody = false; } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Creating/AtomicCreateResourceWithClientGeneratedIdTests.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Creating/AtomicCreateResourceWithClientGeneratedIdTests.cs index 4d7b7177cf..e20d8d45ff 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Creating/AtomicCreateResourceWithClientGeneratedIdTests.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Creating/AtomicCreateResourceWithClientGeneratedIdTests.cs @@ -28,7 +28,6 @@ public AtomicCreateResourceWithClientGeneratedIdTests(IntegrationTestContext(); services.AddSingleton(); - services.AddSingleton(); }); } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/DateMustBeInThePastAttribute.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/DateMustBeInThePastAttribute.cs index b273eca898..2a76f8ef34 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/DateMustBeInThePastAttribute.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/DateMustBeInThePastAttribute.cs @@ -2,7 +2,6 @@ using System.Reflection; using JsonApiDotNetCore.Resources; using Microsoft.Extensions.DependencyInjection; -using TestBuildingBlocks; namespace JsonApiDotNetCoreTests.IntegrationTests.AtomicOperations; @@ -20,9 +19,11 @@ internal sealed class DateMustBeInThePastAttribute : ValidationAttribute if (propertyInfo.PropertyType == typeof(DateTimeOffset) || propertyInfo.PropertyType == typeof(DateTimeOffset?)) { var typedValue = (DateTimeOffset?)propertyInfo.GetValue(validationContext.ObjectInstance); - var systemClock = validationContext.GetRequiredService(); - if (typedValue >= systemClock.UtcNow) + var timeProvider = validationContext.GetRequiredService(); + DateTimeOffset utcNow = timeProvider.GetUtcNow(); + + if (typedValue >= utcNow) { return new ValidationResult($"{validationContext.MemberName} must be in the past."); } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Meta/AtomicResourceMetaTests.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Meta/AtomicResourceMetaTests.cs index 8c08ccedae..4d4982f732 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Meta/AtomicResourceMetaTests.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Meta/AtomicResourceMetaTests.cs @@ -27,7 +27,6 @@ public AtomicResourceMetaTests(IntegrationTestContext(); services.AddSingleton(); - services.AddSingleton(); }); var hitCounter = _testContext.Factory.Services.GetRequiredService(); diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/ModelStateValidation/AtomicModelStateValidationTests.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/ModelStateValidation/AtomicModelStateValidationTests.cs index 82c190dc58..09596c2f00 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/ModelStateValidation/AtomicModelStateValidationTests.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/ModelStateValidation/AtomicModelStateValidationTests.cs @@ -17,8 +17,6 @@ public AtomicModelStateValidationTests(IntegrationTestContext services.AddSingleton()); - testContext.UseController(); } @@ -74,7 +72,8 @@ public async Task Cannot_create_resource_with_multiple_violations() public async Task Cannot_create_resource_when_violation_from_custom_ValidationAttribute() { // Arrange - var clock = _testContext.Factory.Services.GetRequiredService(); + var timeProvider = _testContext.Factory.Services.GetRequiredService(); + DateTimeOffset utcNow = timeProvider.GetUtcNow(); var requestBody = new { @@ -90,7 +89,7 @@ public async Task Cannot_create_resource_when_violation_from_custom_ValidationAt { title = "some", lengthInSeconds = 120, - releasedAt = clock.UtcNow.AddDays(1) + releasedAt = utcNow.AddDays(1) } } } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/QueryStrings/AtomicQueryStringTests.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/QueryStrings/AtomicQueryStringTests.cs index 35cd7ed32b..e979e164c9 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/QueryStrings/AtomicQueryStringTests.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/QueryStrings/AtomicQueryStringTests.cs @@ -20,12 +20,7 @@ public AtomicQueryStringTests(IntegrationTestContext(); testContext.UseController(); - testContext.ConfigureServices(services => - { - services.AddResourceDefinition(); - - services.AddSingleton(); - }); + testContext.ConfigureServices(services => services.AddResourceDefinition()); } [Fact] @@ -272,12 +267,13 @@ public async Task Cannot_use_sparse_fieldset_at_operations_endpoint() public async Task Can_use_Queryable_handler_at_resource_endpoint() { // Arrange - var clock = _testContext.Factory.Services.GetRequiredService(); + var timeProvider = _testContext.Factory.Services.GetRequiredService(); + DateTimeOffset utcNow = timeProvider.GetUtcNow(); List musicTracks = _fakers.MusicTrack.GenerateList(3); - musicTracks[0].ReleasedAt = clock.UtcNow.AddMonths(5); - musicTracks[1].ReleasedAt = clock.UtcNow.AddMonths(-5); - musicTracks[2].ReleasedAt = clock.UtcNow.AddMonths(-1); + musicTracks[0].ReleasedAt = utcNow.AddMonths(5); + musicTracks[1].ReleasedAt = utcNow.AddMonths(-5); + musicTracks[2].ReleasedAt = utcNow.AddMonths(-1); await _testContext.RunOnDatabaseAsync(async dbContext => { diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/QueryStrings/MusicTrackReleaseDefinition.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/QueryStrings/MusicTrackReleaseDefinition.cs index 84827322ad..b72b3eb3d2 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/QueryStrings/MusicTrackReleaseDefinition.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/QueryStrings/MusicTrackReleaseDefinition.cs @@ -1,23 +1,21 @@ using JetBrains.Annotations; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Resources; using Microsoft.Extensions.Primitives; -using TestBuildingBlocks; namespace JsonApiDotNetCoreTests.IntegrationTests.AtomicOperations.QueryStrings; [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] public sealed class MusicTrackReleaseDefinition : JsonApiResourceDefinition { - private readonly ISystemClock _systemClock; + private readonly TimeProvider _timeProvider; - public MusicTrackReleaseDefinition(IResourceGraph resourceGraph, ISystemClock systemClock) + public MusicTrackReleaseDefinition(IResourceGraph resourceGraph, TimeProvider timeProvider) : base(resourceGraph) { - ArgumentGuard.NotNull(systemClock); + ArgumentNullException.ThrowIfNull(timeProvider); - _systemClock = systemClock; + _timeProvider = timeProvider; } public override QueryStringParameterHandlers OnRegisterQueryableHandlersForQueryStringParameters() @@ -34,7 +32,8 @@ private IQueryable FilterOnRecentlyReleased(IQueryable s if (bool.Parse(parameterValue.ToString())) { - tracks = tracks.Where(musicTrack => musicTrack.ReleasedAt < _systemClock.UtcNow && musicTrack.ReleasedAt > _systemClock.UtcNow.AddMonths(-3)); + DateTimeOffset utcNow = _timeProvider.GetUtcNow(); + tracks = tracks.Where(musicTrack => musicTrack.ReleasedAt < utcNow && musicTrack.ReleasedAt > utcNow.AddMonths(-3)); } return tracks; diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Updating/Resources/AtomicUpdateResourceTests.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Updating/Resources/AtomicUpdateResourceTests.cs index 282fcea377..29a3e10fd5 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Updating/Resources/AtomicUpdateResourceTests.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/AtomicOperations/Updating/Resources/AtomicUpdateResourceTests.cs @@ -29,7 +29,6 @@ public AtomicUpdateResourceTests(IntegrationTestContext(); services.AddSingleton(); - services.AddSingleton(); }); var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService(); diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/CompositeKeys/Car.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/CompositeKeys/Car.cs index d61d378db7..f77626f13e 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/CompositeKeys/Car.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/CompositeKeys/Car.cs @@ -12,13 +12,13 @@ public sealed class Car : Identifiable [NotMapped] public override string? Id { - get => RegionId == default && LicensePlate == default ? null : $"{RegionId}:{LicensePlate}"; + get => RegionId == 0 && LicensePlate == null ? null : $"{RegionId}:{LicensePlate}"; set { if (value == null) { - RegionId = default; - LicensePlate = default; + RegionId = 0; + LicensePlate = null; return; } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/ContentNegotiation/CustomExtensions/CapturingDocumentAdapter.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/ContentNegotiation/CustomExtensions/CapturingDocumentAdapter.cs index 705d5e6ed6..fc138415b3 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/ContentNegotiation/CustomExtensions/CapturingDocumentAdapter.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/ContentNegotiation/CustomExtensions/CapturingDocumentAdapter.cs @@ -1,4 +1,3 @@ -using JsonApiDotNetCore; using JsonApiDotNetCore.Serialization.Objects; using JsonApiDotNetCore.Serialization.Request.Adapters; @@ -11,8 +10,8 @@ internal sealed class CapturingDocumentAdapter : IDocumentAdapter public CapturingDocumentAdapter(IDocumentAdapter innerAdapter, RequestDocumentStore requestDocumentStore) { - ArgumentGuard.NotNull(innerAdapter); - ArgumentGuard.NotNull(requestDocumentStore); + ArgumentNullException.ThrowIfNull(innerAdapter); + ArgumentNullException.ThrowIfNull(requestDocumentStore); _innerAdapter = innerAdapter; _requestDocumentStore = requestDocumentStore; diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/ContentNegotiation/CustomExtensions/CustomExtensionsContentTypeTests.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/ContentNegotiation/CustomExtensions/CustomExtensionsContentTypeTests.cs index 3450b571f4..3a991dc13d 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/ContentNegotiation/CustomExtensions/CustomExtensionsContentTypeTests.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/ContentNegotiation/CustomExtensions/CustomExtensionsContentTypeTests.cs @@ -1,12 +1,14 @@ using System.Net; using System.Net.Http.Headers; using FluentAssertions; +using FluentAssertions.Extensions; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Middleware; using JsonApiDotNetCore.Serialization.Objects; using JsonApiDotNetCore.Serialization.Request.Adapters; using JsonApiDotNetCore.Serialization.Response; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using TestBuildingBlocks; using Xunit; @@ -14,6 +16,7 @@ namespace JsonApiDotNetCoreTests.IntegrationTests.ContentNegotiation.CustomExten public sealed class CustomExtensionsContentTypeTests : IClassFixture, PolicyDbContext>> { + private static readonly DateTimeOffset CurrentTime = 31.December(2024).At(21, 53, 40).AsUtc(); private readonly IntegrationTestContext, PolicyDbContext> _testContext; public CustomExtensionsContentTypeTests(IntegrationTestContext, PolicyDbContext> testContext) @@ -39,6 +42,9 @@ public CustomExtensionsContentTypeTests(IntegrationTestContext services.Replace( + ServiceDescriptor.Singleton(new FrozenTimeProvider(CurrentTime, TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time"))))); + var options = (JsonApiOptions)_testContext.Factory.Services.GetRequiredService(); options.IncludeExtensions(ServerTimeMediaTypeExtension.ServerTime, ServerTimeMediaTypeExtension.RelaxedServerTime); } @@ -108,7 +114,8 @@ public async Task Permits_JsonApi_ContentType_header_with_ServerTime_extension() httpResponse.Content.Headers.ContentType.ShouldNotBeNull(); httpResponse.Content.Headers.ContentType.ToString().Should().Be(ServerTimeMediaTypes.ServerTime.ToString()); - responseDocument.Meta.ShouldContainKey("localServerTime"); + responseDocument.Meta.ShouldContainKey("localServerTime").With(time => + time.ShouldNotBeNull().ToString().Should().Be("2025-01-01T06:53:40.0000000+09:00")); } [Fact] @@ -143,7 +150,7 @@ public async Task Permits_JsonApi_ContentType_header_with_relaxed_ServerTime_ext httpResponse.Content.Headers.ContentType.ShouldNotBeNull(); httpResponse.Content.Headers.ContentType.ToString().Should().Be(ServerTimeMediaTypes.RelaxedServerTime.ToString()); - responseDocument.Meta.ShouldContainKey("utcServerTime"); + responseDocument.Meta.ShouldContainKey("utcServerTime").With(time => time.ShouldNotBeNull().ToString().Should().Be("2024-12-31T21:53:40.0000000Z")); } [Fact] @@ -185,7 +192,7 @@ public async Task Permits_JsonApi_ContentType_header_with_AtomicOperations_and_S httpResponse.Content.Headers.ContentType.ShouldNotBeNull(); httpResponse.Content.Headers.ContentType.ToString().Should().Be(ServerTimeMediaTypes.AtomicOperationsWithServerTime.ToString()); - responseDocument.Meta.ShouldContainKey("utcServerTime"); + responseDocument.Meta.ShouldContainKey("utcServerTime").With(time => time.ShouldNotBeNull().ToString().Should().Be("2024-12-31T21:53:40.0000000Z")); } [Fact] diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/ContentNegotiation/CustomExtensions/ServerTimeResponseMeta.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/ContentNegotiation/CustomExtensions/ServerTimeResponseMeta.cs index 1787228478..27487e0149 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/ContentNegotiation/CustomExtensions/ServerTimeResponseMeta.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/ContentNegotiation/CustomExtensions/ServerTimeResponseMeta.cs @@ -1,15 +1,19 @@ +using System.Globalization; using JsonApiDotNetCore.Middleware; using JsonApiDotNetCore.Serialization.Response; namespace JsonApiDotNetCoreTests.IntegrationTests.ContentNegotiation.CustomExtensions; -internal sealed class ServerTimeResponseMeta(IJsonApiRequest request, RequestDocumentStore documentStore) : IResponseMeta +internal sealed class ServerTimeResponseMeta(IJsonApiRequest request, RequestDocumentStore documentStore, TimeProvider timeProvider) : IResponseMeta { + private readonly IJsonApiRequest _request = request; private readonly RequestDocumentStore _documentStore = documentStore; + private readonly TimeProvider _timeProvider = timeProvider; public IDictionary? GetMeta() { - if (request.Extensions.Contains(ServerTimeMediaTypeExtension.ServerTime) || request.Extensions.Contains(ServerTimeMediaTypeExtension.RelaxedServerTime)) + if (_request.Extensions.Contains(ServerTimeMediaTypeExtension.ServerTime) || + _request.Extensions.Contains(ServerTimeMediaTypeExtension.RelaxedServerTime)) { if (_documentStore.Document is not { Meta: not null } || !_documentStore.Document.Meta.TryGetValue("useLocalTime", out object? useLocalTimeValue) || useLocalTimeValue == null || !bool.TryParse(useLocalTimeValue.ToString(), out bool useLocalTime)) @@ -20,11 +24,11 @@ internal sealed class ServerTimeResponseMeta(IJsonApiRequest request, RequestDoc return useLocalTime ? new Dictionary { - ["localServerTime"] = DateTime.Now.ToString("O") + ["localServerTime"] = _timeProvider.GetLocalNow().ToString("O", CultureInfo.InvariantCulture) } : new Dictionary { - ["utcServerTime"] = DateTime.UtcNow.ToString("O") + ["utcServerTime"] = _timeProvider.GetUtcNow().UtcDateTime.ToString("O", CultureInfo.InvariantCulture) }; } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/EagerLoading/BuildingDefinition.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/EagerLoading/BuildingDefinition.cs index 18dca5a502..dbdfea8a6f 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/EagerLoading/BuildingDefinition.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/EagerLoading/BuildingDefinition.cs @@ -1,5 +1,4 @@ using JetBrains.Annotations; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Middleware; using JsonApiDotNetCore.Resources; @@ -14,7 +13,7 @@ public sealed class BuildingDefinition : JsonApiResourceDefinition : JsonApiRes protected HitCountingResourceDefinition(IResourceGraph resourceGraph, ResourceDefinitionHitCounter hitCounter) : base(resourceGraph) { - ArgumentGuard.NotNull(hitCounter); + ArgumentNullException.ThrowIfNull(hitCounter); _hitCounter = hitCounter; } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/IdObfuscation/ObfuscatedIdentifiable.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/IdObfuscation/ObfuscatedIdentifiable.cs index 0aa2203d8a..af6a8a1416 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/IdObfuscation/ObfuscatedIdentifiable.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/IdObfuscation/ObfuscatedIdentifiable.cs @@ -8,11 +8,11 @@ public abstract class ObfuscatedIdentifiable : Identifiable protected override string? GetStringId(int value) { - return value == default ? null : Codec.Encode(value); + return value == 0 ? null : Codec.Encode(value); } protected override int GetTypedId(string? value) { - return value == null ? default : Codec.Decode(value); + return value == null ? 0 : Codec.Decode(value); } } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/InputValidation/ModelState/ModelStateValidationTests.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/InputValidation/ModelState/ModelStateValidationTests.cs index 6dc7282cd8..e667cb0ffb 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/InputValidation/ModelState/ModelStateValidationTests.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/InputValidation/ModelState/ModelStateValidationTests.cs @@ -3,9 +3,6 @@ using JsonApiDotNetCore.Serialization.Objects; using TestBuildingBlocks; using Xunit; -#if NET6_0 -using Microsoft.Extensions.DependencyInjection; -#endif namespace JsonApiDotNetCoreTests.IntegrationTests.InputValidation.ModelState; @@ -20,12 +17,6 @@ public ModelStateValidationTests(IntegrationTestContext(); testContext.UseController(); - -#if NET6_0 - testContext.ConfigureServices(services => - // Polyfill for missing DateOnly/TimeOnly support in .NET 6 ModelState validation. - services.AddDateOnlyTimeOnlyStringConverters()); -#endif } [Fact] diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/NamingConventions/JsonKebabCaseNamingPolicy.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/NamingConventions/JsonKebabCaseNamingPolicy.cs deleted file mode 100644 index 1d2f948068..0000000000 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/NamingConventions/JsonKebabCaseNamingPolicy.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System.Text; -using System.Text.Json; - -namespace JsonApiDotNetCoreTests.IntegrationTests.NamingConventions; - -// Based on https://github.com/J0rgeSerran0/JsonNamingPolicy -internal sealed class JsonKebabCaseNamingPolicy : JsonNamingPolicy -{ - private const char Separator = '-'; - - public static readonly JsonKebabCaseNamingPolicy Instance = new(); - - public override string ConvertName(string name) - { - if (string.IsNullOrWhiteSpace(name)) - { - return string.Empty; - } - - ReadOnlySpan spanName = name.Trim(); - - var stringBuilder = new StringBuilder(); - bool addCharacter = true; - - bool isNextLower = false; - bool isNextUpper = false; - bool isNextSpace = false; - - for (int position = 0; position < spanName.Length; position++) - { - if (position != 0) - { - bool isCurrentSpace = spanName[position] == 32; - bool isPreviousSpace = spanName[position - 1] == 32; - bool isPreviousSeparator = spanName[position - 1] == 95; - - if (position + 1 != spanName.Length) - { - isNextLower = spanName[position + 1] is >= 'a' and <= 'z'; - isNextUpper = spanName[position + 1] is >= 'A' and <= 'Z'; - isNextSpace = spanName[position + 1] == ' '; - } - - if (isCurrentSpace && (isPreviousSpace || isPreviousSeparator || isNextUpper || isNextSpace)) - { - addCharacter = false; - } - else - { - bool isCurrentUpper = spanName[position] is >= 'A' and <= 'Z'; - bool isPreviousLower = spanName[position - 1] is >= 'a' and <= 'z'; - bool isPreviousNumber = spanName[position - 1] is >= '0' and <= '9'; - - if (isCurrentUpper && (isPreviousLower || isPreviousNumber || isNextLower || isNextSpace)) - { - stringBuilder.Append(Separator); - } - else - { - if (isCurrentSpace) - { - stringBuilder.Append(Separator); - addCharacter = false; - } - } - } - } - - if (addCharacter) - { - stringBuilder.Append(spanName[position]); - } - else - { - addCharacter = true; - } - } - - return stringBuilder.ToString().ToLowerInvariant(); - } -} diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/NamingConventions/KebabCasingConventionStartup.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/NamingConventions/KebabCasingConventionStartup.cs index da3d3b10f9..6321943718 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/NamingConventions/KebabCasingConventionStartup.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/NamingConventions/KebabCasingConventionStartup.cs @@ -1,3 +1,4 @@ +using System.Text.Json; using JetBrains.Annotations; using JsonApiDotNetCore.Configuration; using TestBuildingBlocks; @@ -16,7 +17,7 @@ protected override void SetJsonApiOptions(JsonApiOptions options) options.UseRelativeLinks = true; options.IncludeTotalResourceCount = true; - options.SerializerOptions.PropertyNamingPolicy = JsonKebabCaseNamingPolicy.Instance; - options.SerializerOptions.DictionaryKeyPolicy = JsonKebabCaseNamingPolicy.Instance; + options.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.KebabCaseLower; + options.SerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.KebabCaseLower; } } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/IsUpperCase/IsUpperCaseExpression.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/IsUpperCase/IsUpperCaseExpression.cs index bea7ccd2ba..7a4bfa0788 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/IsUpperCase/IsUpperCaseExpression.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/IsUpperCase/IsUpperCaseExpression.cs @@ -1,5 +1,4 @@ using System.Text; -using JsonApiDotNetCore; using JsonApiDotNetCore.Queries.Expressions; namespace JsonApiDotNetCoreTests.IntegrationTests.QueryStrings.CustomFunctions.IsUpperCase; @@ -27,7 +26,7 @@ internal sealed class IsUpperCaseExpression : FilterExpression public IsUpperCaseExpression(ResourceFieldChainExpression targetAttribute) { - ArgumentGuard.NotNull(targetAttribute); + ArgumentNullException.ThrowIfNull(targetAttribute); TargetAttribute = targetAttribute; } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/StringLength/LengthExpression.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/StringLength/LengthExpression.cs index 727d3ec808..1fcf8b45dd 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/StringLength/LengthExpression.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/StringLength/LengthExpression.cs @@ -1,5 +1,4 @@ using System.Text; -using JsonApiDotNetCore; using JsonApiDotNetCore.Queries.Expressions; namespace JsonApiDotNetCoreTests.IntegrationTests.QueryStrings.CustomFunctions.StringLength; @@ -31,7 +30,7 @@ internal sealed class LengthExpression : FunctionExpression public LengthExpression(ResourceFieldChainExpression targetAttribute) { - ArgumentGuard.NotNull(targetAttribute); + ArgumentNullException.ThrowIfNull(targetAttribute); TargetAttribute = targetAttribute; } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/Sum/SumExpression.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/Sum/SumExpression.cs index 7e137ad3d7..f353c1552b 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/Sum/SumExpression.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/Sum/SumExpression.cs @@ -1,5 +1,4 @@ using System.Text; -using JsonApiDotNetCore; using JsonApiDotNetCore.Queries.Expressions; namespace JsonApiDotNetCoreTests.IntegrationTests.QueryStrings.CustomFunctions.Sum; @@ -38,8 +37,8 @@ internal sealed class SumExpression : FunctionExpression public SumExpression(ResourceFieldChainExpression targetToManyRelationship, QueryExpression selector) { - ArgumentGuard.NotNull(targetToManyRelationship); - ArgumentGuard.NotNull(selector); + ArgumentNullException.ThrowIfNull(targetToManyRelationship); + ArgumentNullException.ThrowIfNull(selector); TargetToManyRelationship = targetToManyRelationship; Selector = selector; diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/TimeOffset/FilterRewritingResourceDefinition.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/TimeOffset/FilterRewritingResourceDefinition.cs index 1a704d3883..e6578e5c0c 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/TimeOffset/FilterRewritingResourceDefinition.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/TimeOffset/FilterRewritingResourceDefinition.cs @@ -2,16 +2,15 @@ using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Queries.Expressions; using JsonApiDotNetCore.Resources; -using TestBuildingBlocks; namespace JsonApiDotNetCoreTests.IntegrationTests.QueryStrings.CustomFunctions.TimeOffset; [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] -public class FilterRewritingResourceDefinition(IResourceGraph resourceGraph, ISystemClock systemClock) +public class FilterRewritingResourceDefinition(IResourceGraph resourceGraph, TimeProvider timeProvider) : JsonApiResourceDefinition(resourceGraph) where TResource : class, IIdentifiable { - private readonly FilterTimeOffsetRewriter _rewriter = new(systemClock); + private readonly FilterTimeOffsetRewriter _rewriter = new(timeProvider); public override FilterExpression? OnApplyFilter(FilterExpression? existingFilter) { diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/TimeOffset/FilterTimeOffsetRewriter.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/TimeOffset/FilterTimeOffsetRewriter.cs index 9f9c97c73a..97c975a059 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/TimeOffset/FilterTimeOffsetRewriter.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/TimeOffset/FilterTimeOffsetRewriter.cs @@ -1,9 +1,8 @@ using JsonApiDotNetCore.Queries.Expressions; -using TestBuildingBlocks; namespace JsonApiDotNetCoreTests.IntegrationTests.QueryStrings.CustomFunctions.TimeOffset; -internal sealed class FilterTimeOffsetRewriter(ISystemClock systemClock) : QueryExpressionRewriter +internal sealed class FilterTimeOffsetRewriter(TimeProvider timeProvider) : QueryExpressionRewriter { private static readonly Dictionary InverseComparisonOperatorTable = new() { @@ -14,21 +13,21 @@ internal sealed class FilterTimeOffsetRewriter(ISystemClock systemClock) : Query [ComparisonOperator.LessOrEqual] = ComparisonOperator.GreaterOrEqual }; - private readonly ISystemClock _systemClock = systemClock; + private readonly TimeProvider _timeProvider = timeProvider; public override QueryExpression? VisitComparison(ComparisonExpression expression, object? argument) { if (expression.Right is TimeOffsetExpression timeOffset) { - DateTime currentTime = _systemClock.UtcNow.UtcDateTime; + DateTime utcNow = _timeProvider.GetUtcNow().UtcDateTime; var offsetComparison = new ComparisonExpression(timeOffset.Value < TimeSpan.Zero ? InverseComparisonOperatorTable[expression.Operator] : expression.Operator, - expression.Left, new LiteralConstantExpression(currentTime + timeOffset.Value)); + expression.Left, new LiteralConstantExpression(utcNow + timeOffset.Value)); ComparisonExpression? timeComparison = expression.Operator is ComparisonOperator.LessThan or ComparisonOperator.LessOrEqual ? new ComparisonExpression(timeOffset.Value < TimeSpan.Zero ? ComparisonOperator.LessOrEqual : ComparisonOperator.GreaterOrEqual, - expression.Left, new LiteralConstantExpression(currentTime)) + expression.Left, new LiteralConstantExpression(utcNow)) : null; return timeComparison == null ? offsetComparison : new LogicalExpression(LogicalOperator.And, offsetComparison, timeComparison); diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/TimeOffset/TimeOffsetExpression.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/TimeOffset/TimeOffsetExpression.cs index 1adf976257..8229276acd 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/TimeOffset/TimeOffsetExpression.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/TimeOffset/TimeOffsetExpression.cs @@ -1,5 +1,4 @@ using System.Text; -using JsonApiDotNetCore; using JsonApiDotNetCore.Queries.Expressions; namespace JsonApiDotNetCoreTests.IntegrationTests.QueryStrings.CustomFunctions.TimeOffset; @@ -34,7 +33,7 @@ internal sealed class TimeOffsetExpression : FunctionExpression public TimeOffsetExpression(LiteralConstantExpression timeSpanConstant) { - ArgumentGuard.NotNull(timeSpanConstant); + ArgumentNullException.ThrowIfNull(timeSpanConstant); if (timeSpanConstant.TypedValue is not TimeSpan timeSpan) { diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/TimeOffset/TimeOffsetTests.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/TimeOffset/TimeOffsetTests.cs index 6dffa5ef18..3cee32fe8b 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/TimeOffset/TimeOffsetTests.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/CustomFunctions/TimeOffset/TimeOffsetTests.cs @@ -1,6 +1,5 @@ using System.Net; using FluentAssertions; -using FluentAssertions.Extensions; using Humanizer; using JsonApiDotNetCore.Queries.Expressions; using JsonApiDotNetCore.Queries.Parsing; @@ -27,7 +26,6 @@ public TimeOffsetTests(IntegrationTestContext { services.AddTransient(); - services.AddSingleton(); services.AddScoped(typeof(IResourceDefinition<,>), typeof(FilterRewritingResourceDefinition<,>)); }); } @@ -46,16 +44,17 @@ public TimeOffsetTests(IntegrationTestContext(); + var timeProvider = _testContext.Factory.Services.GetRequiredService(); + DateTimeOffset utcNow = timeProvider.GetUtcNow(); List reminders = _fakers.Reminder.GenerateList(7); - reminders[0].RemindsAt = clock.UtcNow.Add(TimeSpan.FromMinutes(-15)).DateTime.AsUtc(); - reminders[1].RemindsAt = clock.UtcNow.Add(TimeSpan.FromMinutes(-10)).DateTime.AsUtc(); - reminders[2].RemindsAt = clock.UtcNow.Add(TimeSpan.FromMinutes(-5)).DateTime.AsUtc(); - reminders[3].RemindsAt = clock.UtcNow.Add(TimeSpan.FromMinutes(0)).DateTime.AsUtc(); - reminders[4].RemindsAt = clock.UtcNow.Add(TimeSpan.FromMinutes(5)).DateTime.AsUtc(); - reminders[5].RemindsAt = clock.UtcNow.Add(TimeSpan.FromMinutes(10)).DateTime.AsUtc(); - reminders[6].RemindsAt = clock.UtcNow.Add(TimeSpan.FromMinutes(15)).DateTime.AsUtc(); + reminders[0].RemindsAt = utcNow.Add(TimeSpan.FromMinutes(-15)).UtcDateTime; + reminders[1].RemindsAt = utcNow.Add(TimeSpan.FromMinutes(-10)).UtcDateTime; + reminders[2].RemindsAt = utcNow.Add(TimeSpan.FromMinutes(-5)).UtcDateTime; + reminders[3].RemindsAt = utcNow.Add(TimeSpan.FromMinutes(0)).UtcDateTime; + reminders[4].RemindsAt = utcNow.Add(TimeSpan.FromMinutes(5)).UtcDateTime; + reminders[5].RemindsAt = utcNow.Add(TimeSpan.FromMinutes(10)).UtcDateTime; + reminders[6].RemindsAt = utcNow.Add(TimeSpan.FromMinutes(15)).UtcDateTime; await _testContext.RunOnDatabaseAsync(async dbContext => { @@ -200,16 +199,17 @@ public async Task Cannot_filter_text_match_on_relative_time() public async Task Can_filter_comparison_on_relative_time_in_nested_expression() { // Arrange - var clock = _testContext.Factory.Services.GetRequiredService(); + var timeProvider = _testContext.Factory.Services.GetRequiredService(); + DateTimeOffset utcNow = timeProvider.GetUtcNow(); Calendar calendar = _fakers.Calendar.GenerateOne(); calendar.Appointments = _fakers.Appointment.GenerateSet(2); calendar.Appointments.ElementAt(0).Reminders = _fakers.Reminder.GenerateList(1); - calendar.Appointments.ElementAt(0).Reminders[0].RemindsAt = clock.UtcNow.DateTime.AsUtc(); + calendar.Appointments.ElementAt(0).Reminders[0].RemindsAt = utcNow.UtcDateTime; calendar.Appointments.ElementAt(1).Reminders = _fakers.Reminder.GenerateList(1); - calendar.Appointments.ElementAt(1).Reminders[0].RemindsAt = clock.UtcNow.Add(TimeSpan.FromMinutes(30)).DateTime.AsUtc(); + calendar.Appointments.ElementAt(1).Reminders[0].RemindsAt = utcNow.Add(TimeSpan.FromMinutes(30)).UtcDateTime; await _testContext.RunOnDatabaseAsync(async dbContext => { diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/SerializerIgnoreConditionTests.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/SerializerIgnoreConditionTests.cs index a0e770e555..89db819a2c 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/SerializerIgnoreConditionTests.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/QueryStrings/SerializerIgnoreConditionTests.cs @@ -32,7 +32,7 @@ public async Task Applies_configuration_for_ignore_condition(JsonIgnoreCondition Calendar calendar = _fakers.Calendar.GenerateOne(); calendar.TimeZone = null; - calendar.DefaultAppointmentDurationInMinutes = default; + calendar.DefaultAppointmentDurationInMinutes = 0; calendar.ShowWeekNumbers = true; calendar.MostRecentAppointment = _fakers.Appointment.GenerateOne(); calendar.MostRecentAppointment.Description = null; diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/ReadWrite/RgbColor.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/ReadWrite/RgbColor.cs index 8eeabbee1d..28762384c9 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/ReadWrite/RgbColor.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/ReadWrite/RgbColor.cs @@ -8,11 +8,6 @@ namespace JsonApiDotNetCoreTests.IntegrationTests.ReadWrite; [Resource(ControllerNamespace = "JsonApiDotNetCoreTests.IntegrationTests.ReadWrite")] public sealed class RgbColor : Identifiable { -#if NET6_0 - // Workaround for bug in .NET 6, see https://github.com/json-api-dotnet/JsonApiDotNetCore/issues/1153. - public override string? Id { get; set; } -#endif - [Attr] public string DisplayName { get; set; } = null!; diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/GiftCertificate.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/GiftCertificate.cs index 6a04e8a1ab..169df54e16 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/GiftCertificate.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/GiftCertificate.cs @@ -2,7 +2,6 @@ using JetBrains.Annotations; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; -using TestBuildingBlocks; namespace JsonApiDotNetCoreTests.IntegrationTests.ResourceConstructorInjection; @@ -10,14 +9,14 @@ namespace JsonApiDotNetCoreTests.IntegrationTests.ResourceConstructorInjection; [Resource(ControllerNamespace = "JsonApiDotNetCoreTests.IntegrationTests.ResourceConstructorInjection")] public sealed class GiftCertificate(InjectionDbContext injectionDbContext) : Identifiable { - private readonly ISystemClock _systemClock = injectionDbContext.SystemClock; + private readonly TimeProvider _timeProvider = injectionDbContext.TimeProvider; [Attr] public DateTimeOffset IssueDate { get; set; } [Attr(Capabilities = AttrCapabilities.AllowView)] [NotMapped] - public bool HasExpired => IssueDate.AddYears(1) < _systemClock.UtcNow; + public bool HasExpired => IssueDate.AddYears(1) < _timeProvider.GetUtcNow(); [HasOne] public PostOffice? Issuer { get; set; } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/InjectionDbContext.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/InjectionDbContext.cs index 57ec534cae..9c89882a74 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/InjectionDbContext.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/InjectionDbContext.cs @@ -1,5 +1,4 @@ using JetBrains.Annotations; -using JsonApiDotNetCore; using Microsoft.EntityFrameworkCore; using TestBuildingBlocks; @@ -8,16 +7,16 @@ namespace JsonApiDotNetCoreTests.IntegrationTests.ResourceConstructorInjection; [UsedImplicitly(ImplicitUseTargetFlags.Members)] public sealed class InjectionDbContext : TestableDbContext { - public ISystemClock SystemClock { get; } + public TimeProvider TimeProvider { get; } public DbSet PostOffices => Set(); public DbSet GiftCertificates => Set(); - public InjectionDbContext(DbContextOptions options, ISystemClock systemClock) + public InjectionDbContext(DbContextOptions options, TimeProvider timeProvider) : base(options) { - ArgumentGuard.NotNull(systemClock); + ArgumentNullException.ThrowIfNull(timeProvider); - SystemClock = systemClock; + TimeProvider = timeProvider; } } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/InjectionFakers.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/InjectionFakers.cs index 28c7d28dd7..fc6cda269a 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/InjectionFakers.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/InjectionFakers.cs @@ -1,5 +1,4 @@ using Bogus; -using JsonApiDotNetCore; using Microsoft.Extensions.DependencyInjection; using TestBuildingBlocks; @@ -20,17 +19,20 @@ internal sealed class InjectionFakers public InjectionFakers(IServiceProvider serviceProvider) { - ArgumentGuard.NotNull(serviceProvider); + ArgumentNullException.ThrowIfNull(serviceProvider); _serviceProvider = serviceProvider; + var timeProvider = serviceProvider.GetRequiredService(); + DateTime systemTimeUtc = timeProvider.GetUtcNow().UtcDateTime; + _lazyPostOfficeFaker = new Lazy>(() => new Faker() - .MakeDeterministic() + .MakeDeterministic(systemTimeUtc) .CustomInstantiator(_ => new PostOffice(ResolveDbContext())) .RuleFor(postOffice => postOffice.Address, faker => faker.Address.FullAddress())); _lazyGiftCertificateFaker = new Lazy>(() => new Faker() - .MakeDeterministic() + .MakeDeterministic(systemTimeUtc) .CustomInstantiator(_ => new GiftCertificate(ResolveDbContext())) .RuleFor(giftCertificate => giftCertificate.IssueDate, faker => faker.Date.PastOffset().TruncateToWholeMilliseconds())); } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/PostOffice.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/PostOffice.cs index 86658bb9d7..129efabe9f 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/PostOffice.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/PostOffice.cs @@ -2,7 +2,6 @@ using JetBrains.Annotations; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; -using TestBuildingBlocks; namespace JsonApiDotNetCoreTests.IntegrationTests.ResourceConstructorInjection; @@ -10,7 +9,7 @@ namespace JsonApiDotNetCoreTests.IntegrationTests.ResourceConstructorInjection; [Resource(ControllerNamespace = "JsonApiDotNetCoreTests.IntegrationTests.ResourceConstructorInjection")] public sealed class PostOffice(InjectionDbContext injectionDbContext) : Identifiable { - private readonly ISystemClock _systemClock = injectionDbContext.SystemClock; + private readonly TimeProvider _timeProvider = injectionDbContext.TimeProvider; [Attr] public string Address { get; set; } = null!; @@ -24,7 +23,7 @@ public sealed class PostOffice(InjectionDbContext injectionDbContext) : Identifi private bool IsWithinOperatingHours() { - DateTimeOffset currentTime = _systemClock.UtcNow; - return currentTime.DayOfWeek is >= DayOfWeek.Monday and <= DayOfWeek.Friday && currentTime.Hour is >= 9 and <= 17; + DateTimeOffset utcNow = _timeProvider.GetUtcNow(); + return utcNow.DayOfWeek is >= DayOfWeek.Monday and <= DayOfWeek.Friday && utcNow.Hour is >= 9 and <= 17; } } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/ResourceInjectionTests.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/ResourceInjectionTests.cs index 1dc86eeb1a..4163a0bade 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/ResourceInjectionTests.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceConstructorInjection/ResourceInjectionTests.cs @@ -4,6 +4,7 @@ using JsonApiDotNetCore.Serialization.Objects; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using TestBuildingBlocks; using Xunit; @@ -11,6 +12,10 @@ namespace JsonApiDotNetCoreTests.IntegrationTests.ResourceConstructorInjection; public sealed class ResourceInjectionTests : IClassFixture, InjectionDbContext>> { + private static readonly DateTimeOffset CurrentTime = 31.January(2021).At(17, 1).AsUtc(); + private static readonly DateTimeOffset OfficeIsOpenTime = 27.January(2021).At(13, 53).AsUtc(); + private static readonly DateTimeOffset OfficeIsClosedTime = 30.January(2021).At(21, 43).AsUtc(); + private readonly IntegrationTestContext, InjectionDbContext> _testContext; private readonly InjectionFakers _fakers; @@ -21,7 +26,10 @@ public ResourceInjectionTests(IntegrationTestContext(); testContext.UseController(); - testContext.ConfigureServices(services => services.AddSingleton()); + testContext.PostConfigureServices(services => services.Replace(ServiceDescriptor.Singleton(new FrozenTimeProvider(CurrentTime)))); + + var timeProvider = (FrozenTimeProvider)testContext.Factory.Services.GetRequiredService(); + timeProvider.Reset(); _fakers = new InjectionFakers(testContext.Factory.Services); } @@ -30,11 +38,8 @@ public ResourceInjectionTests(IntegrationTestContext(); - clock.UtcNow = 27.January(2021).AsUtc(); - GiftCertificate certificate = _fakers.GiftCertificate.GenerateOne(); - certificate.IssueDate = 28.January(2020).AsUtc(); + certificate.IssueDate = CurrentTime.AddYears(-1).AddDays(1).UtcDateTime; await _testContext.RunOnDatabaseAsync(async dbContext => { @@ -60,8 +65,8 @@ await _testContext.RunOnDatabaseAsync(async dbContext => public async Task Can_filter_resources_by_ID() { // Arrange - var clock = (FrozenSystemClock)_testContext.Factory.Services.GetRequiredService(); - clock.UtcNow = 27.January(2021).At(13, 53).AsUtc(); + var timeProvider = (FrozenTimeProvider)_testContext.Factory.Services.GetRequiredService(); + timeProvider.SetUtcNow(OfficeIsOpenTime); List postOffices = _fakers.PostOffice.GenerateList(2); @@ -90,8 +95,8 @@ await _testContext.RunOnDatabaseAsync(async dbContext => public async Task Can_get_secondary_resource_with_fieldset() { // Arrange - var clock = (FrozenSystemClock)_testContext.Factory.Services.GetRequiredService(); - clock.UtcNow = 27.January(2021).At(13, 53).AsUtc(); + var timeProvider = (FrozenTimeProvider)_testContext.Factory.Services.GetRequiredService(); + timeProvider.SetUtcNow(OfficeIsOpenTime); GiftCertificate certificate = _fakers.GiftCertificate.GenerateOne(); certificate.Issuer = _fakers.PostOffice.GenerateOne(); @@ -120,12 +125,12 @@ await _testContext.RunOnDatabaseAsync(async dbContext => public async Task Can_create_resource_with_ToOne_relationship_and_include() { // Arrange - var clock = (FrozenSystemClock)_testContext.Factory.Services.GetRequiredService(); - clock.UtcNow = 19.March(1998).At(6, 34).AsUtc(); + var timeProvider = (FrozenTimeProvider)_testContext.Factory.Services.GetRequiredService(); + timeProvider.SetUtcNow(OfficeIsClosedTime); PostOffice existingOffice = _fakers.PostOffice.GenerateOne(); - DateTimeOffset newIssueDate = 18.March(1997).AsUtc(); + DateTimeOffset newIssueDate = OfficeIsClosedTime.AddYears(-1).AddDays(-1).UtcDateTime; await _testContext.RunOnDatabaseAsync(async dbContext => { @@ -202,8 +207,8 @@ await _testContext.RunOnDatabaseAsync(async dbContext => public async Task Can_update_resource_with_ToMany_relationship() { // Arrange - var clock = (FrozenSystemClock)_testContext.Factory.Services.GetRequiredService(); - clock.UtcNow = 19.March(1998).At(6, 34).AsUtc(); + var timeProvider = (FrozenTimeProvider)_testContext.Factory.Services.GetRequiredService(); + timeProvider.SetUtcNow(OfficeIsClosedTime); PostOffice existingOffice = _fakers.PostOffice.GenerateOne(); existingOffice.GiftCertificates = _fakers.GiftCertificate.GenerateList(1); diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceInheritance/ResourceTypeCapturingDefinition.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceInheritance/ResourceTypeCapturingDefinition.cs index bae85f8754..c12cf527b2 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceInheritance/ResourceTypeCapturingDefinition.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceInheritance/ResourceTypeCapturingDefinition.cs @@ -1,5 +1,4 @@ using JetBrains.Annotations; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Middleware; using JsonApiDotNetCore.Resources; @@ -20,8 +19,8 @@ public sealed class ResourceTypeCapturingDefinition : JsonApiRes public ResourceTypeCapturingDefinition(IResourceGraph resourceGraph, IJsonApiRequest request, ResourceTypeCaptureStore captureStore) : base(resourceGraph) { - ArgumentGuard.NotNull(request); - ArgumentGuard.NotNull(captureStore); + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(captureStore); _request = request; _captureStore = captureStore; diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceInheritance/WheelSortDefinition.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceInheritance/WheelSortDefinition.cs index 7785622e9e..98b3e0cdaa 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceInheritance/WheelSortDefinition.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/ResourceInheritance/WheelSortDefinition.cs @@ -1,7 +1,6 @@ using System.Collections.Immutable; using System.ComponentModel; using JetBrains.Annotations; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Queries.Expressions; using JsonApiDotNetCore.Resources; @@ -19,7 +18,7 @@ public sealed class WheelSortDefinition : JsonApiResourceDefinition public WheelSortDefinition(IResourceGraph resourceGraph, IHttpContextAccessor httpContextAccessor) : base(resourceGraph) { - ArgumentGuard.NotNull(httpContextAccessor); + ArgumentNullException.ThrowIfNull(httpContextAccessor); _httpContextAccessor = httpContextAccessor; } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/SoftDeletion/SoftDeletionAwareResourceService.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/SoftDeletion/SoftDeletionAwareResourceService.cs index 8f1ce719e8..ce64b677ee 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/SoftDeletion/SoftDeletionAwareResourceService.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/SoftDeletion/SoftDeletionAwareResourceService.cs @@ -7,20 +7,19 @@ using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Services; using Microsoft.Extensions.Logging; -using TestBuildingBlocks; namespace JsonApiDotNetCoreTests.IntegrationTests.SoftDeletion; [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] public class SoftDeletionAwareResourceService( - ISystemClock systemClock, ITargetedFields targetedFields, IResourceRepositoryAccessor repositoryAccessor, IQueryLayerComposer queryLayerComposer, + TimeProvider timeProvider, ITargetedFields targetedFields, IResourceRepositoryAccessor repositoryAccessor, IQueryLayerComposer queryLayerComposer, IPaginationContext paginationContext, IJsonApiOptions options, ILoggerFactory loggerFactory, IJsonApiRequest request, IResourceChangeTracker resourceChangeTracker, IResourceDefinitionAccessor resourceDefinitionAccessor) : JsonApiResourceService(repositoryAccessor, queryLayerComposer, paginationContext, options, loggerFactory, request, resourceChangeTracker, resourceDefinitionAccessor) where TResource : class, IIdentifiable { - private readonly ISystemClock _systemClock = systemClock; + private readonly TimeProvider _timeProvider = timeProvider; private readonly ITargetedFields _targetedFields = targetedFields; private readonly IResourceRepositoryAccessor _repositoryAccessor = repositoryAccessor; private readonly IJsonApiRequest _request = request; @@ -90,7 +89,7 @@ private async Task SoftDeleteAsync([DisallowNull] TId id, CancellationToken canc { TResource resourceFromDatabase = await GetPrimaryResourceForUpdateAsync(id, cancellationToken); - ((ISoftDeletable)resourceFromDatabase).SoftDeletedAt = _systemClock.UtcNow; + ((ISoftDeletable)resourceFromDatabase).SoftDeletedAt = _timeProvider.GetUtcNow(); // A delete operation does not target any fields, so we can just pass resourceFromDatabase twice. await _repositoryAccessor.UpdateAsync(resourceFromDatabase, resourceFromDatabase, cancellationToken); diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/SoftDeletion/SoftDeletionFakers.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/SoftDeletion/SoftDeletionFakers.cs index 1cbf435c45..aa25cae9d2 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/SoftDeletion/SoftDeletionFakers.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/SoftDeletion/SoftDeletionFakers.cs @@ -8,14 +8,23 @@ namespace JsonApiDotNetCoreTests.IntegrationTests.SoftDeletion; internal sealed class SoftDeletionFakers { - private readonly Lazy> _lazyCompanyFaker = new(() => new Faker() - .MakeDeterministic() - .RuleFor(company => company.Name, faker => faker.Company.CompanyName())); + private readonly Lazy> _lazyCompanyFaker; - private readonly Lazy> _lazyDepartmentFaker = new(() => new Faker() - .MakeDeterministic() - .RuleFor(department => department.Name, faker => faker.Commerce.Department())); + private readonly Lazy> _lazyDepartmentFaker; public Faker Company => _lazyCompanyFaker.Value; public Faker Department => _lazyDepartmentFaker.Value; + + public SoftDeletionFakers(DateTimeOffset systemTime) + { + DateTime systemTimeUtc = systemTime.UtcDateTime; + + _lazyCompanyFaker = new Lazy>(() => new Faker() + .MakeDeterministic(systemTimeUtc) + .RuleFor(company => company.Name, faker => faker.Company.CompanyName())); + + _lazyDepartmentFaker = new Lazy>(() => new Faker() + .MakeDeterministic(systemTimeUtc) + .RuleFor(department => department.Name, faker => faker.Commerce.Department())); + } } diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/SoftDeletion/SoftDeletionTests.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/SoftDeletion/SoftDeletionTests.cs index 9de187d493..d8c10f2d1e 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/SoftDeletion/SoftDeletionTests.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/SoftDeletion/SoftDeletionTests.cs @@ -5,6 +5,7 @@ using JsonApiDotNetCore.Serialization.Objects; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using TestBuildingBlocks; using Xunit; @@ -12,10 +13,11 @@ namespace JsonApiDotNetCoreTests.IntegrationTests.SoftDeletion; public sealed class SoftDeletionTests : IClassFixture, SoftDeletionDbContext>> { + private static readonly DateTimeOffset CurrentTime = 1.January(2005).AsUtc(); private static readonly DateTimeOffset SoftDeletionTime = 1.January(2001).AsUtc(); private readonly IntegrationTestContext, SoftDeletionDbContext> _testContext; - private readonly SoftDeletionFakers _fakers = new(); + private readonly SoftDeletionFakers _fakers = new(CurrentTime); public SoftDeletionTests(IntegrationTestContext, SoftDeletionDbContext> testContext) { @@ -28,12 +30,12 @@ public SoftDeletionTests(IntegrationTestContext>(); services.AddResourceService>(); - - services.AddSingleton(new FrozenSystemClock - { - UtcNow = 1.January(2005).AsUtc() - }); }); + + testContext.PostConfigureServices(services => services.Replace(ServiceDescriptor.Singleton(new FrozenTimeProvider(CurrentTime)))); + + var timeProvider = (FrozenTimeProvider)testContext.Factory.Services.GetRequiredService(); + timeProvider.Reset(); } [Fact] diff --git a/test/JsonApiDotNetCoreTests/IntegrationTests/ZeroKeys/WhiteSpaceAsKeyTests.cs b/test/JsonApiDotNetCoreTests/IntegrationTests/ZeroKeys/WhiteSpaceAsKeyTests.cs index 9e47b3e6ce..249026e82d 100644 --- a/test/JsonApiDotNetCoreTests/IntegrationTests/ZeroKeys/WhiteSpaceAsKeyTests.cs +++ b/test/JsonApiDotNetCoreTests/IntegrationTests/ZeroKeys/WhiteSpaceAsKeyTests.cs @@ -1,7 +1,6 @@ using System.Net; using System.Reflection; using FluentAssertions; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.AspNetCore.Mvc.ModelBinding; @@ -604,7 +603,7 @@ private sealed class PreserveWhitespaceModelMetadataProvider : ModelMetadataProv public PreserveWhitespaceModelMetadataProvider(ModelMetadataProvider innerProvider) { - ArgumentGuard.NotNull(innerProvider); + ArgumentNullException.ThrowIfNull(innerProvider); _innerProvider = innerProvider; } diff --git a/test/JsonApiDotNetCoreTests/JsonApiDotNetCoreTests.csproj b/test/JsonApiDotNetCoreTests/JsonApiDotNetCoreTests.csproj index 38d665aa5b..6bc5a666a1 100644 --- a/test/JsonApiDotNetCoreTests/JsonApiDotNetCoreTests.csproj +++ b/test/JsonApiDotNetCoreTests/JsonApiDotNetCoreTests.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net9.0;net8.0 @@ -13,7 +13,6 @@ - diff --git a/test/JsonApiDotNetCoreTests/UnitTests/Configuration/DependencyContainerRegistrationTests.cs b/test/JsonApiDotNetCoreTests/UnitTests/Configuration/DependencyContainerRegistrationTests.cs index 1249cd5dfa..1bf13394b5 100644 --- a/test/JsonApiDotNetCoreTests/UnitTests/Configuration/DependencyContainerRegistrationTests.cs +++ b/test/JsonApiDotNetCoreTests/UnitTests/Configuration/DependencyContainerRegistrationTests.cs @@ -1,6 +1,5 @@ using FluentAssertions; using JetBrains.Annotations; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Controllers.Annotations; using JsonApiDotNetCore.Queries; @@ -148,7 +147,7 @@ private sealed class SomeSingletonService // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local public SomeSingletonService(SomeScopedService scopedService) { - ArgumentGuard.NotNull(scopedService); + ArgumentNullException.ThrowIfNull(scopedService); } } @@ -161,7 +160,7 @@ private sealed class CircularServiceA // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local public CircularServiceA(CircularServiceB serviceB) { - ArgumentGuard.NotNull(serviceB); + ArgumentNullException.ThrowIfNull(serviceB); } } @@ -171,7 +170,7 @@ private sealed class CircularServiceB // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local public CircularServiceB(CircularServiceA serviceA) { - ArgumentGuard.NotNull(serviceA); + ArgumentNullException.ThrowIfNull(serviceA); } } diff --git a/test/JsonApiDotNetCoreTests/UnitTests/Controllers/DefaultOperationFilterTests.cs b/test/JsonApiDotNetCoreTests/UnitTests/Controllers/DefaultOperationFilterTests.cs index d977518940..66560fdf7b 100644 --- a/test/JsonApiDotNetCoreTests/UnitTests/Controllers/DefaultOperationFilterTests.cs +++ b/test/JsonApiDotNetCoreTests/UnitTests/Controllers/DefaultOperationFilterTests.cs @@ -1,6 +1,5 @@ using FluentAssertions; using JetBrains.Annotations; -using JsonApiDotNetCore; using JsonApiDotNetCore.AtomicOperations; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Controllers; @@ -85,7 +84,7 @@ private sealed class FakeOperationFilter : DefaultOperationFilter public FakeOperationFilter(Func isResourceTypeEnabled) { - ArgumentGuard.NotNull(isResourceTypeEnabled); + ArgumentNullException.ThrowIfNull(isResourceTypeEnabled); _isResourceTypeEnabled = isResourceTypeEnabled; } diff --git a/test/JsonApiDotNetCoreTests/UnitTests/Serialization/Extensions/ResourceObjectConverterTests.cs b/test/JsonApiDotNetCoreTests/UnitTests/Serialization/Extensions/ResourceObjectConverterTests.cs index f87ded5c1b..266874cdf9 100644 --- a/test/JsonApiDotNetCoreTests/UnitTests/Serialization/Extensions/ResourceObjectConverterTests.cs +++ b/test/JsonApiDotNetCoreTests/UnitTests/Serialization/Extensions/ResourceObjectConverterTests.cs @@ -2,7 +2,6 @@ using System.Text.Json; using FluentAssertions; using JetBrains.Annotations; -using JsonApiDotNetCore; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Middleware; using JsonApiDotNetCore.Resources; @@ -411,8 +410,8 @@ private sealed class ExtensionAwareResourceObjectConverter : ResourceObjectConve public ExtensionAwareResourceObjectConverter(IResourceGraph resourceGraph, JsonApiRequestAccessor requestAccessor) : base(resourceGraph) { - ArgumentGuard.NotNull(resourceGraph); - ArgumentGuard.NotNull(requestAccessor); + ArgumentNullException.ThrowIfNull(resourceGraph); + ArgumentNullException.ThrowIfNull(requestAccessor); _resourceGraph = resourceGraph; _requestAccessor = requestAccessor; @@ -478,7 +477,7 @@ private sealed class JsonApiRequestAccessor public JsonApiRequestAccessor(IJsonApiRequest request) { - ArgumentGuard.NotNull(request); + ArgumentNullException.ThrowIfNull(request); Request = request; } diff --git a/test/JsonApiDotNetCoreTests/UnitTests/Serialization/InputConversionTests.cs b/test/JsonApiDotNetCoreTests/UnitTests/Serialization/InputConversionTests.cs index 37307b1ab5..68b49ef7b8 100644 --- a/test/JsonApiDotNetCoreTests/UnitTests/Serialization/InputConversionTests.cs +++ b/test/JsonApiDotNetCoreTests/UnitTests/Serialization/InputConversionTests.cs @@ -153,26 +153,26 @@ public void Converts_various_data_types_with_defaults() WriteOperation = WriteOperationKind.CreateResource }); - const bool booleanValue = default; - const bool nullableBooleanValue = default; - const char charValue = default; - const char nullableCharValue = default; - const ulong unsignedLongValue = default; - const ulong nullableUnsignedLongValue = default; - const decimal decimalValue = default; - const decimal nullableDecimalValue = default; - const float floatValue = default; - const float nullableFloatValue = default; - const string stringValue = default!; - const string? nullableStringValue = default; - Guid guidValue = default; - Guid nullableGuidValue = default; + const bool booleanValue = false; + const bool nullableBooleanValue = false; + const char charValue = '\0'; + const char nullableCharValue = '\0'; + const ulong unsignedLongValue = 0; + const ulong nullableUnsignedLongValue = 0; + const decimal decimalValue = 0; + const decimal nullableDecimalValue = 0; + const float floatValue = 0; + const float nullableFloatValue = 0; + const string stringValue = null!; + const string? nullableStringValue = null; + var guidValue = Guid.Empty; + var nullableGuidValue = Guid.Empty; DateTime dateTimeValue = default; DateTime nullableDateTimeValue = default; DateTimeOffset dateTimeOffsetValue = default; DateTimeOffset nullableDateTimeOffsetValue = default; - TimeSpan timeSpanValue = default; - TimeSpan nullableTimeSpanValue = default; + TimeSpan timeSpanValue = TimeSpan.Zero; + TimeSpan nullableTimeSpanValue = TimeSpan.Zero; const DayOfWeek enumValue = default; const DayOfWeek nullableEnumValue = default; diff --git a/test/JsonApiDotNetCoreTests/UnitTests/TypeConversion/RuntimeTypeConverterTests.cs b/test/JsonApiDotNetCoreTests/UnitTests/TypeConversion/RuntimeTypeConverterTests.cs index 1263912faf..c7b0bf9450 100644 --- a/test/JsonApiDotNetCoreTests/UnitTests/TypeConversion/RuntimeTypeConverterTests.cs +++ b/test/JsonApiDotNetCoreTests/UnitTests/TypeConversion/RuntimeTypeConverterTests.cs @@ -109,29 +109,29 @@ public void Returns_same_instance_for_interface() } [Theory] - [InlineData(typeof(bool), default(bool))] + [InlineData(typeof(bool), false)] [InlineData(typeof(bool?), null)] - [InlineData(typeof(byte), default(byte))] + [InlineData(typeof(byte), 0)] [InlineData(typeof(byte?), null)] - [InlineData(typeof(sbyte), default(sbyte))] + [InlineData(typeof(sbyte), 0)] [InlineData(typeof(sbyte?), null)] - [InlineData(typeof(char), default(char))] + [InlineData(typeof(char), '\0')] [InlineData(typeof(char?), null)] - [InlineData(typeof(short), default(short))] + [InlineData(typeof(short), 0)] [InlineData(typeof(short?), null)] - [InlineData(typeof(ushort), default(ushort))] + [InlineData(typeof(ushort), 0)] [InlineData(typeof(ushort?), null)] - [InlineData(typeof(int), default(int))] + [InlineData(typeof(int), 0)] [InlineData(typeof(int?), null)] - [InlineData(typeof(uint), default(uint))] + [InlineData(typeof(uint), 0)] [InlineData(typeof(uint?), null)] - [InlineData(typeof(long), default(long))] + [InlineData(typeof(long), 0)] [InlineData(typeof(long?), null)] - [InlineData(typeof(ulong), default(ulong))] + [InlineData(typeof(ulong), 0)] [InlineData(typeof(ulong?), null)] - [InlineData(typeof(float), default(float))] + [InlineData(typeof(float), 0)] [InlineData(typeof(float?), null)] - [InlineData(typeof(double), default(double))] + [InlineData(typeof(double), 0)] [InlineData(typeof(double?), null)] [InlineData(typeof(decimal), 0)] [InlineData(typeof(decimal?), null)] diff --git a/test/MultiDbContextTests/MultiDbContextTests.csproj b/test/MultiDbContextTests/MultiDbContextTests.csproj index 54497bfada..e80f03c69e 100644 --- a/test/MultiDbContextTests/MultiDbContextTests.csproj +++ b/test/MultiDbContextTests/MultiDbContextTests.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net9.0;net8.0 diff --git a/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj b/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj index 080666d491..4deb6b21cd 100644 --- a/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj +++ b/test/NoEntityFrameworkTests/NoEntityFrameworkTests.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net9.0;net8.0 diff --git a/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicCreateResourceTests.cs b/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicCreateResourceTests.cs index dd8866d0d3..e36fcf1a58 100644 --- a/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicCreateResourceTests.cs +++ b/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicCreateResourceTests.cs @@ -1,5 +1,4 @@ using FluentAssertions; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Kiota.Abstractions; using Microsoft.Kiota.Http.HttpClientLibrary; using OpenApiKiotaEndToEndTests.AtomicOperations.GeneratedCode; @@ -26,8 +25,6 @@ public AtomicCreateResourceTests(IntegrationTestContext(); - testContext.ConfigureServices(services => services.AddSingleton()); - _fakers = new OperationsFakers(testContext.Factory.Services); } diff --git a/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicDeleteResourceTests.cs b/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicDeleteResourceTests.cs index fc4d5e96fe..31961ef38c 100644 --- a/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicDeleteResourceTests.cs +++ b/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicDeleteResourceTests.cs @@ -1,5 +1,4 @@ using FluentAssertions; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Kiota.Http.HttpClientLibrary; using OpenApiKiotaEndToEndTests.AtomicOperations.GeneratedCode; using OpenApiKiotaEndToEndTests.AtomicOperations.GeneratedCode.Models; @@ -25,8 +24,6 @@ public AtomicDeleteResourceTests(IntegrationTestContext(); - testContext.ConfigureServices(services => services.AddSingleton()); - _fakers = new OperationsFakers(testContext.Factory.Services); } diff --git a/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicLocalIdTests.cs b/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicLocalIdTests.cs index 0a5e87ba64..1f0bb873d3 100644 --- a/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicLocalIdTests.cs +++ b/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicLocalIdTests.cs @@ -1,6 +1,5 @@ using FluentAssertions; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Kiota.Abstractions; using Microsoft.Kiota.Http.HttpClientLibrary; using OpenApiKiotaEndToEndTests.AtomicOperations.GeneratedCode; @@ -26,8 +25,6 @@ public AtomicLocalIdTests(IntegrationTestContext(); - testContext.ConfigureServices(services => services.AddSingleton()); - _fakers = new OperationsFakers(testContext.Factory.Services); } diff --git a/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicRelationshipTests.cs b/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicRelationshipTests.cs index a0e6c2756d..34b8ee8807 100644 --- a/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicRelationshipTests.cs +++ b/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicRelationshipTests.cs @@ -1,6 +1,5 @@ using FluentAssertions; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Kiota.Http.HttpClientLibrary; using OpenApiKiotaEndToEndTests.AtomicOperations.GeneratedCode; using OpenApiKiotaEndToEndTests.AtomicOperations.GeneratedCode.Models; @@ -26,8 +25,6 @@ public AtomicRelationshipTests(IntegrationTestContext(); - testContext.ConfigureServices(services => services.AddSingleton()); - _fakers = new OperationsFakers(testContext.Factory.Services); } diff --git a/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicUpdateResourceTests.cs b/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicUpdateResourceTests.cs index bd6a1c0400..83a40dd3de 100644 --- a/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicUpdateResourceTests.cs +++ b/test/OpenApiKiotaEndToEndTests/AtomicOperations/AtomicUpdateResourceTests.cs @@ -28,11 +28,7 @@ public AtomicUpdateResourceTests(IntegrationTestContext(); - testContext.ConfigureServices(services => - { - services.AddSingleton(); - services.AddScoped(typeof(IResourceChangeTracker<>), typeof(NeverSameResourceChangeTracker<>)); - }); + testContext.ConfigureServices(services => services.AddScoped(typeof(IResourceChangeTracker<>), typeof(NeverSameResourceChangeTracker<>))); _fakers = new OperationsFakers(testContext.Factory.Services); } diff --git a/test/OpenApiKiotaEndToEndTests/OpenApiKiotaEndToEndTests.csproj b/test/OpenApiKiotaEndToEndTests/OpenApiKiotaEndToEndTests.csproj index 5370723e4f..d70baa4441 100644 --- a/test/OpenApiKiotaEndToEndTests/OpenApiKiotaEndToEndTests.csproj +++ b/test/OpenApiKiotaEndToEndTests/OpenApiKiotaEndToEndTests.csproj @@ -1,6 +1,6 @@ - net8.0 + net9.0 @@ -25,6 +25,10 @@ + + + + @@ -40,7 +44,7 @@ + Command="dotnet kiota generate --language CSharp --class-name ModelStateValidationClient --namespace-name OpenApiKiotaEndToEndTests.ModelStateValidation.GeneratedCode --output ./ModelStateValidation/GeneratedCode --backing-store --exclude-backward-compatible --clean-output --clear-cache --log-level Error --openapi ../OpenApiTests/ModelStateValidation/GeneratedSwagger/swagger.g.json" /> (T source, string propertyName) where T : class { - ArgumentGuard.NotNull(source); - ArgumentGuard.NotNull(propertyName); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(propertyName); PropertyInfo property = GetExistingProperty(typeof(T), propertyName); @@ -44,8 +43,8 @@ public abstract class BaseOpenApiNSwagClientTests protected static void SetPropertyToInitialValue(T source, string propertyName) where T : class, new() { - ArgumentGuard.NotNull(source); - ArgumentGuard.NotNull(propertyName); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(propertyName); var emptyRelationshipsObject = new T(); object? defaultValue = emptyRelationshipsObject.GetPropertyValue(propertyName); @@ -59,8 +58,8 @@ protected static void SetPropertyToInitialValue(T source, string propertyName protected static void SetDataPropertyToNull(T source, string relationshipPropertyName) where T : class { - ArgumentGuard.NotNull(source); - ArgumentGuard.NotNull(relationshipPropertyName); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(relationshipPropertyName); PropertyInfo relationshipProperty = GetExistingProperty(typeof(T), relationshipPropertyName); object? relationshipValue = relationshipProperty.GetValue(source); diff --git a/test/OpenApiNSwagClientTests/FakeHttpClientWrapper.cs b/test/OpenApiNSwagClientTests/FakeHttpClientWrapper.cs index 4da95f8f9b..353933e630 100644 --- a/test/OpenApiNSwagClientTests/FakeHttpClientWrapper.cs +++ b/test/OpenApiNSwagClientTests/FakeHttpClientWrapper.cs @@ -3,7 +3,6 @@ using System.Text; using System.Text.Json; using JsonApiDotNetCore.Middleware; -using JsonApiDotNetCore.OpenApi.Client.NSwag; namespace OpenApiNSwagClientTests; @@ -86,7 +85,7 @@ private sealed class FakeHttpMessageHandler(HttpResponseMessage response) : Http public void SetResponse(HttpResponseMessage response) { - ArgumentGuard.NotNull(response); + ArgumentNullException.ThrowIfNull(response); _response = response; } diff --git a/test/OpenApiNSwagClientTests/FakerFactory.cs b/test/OpenApiNSwagClientTests/FakerFactory.cs index c0b38326f5..024dd92287 100644 --- a/test/OpenApiNSwagClientTests/FakerFactory.cs +++ b/test/OpenApiNSwagClientTests/FakerFactory.cs @@ -23,7 +23,7 @@ private static AutoFaker GetDeterministicFaker() where TTarget : class { var autoFaker = new AutoFaker(); - autoFaker.UseDateTimeReference(FrozenSystemClock.DefaultDateTimeUtc); + autoFaker.UseDateTimeReference(IntegrationTest.DefaultDateTimeUtc.UtcDateTime); autoFaker.UseSeed(FakerExtensions.GetFakerSeed()); return autoFaker; } diff --git a/test/OpenApiNSwagClientTests/ObjectExtensions.cs b/test/OpenApiNSwagClientTests/ObjectExtensions.cs index fe6fb60da5..6be27b4e3b 100644 --- a/test/OpenApiNSwagClientTests/ObjectExtensions.cs +++ b/test/OpenApiNSwagClientTests/ObjectExtensions.cs @@ -1,5 +1,4 @@ using System.Reflection; -using JsonApiDotNetCore.OpenApi.Client.NSwag; namespace OpenApiNSwagClientTests; @@ -7,8 +6,8 @@ internal static class ObjectExtensions { public static object? GetPropertyValue(this object source, string propertyName) { - ArgumentGuard.NotNull(source); - ArgumentGuard.NotNull(propertyName); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(propertyName); PropertyInfo propertyInfo = GetExistingProperty(source.GetType(), propertyName); return propertyInfo.GetValue(source); @@ -16,8 +15,8 @@ internal static class ObjectExtensions public static void SetPropertyValue(this object source, string propertyName, object? value) { - ArgumentGuard.NotNull(source); - ArgumentGuard.NotNull(propertyName); + ArgumentNullException.ThrowIfNull(source); + ArgumentNullException.ThrowIfNull(propertyName); PropertyInfo propertyInfo = GetExistingProperty(source.GetType(), propertyName); propertyInfo.SetValue(source, value); diff --git a/test/OpenApiNSwagClientTests/OpenApiNSwagClientTests.csproj b/test/OpenApiNSwagClientTests/OpenApiNSwagClientTests.csproj index 6c5951e1d8..35a6ae73ff 100644 --- a/test/OpenApiNSwagClientTests/OpenApiNSwagClientTests.csproj +++ b/test/OpenApiNSwagClientTests/OpenApiNSwagClientTests.csproj @@ -1,7 +1,7 @@ - net8.0 + net9.0 diff --git a/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicCreateResourceTests.cs b/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicCreateResourceTests.cs index bf419f7ffe..8ff2a49913 100644 --- a/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicCreateResourceTests.cs +++ b/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicCreateResourceTests.cs @@ -1,6 +1,5 @@ using FluentAssertions; using JsonApiDotNetCore.OpenApi.Client.NSwag; -using Microsoft.Extensions.DependencyInjection; using OpenApiNSwagEndToEndTests.AtomicOperations.GeneratedCode; using OpenApiTests; using OpenApiTests.AtomicOperations; @@ -25,8 +24,6 @@ public AtomicCreateResourceTests(IntegrationTestContext(); - testContext.ConfigureServices(services => services.AddSingleton()); - _fakers = new OperationsFakers(testContext.Factory.Services); } diff --git a/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicDeleteResourceTests.cs b/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicDeleteResourceTests.cs index 9d99cd4f82..d183c464aa 100644 --- a/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicDeleteResourceTests.cs +++ b/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicDeleteResourceTests.cs @@ -1,6 +1,5 @@ using FluentAssertions; using JsonApiDotNetCore.OpenApi.Client.NSwag; -using Microsoft.Extensions.DependencyInjection; using OpenApiNSwagEndToEndTests.AtomicOperations.GeneratedCode; using OpenApiTests; using OpenApiTests.AtomicOperations; @@ -24,8 +23,6 @@ public AtomicDeleteResourceTests(IntegrationTestContext(); - testContext.ConfigureServices(services => services.AddSingleton()); - _fakers = new OperationsFakers(testContext.Factory.Services); } diff --git a/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicLocalIdTests.cs b/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicLocalIdTests.cs index ed05cb45ae..4f31d5a904 100644 --- a/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicLocalIdTests.cs +++ b/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicLocalIdTests.cs @@ -1,7 +1,6 @@ using FluentAssertions; using JsonApiDotNetCore.OpenApi.Client.NSwag; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; using OpenApiNSwagEndToEndTests.AtomicOperations.GeneratedCode; using OpenApiTests; using OpenApiTests.AtomicOperations; @@ -24,8 +23,6 @@ public AtomicLocalIdTests(IntegrationTestContext(); - testContext.ConfigureServices(services => services.AddSingleton()); - _fakers = new OperationsFakers(testContext.Factory.Services); } diff --git a/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicRelationshipTests.cs b/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicRelationshipTests.cs index 1e69ed3ff5..ddac919415 100644 --- a/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicRelationshipTests.cs +++ b/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicRelationshipTests.cs @@ -1,7 +1,6 @@ using FluentAssertions; using JsonApiDotNetCore.OpenApi.Client.NSwag; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; using OpenApiNSwagEndToEndTests.AtomicOperations.GeneratedCode; using OpenApiTests; using OpenApiTests.AtomicOperations; @@ -25,8 +24,6 @@ public AtomicRelationshipTests(IntegrationTestContext(); - testContext.ConfigureServices(services => services.AddSingleton()); - _fakers = new OperationsFakers(testContext.Factory.Services); } diff --git a/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicUpdateResourceTests.cs b/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicUpdateResourceTests.cs index 8b1b11e2ad..9d1d532e8f 100644 --- a/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicUpdateResourceTests.cs +++ b/test/OpenApiNSwagEndToEndTests/AtomicOperations/AtomicUpdateResourceTests.cs @@ -26,11 +26,7 @@ public AtomicUpdateResourceTests(IntegrationTestContext(); - testContext.ConfigureServices(services => - { - services.AddSingleton(); - services.AddScoped(typeof(IResourceChangeTracker<>), typeof(NeverSameResourceChangeTracker<>)); - }); + testContext.ConfigureServices(services => services.AddScoped(typeof(IResourceChangeTracker<>), typeof(NeverSameResourceChangeTracker<>))); _fakers = new OperationsFakers(testContext.Factory.Services); } diff --git a/test/OpenApiNSwagEndToEndTests/OpenApiNSwagEndToEndTests.csproj b/test/OpenApiNSwagEndToEndTests/OpenApiNSwagEndToEndTests.csproj index 5c1ffd2c68..00b75a4139 100644 --- a/test/OpenApiNSwagEndToEndTests/OpenApiNSwagEndToEndTests.csproj +++ b/test/OpenApiNSwagEndToEndTests/OpenApiNSwagEndToEndTests.csproj @@ -1,7 +1,7 @@ - net8.0 + net9.0 @@ -34,7 +34,7 @@ %(Name)Client %(ClassName).cs - + ModelStateValidation $(MSBuildProjectName).%(Name).GeneratedCode %(Name)Client diff --git a/test/OpenApiTests/AtomicOperations/Enrollment.cs b/test/OpenApiTests/AtomicOperations/Enrollment.cs index 5a8bfa0c70..c89cf2537c 100644 --- a/test/OpenApiTests/AtomicOperations/Enrollment.cs +++ b/test/OpenApiTests/AtomicOperations/Enrollment.cs @@ -1,7 +1,6 @@ using JetBrains.Annotations; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; -using TestBuildingBlocks; namespace OpenApiTests.AtomicOperations; @@ -9,9 +8,9 @@ namespace OpenApiTests.AtomicOperations; [Resource(ControllerNamespace = "OpenApiTests.AtomicOperations")] public sealed class Enrollment(OperationsDbContext dbContext) : Identifiable { - private readonly ISystemClock _systemClock = dbContext.SystemClock; + private readonly TimeProvider _timeProvider = dbContext.TimeProvider; - private DateOnly Today => DateOnly.FromDateTime(_systemClock.UtcNow.Date); + private DateOnly Today => DateOnly.FromDateTime(_timeProvider.GetUtcNow().Date); [Attr] public DateOnly EnrolledAt { get; set; } diff --git a/test/OpenApiTests/AtomicOperations/OperationsDbContext.cs b/test/OpenApiTests/AtomicOperations/OperationsDbContext.cs index 6bb387ec5e..21164ba769 100644 --- a/test/OpenApiTests/AtomicOperations/OperationsDbContext.cs +++ b/test/OpenApiTests/AtomicOperations/OperationsDbContext.cs @@ -5,10 +5,10 @@ namespace OpenApiTests.AtomicOperations; [UsedImplicitly(ImplicitUseTargetFlags.Members)] -public sealed class OperationsDbContext(ISystemClock systemClock, DbContextOptions options) +public sealed class OperationsDbContext(TimeProvider timeProvider, DbContextOptions options) : TestableDbContext(options) { - internal ISystemClock SystemClock { get; } = systemClock; + internal TimeProvider TimeProvider { get; } = timeProvider; public DbSet Courses => Set(); public DbSet Teachers => Set(); diff --git a/test/OpenApiTests/AtomicOperations/OperationsTests.cs b/test/OpenApiTests/AtomicOperations/OperationsTests.cs index 95eee0df56..42bcdfdb56 100644 --- a/test/OpenApiTests/AtomicOperations/OperationsTests.cs +++ b/test/OpenApiTests/AtomicOperations/OperationsTests.cs @@ -20,8 +20,6 @@ public OperationsTests(OpenApiTestContext, O testContext.UseController(); testContext.UseController(); - testContext.ConfigureServices(services => services.AddSingleton()); - var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService(); options.IncludeJsonApiVersion = true; diff --git a/test/OpenApiTests/ModelStateValidation/GeneratedSwagger/net6.0/swagger.g.json b/test/OpenApiTests/ModelStateValidation/GeneratedSwagger/net6.0/swagger.g.json deleted file mode 100644 index 87835d7ef5..0000000000 --- a/test/OpenApiTests/ModelStateValidation/GeneratedSwagger/net6.0/swagger.g.json +++ /dev/null @@ -1,904 +0,0 @@ -{ - "openapi": "3.0.1", - "info": { - "title": "OpenApiTests", - "version": "1.0" - }, - "servers": [ - { - "url": "http://localhost" - } - ], - "paths": { - "/socialMediaAccounts": { - "post": { - "tags": [ - "socialMediaAccounts" - ], - "summary": "Creates a new socialMediaAccount.", - "operationId": "postSocialMediaAccount", - "parameters": [ - { - "name": "query", - "in": "query", - "description": "For syntax, see the documentation for the [`include`](https://www.jsonapi.net/usage/reading/including-relationships.html)/[`filter`](https://www.jsonapi.net/usage/reading/filtering.html)/[`sort`](https://www.jsonapi.net/usage/reading/sorting.html)/[`page`](https://www.jsonapi.net/usage/reading/pagination.html)/[`fields`](https://www.jsonapi.net/usage/reading/sparse-fieldset-selection.html) query string parameters.", - "schema": { - "type": "object", - "additionalProperties": { - "type": "string", - "nullable": true - }, - "example": "" - } - } - ], - "requestBody": { - "description": "The attributes and relationships of the socialMediaAccount to create.", - "content": { - "application/vnd.api+json": { - "schema": { - "allOf": [ - { - "$ref": "#/components/schemas/createSocialMediaAccountRequestDocument" - } - ] - } - } - }, - "required": true - }, - "responses": { - "201": { - "description": "The socialMediaAccount was successfully created, which resulted in additional changes. The newly created socialMediaAccount is returned.", - "headers": { - "Location": { - "description": "The URL at which the newly created socialMediaAccount can be retrieved.", - "required": true, - "schema": { - "type": "string", - "format": "uri" - } - } - }, - "content": { - "application/vnd.api+json": { - "schema": { - "$ref": "#/components/schemas/socialMediaAccountPrimaryResponseDocument" - } - } - } - }, - "204": { - "description": "The socialMediaAccount was successfully created, which did not result in additional changes." - }, - "400": { - "description": "The query string is invalid or the request body is missing or malformed.", - "content": { - "application/vnd.api+json": { - "schema": { - "$ref": "#/components/schemas/errorResponseDocument" - } - } - } - }, - "403": { - "description": "Client-generated IDs cannot be used at this endpoint.", - "content": { - "application/vnd.api+json": { - "schema": { - "$ref": "#/components/schemas/errorResponseDocument" - } - } - } - }, - "404": { - "description": "A related resource does not exist.", - "content": { - "application/vnd.api+json": { - "schema": { - "$ref": "#/components/schemas/errorResponseDocument" - } - } - } - }, - "409": { - "description": "The request body contains conflicting information or another resource with the same ID already exists.", - "content": { - "application/vnd.api+json": { - "schema": { - "$ref": "#/components/schemas/errorResponseDocument" - } - } - } - }, - "422": { - "description": "Validation of the request body failed.", - "content": { - "application/vnd.api+json": { - "schema": { - "$ref": "#/components/schemas/errorResponseDocument" - } - } - } - } - } - } - }, - "/socialMediaAccounts/{id}": { - "patch": { - "tags": [ - "socialMediaAccounts" - ], - "summary": "Updates an existing socialMediaAccount.", - "operationId": "patchSocialMediaAccount", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "The identifier of the socialMediaAccount to update.", - "required": true, - "schema": { - "minLength": 1, - "type": "string", - "format": "uuid" - } - }, - { - "name": "query", - "in": "query", - "description": "For syntax, see the documentation for the [`include`](https://www.jsonapi.net/usage/reading/including-relationships.html)/[`filter`](https://www.jsonapi.net/usage/reading/filtering.html)/[`sort`](https://www.jsonapi.net/usage/reading/sorting.html)/[`page`](https://www.jsonapi.net/usage/reading/pagination.html)/[`fields`](https://www.jsonapi.net/usage/reading/sparse-fieldset-selection.html) query string parameters.", - "schema": { - "type": "object", - "additionalProperties": { - "type": "string", - "nullable": true - }, - "example": "" - } - } - ], - "requestBody": { - "description": "The attributes and relationships of the socialMediaAccount to update. Omitted fields are left unchanged.", - "content": { - "application/vnd.api+json": { - "schema": { - "allOf": [ - { - "$ref": "#/components/schemas/updateSocialMediaAccountRequestDocument" - } - ] - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "The socialMediaAccount was successfully updated, which resulted in additional changes. The updated socialMediaAccount is returned.", - "content": { - "application/vnd.api+json": { - "schema": { - "$ref": "#/components/schemas/socialMediaAccountPrimaryResponseDocument" - } - } - } - }, - "204": { - "description": "The socialMediaAccount was successfully updated, which did not result in additional changes." - }, - "400": { - "description": "The query string is invalid or the request body is missing or malformed.", - "content": { - "application/vnd.api+json": { - "schema": { - "$ref": "#/components/schemas/errorResponseDocument" - } - } - } - }, - "404": { - "description": "The socialMediaAccount or a related resource does not exist.", - "content": { - "application/vnd.api+json": { - "schema": { - "$ref": "#/components/schemas/errorResponseDocument" - } - } - } - }, - "409": { - "description": "A resource type or identifier in the request body is incompatible.", - "content": { - "application/vnd.api+json": { - "schema": { - "$ref": "#/components/schemas/errorResponseDocument" - } - } - } - }, - "422": { - "description": "Validation of the request body failed.", - "content": { - "application/vnd.api+json": { - "schema": { - "$ref": "#/components/schemas/errorResponseDocument" - } - } - } - } - } - } - } - }, - "components": { - "schemas": { - "attributesInCreateSocialMediaAccountRequest": { - "required": [ - "lastName" - ], - "type": "object", - "properties": { - "alternativeId": { - "type": "string", - "format": "uuid", - "nullable": true - }, - "firstName": { - "type": "string", - "nullable": true - }, - "lastName": { - "type": "string" - }, - "userName": { - "maxLength": 18, - "minLength": 3, - "pattern": "^[a-zA-Z]+$", - "type": "string", - "nullable": true - }, - "creditCard": { - "type": "string", - "format": "credit-card", - "nullable": true - }, - "email": { - "type": "string", - "format": "email", - "nullable": true - }, - "password": { - "type": "string", - "nullable": true - }, - "phone": { - "type": "string", - "format": "tel", - "nullable": true - }, - "age": { - "maximum": 122.9, - "minimum": 0.1, - "type": "number", - "format": "double", - "nullable": true - }, - "profilePicture": { - "type": "string", - "format": "uri", - "nullable": true - }, - "backgroundPicture": { - "type": "string", - "format": "uri", - "nullable": true - }, - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "nullable": true - }, - "countryCode": { - "type": "string", - "nullable": true - }, - "planet": { - "type": "string", - "nullable": true - }, - "nextRevalidation": { - "type": "string", - "format": "date-span", - "nullable": true - }, - "validatedAt": { - "type": "string", - "format": "date-time", - "nullable": true - }, - "validatedAtDate": { - "type": "string", - "format": "date", - "nullable": true - }, - "validatedAtTime": { - "type": "string", - "format": "time", - "nullable": true - } - }, - "additionalProperties": false - }, - "attributesInUpdateSocialMediaAccountRequest": { - "type": "object", - "properties": { - "alternativeId": { - "type": "string", - "format": "uuid", - "nullable": true - }, - "firstName": { - "type": "string", - "nullable": true - }, - "lastName": { - "type": "string" - }, - "userName": { - "maxLength": 18, - "minLength": 3, - "pattern": "^[a-zA-Z]+$", - "type": "string", - "nullable": true - }, - "creditCard": { - "type": "string", - "format": "credit-card", - "nullable": true - }, - "email": { - "type": "string", - "format": "email", - "nullable": true - }, - "password": { - "type": "string", - "nullable": true - }, - "phone": { - "type": "string", - "format": "tel", - "nullable": true - }, - "age": { - "maximum": 122.9, - "minimum": 0.1, - "type": "number", - "format": "double", - "nullable": true - }, - "profilePicture": { - "type": "string", - "format": "uri", - "nullable": true - }, - "backgroundPicture": { - "type": "string", - "format": "uri", - "nullable": true - }, - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "nullable": true - }, - "countryCode": { - "type": "string", - "nullable": true - }, - "planet": { - "type": "string", - "nullable": true - }, - "nextRevalidation": { - "type": "string", - "format": "date-span", - "nullable": true - }, - "validatedAt": { - "type": "string", - "format": "date-time", - "nullable": true - }, - "validatedAtDate": { - "type": "string", - "format": "date", - "nullable": true - }, - "validatedAtTime": { - "type": "string", - "format": "time", - "nullable": true - } - }, - "additionalProperties": false - }, - "createSocialMediaAccountRequestDocument": { - "required": [ - "data" - ], - "type": "object", - "properties": { - "data": { - "allOf": [ - { - "$ref": "#/components/schemas/dataInCreateSocialMediaAccountRequest" - } - ] - }, - "meta": { - "allOf": [ - { - "$ref": "#/components/schemas/meta" - } - ] - } - }, - "additionalProperties": false - }, - "dataInCreateSocialMediaAccountRequest": { - "required": [ - "type" - ], - "type": "object", - "properties": { - "type": { - "allOf": [ - { - "$ref": "#/components/schemas/socialMediaAccountResourceType" - } - ] - }, - "attributes": { - "allOf": [ - { - "$ref": "#/components/schemas/attributesInCreateSocialMediaAccountRequest" - } - ] - }, - "meta": { - "allOf": [ - { - "$ref": "#/components/schemas/meta" - } - ] - } - }, - "additionalProperties": false - }, - "dataInResponse": { - "required": [ - "type" - ], - "type": "object", - "properties": { - "type": { - "allOf": [ - { - "$ref": "#/components/schemas/resourceType" - } - ] - }, - "meta": { - "allOf": [ - { - "$ref": "#/components/schemas/meta" - } - ] - } - }, - "additionalProperties": false, - "discriminator": { - "propertyName": "type", - "mapping": { - "socialMediaAccounts": "#/components/schemas/socialMediaAccountDataInResponse" - } - }, - "x-abstract": true - }, - "dataInUpdateSocialMediaAccountRequest": { - "required": [ - "id", - "type" - ], - "type": "object", - "properties": { - "type": { - "allOf": [ - { - "$ref": "#/components/schemas/socialMediaAccountResourceType" - } - ] - }, - "id": { - "minLength": 1, - "type": "string", - "format": "uuid" - }, - "attributes": { - "allOf": [ - { - "$ref": "#/components/schemas/attributesInUpdateSocialMediaAccountRequest" - } - ] - }, - "meta": { - "allOf": [ - { - "$ref": "#/components/schemas/meta" - } - ] - } - }, - "additionalProperties": false - }, - "errorLinks": { - "type": "object", - "properties": { - "about": { - "type": "string", - "nullable": true - }, - "type": { - "type": "string", - "nullable": true - } - }, - "additionalProperties": false - }, - "errorObject": { - "type": "object", - "properties": { - "id": { - "type": "string", - "nullable": true - }, - "links": { - "allOf": [ - { - "$ref": "#/components/schemas/errorLinks" - } - ], - "nullable": true - }, - "status": { - "type": "string" - }, - "code": { - "type": "string", - "nullable": true - }, - "title": { - "type": "string", - "nullable": true - }, - "detail": { - "type": "string", - "nullable": true - }, - "source": { - "allOf": [ - { - "$ref": "#/components/schemas/errorSource" - } - ], - "nullable": true - }, - "meta": { - "allOf": [ - { - "$ref": "#/components/schemas/meta" - } - ] - } - }, - "additionalProperties": false - }, - "errorResponseDocument": { - "required": [ - "errors", - "links" - ], - "type": "object", - "properties": { - "links": { - "allOf": [ - { - "$ref": "#/components/schemas/errorTopLevelLinks" - } - ] - }, - "errors": { - "type": "array", - "items": { - "$ref": "#/components/schemas/errorObject" - } - }, - "meta": { - "allOf": [ - { - "$ref": "#/components/schemas/meta" - } - ] - } - }, - "additionalProperties": false - }, - "errorSource": { - "type": "object", - "properties": { - "pointer": { - "type": "string", - "nullable": true - }, - "parameter": { - "type": "string", - "nullable": true - }, - "header": { - "type": "string", - "nullable": true - } - }, - "additionalProperties": false - }, - "errorTopLevelLinks": { - "type": "object", - "properties": { - "self": { - "type": "string" - }, - "describedby": { - "type": "string" - } - }, - "additionalProperties": false - }, - "meta": { - "type": "object", - "additionalProperties": { - "nullable": true - } - }, - "resourceLinks": { - "type": "object", - "properties": { - "self": { - "type": "string" - } - }, - "additionalProperties": false - }, - "resourceTopLevelLinks": { - "type": "object", - "properties": { - "self": { - "type": "string" - }, - "describedby": { - "type": "string" - } - }, - "additionalProperties": false - }, - "resourceType": { - "enum": [ - "socialMediaAccounts" - ], - "type": "string" - }, - "socialMediaAccountAttributesInResponse": { - "type": "object", - "properties": { - "alternativeId": { - "type": "string", - "format": "uuid", - "nullable": true - }, - "firstName": { - "type": "string", - "nullable": true - }, - "lastName": { - "type": "string" - }, - "userName": { - "maxLength": 18, - "minLength": 3, - "pattern": "^[a-zA-Z]+$", - "type": "string", - "nullable": true - }, - "creditCard": { - "type": "string", - "format": "credit-card", - "nullable": true - }, - "email": { - "type": "string", - "format": "email", - "nullable": true - }, - "password": { - "type": "string", - "nullable": true - }, - "phone": { - "type": "string", - "format": "tel", - "nullable": true - }, - "age": { - "maximum": 122.9, - "minimum": 0.1, - "type": "number", - "format": "double", - "nullable": true - }, - "profilePicture": { - "type": "string", - "format": "uri", - "nullable": true - }, - "backgroundPicture": { - "type": "string", - "format": "uri", - "nullable": true - }, - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "nullable": true - }, - "countryCode": { - "type": "string", - "nullable": true - }, - "planet": { - "type": "string", - "nullable": true - }, - "nextRevalidation": { - "type": "string", - "format": "date-span", - "nullable": true - }, - "validatedAt": { - "type": "string", - "format": "date-time", - "nullable": true - }, - "validatedAtDate": { - "type": "string", - "format": "date", - "nullable": true - }, - "validatedAtTime": { - "type": "string", - "format": "time", - "nullable": true - } - }, - "additionalProperties": false - }, - "socialMediaAccountDataInResponse": { - "allOf": [ - { - "$ref": "#/components/schemas/dataInResponse" - }, - { - "required": [ - "id" - ], - "type": "object", - "properties": { - "id": { - "minLength": 1, - "type": "string", - "format": "uuid" - }, - "attributes": { - "allOf": [ - { - "$ref": "#/components/schemas/socialMediaAccountAttributesInResponse" - } - ] - }, - "links": { - "allOf": [ - { - "$ref": "#/components/schemas/resourceLinks" - } - ] - } - }, - "additionalProperties": false - } - ], - "additionalProperties": false - }, - "socialMediaAccountPrimaryResponseDocument": { - "required": [ - "data", - "links" - ], - "type": "object", - "properties": { - "links": { - "allOf": [ - { - "$ref": "#/components/schemas/resourceTopLevelLinks" - } - ] - }, - "data": { - "allOf": [ - { - "$ref": "#/components/schemas/socialMediaAccountDataInResponse" - } - ] - }, - "included": { - "type": "array", - "items": { - "$ref": "#/components/schemas/dataInResponse" - } - }, - "meta": { - "allOf": [ - { - "$ref": "#/components/schemas/meta" - } - ] - } - }, - "additionalProperties": false - }, - "socialMediaAccountResourceType": { - "enum": [ - "socialMediaAccounts" - ], - "type": "string" - }, - "updateSocialMediaAccountRequestDocument": { - "required": [ - "data" - ], - "type": "object", - "properties": { - "data": { - "allOf": [ - { - "$ref": "#/components/schemas/dataInUpdateSocialMediaAccountRequest" - } - ] - }, - "meta": { - "allOf": [ - { - "$ref": "#/components/schemas/meta" - } - ] - } - }, - "additionalProperties": false - } - } - } -} \ No newline at end of file diff --git a/test/OpenApiTests/ModelStateValidation/GeneratedSwagger/net8.0/swagger.g.json b/test/OpenApiTests/ModelStateValidation/GeneratedSwagger/swagger.g.json similarity index 100% rename from test/OpenApiTests/ModelStateValidation/GeneratedSwagger/net8.0/swagger.g.json rename to test/OpenApiTests/ModelStateValidation/GeneratedSwagger/swagger.g.json diff --git a/test/OpenApiTests/ModelStateValidation/ModelStateValidationTests.cs b/test/OpenApiTests/ModelStateValidation/ModelStateValidationTests.cs index facb2f3078..63ac40de2c 100644 --- a/test/OpenApiTests/ModelStateValidation/ModelStateValidationTests.cs +++ b/test/OpenApiTests/ModelStateValidation/ModelStateValidationTests.cs @@ -22,13 +22,7 @@ public ModelStateValidationTests(OpenApiTestContext(); - const string targetFramework = -#if NET6_0 - "net6.0"; -#else - "net8.0"; -#endif - testContext.SwaggerDocumentOutputDirectory = $"{GetType().Namespace!.Replace('.', '/')}/GeneratedSwagger/{targetFramework}"; + testContext.SwaggerDocumentOutputDirectory = $"{GetType().Namespace!.Replace('.', '/')}/GeneratedSwagger"; } [Theory] @@ -56,11 +50,9 @@ public async Task Length_annotation_on_resource_string_property_produces_expecte // Assert document.Should().ContainPath($"components.schemas.{modelName}.properties.firstName").With(firstNameElement => { -#if !NET6_0 + firstNameElement.Should().HaveProperty("type", "string"); firstNameElement.Should().HaveProperty("maxLength", 20); firstNameElement.Should().HaveProperty("minLength", 2); -#endif - firstNameElement.Should().HaveProperty("type", "string"); }); } @@ -74,8 +66,8 @@ public async Task Required_annotation_with_AllowEmptyStrings_on_resource_propert // Assert document.Should().ContainPath($"components.schemas.{modelName}.properties.lastName").With(lastNameElement => { - lastNameElement.Should().NotContainPath("minLength"); lastNameElement.Should().HaveProperty("type", "string"); + lastNameElement.Should().NotContainPath("minLength"); }); } @@ -89,9 +81,9 @@ public async Task StringLength_annotation_on_resource_property_produces_expected // Assert document.Should().ContainPath($"components.schemas.{modelName}.properties.userName").With(userNameElement => { + userNameElement.Should().HaveProperty("type", "string"); userNameElement.Should().HaveProperty("maxLength", 18); userNameElement.Should().HaveProperty("minLength", 3); - userNameElement.Should().HaveProperty("type", "string"); }); } @@ -105,8 +97,8 @@ public async Task RegularExpression_annotation_on_resource_property_produces_exp // Assert document.Should().ContainPath($"components.schemas.{modelName}.properties.userName").With(userNameElement => { - userNameElement.Should().HaveProperty("pattern", "^[a-zA-Z]+$"); userNameElement.Should().HaveProperty("type", "string"); + userNameElement.Should().HaveProperty("pattern", "^[a-zA-Z]+$"); }); } @@ -150,12 +142,10 @@ public async Task Min_max_length_annotation_on_resource_property_produces_expect // Assert document.Should().ContainPath($"components.schemas.{modelName}.properties.password").With(passwordElement => { -#if !NET6_0 + passwordElement.Should().HaveProperty("type", "string"); passwordElement.Should().HaveProperty("format", "byte"); passwordElement.Should().HaveProperty("maxLength", SocialMediaAccount.MaxPasswordCharsInBase64); passwordElement.Should().HaveProperty("minLength", SocialMediaAccount.MinPasswordCharsInBase64); -#endif - passwordElement.Should().HaveProperty("type", "string"); }); } @@ -184,14 +174,12 @@ public async Task Range_annotation_on_resource_property_produces_expected_schema // Assert document.Should().ContainPath($"components.schemas.{modelName}.properties.age").With(ageElement => { + ageElement.Should().HaveProperty("type", "number"); + ageElement.Should().HaveProperty("format", "double"); ageElement.Should().HaveProperty("maximum", 122.9); ageElement.Should().HaveProperty("minimum", 0.1); -#if !NET6_0 ageElement.Should().ContainPath("exclusiveMaximum").With(exclusiveElement => exclusiveElement.Should().Be(true)); ageElement.Should().ContainPath("exclusiveMinimum").With(exclusiveElement => exclusiveElement.Should().Be(true)); -#endif - ageElement.Should().HaveProperty("type", "number"); - ageElement.Should().HaveProperty("format", "double"); }); } @@ -235,15 +223,13 @@ public async Task Length_annotation_on_resource_list_property_produces_expected_ // Assert document.Should().ContainPath($"components.schemas.{modelName}.properties.tags").With(tagsElement => { -#if !NET6_0 + tagsElement.Should().HaveProperty("type", "array"); tagsElement.Should().HaveProperty("maxItems", 10); tagsElement.Should().HaveProperty("minItems", 1); -#endif - tagsElement.Should().HaveProperty("type", "array"); - tagsElement.Should().ContainPath("items").With(itemsEl => + tagsElement.Should().ContainPath("items").With(itemsElement => { - itemsEl.Should().HaveProperty("type", "string"); + itemsElement.Should().HaveProperty("type", "string"); }); }); } diff --git a/test/OpenApiTests/ModelStateValidation/SocialMediaAccount.cs b/test/OpenApiTests/ModelStateValidation/SocialMediaAccount.cs index 5f6c8fcc2f..28fbd7148d 100644 --- a/test/OpenApiTests/ModelStateValidation/SocialMediaAccount.cs +++ b/test/OpenApiTests/ModelStateValidation/SocialMediaAccount.cs @@ -20,14 +20,12 @@ public sealed class SocialMediaAccount : Identifiable public Guid? AlternativeId { get; set; } [Attr] -#if !NET6_0 [Length(2, 20)] -#endif public string? FirstName { get; set; } [Attr] [Required(AllowEmptyStrings = true)] - public string LastName { get; set; } = default!; + public string LastName { get; set; } = null!; [Attr] [StringLength(18, MinimumLength = 3)] @@ -43,11 +41,9 @@ public sealed class SocialMediaAccount : Identifiable public string? Email { get; set; } [Attr] -#if !NET6_0 [Base64String] [MinLength(MinPasswordCharsInBase64)] [MaxLength(MaxPasswordCharsInBase64)] -#endif public string? Password { get; set; } [Attr] @@ -55,11 +51,7 @@ public sealed class SocialMediaAccount : Identifiable public string? Phone { get; set; } [Attr] -#if NET6_0 - [Range(0.1, 122.9)] -#else [Range(0.1, 122.9, MinimumIsExclusive = true, MaximumIsExclusive = true)] -#endif public double? Age { get; set; } [Attr] @@ -70,21 +62,15 @@ public sealed class SocialMediaAccount : Identifiable public string? BackgroundPicture { get; set; } [Attr] -#if !NET6_0 [Length(1, 10)] -#endif public List? Tags { get; set; } [Attr] -#if !NET6_0 [AllowedValues(null, "NL", "FR")] -#endif public string? CountryCode { get; set; } [Attr] -#if !NET6_0 [DeniedValues("pluto")] -#endif public string? Planet { get; set; } [Attr] diff --git a/test/OpenApiTests/OpenApiTests.csproj b/test/OpenApiTests/OpenApiTests.csproj index 8a853acbf6..ed2a75b5f4 100644 --- a/test/OpenApiTests/OpenApiTests.csproj +++ b/test/OpenApiTests/OpenApiTests.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net9.0;net8.0 True false $(NoWarn);1591 diff --git a/test/SourceGeneratorTests/SourceGeneratorTests.csproj b/test/SourceGeneratorTests/SourceGeneratorTests.csproj index e28bdc20d1..4f487fa168 100644 --- a/test/SourceGeneratorTests/SourceGeneratorTests.csproj +++ b/test/SourceGeneratorTests/SourceGeneratorTests.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net9.0;net8.0 diff --git a/test/TestBuildingBlocks/CapturingLoggerProvider.cs b/test/TestBuildingBlocks/CapturingLoggerProvider.cs index 3996b1c9e2..07366f5db1 100644 --- a/test/TestBuildingBlocks/CapturingLoggerProvider.cs +++ b/test/TestBuildingBlocks/CapturingLoggerProvider.cs @@ -1,5 +1,4 @@ using JetBrains.Annotations; -using JsonApiDotNetCore; using Microsoft.Extensions.Logging; namespace TestBuildingBlocks; @@ -10,7 +9,11 @@ public sealed class CapturingLoggerProvider : ILoggerProvider private static readonly Func DefaultFilter = (_, _) => true; private readonly Func _filter; +#if NET8_0 private readonly object _lockObject = new(); +#else + private readonly Lock _lockObject = new(); +#endif private readonly List _messages = []; public CapturingLoggerProvider() @@ -25,14 +28,14 @@ public CapturingLoggerProvider(LogLevel minimumLevel) public CapturingLoggerProvider(Func filter) { - ArgumentGuard.NotNull(filter); + ArgumentNullException.ThrowIfNull(filter); _filter = filter; } public ILogger CreateLogger(string categoryName) { - ArgumentGuard.NotNullNorEmpty(categoryName); + ArgumentException.ThrowIfNullOrEmpty(categoryName); return new CapturingLogger(this, categoryName, _filter); } diff --git a/test/TestBuildingBlocks/DbContextExtensions.cs b/test/TestBuildingBlocks/DbContextExtensions.cs index 1d1dbc0650..d3a8a0e8ad 100644 --- a/test/TestBuildingBlocks/DbContextExtensions.cs +++ b/test/TestBuildingBlocks/DbContextExtensions.cs @@ -44,14 +44,10 @@ private static async Task ClearTablesAsync(this DbContext dbContext, params Type } else { -#if !NET6_0 #pragma warning disable EF1002 // Risk of vulnerability to SQL injection. -#endif // Justification: Table names cannot be parameterized. await dbContext.Database.ExecuteSqlRawAsync($"DELETE FROM \"{tableName}\""); -#if !NET6_0 #pragma warning restore EF1002 // Risk of vulnerability to SQL injection. -#endif } } } diff --git a/test/TestBuildingBlocks/FakerExtensions.cs b/test/TestBuildingBlocks/FakerExtensions.cs index c6634d62f7..b6cb073e8c 100644 --- a/test/TestBuildingBlocks/FakerExtensions.cs +++ b/test/TestBuildingBlocks/FakerExtensions.cs @@ -7,7 +7,7 @@ namespace TestBuildingBlocks; public static class FakerExtensions { - public static Faker MakeDeterministic(this Faker faker) + public static Faker MakeDeterministic(this Faker faker, DateTime? systemTimeUtc = null) where T : class { int seed = GetFakerSeed(); @@ -15,7 +15,7 @@ public static Faker MakeDeterministic(this Faker faker) // Setting the system DateTime to kind Utc, so that faker calls like PastOffset() don't depend on the system time zone. // See https://docs.microsoft.com/en-us/dotnet/api/system.datetimeoffset.op_implicit?view=net-6.0#remarks - faker.UseDateTimeReference(FrozenSystemClock.DefaultDateTimeUtc); + faker.UseDateTimeReference(systemTimeUtc ?? IntegrationTest.DefaultDateTimeUtc.UtcDateTime); return faker; } diff --git a/test/TestBuildingBlocks/FrozenSystemClock.cs b/test/TestBuildingBlocks/FrozenSystemClock.cs deleted file mode 100644 index eab141518c..0000000000 --- a/test/TestBuildingBlocks/FrozenSystemClock.cs +++ /dev/null @@ -1,11 +0,0 @@ -using FluentAssertions.Extensions; - -namespace TestBuildingBlocks; - -public sealed class FrozenSystemClock : ISystemClock -{ - public static readonly DateTime DefaultDateTimeUtc = 1.January(2020).At(1, 1, 1).AsUtc(); - public static readonly DateTimeOffset DefaultDateTimeOffsetUtc = DefaultDateTimeUtc; - - public DateTimeOffset UtcNow { get; set; } = DefaultDateTimeOffsetUtc; -} diff --git a/test/TestBuildingBlocks/FrozenTimeProvider.cs b/test/TestBuildingBlocks/FrozenTimeProvider.cs new file mode 100644 index 0000000000..7b237eb00e --- /dev/null +++ b/test/TestBuildingBlocks/FrozenTimeProvider.cs @@ -0,0 +1,44 @@ +using System.Globalization; + +namespace TestBuildingBlocks; + +public sealed class FrozenTimeProvider(DateTimeOffset startDateTime, TimeZoneInfo? localTimeZone = null) : TimeProvider +{ + private readonly DateTimeOffset _startDateTime = startDateTime; + private readonly TimeZoneInfo? _localTimeZone = localTimeZone; + + private DateTimeOffset _dateTime = startDateTime; + + public override TimeZoneInfo LocalTimeZone => _localTimeZone ?? throw new NotSupportedException(); + public override long TimestampFrequency => throw new NotSupportedException(); + + public override DateTimeOffset GetUtcNow() + { + return _dateTime; + } + + public void SetUtcNow(DateTimeOffset value) + { + _dateTime = value; + } + + public void Reset() + { + _dateTime = _startDateTime; + } + + public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) + { + throw new NotSupportedException(); + } + + public override long GetTimestamp() + { + throw new NotSupportedException(); + } + + public override string ToString() + { + return _dateTime.ToString("yyyy-MM-ddTHH:mm:ss.fff", CultureInfo.InvariantCulture); + } +} diff --git a/test/TestBuildingBlocks/ISystemClock.cs b/test/TestBuildingBlocks/ISystemClock.cs deleted file mode 100644 index eb1c8628a3..0000000000 --- a/test/TestBuildingBlocks/ISystemClock.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace TestBuildingBlocks; - -public interface ISystemClock -{ - DateTimeOffset UtcNow { get; } -} diff --git a/test/TestBuildingBlocks/IntegrationTest.cs b/test/TestBuildingBlocks/IntegrationTest.cs index 79c88b743e..0b94ac7448 100644 --- a/test/TestBuildingBlocks/IntegrationTest.cs +++ b/test/TestBuildingBlocks/IntegrationTest.cs @@ -1,6 +1,7 @@ using System.Net.Http.Headers; using System.Text; using System.Text.Json; +using FluentAssertions.Extensions; using JsonApiDotNetCore.Middleware; using Xunit; @@ -19,6 +20,8 @@ public abstract class IntegrationTest : IAsyncLifetime private static readonly SemaphoreSlim ThrottleSemaphore = GetDefaultThrottleSemaphore(); + public static DateTimeOffset DefaultDateTimeUtc { get; } = 1.January(2020).At(1, 2, 3).AsUtc(); + protected abstract JsonSerializerOptions SerializerOptions { get; } private static SemaphoreSlim GetDefaultThrottleSemaphore() diff --git a/test/TestBuildingBlocks/IntegrationTestContext.cs b/test/TestBuildingBlocks/IntegrationTestContext.cs index a9abb26a83..c895765a3e 100644 --- a/test/TestBuildingBlocks/IntegrationTestContext.cs +++ b/test/TestBuildingBlocks/IntegrationTestContext.cs @@ -9,6 +9,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; @@ -75,6 +76,8 @@ private WebApplicationFactory CreateFactory() { _configureServices?.Invoke(services); + services.Replace(ServiceDescriptor.Singleton(new FrozenTimeProvider(DefaultDateTimeUtc))); + services.ReplaceControllers(_testControllerProvider); services.AddDbContext(options => diff --git a/test/TestBuildingBlocks/MarkedText.cs b/test/TestBuildingBlocks/MarkedText.cs index f0935b0c2a..003fd0a24f 100644 --- a/test/TestBuildingBlocks/MarkedText.cs +++ b/test/TestBuildingBlocks/MarkedText.cs @@ -1,6 +1,5 @@ using System.Diagnostics; using JetBrains.Annotations; -using JsonApiDotNetCore; namespace TestBuildingBlocks; @@ -14,7 +13,7 @@ public sealed class MarkedText public MarkedText(string source, char marker) { - ArgumentGuard.NotNull(source); + ArgumentNullException.ThrowIfNull(source); Source = source; Position = GetPositionFromMarker(marker); diff --git a/test/TestBuildingBlocks/ServiceCollectionExtensions.cs b/test/TestBuildingBlocks/ServiceCollectionExtensions.cs index 2a11397f69..8e5102fa23 100644 --- a/test/TestBuildingBlocks/ServiceCollectionExtensions.cs +++ b/test/TestBuildingBlocks/ServiceCollectionExtensions.cs @@ -1,5 +1,4 @@ using System.Reflection; -using JsonApiDotNetCore; using Microsoft.AspNetCore.Mvc.ApplicationParts; using Microsoft.AspNetCore.Mvc.Controllers; using Microsoft.Extensions.DependencyInjection; @@ -10,7 +9,7 @@ internal static class ServiceCollectionExtensions { public static void ReplaceControllers(this IServiceCollection services, TestControllerProvider provider) { - ArgumentGuard.NotNull(services); + ArgumentNullException.ThrowIfNull(services); services.AddMvcCore().ConfigureApplicationPartManager(manager => { diff --git a/test/TestBuildingBlocks/TestBuildingBlocks.csproj b/test/TestBuildingBlocks/TestBuildingBlocks.csproj index 44f30582dc..3f16e3818e 100644 --- a/test/TestBuildingBlocks/TestBuildingBlocks.csproj +++ b/test/TestBuildingBlocks/TestBuildingBlocks.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net9.0;net8.0 diff --git a/test/TestBuildingBlocks/XUnitLoggerProvider.cs b/test/TestBuildingBlocks/XUnitLoggerProvider.cs index e264a9bf4a..a6214032af 100644 --- a/test/TestBuildingBlocks/XUnitLoggerProvider.cs +++ b/test/TestBuildingBlocks/XUnitLoggerProvider.cs @@ -1,5 +1,4 @@ using System.Text; -using JsonApiDotNetCore; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Xunit.Abstractions; @@ -15,7 +14,7 @@ public sealed class XUnitLoggerProvider : ILoggerProvider public XUnitLoggerProvider(ITestOutputHelper testOutputHelper, string? categoryPrefixFilter, LogOutputFields outputFields = LogOutputFields.All) { - ArgumentGuard.NotNull(testOutputHelper); + ArgumentNullException.ThrowIfNull(testOutputHelper); _testOutputHelper = testOutputHelper; _categoryPrefixFilter = categoryPrefixFilter; @@ -24,7 +23,7 @@ public XUnitLoggerProvider(ITestOutputHelper testOutputHelper, string? categoryP public ILogger CreateLogger(string categoryName) { - ArgumentGuard.NotNullNorEmpty(categoryName); + ArgumentException.ThrowIfNullOrEmpty(categoryName); if (_categoryPrefixFilter == null || categoryName.StartsWith(_categoryPrefixFilter, StringComparison.Ordinal)) { diff --git a/test/UnitTests/Models/IdentifiableTests.cs b/test/UnitTests/Models/IdentifiableTests.cs index 993a3988f2..ad11081c65 100644 --- a/test/UnitTests/Models/IdentifiableTests.cs +++ b/test/UnitTests/Models/IdentifiableTests.cs @@ -33,7 +33,7 @@ public void GetStringId_Returns_Null_If_Object_Is_Default() { var resource = new IntId(); - string? stringId = resource.ExposedGetStringId(default); + string? stringId = resource.ExposedGetStringId(0); stringId.Should().BeNull(); } diff --git a/test/UnitTests/Models/ResourceConstructionExpressionTests.cs b/test/UnitTests/Models/ResourceConstructionExpressionTests.cs index bfa4e97e32..d8345b5de3 100644 --- a/test/UnitTests/Models/ResourceConstructionExpressionTests.cs +++ b/test/UnitTests/Models/ResourceConstructionExpressionTests.cs @@ -2,7 +2,6 @@ using System.Linq.Expressions; using FluentAssertions; using JetBrains.Annotations; -using JsonApiDotNetCore; using JsonApiDotNetCore.Resources; using TestBuildingBlocks; using Xunit; @@ -52,7 +51,7 @@ private sealed class ResourceWithStringConstructor : Identifiable public ResourceWithStringConstructor(string text) { - ArgumentGuard.NotNullNorEmpty(text); + ArgumentException.ThrowIfNullOrEmpty(text); Text = text; } diff --git a/test/UnitTests/UnitTests.csproj b/test/UnitTests/UnitTests.csproj index 99fc7ce781..68076a51e1 100644 --- a/test/UnitTests/UnitTests.csproj +++ b/test/UnitTests/UnitTests.csproj @@ -1,6 +1,6 @@ - net8.0;net6.0 + net9.0;net8.0