From 4c6b02c536da0485c1879548b6074f6762adf2ec Mon Sep 17 00:00:00 2001 From: Bart Koelman Date: Wed, 3 Mar 2021 20:57:40 +0100 Subject: [PATCH 01/32] Auto-formatted codebase using Resharper --- .../Executor/Create/BeforeCreateWithDbValuesTests.cs | 2 ++ .../Executor/IdentifiableManyToManyOnReturnTests.cs | 1 + 2 files changed, 3 insertions(+) diff --git a/test/UnitTests/ResourceHooks/Executor/Create/BeforeCreateWithDbValuesTests.cs b/test/UnitTests/ResourceHooks/Executor/Create/BeforeCreateWithDbValuesTests.cs index 1abe506884..6ba3586b8a 100644 --- a/test/UnitTests/ResourceHooks/Executor/Create/BeforeCreateWithDbValuesTests.cs +++ b/test/UnitTests/ResourceHooks/Executor/Create/BeforeCreateWithDbValuesTests.cs @@ -3,6 +3,8 @@ using JsonApiDotNetCore.Hooks.Internal; using JsonApiDotNetCore.Hooks.Internal.Discovery; using JsonApiDotNetCore.Hooks.Internal.Execution; +using JsonApiDotNetCore.Queries; +using JsonApiDotNetCore.Resources; using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; using Microsoft.EntityFrameworkCore; diff --git a/test/UnitTests/ResourceHooks/Executor/IdentifiableManyToManyOnReturnTests.cs b/test/UnitTests/ResourceHooks/Executor/IdentifiableManyToManyOnReturnTests.cs index a9a5ac1587..242b5f4dea 100644 --- a/test/UnitTests/ResourceHooks/Executor/IdentifiableManyToManyOnReturnTests.cs +++ b/test/UnitTests/ResourceHooks/Executor/IdentifiableManyToManyOnReturnTests.cs @@ -3,6 +3,7 @@ using JsonApiDotNetCore.Hooks.Internal; using JsonApiDotNetCore.Hooks.Internal.Discovery; using JsonApiDotNetCore.Hooks.Internal.Execution; +using JsonApiDotNetCore.Queries; using JsonApiDotNetCoreExample.Models; using Moq; using Xunit; From d909d9f2b24d8173f0ec10303de0beddb550d58c Mon Sep 17 00:00:00 2001 From: Bart Koelman Date: Wed, 3 Mar 2021 21:43:24 +0100 Subject: [PATCH 02/32] Replaced "var _" with discards --- .../Executor/Create/BeforeCreateWithDbValuesTests.cs | 2 -- .../Executor/IdentifiableManyToManyOnReturnTests.cs | 1 - 2 files changed, 3 deletions(-) diff --git a/test/UnitTests/ResourceHooks/Executor/Create/BeforeCreateWithDbValuesTests.cs b/test/UnitTests/ResourceHooks/Executor/Create/BeforeCreateWithDbValuesTests.cs index 6ba3586b8a..1abe506884 100644 --- a/test/UnitTests/ResourceHooks/Executor/Create/BeforeCreateWithDbValuesTests.cs +++ b/test/UnitTests/ResourceHooks/Executor/Create/BeforeCreateWithDbValuesTests.cs @@ -3,8 +3,6 @@ using JsonApiDotNetCore.Hooks.Internal; using JsonApiDotNetCore.Hooks.Internal.Discovery; using JsonApiDotNetCore.Hooks.Internal.Execution; -using JsonApiDotNetCore.Queries; -using JsonApiDotNetCore.Resources; using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; using Microsoft.EntityFrameworkCore; diff --git a/test/UnitTests/ResourceHooks/Executor/IdentifiableManyToManyOnReturnTests.cs b/test/UnitTests/ResourceHooks/Executor/IdentifiableManyToManyOnReturnTests.cs index 242b5f4dea..a9a5ac1587 100644 --- a/test/UnitTests/ResourceHooks/Executor/IdentifiableManyToManyOnReturnTests.cs +++ b/test/UnitTests/ResourceHooks/Executor/IdentifiableManyToManyOnReturnTests.cs @@ -3,7 +3,6 @@ using JsonApiDotNetCore.Hooks.Internal; using JsonApiDotNetCore.Hooks.Internal.Discovery; using JsonApiDotNetCore.Hooks.Internal.Execution; -using JsonApiDotNetCore.Queries; using JsonApiDotNetCoreExample.Models; using Moq; using Xunit; From 0b998d06f460ce70a3969beab858f94acdba878b Mon Sep 17 00:00:00 2001 From: Bart Koelman Date: Wed, 3 Mar 2021 22:18:05 +0100 Subject: [PATCH 03/32] Test: fail the build with an inspectcode warning --- JsonApiDotNetCore.sln.DotSettings | 1 + 1 file changed, 1 insertion(+) diff --git a/JsonApiDotNetCore.sln.DotSettings b/JsonApiDotNetCore.sln.DotSettings index 0404af6c5b..831f8b5f91 100644 --- a/JsonApiDotNetCore.sln.DotSettings +++ b/JsonApiDotNetCore.sln.DotSettings @@ -75,6 +75,7 @@ JsonApiDotNetCore.ArgumentGuard.NotNull($EXPR$, $NAME$); SUGGESTION WARNING HINT + WARNING WARNING WARNING <?xml version="1.0" encoding="utf-16"?><Profile name="JADNC Full Cleanup"><XMLReformatCode>True</XMLReformatCode><CSCodeStyleAttributes ArrangeTypeAccessModifier="True" ArrangeTypeMemberAccessModifier="True" SortModifiers="True" RemoveRedundantParentheses="True" AddMissingParentheses="True" ArrangeBraces="True" ArrangeAttributes="True" ArrangeArgumentsStyle="True" ArrangeCodeBodyStyle="True" ArrangeVarStyle="True" ArrangeTrailingCommas="True" ArrangeObjectCreation="True" ArrangeDefaultValue="True" /><CssAlphabetizeProperties>True</CssAlphabetizeProperties><JsInsertSemicolon>True</JsInsertSemicolon><FormatAttributeQuoteDescriptor>True</FormatAttributeQuoteDescriptor><CorrectVariableKindsDescriptor>True</CorrectVariableKindsDescriptor><VariablesToInnerScopesDescriptor>True</VariablesToInnerScopesDescriptor><StringToTemplatesDescriptor>True</StringToTemplatesDescriptor><JsReformatCode>True</JsReformatCode><JsFormatDocComments>True</JsFormatDocComments><RemoveRedundantQualifiersTs>True</RemoveRedundantQualifiersTs><OptimizeImportsTs>True</OptimizeImportsTs><OptimizeReferenceCommentsTs>True</OptimizeReferenceCommentsTs><PublicModifierStyleTs>True</PublicModifierStyleTs><ExplicitAnyTs>True</ExplicitAnyTs><TypeAnnotationStyleTs>True</TypeAnnotationStyleTs><RelativePathStyleTs>True</RelativePathStyleTs><AsInsteadOfCastTs>True</AsInsteadOfCastTs><HtmlReformatCode>True</HtmlReformatCode><AspOptimizeRegisterDirectives>True</AspOptimizeRegisterDirectives><RemoveCodeRedundancies>True</RemoveCodeRedundancies><CSUseAutoProperty>True</CSUseAutoProperty><CSMakeFieldReadonly>True</CSMakeFieldReadonly><CSMakeAutoPropertyGetOnly>True</CSMakeAutoPropertyGetOnly><CSArrangeQualifiers>True</CSArrangeQualifiers><CSFixBuiltinTypeReferences>True</CSFixBuiltinTypeReferences><CssReformatCode>True</CssReformatCode><CSOptimizeUsings><OptimizeUsings>True</OptimizeUsings><EmbraceInRegion>False</EmbraceInRegion><RegionName></RegionName></CSOptimizeUsings><CSShortenReferences>True</CSShortenReferences><CSReformatCode>True</CSReformatCode><CSharpFormatDocComments>True</CSharpFormatDocComments><CSReorderTypeMembers>True</CSReorderTypeMembers><XAMLCollapseEmptyTags>False</XAMLCollapseEmptyTags></Profile> From 0afa6929f58c02a0dab3d2d9b6d2e1f0a422bb93 Mon Sep 17 00:00:00 2001 From: Bart Koelman Date: Wed, 3 Mar 2021 22:20:49 +0100 Subject: [PATCH 04/32] Test: fail the build with formatting violations --- JsonApiDotNetCore.sln.DotSettings | 1 - .../AtomicOperations/EntityFrameworkCoreTransaction.cs | 4 ++-- test/TestBuildingBlocks/IntegrationTest.cs | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/JsonApiDotNetCore.sln.DotSettings b/JsonApiDotNetCore.sln.DotSettings index 831f8b5f91..0404af6c5b 100644 --- a/JsonApiDotNetCore.sln.DotSettings +++ b/JsonApiDotNetCore.sln.DotSettings @@ -75,7 +75,6 @@ JsonApiDotNetCore.ArgumentGuard.NotNull($EXPR$, $NAME$); SUGGESTION WARNING HINT - WARNING WARNING WARNING <?xml version="1.0" encoding="utf-16"?><Profile name="JADNC Full Cleanup"><XMLReformatCode>True</XMLReformatCode><CSCodeStyleAttributes ArrangeTypeAccessModifier="True" ArrangeTypeMemberAccessModifier="True" SortModifiers="True" RemoveRedundantParentheses="True" AddMissingParentheses="True" ArrangeBraces="True" ArrangeAttributes="True" ArrangeArgumentsStyle="True" ArrangeCodeBodyStyle="True" ArrangeVarStyle="True" ArrangeTrailingCommas="True" ArrangeObjectCreation="True" ArrangeDefaultValue="True" /><CssAlphabetizeProperties>True</CssAlphabetizeProperties><JsInsertSemicolon>True</JsInsertSemicolon><FormatAttributeQuoteDescriptor>True</FormatAttributeQuoteDescriptor><CorrectVariableKindsDescriptor>True</CorrectVariableKindsDescriptor><VariablesToInnerScopesDescriptor>True</VariablesToInnerScopesDescriptor><StringToTemplatesDescriptor>True</StringToTemplatesDescriptor><JsReformatCode>True</JsReformatCode><JsFormatDocComments>True</JsFormatDocComments><RemoveRedundantQualifiersTs>True</RemoveRedundantQualifiersTs><OptimizeImportsTs>True</OptimizeImportsTs><OptimizeReferenceCommentsTs>True</OptimizeReferenceCommentsTs><PublicModifierStyleTs>True</PublicModifierStyleTs><ExplicitAnyTs>True</ExplicitAnyTs><TypeAnnotationStyleTs>True</TypeAnnotationStyleTs><RelativePathStyleTs>True</RelativePathStyleTs><AsInsteadOfCastTs>True</AsInsteadOfCastTs><HtmlReformatCode>True</HtmlReformatCode><AspOptimizeRegisterDirectives>True</AspOptimizeRegisterDirectives><RemoveCodeRedundancies>True</RemoveCodeRedundancies><CSUseAutoProperty>True</CSUseAutoProperty><CSMakeFieldReadonly>True</CSMakeFieldReadonly><CSMakeAutoPropertyGetOnly>True</CSMakeAutoPropertyGetOnly><CSArrangeQualifiers>True</CSArrangeQualifiers><CSFixBuiltinTypeReferences>True</CSFixBuiltinTypeReferences><CssReformatCode>True</CssReformatCode><CSOptimizeUsings><OptimizeUsings>True</OptimizeUsings><EmbraceInRegion>False</EmbraceInRegion><RegionName></RegionName></CSOptimizeUsings><CSShortenReferences>True</CSShortenReferences><CSReformatCode>True</CSReformatCode><CSharpFormatDocComments>True</CSharpFormatDocComments><CSReorderTypeMembers>True</CSReorderTypeMembers><XAMLCollapseEmptyTags>False</XAMLCollapseEmptyTags></Profile> diff --git a/src/JsonApiDotNetCore/AtomicOperations/EntityFrameworkCoreTransaction.cs b/src/JsonApiDotNetCore/AtomicOperations/EntityFrameworkCoreTransaction.cs index edb1cdd45d..74c9f1c9f8 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/EntityFrameworkCoreTransaction.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/EntityFrameworkCoreTransaction.cs @@ -21,13 +21,13 @@ public sealed class EntityFrameworkCoreTransaction : IOperationsTransaction public Guid TransactionId => _transaction.TransactionId; public EntityFrameworkCoreTransaction(IDbContextTransaction transaction, DbContext dbContext) - { +{ ArgumentGuard.NotNull(transaction, nameof(transaction)); ArgumentGuard.NotNull(dbContext, nameof(dbContext)); _transaction = transaction; _dbContext = dbContext; - } +} /// /// Detaches all entities from the Entity Framework Core change tracker. diff --git a/test/TestBuildingBlocks/IntegrationTest.cs b/test/TestBuildingBlocks/IntegrationTest.cs index bb2e051793..bad324a632 100644 --- a/test/TestBuildingBlocks/IntegrationTest.cs +++ b/test/TestBuildingBlocks/IntegrationTest.cs @@ -12,7 +12,7 @@ namespace TestBuildingBlocks /// A base class for tests that conveniently enables to execute HTTP requests against json:api endpoints. /// public abstract class IntegrationTest - { +{ public async Task<(HttpResponseMessage httpResponse, TResponseDocument responseDocument)> ExecuteGetAsync(string requestUrl, IEnumerable acceptHeaders = null) { From aeead1f8628e5ea5d2e16df9c0b0981d7878899d Mon Sep 17 00:00:00 2001 From: Bart Koelman Date: Thu, 4 Mar 2021 09:47:23 +0100 Subject: [PATCH 05/32] Revert "Test: fail the build with formatting violations" This reverts commit 2d4714bc6faedc0a3fffed788b66233ea617c3e6. --- JsonApiDotNetCore.sln.DotSettings | 1 + .../AtomicOperations/EntityFrameworkCoreTransaction.cs | 4 ++-- test/TestBuildingBlocks/IntegrationTest.cs | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/JsonApiDotNetCore.sln.DotSettings b/JsonApiDotNetCore.sln.DotSettings index 0404af6c5b..831f8b5f91 100644 --- a/JsonApiDotNetCore.sln.DotSettings +++ b/JsonApiDotNetCore.sln.DotSettings @@ -75,6 +75,7 @@ JsonApiDotNetCore.ArgumentGuard.NotNull($EXPR$, $NAME$); SUGGESTION WARNING HINT + WARNING WARNING WARNING <?xml version="1.0" encoding="utf-16"?><Profile name="JADNC Full Cleanup"><XMLReformatCode>True</XMLReformatCode><CSCodeStyleAttributes ArrangeTypeAccessModifier="True" ArrangeTypeMemberAccessModifier="True" SortModifiers="True" RemoveRedundantParentheses="True" AddMissingParentheses="True" ArrangeBraces="True" ArrangeAttributes="True" ArrangeArgumentsStyle="True" ArrangeCodeBodyStyle="True" ArrangeVarStyle="True" ArrangeTrailingCommas="True" ArrangeObjectCreation="True" ArrangeDefaultValue="True" /><CssAlphabetizeProperties>True</CssAlphabetizeProperties><JsInsertSemicolon>True</JsInsertSemicolon><FormatAttributeQuoteDescriptor>True</FormatAttributeQuoteDescriptor><CorrectVariableKindsDescriptor>True</CorrectVariableKindsDescriptor><VariablesToInnerScopesDescriptor>True</VariablesToInnerScopesDescriptor><StringToTemplatesDescriptor>True</StringToTemplatesDescriptor><JsReformatCode>True</JsReformatCode><JsFormatDocComments>True</JsFormatDocComments><RemoveRedundantQualifiersTs>True</RemoveRedundantQualifiersTs><OptimizeImportsTs>True</OptimizeImportsTs><OptimizeReferenceCommentsTs>True</OptimizeReferenceCommentsTs><PublicModifierStyleTs>True</PublicModifierStyleTs><ExplicitAnyTs>True</ExplicitAnyTs><TypeAnnotationStyleTs>True</TypeAnnotationStyleTs><RelativePathStyleTs>True</RelativePathStyleTs><AsInsteadOfCastTs>True</AsInsteadOfCastTs><HtmlReformatCode>True</HtmlReformatCode><AspOptimizeRegisterDirectives>True</AspOptimizeRegisterDirectives><RemoveCodeRedundancies>True</RemoveCodeRedundancies><CSUseAutoProperty>True</CSUseAutoProperty><CSMakeFieldReadonly>True</CSMakeFieldReadonly><CSMakeAutoPropertyGetOnly>True</CSMakeAutoPropertyGetOnly><CSArrangeQualifiers>True</CSArrangeQualifiers><CSFixBuiltinTypeReferences>True</CSFixBuiltinTypeReferences><CssReformatCode>True</CssReformatCode><CSOptimizeUsings><OptimizeUsings>True</OptimizeUsings><EmbraceInRegion>False</EmbraceInRegion><RegionName></RegionName></CSOptimizeUsings><CSShortenReferences>True</CSShortenReferences><CSReformatCode>True</CSReformatCode><CSharpFormatDocComments>True</CSharpFormatDocComments><CSReorderTypeMembers>True</CSReorderTypeMembers><XAMLCollapseEmptyTags>False</XAMLCollapseEmptyTags></Profile> diff --git a/src/JsonApiDotNetCore/AtomicOperations/EntityFrameworkCoreTransaction.cs b/src/JsonApiDotNetCore/AtomicOperations/EntityFrameworkCoreTransaction.cs index 74c9f1c9f8..edb1cdd45d 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/EntityFrameworkCoreTransaction.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/EntityFrameworkCoreTransaction.cs @@ -21,13 +21,13 @@ public sealed class EntityFrameworkCoreTransaction : IOperationsTransaction public Guid TransactionId => _transaction.TransactionId; public EntityFrameworkCoreTransaction(IDbContextTransaction transaction, DbContext dbContext) -{ + { ArgumentGuard.NotNull(transaction, nameof(transaction)); ArgumentGuard.NotNull(dbContext, nameof(dbContext)); _transaction = transaction; _dbContext = dbContext; -} + } /// /// Detaches all entities from the Entity Framework Core change tracker. diff --git a/test/TestBuildingBlocks/IntegrationTest.cs b/test/TestBuildingBlocks/IntegrationTest.cs index bad324a632..bb2e051793 100644 --- a/test/TestBuildingBlocks/IntegrationTest.cs +++ b/test/TestBuildingBlocks/IntegrationTest.cs @@ -12,7 +12,7 @@ namespace TestBuildingBlocks /// A base class for tests that conveniently enables to execute HTTP requests against json:api endpoints. /// public abstract class IntegrationTest -{ + { public async Task<(HttpResponseMessage httpResponse, TResponseDocument responseDocument)> ExecuteGetAsync(string requestUrl, IEnumerable acceptHeaders = null) { From d369ab41581a568897a191c1d7064244c3962b10 Mon Sep 17 00:00:00 2001 From: Bart Koelman Date: Thu, 4 Mar 2021 13:50:56 +0100 Subject: [PATCH 06/32] Revert "Test: fail the build with an inspectcode warning" This reverts commit 549a6f691382cefa1f4fd43e5847cfd096b283f1. --- JsonApiDotNetCore.sln.DotSettings | 1 - 1 file changed, 1 deletion(-) diff --git a/JsonApiDotNetCore.sln.DotSettings b/JsonApiDotNetCore.sln.DotSettings index 831f8b5f91..0404af6c5b 100644 --- a/JsonApiDotNetCore.sln.DotSettings +++ b/JsonApiDotNetCore.sln.DotSettings @@ -75,7 +75,6 @@ JsonApiDotNetCore.ArgumentGuard.NotNull($EXPR$, $NAME$); SUGGESTION WARNING HINT - WARNING WARNING WARNING <?xml version="1.0" encoding="utf-16"?><Profile name="JADNC Full Cleanup"><XMLReformatCode>True</XMLReformatCode><CSCodeStyleAttributes ArrangeTypeAccessModifier="True" ArrangeTypeMemberAccessModifier="True" SortModifiers="True" RemoveRedundantParentheses="True" AddMissingParentheses="True" ArrangeBraces="True" ArrangeAttributes="True" ArrangeArgumentsStyle="True" ArrangeCodeBodyStyle="True" ArrangeVarStyle="True" ArrangeTrailingCommas="True" ArrangeObjectCreation="True" ArrangeDefaultValue="True" /><CssAlphabetizeProperties>True</CssAlphabetizeProperties><JsInsertSemicolon>True</JsInsertSemicolon><FormatAttributeQuoteDescriptor>True</FormatAttributeQuoteDescriptor><CorrectVariableKindsDescriptor>True</CorrectVariableKindsDescriptor><VariablesToInnerScopesDescriptor>True</VariablesToInnerScopesDescriptor><StringToTemplatesDescriptor>True</StringToTemplatesDescriptor><JsReformatCode>True</JsReformatCode><JsFormatDocComments>True</JsFormatDocComments><RemoveRedundantQualifiersTs>True</RemoveRedundantQualifiersTs><OptimizeImportsTs>True</OptimizeImportsTs><OptimizeReferenceCommentsTs>True</OptimizeReferenceCommentsTs><PublicModifierStyleTs>True</PublicModifierStyleTs><ExplicitAnyTs>True</ExplicitAnyTs><TypeAnnotationStyleTs>True</TypeAnnotationStyleTs><RelativePathStyleTs>True</RelativePathStyleTs><AsInsteadOfCastTs>True</AsInsteadOfCastTs><HtmlReformatCode>True</HtmlReformatCode><AspOptimizeRegisterDirectives>True</AspOptimizeRegisterDirectives><RemoveCodeRedundancies>True</RemoveCodeRedundancies><CSUseAutoProperty>True</CSUseAutoProperty><CSMakeFieldReadonly>True</CSMakeFieldReadonly><CSMakeAutoPropertyGetOnly>True</CSMakeAutoPropertyGetOnly><CSArrangeQualifiers>True</CSArrangeQualifiers><CSFixBuiltinTypeReferences>True</CSFixBuiltinTypeReferences><CssReformatCode>True</CssReformatCode><CSOptimizeUsings><OptimizeUsings>True</OptimizeUsings><EmbraceInRegion>False</EmbraceInRegion><RegionName></RegionName></CSOptimizeUsings><CSShortenReferences>True</CSShortenReferences><CSReformatCode>True</CSReformatCode><CSharpFormatDocComments>True</CSharpFormatDocComments><CSReorderTypeMembers>True</CSReorderTypeMembers><XAMLCollapseEmptyTags>False</XAMLCollapseEmptyTags></Profile> From 49a833465d93d053263a99bebc80faf229054374 Mon Sep 17 00:00:00 2001 From: Bart Koelman Date: Thu, 4 Mar 2021 18:26:29 +0100 Subject: [PATCH 07/32] Empty commit From 9b1ab1864a9ffd65225a86b230a8fe17b9f61938 Mon Sep 17 00:00:00 2001 From: Bart Koelman Date: Fri, 5 Mar 2021 14:07:24 +0100 Subject: [PATCH 08/32] Use extension method for null/empty checks and assertions --- src/JsonApiDotNetCore/ArgumentGuard.cs | 17 +++++++++++++-- .../AtomicOperations/LocalIdTracker.cs | 14 ++++++------- .../AtomicOperations/LocalIdValidator.cs | 2 +- .../Configuration/ResourceGraph.cs | 2 +- .../DisableQueryStringAttribute.cs | 2 +- .../Controllers/BaseJsonApiController.cs | 10 ++++----- .../Controllers/ModelStateViolation.cs | 4 ++-- .../Errors/JsonApiException.cs | 10 +++------ .../Errors/MissingResourceInRelationship.cs | 6 +++--- .../Middleware/JsonApiRoutingConvention.cs | 2 +- .../Queries/Expressions/IncludeExpression.cs | 7 +------ .../PaginationQueryStringValueExpression.cs | 7 +------ .../ResourceFieldChainExpression.cs | 7 +------ .../Queries/Expressions/SortExpression.cs | 7 +------ .../Expressions/SparseFieldSetExpression.cs | 7 +------ .../Expressions/SparseFieldTableExpression.cs | 7 +------ .../LambdaParameterNameFactory.cs | 2 +- .../LambdaParameterNameScope.cs | 2 +- .../QueryableBuilding/QueryableBuilder.cs | 3 +-- src/JsonApiDotNetCore/Queries/QueryLayer.cs | 3 +-- .../FilterQueryStringParameterReader.cs | 2 +- .../Internal/LegacyFilterNotationConverter.cs | 6 +++--- .../SortQueryStringParameterReader.cs | 2 +- ...parseFieldSetQueryStringParameterReader.cs | 2 +- .../MemoryLeakDetectionBugRewriter.cs | 2 +- .../Annotations/HasManyThroughAttribute.cs | 2 +- .../Annotations/ResourceAttribute.cs | 2 +- .../Resources/ResourceDefinitionAccessor.cs | 2 +- .../Serialization/BaseDeserializer.cs | 6 +++--- .../Serialization/Building/LinkBuilder.cs | 4 ++-- .../Client/Internal/ResponseDeserializer.cs | 6 +++--- .../Serialization/RequestDeserializer.cs | 2 +- .../Services/JsonApiResourceService.cs | 8 +++---- .../Controllers/BaseJsonApiControllerTests.cs | 21 +++++++++++-------- .../Models/ResourceWithStringConstructor.cs | 2 +- 35 files changed, 85 insertions(+), 105 deletions(-) diff --git a/src/JsonApiDotNetCore/ArgumentGuard.cs b/src/JsonApiDotNetCore/ArgumentGuard.cs index 28640848a2..382e530c08 100644 --- a/src/JsonApiDotNetCore/ArgumentGuard.cs +++ b/src/JsonApiDotNetCore/ArgumentGuard.cs @@ -20,13 +20,26 @@ public static void NotNull([CanBeNull] [NoEnumeration] T value, [NotNull] [In [AssertionMethod] [ContractAnnotation("value: null => halt")] - public static void NotNullNorEmpty([CanBeNull] IEnumerable value, [NotNull] [InvokerParameterName] string name) + public static void NotNullNorEmpty([CanBeNull] IEnumerable value, [NotNull] [InvokerParameterName] string name, + [CanBeNull] string collectionName = null) { NotNull(value, name); if (!value.Any()) { - throw new ArgumentException("Collection cannot be empty.", name); + throw new ArgumentException($"Must have one or more {collectionName ?? name}.", name); + } + } + + [AssertionMethod] + [ContractAnnotation("value: null => halt")] + public static void NotNullNorEmpty([CanBeNull] string value, [NotNull] [InvokerParameterName] string name) + { + NotNull(value, name); + + if (value == string.Empty) + { + throw new ArgumentException("String cannot be null or empty.", name); } } } diff --git a/src/JsonApiDotNetCore/AtomicOperations/LocalIdTracker.cs b/src/JsonApiDotNetCore/AtomicOperations/LocalIdTracker.cs index 56faba2b66..453267d828 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/LocalIdTracker.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/LocalIdTracker.cs @@ -20,8 +20,8 @@ public void Reset() /// public void Declare(string localId, string resourceType) { - ArgumentGuard.NotNull(localId, nameof(localId)); - ArgumentGuard.NotNull(resourceType, nameof(resourceType)); + ArgumentGuard.NotNullNorEmpty(localId, nameof(localId)); + ArgumentGuard.NotNullNorEmpty(resourceType, nameof(resourceType)); AssertIsNotDeclared(localId); @@ -43,9 +43,9 @@ private void AssertIsNotDeclared(string localId) /// public void Assign(string localId, string resourceType, string stringId) { - ArgumentGuard.NotNull(localId, nameof(localId)); - ArgumentGuard.NotNull(resourceType, nameof(resourceType)); - ArgumentGuard.NotNull(stringId, nameof(stringId)); + ArgumentGuard.NotNullNorEmpty(localId, nameof(localId)); + ArgumentGuard.NotNullNorEmpty(resourceType, nameof(resourceType)); + ArgumentGuard.NotNullNorEmpty(stringId, nameof(stringId)); AssertIsDeclared(localId); @@ -64,8 +64,8 @@ public void Assign(string localId, string resourceType, string stringId) /// public string GetValue(string localId, string resourceType) { - ArgumentGuard.NotNull(localId, nameof(localId)); - ArgumentGuard.NotNull(resourceType, nameof(resourceType)); + ArgumentGuard.NotNullNorEmpty(localId, nameof(localId)); + ArgumentGuard.NotNullNorEmpty(resourceType, nameof(resourceType)); AssertIsDeclared(localId); diff --git a/src/JsonApiDotNetCore/AtomicOperations/LocalIdValidator.cs b/src/JsonApiDotNetCore/AtomicOperations/LocalIdValidator.cs index 47ab571cb3..79ea1bf6ba 100644 --- a/src/JsonApiDotNetCore/AtomicOperations/LocalIdValidator.cs +++ b/src/JsonApiDotNetCore/AtomicOperations/LocalIdValidator.cs @@ -91,7 +91,7 @@ private void AssignLocalId(OperationContainer operation) { ResourceContext resourceContext = _resourceContextProvider.GetResourceContext(operation.Resource.GetType()); - _localIdTracker.Assign(operation.Resource.LocalId, resourceContext.PublicName, string.Empty); + _localIdTracker.Assign(operation.Resource.LocalId, resourceContext.PublicName, "placeholder"); } } diff --git a/src/JsonApiDotNetCore/Configuration/ResourceGraph.cs b/src/JsonApiDotNetCore/Configuration/ResourceGraph.cs index 3f56e3fffe..8689f5a6ac 100644 --- a/src/JsonApiDotNetCore/Configuration/ResourceGraph.cs +++ b/src/JsonApiDotNetCore/Configuration/ResourceGraph.cs @@ -32,7 +32,7 @@ public IReadOnlyCollection GetResourceContexts() /// public ResourceContext GetResourceContext(string resourceName) { - ArgumentGuard.NotNull(resourceName, nameof(resourceName)); + ArgumentGuard.NotNullNorEmpty(resourceName, nameof(resourceName)); return _resources.SingleOrDefault(e => e.PublicName == resourceName); } diff --git a/src/JsonApiDotNetCore/Controllers/Annotations/DisableQueryStringAttribute.cs b/src/JsonApiDotNetCore/Controllers/Annotations/DisableQueryStringAttribute.cs index e363b1aabb..4bf10ec976 100644 --- a/src/JsonApiDotNetCore/Controllers/Annotations/DisableQueryStringAttribute.cs +++ b/src/JsonApiDotNetCore/Controllers/Annotations/DisableQueryStringAttribute.cs @@ -48,7 +48,7 @@ public DisableQueryStringAttribute(StandardQueryStringParameters parameters) /// public DisableQueryStringAttribute(string parameterNames) { - ArgumentGuard.NotNull(parameterNames, nameof(parameterNames)); + ArgumentGuard.NotNullNorEmpty(parameterNames, nameof(parameterNames)); ParameterNames = parameterNames.Split(",").ToList(); } diff --git a/src/JsonApiDotNetCore/Controllers/BaseJsonApiController.cs b/src/JsonApiDotNetCore/Controllers/BaseJsonApiController.cs index d625abbdec..978fe828f5 100644 --- a/src/JsonApiDotNetCore/Controllers/BaseJsonApiController.cs +++ b/src/JsonApiDotNetCore/Controllers/BaseJsonApiController.cs @@ -130,7 +130,7 @@ public virtual async Task GetSecondaryAsync(TId id, string relati relationshipName }); - ArgumentGuard.NotNull(relationshipName, nameof(relationshipName)); + ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName)); if (_getSecondary == null) { @@ -153,7 +153,7 @@ public virtual async Task GetRelationshipAsync(TId id, string rel relationshipName }); - ArgumentGuard.NotNull(relationshipName, nameof(relationshipName)); + ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName)); if (_getRelationship == null) { @@ -232,7 +232,7 @@ public virtual async Task PostRelationshipAsync(TId id, string re secondaryResourceIds }); - ArgumentGuard.NotNull(relationshipName, nameof(relationshipName)); + ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName)); ArgumentGuard.NotNull(secondaryResourceIds, nameof(secondaryResourceIds)); if (_addToRelationship == null) @@ -300,7 +300,7 @@ public virtual async Task PatchRelationshipAsync(TId id, string r secondaryResourceIds }); - ArgumentGuard.NotNull(relationshipName, nameof(relationshipName)); + ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName)); if (_setRelationship == null) { @@ -357,7 +357,7 @@ public virtual async Task DeleteRelationshipAsync(TId id, string secondaryResourceIds }); - ArgumentGuard.NotNull(relationshipName, nameof(relationshipName)); + ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName)); ArgumentGuard.NotNull(secondaryResourceIds, nameof(secondaryResourceIds)); if (_removeFromRelationship == null) diff --git a/src/JsonApiDotNetCore/Controllers/ModelStateViolation.cs b/src/JsonApiDotNetCore/Controllers/ModelStateViolation.cs index 8bda54c806..2a4c8cfb84 100644 --- a/src/JsonApiDotNetCore/Controllers/ModelStateViolation.cs +++ b/src/JsonApiDotNetCore/Controllers/ModelStateViolation.cs @@ -17,8 +17,8 @@ public sealed class ModelStateViolation public ModelStateViolation(string prefix, string propertyName, Type resourceType, ModelError error) { - ArgumentGuard.NotNull(prefix, nameof(prefix)); - ArgumentGuard.NotNull(propertyName, nameof(propertyName)); + ArgumentGuard.NotNullNorEmpty(prefix, nameof(prefix)); + ArgumentGuard.NotNullNorEmpty(propertyName, nameof(propertyName)); ArgumentGuard.NotNull(resourceType, nameof(resourceType)); ArgumentGuard.NotNull(error, nameof(error)); diff --git a/src/JsonApiDotNetCore/Errors/JsonApiException.cs b/src/JsonApiDotNetCore/Errors/JsonApiException.cs index 55a88e287a..93ba6fe6cb 100644 --- a/src/JsonApiDotNetCore/Errors/JsonApiException.cs +++ b/src/JsonApiDotNetCore/Errors/JsonApiException.cs @@ -34,14 +34,10 @@ public JsonApiException(Error error, Exception innerException = null) public JsonApiException(IEnumerable errors, Exception innerException = null) : base(null, innerException) { - ArgumentGuard.NotNull(errors, nameof(errors)); + List errorList = errors?.ToList(); + ArgumentGuard.NotNullNorEmpty(errorList, nameof(errors)); - Errors = errors.ToList(); - - if (!Errors.Any()) - { - throw new ArgumentException("At least one error is required.", nameof(errors)); - } + Errors = errorList; } } } diff --git a/src/JsonApiDotNetCore/Errors/MissingResourceInRelationship.cs b/src/JsonApiDotNetCore/Errors/MissingResourceInRelationship.cs index 95ef199932..7afe5b04cc 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, nameof(relationshipName)); - ArgumentGuard.NotNull(resourceType, nameof(resourceType)); - ArgumentGuard.NotNull(resourceId, nameof(resourceId)); + ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName)); + ArgumentGuard.NotNullNorEmpty(resourceType, nameof(resourceType)); + ArgumentGuard.NotNullNorEmpty(resourceId, nameof(resourceId)); RelationshipName = relationshipName; ResourceType = resourceType; diff --git a/src/JsonApiDotNetCore/Middleware/JsonApiRoutingConvention.cs b/src/JsonApiDotNetCore/Middleware/JsonApiRoutingConvention.cs index 4d64bfe9d0..d59e1699c0 100644 --- a/src/JsonApiDotNetCore/Middleware/JsonApiRoutingConvention.cs +++ b/src/JsonApiDotNetCore/Middleware/JsonApiRoutingConvention.cs @@ -48,7 +48,7 @@ public JsonApiRoutingConvention(IJsonApiOptions options, IResourceContextProvide /// public Type GetResourceTypeForController(string controllerName) { - ArgumentGuard.NotNull(controllerName, nameof(controllerName)); + ArgumentGuard.NotNullNorEmpty(controllerName, nameof(controllerName)); if (_registeredResources.TryGetValue(controllerName, out ResourceContext resourceContext)) { diff --git a/src/JsonApiDotNetCore/Queries/Expressions/IncludeExpression.cs b/src/JsonApiDotNetCore/Queries/Expressions/IncludeExpression.cs index 538d698193..8ba61be88e 100644 --- a/src/JsonApiDotNetCore/Queries/Expressions/IncludeExpression.cs +++ b/src/JsonApiDotNetCore/Queries/Expressions/IncludeExpression.cs @@ -16,12 +16,7 @@ public class IncludeExpression : QueryExpression public IncludeExpression(IReadOnlyCollection elements) { - ArgumentGuard.NotNull(elements, nameof(elements)); - - if (!elements.Any()) - { - throw new ArgumentException("Must have one or more elements.", nameof(elements)); - } + ArgumentGuard.NotNullNorEmpty(elements, nameof(elements)); Elements = elements; } diff --git a/src/JsonApiDotNetCore/Queries/Expressions/PaginationQueryStringValueExpression.cs b/src/JsonApiDotNetCore/Queries/Expressions/PaginationQueryStringValueExpression.cs index 7046c7b1ad..1850ab0b02 100644 --- a/src/JsonApiDotNetCore/Queries/Expressions/PaginationQueryStringValueExpression.cs +++ b/src/JsonApiDotNetCore/Queries/Expressions/PaginationQueryStringValueExpression.cs @@ -15,12 +15,7 @@ public class PaginationQueryStringValueExpression : QueryExpression public PaginationQueryStringValueExpression(IReadOnlyCollection elements) { - ArgumentGuard.NotNull(elements, nameof(elements)); - - if (!elements.Any()) - { - throw new ArgumentException("Must have one or more elements.", nameof(elements)); - } + ArgumentGuard.NotNullNorEmpty(elements, nameof(elements)); Elements = elements; } diff --git a/src/JsonApiDotNetCore/Queries/Expressions/ResourceFieldChainExpression.cs b/src/JsonApiDotNetCore/Queries/Expressions/ResourceFieldChainExpression.cs index 156c7cd091..2ebec58d17 100644 --- a/src/JsonApiDotNetCore/Queries/Expressions/ResourceFieldChainExpression.cs +++ b/src/JsonApiDotNetCore/Queries/Expressions/ResourceFieldChainExpression.cs @@ -23,12 +23,7 @@ public ResourceFieldChainExpression(ResourceFieldAttribute field) public ResourceFieldChainExpression(IReadOnlyCollection fields) { - ArgumentGuard.NotNull(fields, nameof(fields)); - - if (!fields.Any()) - { - throw new ArgumentException("Must have one or more fields.", nameof(fields)); - } + ArgumentGuard.NotNullNorEmpty(fields, nameof(fields)); Fields = fields; } diff --git a/src/JsonApiDotNetCore/Queries/Expressions/SortExpression.cs b/src/JsonApiDotNetCore/Queries/Expressions/SortExpression.cs index ab4d4a6f43..9f9c74b668 100644 --- a/src/JsonApiDotNetCore/Queries/Expressions/SortExpression.cs +++ b/src/JsonApiDotNetCore/Queries/Expressions/SortExpression.cs @@ -15,12 +15,7 @@ public class SortExpression : QueryExpression public SortExpression(IReadOnlyCollection elements) { - ArgumentGuard.NotNull(elements, nameof(elements)); - - if (!elements.Any()) - { - throw new ArgumentException("Must have one or more elements.", nameof(elements)); - } + ArgumentGuard.NotNullNorEmpty(elements, nameof(elements)); Elements = elements; } diff --git a/src/JsonApiDotNetCore/Queries/Expressions/SparseFieldSetExpression.cs b/src/JsonApiDotNetCore/Queries/Expressions/SparseFieldSetExpression.cs index 32ba68c45e..7511ab309a 100644 --- a/src/JsonApiDotNetCore/Queries/Expressions/SparseFieldSetExpression.cs +++ b/src/JsonApiDotNetCore/Queries/Expressions/SparseFieldSetExpression.cs @@ -16,12 +16,7 @@ public class SparseFieldSetExpression : QueryExpression public SparseFieldSetExpression(IReadOnlyCollection fields) { - ArgumentGuard.NotNull(fields, nameof(fields)); - - if (!fields.Any()) - { - throw new ArgumentException("Must have one or more fields.", nameof(fields)); - } + ArgumentGuard.NotNullNorEmpty(fields, nameof(fields)); Fields = fields; } diff --git a/src/JsonApiDotNetCore/Queries/Expressions/SparseFieldTableExpression.cs b/src/JsonApiDotNetCore/Queries/Expressions/SparseFieldTableExpression.cs index 48c86a1cba..4fdc92ec60 100644 --- a/src/JsonApiDotNetCore/Queries/Expressions/SparseFieldTableExpression.cs +++ b/src/JsonApiDotNetCore/Queries/Expressions/SparseFieldTableExpression.cs @@ -17,12 +17,7 @@ public class SparseFieldTableExpression : QueryExpression public SparseFieldTableExpression(IReadOnlyDictionary table) { - ArgumentGuard.NotNull(table, nameof(table)); - - if (!table.Any()) - { - throw new ArgumentException("Must have one or more entries.", nameof(table)); - } + ArgumentGuard.NotNullNorEmpty(table, nameof(table), "entries"); Table = table; } diff --git a/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/LambdaParameterNameFactory.cs b/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/LambdaParameterNameFactory.cs index 40d8b241b3..6309c8ac54 100644 --- a/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/LambdaParameterNameFactory.cs +++ b/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/LambdaParameterNameFactory.cs @@ -14,7 +14,7 @@ public sealed class LambdaParameterNameFactory public LambdaParameterNameScope Create(string typeName) { - ArgumentGuard.NotNull(typeName, nameof(typeName)); + ArgumentGuard.NotNullNorEmpty(typeName, nameof(typeName)); string parameterName = typeName.Camelize(); parameterName = EnsureNameIsUnique(parameterName); diff --git a/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/LambdaParameterNameScope.cs b/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/LambdaParameterNameScope.cs index 178ed800b6..6d555ed23e 100644 --- a/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/LambdaParameterNameScope.cs +++ b/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/LambdaParameterNameScope.cs @@ -12,7 +12,7 @@ public sealed class LambdaParameterNameScope : IDisposable public LambdaParameterNameScope(string name, LambdaParameterNameFactory owner) { - ArgumentGuard.NotNull(name, nameof(name)); + ArgumentGuard.NotNullNorEmpty(name, nameof(name)); ArgumentGuard.NotNull(owner, nameof(owner)); Name = name; diff --git a/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/QueryableBuilder.cs b/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/QueryableBuilder.cs index 4d4187b84f..c85c223364 100644 --- a/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/QueryableBuilder.cs +++ b/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/QueryableBuilder.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Linq.Expressions; using JetBrains.Annotations; using JsonApiDotNetCore.Configuration; @@ -74,7 +73,7 @@ public virtual Expression ApplyQuery(QueryLayer layer) expression = ApplyPagination(expression, layer.Pagination); } - if (layer.Projection != null && layer.Projection.Any()) + if (!layer.Projection.IsNullOrEmpty()) { expression = ApplyProjection(expression, layer.Projection, layer.ResourceContext); } diff --git a/src/JsonApiDotNetCore/Queries/QueryLayer.cs b/src/JsonApiDotNetCore/Queries/QueryLayer.cs index dfc022f164..1ea0f62733 100644 --- a/src/JsonApiDotNetCore/Queries/QueryLayer.cs +++ b/src/JsonApiDotNetCore/Queries/QueryLayer.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Text; using JetBrains.Annotations; using JsonApiDotNetCore.Configuration; @@ -66,7 +65,7 @@ private static void WriteLayer(IndentingStringWriter writer, QueryLayer layer, s writer.WriteLine($"{nameof(Pagination)}: {layer.Pagination}"); } - if (layer.Projection != null && layer.Projection.Any()) + if (!layer.Projection.IsNullOrEmpty()) { writer.WriteLine(nameof(Projection)); diff --git a/src/JsonApiDotNetCore/QueryStrings/Internal/FilterQueryStringParameterReader.cs b/src/JsonApiDotNetCore/QueryStrings/Internal/FilterQueryStringParameterReader.cs index c39c5e6f47..bcfce7fcd5 100644 --- a/src/JsonApiDotNetCore/QueryStrings/Internal/FilterQueryStringParameterReader.cs +++ b/src/JsonApiDotNetCore/QueryStrings/Internal/FilterQueryStringParameterReader.cs @@ -62,7 +62,7 @@ public virtual bool IsEnabled(DisableQueryStringAttribute disableQueryStringAttr /// public virtual bool CanRead(string parameterName) { - ArgumentGuard.NotNull(parameterName, nameof(parameterName)); + ArgumentGuard.NotNullNorEmpty(parameterName, nameof(parameterName)); bool isNested = parameterName.StartsWith("filter[", StringComparison.Ordinal) && parameterName.EndsWith("]", StringComparison.Ordinal); return parameterName == "filter" || isNested; diff --git a/src/JsonApiDotNetCore/QueryStrings/Internal/LegacyFilterNotationConverter.cs b/src/JsonApiDotNetCore/QueryStrings/Internal/LegacyFilterNotationConverter.cs index ff4a47f845..6be267289d 100644 --- a/src/JsonApiDotNetCore/QueryStrings/Internal/LegacyFilterNotationConverter.cs +++ b/src/JsonApiDotNetCore/QueryStrings/Internal/LegacyFilterNotationConverter.cs @@ -29,7 +29,7 @@ public sealed class LegacyFilterNotationConverter public IEnumerable ExtractConditions(string parameterValue) { - ArgumentGuard.NotNull(parameterValue, nameof(parameterValue)); + ArgumentGuard.NotNullNorEmpty(parameterValue, nameof(parameterValue)); if (parameterValue.StartsWith(ExpressionPrefix, StringComparison.Ordinal) || parameterValue.StartsWith(InPrefix, StringComparison.Ordinal) || parameterValue.StartsWith(NotInPrefix, StringComparison.Ordinal)) @@ -47,8 +47,8 @@ public IEnumerable ExtractConditions(string parameterValue) public (string parameterName, string parameterValue) Convert(string parameterName, string parameterValue) { - ArgumentGuard.NotNull(parameterName, nameof(parameterName)); - ArgumentGuard.NotNull(parameterValue, nameof(parameterValue)); + ArgumentGuard.NotNullNorEmpty(parameterName, nameof(parameterName)); + ArgumentGuard.NotNullNorEmpty(parameterValue, nameof(parameterValue)); if (parameterValue.StartsWith(ExpressionPrefix, StringComparison.Ordinal)) { diff --git a/src/JsonApiDotNetCore/QueryStrings/Internal/SortQueryStringParameterReader.cs b/src/JsonApiDotNetCore/QueryStrings/Internal/SortQueryStringParameterReader.cs index 0271d3f95d..058fa6817c 100644 --- a/src/JsonApiDotNetCore/QueryStrings/Internal/SortQueryStringParameterReader.cs +++ b/src/JsonApiDotNetCore/QueryStrings/Internal/SortQueryStringParameterReader.cs @@ -48,7 +48,7 @@ public virtual bool IsEnabled(DisableQueryStringAttribute disableQueryStringAttr /// public virtual bool CanRead(string parameterName) { - ArgumentGuard.NotNull(parameterName, nameof(parameterName)); + ArgumentGuard.NotNullNorEmpty(parameterName, nameof(parameterName)); bool isNested = parameterName.StartsWith("sort[", StringComparison.Ordinal) && parameterName.EndsWith("]", StringComparison.Ordinal); return parameterName == "sort" || isNested; diff --git a/src/JsonApiDotNetCore/QueryStrings/Internal/SparseFieldSetQueryStringParameterReader.cs b/src/JsonApiDotNetCore/QueryStrings/Internal/SparseFieldSetQueryStringParameterReader.cs index 6a0cbf9244..1ab65dc332 100644 --- a/src/JsonApiDotNetCore/QueryStrings/Internal/SparseFieldSetQueryStringParameterReader.cs +++ b/src/JsonApiDotNetCore/QueryStrings/Internal/SparseFieldSetQueryStringParameterReader.cs @@ -49,7 +49,7 @@ public virtual bool IsEnabled(DisableQueryStringAttribute disableQueryStringAttr /// public virtual bool CanRead(string parameterName) { - ArgumentGuard.NotNull(parameterName, nameof(parameterName)); + ArgumentGuard.NotNullNorEmpty(parameterName, nameof(parameterName)); return parameterName.StartsWith("fields[", StringComparison.Ordinal) && parameterName.EndsWith("]", StringComparison.Ordinal); } diff --git a/src/JsonApiDotNetCore/Repositories/MemoryLeakDetectionBugRewriter.cs b/src/JsonApiDotNetCore/Repositories/MemoryLeakDetectionBugRewriter.cs index 9d6c58a0ca..557f330791 100644 --- a/src/JsonApiDotNetCore/Repositories/MemoryLeakDetectionBugRewriter.cs +++ b/src/JsonApiDotNetCore/Repositories/MemoryLeakDetectionBugRewriter.cs @@ -38,7 +38,7 @@ private QueryLayer RewriteLayer(QueryLayer queryLayer) private IDictionary RewriteProjection(IDictionary projection, ResourceContext resourceContext) { - if (projection == null || projection.Count == 0) + if (projection.IsNullOrEmpty()) { return projection; } diff --git a/src/JsonApiDotNetCore/Resources/Annotations/HasManyThroughAttribute.cs b/src/JsonApiDotNetCore/Resources/Annotations/HasManyThroughAttribute.cs index 0b961a47e4..a2e46735b7 100644 --- a/src/JsonApiDotNetCore/Resources/Annotations/HasManyThroughAttribute.cs +++ b/src/JsonApiDotNetCore/Resources/Annotations/HasManyThroughAttribute.cs @@ -119,7 +119,7 @@ public sealed class HasManyThroughAttribute : HasManyAttribute /// public HasManyThroughAttribute(string throughPropertyName) { - ArgumentGuard.NotNull(throughPropertyName, nameof(throughPropertyName)); + ArgumentGuard.NotNullNorEmpty(throughPropertyName, nameof(throughPropertyName)); ThroughPropertyName = throughPropertyName; } diff --git a/src/JsonApiDotNetCore/Resources/Annotations/ResourceAttribute.cs b/src/JsonApiDotNetCore/Resources/Annotations/ResourceAttribute.cs index db6f7c8621..501d085d57 100644 --- a/src/JsonApiDotNetCore/Resources/Annotations/ResourceAttribute.cs +++ b/src/JsonApiDotNetCore/Resources/Annotations/ResourceAttribute.cs @@ -18,7 +18,7 @@ public sealed class ResourceAttribute : Attribute public ResourceAttribute(string publicName) { - ArgumentGuard.NotNull(publicName, nameof(publicName)); + ArgumentGuard.NotNullNorEmpty(publicName, nameof(publicName)); PublicName = publicName; } diff --git a/src/JsonApiDotNetCore/Resources/ResourceDefinitionAccessor.cs b/src/JsonApiDotNetCore/Resources/ResourceDefinitionAccessor.cs index 958e735e4d..9553d7fdfb 100644 --- a/src/JsonApiDotNetCore/Resources/ResourceDefinitionAccessor.cs +++ b/src/JsonApiDotNetCore/Resources/ResourceDefinitionAccessor.cs @@ -72,7 +72,7 @@ public SparseFieldSetExpression OnApplySparseFieldSet(Type resourceType, SparseF public object GetQueryableHandlerForQueryStringParameter(Type resourceType, string parameterName) { ArgumentGuard.NotNull(resourceType, nameof(resourceType)); - ArgumentGuard.NotNull(parameterName, nameof(parameterName)); + ArgumentGuard.NotNullNorEmpty(parameterName, nameof(parameterName)); dynamic resourceDefinition = ResolveResourceDefinition(resourceType); dynamic handlers = resourceDefinition.OnRegisterQueryableHandlersForQueryStringParameters(); diff --git a/src/JsonApiDotNetCore/Serialization/BaseDeserializer.cs b/src/JsonApiDotNetCore/Serialization/BaseDeserializer.cs index c5a393efe9..564c47b7e9 100644 --- a/src/JsonApiDotNetCore/Serialization/BaseDeserializer.cs +++ b/src/JsonApiDotNetCore/Serialization/BaseDeserializer.cs @@ -56,7 +56,7 @@ protected BaseDeserializer(IResourceContextProvider resourceContextProvider, IRe protected object DeserializeBody(string body) { - ArgumentGuard.NotNull(body, nameof(body)); + ArgumentGuard.NotNullNorEmpty(body, nameof(body)); JToken bodyJToken = LoadJToken(body); Document = bodyJToken.ToObject(); @@ -95,7 +95,7 @@ protected IIdentifiable SetAttributes(IIdentifiable resource, IDictionary ParsePageSizeExpressio /// public ResourceLinks GetResourceLinks(string resourceName, string id) { - ArgumentGuard.NotNull(resourceName, nameof(resourceName)); - ArgumentGuard.NotNull(id, nameof(id)); + ArgumentGuard.NotNullNorEmpty(resourceName, nameof(resourceName)); + ArgumentGuard.NotNullNorEmpty(id, nameof(id)); ResourceContext resourceContext = _provider.GetResourceContext(resourceName); diff --git a/src/JsonApiDotNetCore/Serialization/Client/Internal/ResponseDeserializer.cs b/src/JsonApiDotNetCore/Serialization/Client/Internal/ResponseDeserializer.cs index 83c0c94059..82cfac8fcb 100644 --- a/src/JsonApiDotNetCore/Serialization/Client/Internal/ResponseDeserializer.cs +++ b/src/JsonApiDotNetCore/Serialization/Client/Internal/ResponseDeserializer.cs @@ -25,7 +25,7 @@ public ResponseDeserializer(IResourceContextProvider resourceContextProvider, IR public SingleResponse DeserializeSingle(string body) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(body, nameof(body)); + ArgumentGuard.NotNullNorEmpty(body, nameof(body)); object resource = DeserializeBody(body); @@ -43,7 +43,7 @@ public SingleResponse DeserializeSingle(string body) public ManyResponse DeserializeMany(string body) where TResource : class, IIdentifiable { - ArgumentGuard.NotNull(body, nameof(body)); + ArgumentGuard.NotNullNorEmpty(body, nameof(body)); object resources = DeserializeBody(body); @@ -82,7 +82,7 @@ protected override void AfterProcessField(IIdentifiable resource, ResourceFieldA } // if the included property is empty or absent, there is no additional data to be parsed. - if (Document.Included == null || Document.Included.Count == 0) + if (Document.Included.IsNullOrEmpty()) { return; } diff --git a/src/JsonApiDotNetCore/Serialization/RequestDeserializer.cs b/src/JsonApiDotNetCore/Serialization/RequestDeserializer.cs index df0e66f562..3ae8661547 100644 --- a/src/JsonApiDotNetCore/Serialization/RequestDeserializer.cs +++ b/src/JsonApiDotNetCore/Serialization/RequestDeserializer.cs @@ -44,7 +44,7 @@ public RequestDeserializer(IResourceContextProvider resourceContextProvider, IRe /// public object Deserialize(string body) { - ArgumentGuard.NotNull(body, nameof(body)); + ArgumentGuard.NotNullNorEmpty(body, nameof(body)); if (_request.Kind == EndpointKind.Relationship) { diff --git a/src/JsonApiDotNetCore/Services/JsonApiResourceService.cs b/src/JsonApiDotNetCore/Services/JsonApiResourceService.cs index 0b472d9d6e..56eaa3f9c9 100644 --- a/src/JsonApiDotNetCore/Services/JsonApiResourceService.cs +++ b/src/JsonApiDotNetCore/Services/JsonApiResourceService.cs @@ -156,7 +156,7 @@ public virtual async Task GetRelationshipAsync(TId id, string relationsh relationshipName }); - ArgumentGuard.NotNull(relationshipName, nameof(relationshipName)); + ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName)); AssertHasRelationship(_request.Relationship, relationshipName); @@ -286,7 +286,7 @@ public async Task AddToToManyRelationshipAsync(TId primaryId, string relationshi secondaryResourceIds }); - ArgumentGuard.NotNull(relationshipName, nameof(relationshipName)); + ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName)); ArgumentGuard.NotNull(secondaryResourceIds, nameof(secondaryResourceIds)); AssertHasRelationship(_request.Relationship, relationshipName); @@ -401,7 +401,7 @@ public virtual async Task SetRelationshipAsync(TId primaryId, string relationshi secondaryResourceIds }); - ArgumentGuard.NotNull(relationshipName, nameof(relationshipName)); + ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName)); AssertHasRelationship(_request.Relationship, relationshipName); @@ -457,7 +457,7 @@ public async Task RemoveFromToManyRelationshipAsync(TId primaryId, string relati secondaryResourceIds }); - ArgumentGuard.NotNull(relationshipName, nameof(relationshipName)); + ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName)); ArgumentGuard.NotNull(secondaryResourceIds, nameof(secondaryResourceIds)); AssertHasRelationship(_request.Relationship, relationshipName); diff --git a/test/UnitTests/Controllers/BaseJsonApiControllerTests.cs b/test/UnitTests/Controllers/BaseJsonApiControllerTests.cs index 0e58363000..ef7cb6b66d 100644 --- a/test/UnitTests/Controllers/BaseJsonApiControllerTests.cs +++ b/test/UnitTests/Controllers/BaseJsonApiControllerTests.cs @@ -83,14 +83,15 @@ public async Task GetRelationshipsAsync_Calls_Service() { // Arrange const int id = 0; + const string relationshipName = "articles"; var serviceMock = new Mock>(); var controller = new ResourceController(new Mock().Object, NullLoggerFactory.Instance, getRelationship: serviceMock.Object); // Act - await controller.GetRelationshipAsync(id, string.Empty, CancellationToken.None); + await controller.GetRelationshipAsync(id, relationshipName, CancellationToken.None); // Assert - serviceMock.Verify(m => m.GetRelationshipAsync(id, string.Empty, CancellationToken.None), Times.Once); + serviceMock.Verify(m => m.GetRelationshipAsync(id, relationshipName, CancellationToken.None), Times.Once); } [Fact] @@ -102,7 +103,7 @@ public async Task GetRelationshipsAsync_Throws_405_If_No_Service() // Act var exception = await Assert.ThrowsAsync(() => - controller.GetRelationshipAsync(id, string.Empty, CancellationToken.None)); + controller.GetRelationshipAsync(id, "articles", CancellationToken.None)); // Assert Assert.Equal(HttpStatusCode.MethodNotAllowed, exception.Errors[0].StatusCode); @@ -114,14 +115,15 @@ public async Task GetRelationshipAsync_Calls_Service() { // Arrange const int id = 0; + const string relationshipName = "articles"; var serviceMock = new Mock>(); var controller = new ResourceController(new Mock().Object, NullLoggerFactory.Instance, getSecondary: serviceMock.Object); // Act - await controller.GetSecondaryAsync(id, string.Empty, CancellationToken.None); + await controller.GetSecondaryAsync(id, relationshipName, CancellationToken.None); // Assert - serviceMock.Verify(m => m.GetSecondaryAsync(id, string.Empty, CancellationToken.None), Times.Once); + serviceMock.Verify(m => m.GetSecondaryAsync(id, relationshipName, CancellationToken.None), Times.Once); } [Fact] @@ -133,7 +135,7 @@ public async Task GetRelationshipAsync_Throws_405_If_No_Service() // Act var exception = await Assert.ThrowsAsync(() => - controller.GetSecondaryAsync(id, string.Empty, CancellationToken.None)); + controller.GetSecondaryAsync(id, "articles", CancellationToken.None)); // Assert Assert.Equal(HttpStatusCode.MethodNotAllowed, exception.Errors[0].StatusCode); @@ -200,14 +202,15 @@ public async Task PatchRelationshipsAsync_Calls_Service() { // Arrange const int id = 0; + const string relationshipName = "articles"; var serviceMock = new Mock>(); var controller = new ResourceController(new Mock().Object, NullLoggerFactory.Instance, setRelationship: serviceMock.Object); // Act - await controller.PatchRelationshipAsync(id, string.Empty, null, CancellationToken.None); + await controller.PatchRelationshipAsync(id, relationshipName, null, CancellationToken.None); // Assert - serviceMock.Verify(m => m.SetRelationshipAsync(id, string.Empty, null, CancellationToken.None), Times.Once); + serviceMock.Verify(m => m.SetRelationshipAsync(id, relationshipName, null, CancellationToken.None), Times.Once); } [Fact] @@ -219,7 +222,7 @@ public async Task PatchRelationshipsAsync_Throws_405_If_No_Service() // Act var exception = await Assert.ThrowsAsync(() => - controller.PatchRelationshipAsync(id, string.Empty, null, CancellationToken.None)); + controller.PatchRelationshipAsync(id, "articles", null, CancellationToken.None)); // Assert Assert.Equal(HttpStatusCode.MethodNotAllowed, exception.Errors[0].StatusCode); diff --git a/test/UnitTests/Models/ResourceWithStringConstructor.cs b/test/UnitTests/Models/ResourceWithStringConstructor.cs index 8b166f50e4..82c80ae9f6 100644 --- a/test/UnitTests/Models/ResourceWithStringConstructor.cs +++ b/test/UnitTests/Models/ResourceWithStringConstructor.cs @@ -11,7 +11,7 @@ internal sealed class ResourceWithStringConstructor : Identifiable public ResourceWithStringConstructor(string text) { - ArgumentGuard.NotNull(text, nameof(text)); + ArgumentGuard.NotNullNorEmpty(text, nameof(text)); Text = text; } From 85c0205d2053d4b34044049a711f54890a2f7976 Mon Sep 17 00:00:00 2001 From: Bart Koelman Date: Fri, 5 Mar 2021 14:14:23 +0100 Subject: [PATCH 09/32] Removed unused code --- .../Internal/Execution/HookExecutorHelper.cs | 18 ++---------------- .../Execution/IByAffectedRelationships.cs | 2 ++ .../Internal/Execution/IHookExecutorHelper.cs | 5 +---- .../Internal/Execution/IRelationshipGetters.cs | 2 ++ .../Hooks/Internal/ResourceHookExecutor.cs | 2 +- .../Internal/Traversal/IRelationshipGroup.cs | 5 ----- .../CustomRoutes/CustomRouteTests.cs | 1 + 7 files changed, 9 insertions(+), 26 deletions(-) diff --git a/src/JsonApiDotNetCore/Hooks/Internal/Execution/HookExecutorHelper.cs b/src/JsonApiDotNetCore/Hooks/Internal/Execution/HookExecutorHelper.cs index 0ba564f9da..6e1e760756 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/Execution/HookExecutorHelper.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/Execution/HookExecutorHelper.cs @@ -87,7 +87,7 @@ public IResourceHookContainer GetResourceHookContainer(Res return (IResourceHookContainer)GetResourceHookContainer(typeof(TResource), hook); } - public IEnumerable LoadDbValues(LeftType resourceTypeForRepository, IEnumerable resources, ResourceHook hook, + public IEnumerable LoadDbValues(LeftType resourceTypeForRepository, IEnumerable resources, params RelationshipAttribute[] relationshipsToNextLayer) { LeftType idType = TypeHelper.GetIdType(resourceTypeForRepository); @@ -109,20 +109,6 @@ public IEnumerable LoadDbValues(LeftType resourceTypeForRepository, IEnumerable TypeHelper.CopyToList(values, resourceTypeForRepository)); } - public HashSet LoadDbValues(IEnumerable resources, ResourceHook hook, params RelationshipAttribute[] relationships) - where TResource : class, IIdentifiable - { - Type resourceType = typeof(TResource); - IEnumerable dbValues = LoadDbValues(resourceType, resources, hook, relationships)?.Cast(); - - if (dbValues == null) - { - return null; - } - - return new HashSet(dbValues); - } - public bool ShouldLoadDbValues(LeftType resourceType, ResourceHook hook) { IHooksDiscovery discovery = GetHookDiscovery(resourceType); @@ -230,7 +216,7 @@ public Dictionary LoadImplicitlyAffected(Dic } // note that we don't have to check if BeforeImplicitUpdate hook is implemented. If not, it wont ever get here. - IEnumerable includedLefts = LoadDbValues(relationship.LeftType, lefts, ResourceHook.BeforeImplicitUpdateRelationship, relationship); + IEnumerable includedLefts = LoadDbValues(relationship.LeftType, lefts, relationship); AddToImplicitlyAffected(includedLefts, relationship, existingRightResourceList, implicitlyAffected); } diff --git a/src/JsonApiDotNetCore/Hooks/Internal/Execution/IByAffectedRelationships.cs b/src/JsonApiDotNetCore/Hooks/Internal/Execution/IByAffectedRelationships.cs index 2d77f065b0..5d69aa3cdb 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/Execution/IByAffectedRelationships.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/Execution/IByAffectedRelationships.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using JetBrains.Annotations; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; @@ -7,6 +8,7 @@ namespace JsonApiDotNetCore.Hooks.Internal.Execution /// /// An interface that is implemented to expose a relationship dictionary on another class. /// + [PublicAPI] public interface IByAffectedRelationships : IRelationshipGetters where TRightResource : class, IIdentifiable { diff --git a/src/JsonApiDotNetCore/Hooks/Internal/Execution/IHookExecutorHelper.cs b/src/JsonApiDotNetCore/Hooks/Internal/Execution/IHookExecutorHelper.cs index 56a7f635f9..1558349453 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/Execution/IHookExecutorHelper.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/Execution/IHookExecutorHelper.cs @@ -43,13 +43,10 @@ Dictionary LoadImplicitlyAffected(Dictionary /// /// The set of resources to load the db values for /// - /// - /// The hook in which the db values will be displayed. - /// /// /// Relationships that need to be included on resources. /// - IEnumerable LoadDbValues(Type resourceTypeForRepository, IEnumerable resources, ResourceHook hook, params RelationshipAttribute[] relationships); + IEnumerable LoadDbValues(Type resourceTypeForRepository, IEnumerable resources, params RelationshipAttribute[] relationships); /// /// Checks if the display database values option is allowed for the targeted hook, and for a given resource of type diff --git a/src/JsonApiDotNetCore/Hooks/Internal/Execution/IRelationshipGetters.cs b/src/JsonApiDotNetCore/Hooks/Internal/Execution/IRelationshipGetters.cs index ab3d80eca9..85c9224b4c 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/Execution/IRelationshipGetters.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/Execution/IRelationshipGetters.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq.Expressions; +using JetBrains.Annotations; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; @@ -9,6 +10,7 @@ namespace JsonApiDotNetCore.Hooks.Internal.Execution /// /// A helper class that provides insights in which relationships have been updated for which resources. /// + [PublicAPI] public interface IRelationshipGetters where TLeftResource : class, IIdentifiable { diff --git a/src/JsonApiDotNetCore/Hooks/Internal/ResourceHookExecutor.cs b/src/JsonApiDotNetCore/Hooks/Internal/ResourceHookExecutor.cs index dcb3517027..25af51f56b 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/ResourceHookExecutor.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/ResourceHookExecutor.cs @@ -546,7 +546,7 @@ private IEnumerable LoadDbValues(Type resourceType, IEnumerable uniqueResources, return null; } - return _executorHelper.LoadDbValues(resourceType, uniqueResources, targetHook, relationshipsToNextLayer); + return _executorHelper.LoadDbValues(resourceType, uniqueResources, relationshipsToNextLayer); } /// diff --git a/src/JsonApiDotNetCore/Hooks/Internal/Traversal/IRelationshipGroup.cs b/src/JsonApiDotNetCore/Hooks/Internal/Traversal/IRelationshipGroup.cs index 54d93c7905..3dc9c9a8fa 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/Traversal/IRelationshipGroup.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/Traversal/IRelationshipGroup.cs @@ -1,11 +1,6 @@ -using System.Collections.Generic; -using JsonApiDotNetCore.Resources; - namespace JsonApiDotNetCore.Hooks.Internal.Traversal { internal interface IRelationshipGroup { - RelationshipProxy Proxy { get; } - HashSet LeftResources { get; } } } diff --git a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/CustomRoutes/CustomRouteTests.cs b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/CustomRoutes/CustomRouteTests.cs index 7bee8663e2..9663c6c830 100644 --- a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/CustomRoutes/CustomRouteTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/CustomRoutes/CustomRouteTests.cs @@ -28,6 +28,7 @@ public async Task Can_get_resource_at_custom_route() { // Arrange Town town = _fakers.Town.Generate(); + town.Civilians = _fakers.Civilian.Generate(1).ToHashSet(); await _testContext.RunOnDatabaseAsync(async dbContext => { From dc9dceb3127815e676faaed851a458deb47a93c5 Mon Sep 17 00:00:00 2001 From: Bart Koelman Date: Fri, 5 Mar 2021 14:26:38 +0100 Subject: [PATCH 10/32] Formatting: trim trailing whitespace --- .../Execution/DiffableResourceHashSet.cs | 2 +- .../Internal/Execution/HookExecutorHelper.cs | 8 ++--- .../Hooks/Internal/ResourceHookExecutor.cs | 30 +++++++++---------- .../Internal/Traversal/TraversalHelper.cs | 2 +- .../EntityFrameworkCoreRepository.cs | 2 +- .../Annotations/EagerLoadAttribute.cs | 2 +- .../Resources/Annotations/HasManyAttribute.cs | 2 +- .../ServiceCollectionExtensionsTests.cs | 2 +- .../UnitTests/Models/RelationshipDataTests.cs | 8 ++--- 9 files changed, 29 insertions(+), 29 deletions(-) diff --git a/src/JsonApiDotNetCore/Hooks/Internal/Execution/DiffableResourceHashSet.cs b/src/JsonApiDotNetCore/Hooks/Internal/Execution/DiffableResourceHashSet.cs index a61fb4b6d5..5f71106ad4 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/Execution/DiffableResourceHashSet.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/Execution/DiffableResourceHashSet.cs @@ -71,7 +71,7 @@ public override HashSet GetAffected(Expression public IResourceHookContainer GetResourceHookContainer(RightType targetResource, ResourceHook hook = ResourceHook.None) { - // checking the cache if we have a reference for the requested container, - // regardless of the hook we will use it for. If the value is null, - // it means there was no implementation IResourceHookContainer at all, + // checking the cache if we have a reference for the requested container, + // regardless of the hook we will use it for. If the value is null, + // it means there was no implementation IResourceHookContainer at all, // so we need not even bother. if (!_hookContainers.TryGetValue(targetResource, out IResourceHookContainer container)) { @@ -55,7 +55,7 @@ public IResourceHookContainer GetResourceHookContainer(RightType targetResource, return null; } - // if there was a container, first check if it implements the hook we + // if there was a container, first check if it implements the hook we // want to use it for. IEnumerable targetHooks; diff --git a/src/JsonApiDotNetCore/Hooks/Internal/ResourceHookExecutor.cs b/src/JsonApiDotNetCore/Hooks/Internal/ResourceHookExecutor.cs index 25af51f56b..6ee5bad873 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/ResourceHookExecutor.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/ResourceHookExecutor.cs @@ -315,13 +315,13 @@ private void FireNestedBeforeUpdateHooks(ResourcePipeline pipeline, NodeLayer la RelationshipAttribute[] relationships = node.RelationshipsToNextLayer.Select(p => p.Attribute).ToArray(); IEnumerable dbValues = LoadDbValues(resourceType, uniqueResources, ResourceHook.BeforeUpdateRelationship, relationships); - // these are the resources of the current node grouped by + // these are the resources of the current node grouped by // RelationshipAttributes that occurred in the previous layer // so it looks like { HasOneAttribute:owner => owner_new }. - // Note that in the BeforeUpdateRelationship hook of Person, + // Note that in the BeforeUpdateRelationship hook of Person, // we want want inverse relationship attribute: // we now have the one pointing from article -> person, ] - // but we require the the one that points from person -> article + // but we require the the one that points from person -> article currentResourcesGrouped = node.RelationshipsFromPreviousLayer.GetRightResources(); currentResourcesGroupedInverse = ReplaceKeysWithInverseRelationships(currentResourcesGrouped); @@ -342,8 +342,8 @@ private void FireNestedBeforeUpdateHooks(ResourcePipeline pipeline, NodeLayer la if (pipeline != ResourcePipeline.Post) { // To fire a hook for owner_old, we need to first get a reference to it. - // For this, we need to query the database for the HasOneAttribute:owner - // relationship of article1, which is referred to as the + // For this, we need to query the database for the HasOneAttribute:owner + // relationship of article1, which is referred to as the // left side of the HasOneAttribute:owner relationship. Dictionary leftResources = node.RelationshipsFromPreviousLayer.GetLeftResources(); @@ -355,21 +355,21 @@ private void FireNestedBeforeUpdateHooks(ResourcePipeline pipeline, NodeLayer la } // Fire the BeforeImplicitUpdateRelationship hook for article2 - // For this, we need to query the database for the current owner + // For this, we need to query the database for the current owner // relationship value of owner_new. currentResourcesGrouped = node.RelationshipsFromPreviousLayer.GetRightResources(); if (currentResourcesGrouped.Any()) { - // rightResources is grouped by relationships from previous - // layer, ie { HasOneAttribute:owner => owner_new }. But - // to load article2 onto owner_new, we need to have the + // rightResources is grouped by relationships from previous + // layer, ie { HasOneAttribute:owner => owner_new }. But + // to load article2 onto owner_new, we need to have the // RelationshipAttribute from owner to article, which is the // inverse of HasOneAttribute:owner currentResourcesGroupedInverse = ReplaceKeysWithInverseRelationships(currentResourcesGrouped); - // Note that currently in the JsonApiDotNetCore implementation of hooks, - // the root layer is ALWAYS homogenous, so we safely assume - // that for every relationship to the previous layer, the + // Note that currently in the JsonApiDotNetCore implementation of hooks, + // the root layer is ALWAYS homogenous, so we safely assume + // that for every relationship to the previous layer, the // left type is the same. LeftType leftType = currentResourcesGrouped.First().Key.LeftType; FireForAffectedImplicits(leftType, currentResourcesGroupedInverse, pipeline); @@ -388,7 +388,7 @@ private Dictionary ReplaceKeysWithInverseRel { // when Article has one Owner (HasOneAttribute:owner) is set, there is no guarantee // that the inverse attribute was also set (Owner has one Article: HasOneAttr:article). - // If it isn't, JsonApiDotNetCore currently knows nothing about this relationship pointing back, and it + // If it isn't, JsonApiDotNetCore currently knows nothing about this relationship pointing back, and it // currently cannot fire hooks for resources resolved through inverse relationships. IEnumerable> inversableRelationshipAttributes = resourcesByRelationship.Where(kvp => kvp.Key.InverseNavigationProperty != null); @@ -449,7 +449,7 @@ private void ValidateHookResponse(IEnumerable returnedList, ResourcePipeli private IEnumerable CallHook(IResourceHookContainer container, ResourceHook hook, object[] arguments) { MethodInfo method = container.GetType().GetMethod(hook.ToString("G")); - // note that some of the hooks return "void". When these hooks, the + // note that some of the hooks return "void". When these hooks, the // are called reflectively with Invoke like here, the return value // is just null, so we don't have to worry about casting issues here. return (IEnumerable)ThrowJsonApiExceptionOnError(() => method?.Invoke(container, arguments)); @@ -556,7 +556,7 @@ private void FireAfterUpdateRelationship(IResourceHookContainer container, IReso { Dictionary currentResourcesGrouped = node.RelationshipsFromPreviousLayer.GetRightResources(); - // the relationships attributes in currentResourcesGrouped will be pointing from a + // the relationships attributes in currentResourcesGrouped will be pointing from a // resource in the previous layer to a resource in the current (nested) layer. // For the nested hook we need to replace these attributes with their inverse. // See the FireNestedBeforeUpdateHooks method for a more detailed example. diff --git a/src/JsonApiDotNetCore/Hooks/Internal/Traversal/TraversalHelper.cs b/src/JsonApiDotNetCore/Hooks/Internal/Traversal/TraversalHelper.cs index 5e6451b9c1..16fd700cd6 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/Traversal/TraversalHelper.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/Traversal/TraversalHelper.cs @@ -93,7 +93,7 @@ public NodeLayer CreateNextLayer(IEnumerable nodes) // group them conveniently so we can make ChildNodes of them: // there might be several relationship attributes in rights dictionary - // that point to the same right type. + // that point to the same right type. Dictionary>>> leftsGrouped = GroupByRightTypeOfRelationship(lefts); // convert the groups into child nodes diff --git a/src/JsonApiDotNetCore/Repositories/EntityFrameworkCoreRepository.cs b/src/JsonApiDotNetCore/Repositories/EntityFrameworkCoreRepository.cs index b305938bb0..ee194ae2de 100644 --- a/src/JsonApiDotNetCore/Repositories/EntityFrameworkCoreRepository.cs +++ b/src/JsonApiDotNetCore/Repositories/EntityFrameworkCoreRepository.cs @@ -265,7 +265,7 @@ public virtual async Task DeleteAsync(TId id, CancellationToken cancellationToke foreach (RelationshipAttribute relationship in _resourceGraph.GetRelationships()) { // Loads the data of the relationship, if in EF Core it is configured in such a way that loading the related - // entities into memory is required for successfully executing the selected deletion behavior. + // entities into memory is required for successfully executing the selected deletion behavior. if (RequiresLoadOfRelationshipForDeletion(relationship)) { NavigationEntry navigation = GetNavigationEntry(resource, relationship); diff --git a/src/JsonApiDotNetCore/Resources/Annotations/EagerLoadAttribute.cs b/src/JsonApiDotNetCore/Resources/Annotations/EagerLoadAttribute.cs index 17685ccd47..623e7eeeb2 100644 --- a/src/JsonApiDotNetCore/Resources/Annotations/EagerLoadAttribute.cs +++ b/src/JsonApiDotNetCore/Resources/Annotations/EagerLoadAttribute.cs @@ -13,7 +13,7 @@ namespace JsonApiDotNetCore.Resources.Annotations /// Name.First + " " + Name.Last; /// diff --git a/src/JsonApiDotNetCore/Resources/Annotations/HasManyAttribute.cs b/src/JsonApiDotNetCore/Resources/Annotations/HasManyAttribute.cs index b2f51f4a47..3a8b3bc16a 100644 --- a/src/JsonApiDotNetCore/Resources/Annotations/HasManyAttribute.cs +++ b/src/JsonApiDotNetCore/Resources/Annotations/HasManyAttribute.cs @@ -8,7 +8,7 @@ namespace JsonApiDotNetCore.Resources.Annotations /// /// /// Articles { get; set; } diff --git a/test/UnitTests/Extensions/ServiceCollectionExtensionsTests.cs b/test/UnitTests/Extensions/ServiceCollectionExtensionsTests.cs index 4f4d18199a..1bcb21d7ab 100644 --- a/test/UnitTests/Extensions/ServiceCollectionExtensionsTests.cs +++ b/test/UnitTests/Extensions/ServiceCollectionExtensionsTests.cs @@ -75,7 +75,7 @@ public void RegisterResource_DeviatingDbContextPropertyName_RegistersCorrectly() var graph = provider.GetRequiredService(); ResourceContext resourceContext = graph.GetResourceContext(); - // Assert + // Assert Assert.Equal("authors", resourceContext.PublicName); } diff --git a/test/UnitTests/Models/RelationshipDataTests.cs b/test/UnitTests/Models/RelationshipDataTests.cs index ce70b5fdcf..e0393e38b8 100644 --- a/test/UnitTests/Models/RelationshipDataTests.cs +++ b/test/UnitTests/Models/RelationshipDataTests.cs @@ -22,7 +22,7 @@ public void Setting_ExposeData_To_List_Sets_ManyData() } }; - // Act + // Act relationshipData.Data = relationships; // Assert @@ -47,7 +47,7 @@ public void Setting_ExposeData_To_JArray_Sets_ManyData() JArray relationships = JArray.Parse(relationshipsJson); - // Act + // Act relationshipData.Data = relationships; // Assert @@ -69,7 +69,7 @@ public void Setting_ExposeData_To_RIO_Sets_SingleData() Type = "authors" }; - // Act + // Act relationshipData.Data = relationship; // Assert @@ -92,7 +92,7 @@ public void Setting_ExposeData_To_JObject_Sets_SingleData() JObject relationship = JObject.Parse(relationshipJson); - // Act + // Act relationshipData.Data = relationship; // Assert From 362f637b36b33186758a4b21ee3cc95edfd9fa9f Mon Sep 17 00:00:00 2001 From: Bart Koelman Date: Fri, 5 Mar 2021 16:28:14 +0100 Subject: [PATCH 11/32] Boost various hints and suggestions to warning level during cibuild, to not bother devs too much while writing and debugging code. --- Build.ps1 | 2 +- ...piDotNetCore-WarningSeverities.DotSettings | 254 ++++++++++++++++++ JsonApiDotNetCore.sln.DotSettings | 8 +- inspectcode.ps1 | 2 +- 4 files changed, 260 insertions(+), 6 deletions(-) create mode 100644 JsonApiDotNetCore-WarningSeverities.DotSettings diff --git a/Build.ps1 b/Build.ps1 index e614f84c29..9798b5ee6e 100644 --- a/Build.ps1 +++ b/Build.ps1 @@ -19,7 +19,7 @@ function CheckLastExitCode { function RunInspectCode { $outputPath = [System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), 'jetbrains-inspectcode-results.xml') - dotnet jb inspectcode JsonApiDotNetCore.sln --output="$outputPath" --properties:Configuration=Release --severity=WARNING --verbosity=WARN -dsl=GlobalAll -dsl=SolutionPersonal -dsl=ProjectPersonal + dotnet jb inspectcode JsonApiDotNetCore.sln --output="$outputPath" --profile=JsonApiDotNetCore-WarningSeverities.DotSettings --properties:Configuration=Release --severity=WARNING --verbosity=WARN -dsl=GlobalAll -dsl=SolutionPersonal -dsl=ProjectPersonal CheckLastExitCode [xml]$xml = Get-Content "$outputPath" diff --git a/JsonApiDotNetCore-WarningSeverities.DotSettings b/JsonApiDotNetCore-WarningSeverities.DotSettings new file mode 100644 index 0000000000..f4a9ae32e8 --- /dev/null +++ b/JsonApiDotNetCore-WarningSeverities.DotSettings @@ -0,0 +1,254 @@ + + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + WARNING + \ No newline at end of file diff --git a/JsonApiDotNetCore.sln.DotSettings b/JsonApiDotNetCore.sln.DotSettings index 0404af6c5b..a32ac146aa 100644 --- a/JsonApiDotNetCore.sln.DotSettings +++ b/JsonApiDotNetCore.sln.DotSettings @@ -72,6 +72,7 @@ JsonApiDotNetCore.ArgumentGuard.NotNull($EXPR$, $NAME$); WARNING WARNING WARNING + WARNING SUGGESTION WARNING HINT @@ -554,7 +555,6 @@ JsonApiDotNetCore.ArgumentGuard.NotNull($EXPR$, $NAME$); UseExplicitType UseVarWhenEvident UseVarWhenEvident - True False False False @@ -590,7 +590,7 @@ JsonApiDotNetCore.ArgumentGuard.NotNull($EXPR$, $NAME$); JsonApiDotNetCore.ArgumentGuard.NotNull($argument$, nameof($argument$)); $left$ = $right$; $left$ = $right$ ?? throw new ArgumentNullException(nameof($argument$)); - SUGGESTION + WARNING True Replace classic argument null check with Guard clause True @@ -604,7 +604,7 @@ $left$ = $right$; Replace argument null check with Guard clause JsonApiDotNetCore.ArgumentGuard.NotNull($argument$, nameof($argument$)); if ($argument$ == null) throw new ArgumentNullException(nameof($argument$)); - SUGGESTION + WARNING True Replace collection null/empty check with extension method True @@ -617,7 +617,7 @@ $left$ = $right$; Replace collection null/empty check with extension method $collection$.IsNullOrEmpty() $collection$ == null || !$collection$.Any() - SUGGESTION + WARNING True True True diff --git a/inspectcode.ps1 b/inspectcode.ps1 index 83987d5e69..355b8f20dd 100644 --- a/inspectcode.ps1 +++ b/inspectcode.ps1 @@ -16,7 +16,7 @@ if ($LASTEXITCODE -ne 0) { $outputPath = [System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), 'jetbrains-inspectcode-results.xml') $resultPath = [System.IO.Path]::Combine([System.IO.Path]::GetTempPath(), 'jetbrains-inspectcode-results.html') -dotnet jb inspectcode JsonApiDotNetCore.sln --output="$outputPath" --properties:Configuration=Release --severity=WARNING --verbosity=WARN -dsl=GlobalAll -dsl=SolutionPersonal -dsl=ProjectPersonal +dotnet jb inspectcode JsonApiDotNetCore.sln --output="$outputPath" --profile=JsonApiDotNetCore-WarningSeverities.DotSettings --properties:Configuration=Release --severity=WARNING --verbosity=WARN -dsl=GlobalAll -dsl=SolutionPersonal -dsl=ProjectPersonal if ($LASTEXITCODE -ne 0) { throw "Code inspection failed with exit code $LASTEXITCODE" From 8903c26712ca6ce9bdb3ab2c10498d786a90e9c7 Mon Sep 17 00:00:00 2001 From: Bart Koelman Date: Fri, 5 Mar 2021 17:40:26 +0100 Subject: [PATCH 12/32] Fixed remaining warnings --- .../ExampleIntegrationTestContext.cs | 2 ++ test/UnitTests/Builders/ResourceGraphBuilderTests.cs | 3 +++ test/UnitTests/ResourceHooks/DiscoveryTests.cs | 10 ++++++++++ test/UnitTests/ResourceHooks/NotTargeted.cs | 2 ++ 4 files changed, 17 insertions(+) diff --git a/test/JsonApiDotNetCoreExampleTests/ExampleIntegrationTestContext.cs b/test/JsonApiDotNetCoreExampleTests/ExampleIntegrationTestContext.cs index 50e796e08d..96c92656db 100644 --- a/test/JsonApiDotNetCoreExampleTests/ExampleIntegrationTestContext.cs +++ b/test/JsonApiDotNetCoreExampleTests/ExampleIntegrationTestContext.cs @@ -1,3 +1,4 @@ +using JetBrains.Annotations; using JsonApiDotNetCoreExample.Startups; using Microsoft.EntityFrameworkCore; using TestBuildingBlocks; @@ -13,6 +14,7 @@ namespace JsonApiDotNetCoreExampleTests /// /// The EF Core database context, which can be defined in the test project. /// + [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] public sealed class ExampleIntegrationTestContext : BaseIntegrationTestContext where TStartup : class where TDbContext : DbContext diff --git a/test/UnitTests/Builders/ResourceGraphBuilderTests.cs b/test/UnitTests/Builders/ResourceGraphBuilderTests.cs index 35d8ed433d..bcff103f1f 100644 --- a/test/UnitTests/Builders/ResourceGraphBuilderTests.cs +++ b/test/UnitTests/Builders/ResourceGraphBuilderTests.cs @@ -113,8 +113,11 @@ public sealed class TestResource : Identifiable public ISet RelatedResources { get; set; } } + [UsedImplicitly(ImplicitUseTargetFlags.Members)] public sealed class RelatedResource : Identifiable { + [Attr] + public string Unused { get; set; } } } } diff --git a/test/UnitTests/ResourceHooks/DiscoveryTests.cs b/test/UnitTests/ResourceHooks/DiscoveryTests.cs index 4323c15e39..a561f3278c 100644 --- a/test/UnitTests/ResourceHooks/DiscoveryTests.cs +++ b/test/UnitTests/ResourceHooks/DiscoveryTests.cs @@ -6,6 +6,7 @@ using JsonApiDotNetCore.Hooks.Internal.Discovery; using JsonApiDotNetCore.Hooks.Internal.Execution; using JsonApiDotNetCore.Resources; +using JsonApiDotNetCore.Resources.Annotations; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Xunit; @@ -65,8 +66,11 @@ private IServiceProvider MockProvider(object service) return services.BuildServiceProvider(); } + [UsedImplicitly(ImplicitUseTargetFlags.Members)] public sealed class Dummy : Identifiable { + [Attr] + public string Unused { get; set; } } [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] @@ -87,8 +91,11 @@ public override void AfterDelete(HashSet resources, ResourcePipeline pipe } } + [UsedImplicitly(ImplicitUseTargetFlags.Members)] public sealed class AnotherDummy : Identifiable { + [Attr] + public string Unused { get; set; } } public abstract class ResourceDefinitionBase : ResourceHooksDefinition @@ -118,8 +125,11 @@ public AnotherDummyResourceDefinition() } } + [UsedImplicitly(ImplicitUseTargetFlags.Members)] public sealed class YetAnotherDummy : Identifiable { + [Attr] + public string Unused { get; set; } } [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] diff --git a/test/UnitTests/ResourceHooks/NotTargeted.cs b/test/UnitTests/ResourceHooks/NotTargeted.cs index 6404f7e3a0..82e312e750 100644 --- a/test/UnitTests/ResourceHooks/NotTargeted.cs +++ b/test/UnitTests/ResourceHooks/NotTargeted.cs @@ -1,7 +1,9 @@ +using JetBrains.Annotations; using JsonApiDotNetCore.Resources; namespace UnitTests.ResourceHooks { + [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] internal sealed class NotTargeted : Identifiable { } From 599e103a964f76457baf16071d30f061fa22f1ec Mon Sep 17 00:00:00 2001 From: Bart Koelman Date: Fri, 5 Mar 2021 17:53:53 +0100 Subject: [PATCH 13/32] AV1250: Iterator method returns result of defered execution --- .../Definitions/ArticleHooksDefinition.cs | 2 +- .../Definitions/PassportHooksDefinition.cs | 2 +- .../JsonApiDotNetCoreExample/Definitions/TagHooksDefinition.cs | 2 +- .../Definitions/TodoItemHooksDefinition.cs | 2 +- .../Configuration/ResourceDescriptorAssemblyCache.cs | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Examples/JsonApiDotNetCoreExample/Definitions/ArticleHooksDefinition.cs b/src/Examples/JsonApiDotNetCoreExample/Definitions/ArticleHooksDefinition.cs index 5ea4353ecd..03c604e704 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Definitions/ArticleHooksDefinition.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Definitions/ArticleHooksDefinition.cs @@ -29,7 +29,7 @@ public override IEnumerable
OnReturn(HashSet
resources, Resour }); } - return resources.Where(article => article.Caption != "This should not be included"); + return resources.Where(article => article.Caption != "This should not be included").ToArray(); } } } diff --git a/src/Examples/JsonApiDotNetCoreExample/Definitions/PassportHooksDefinition.cs b/src/Examples/JsonApiDotNetCoreExample/Definitions/PassportHooksDefinition.cs index a7a025bede..9292878212 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Definitions/PassportHooksDefinition.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Definitions/PassportHooksDefinition.cs @@ -36,7 +36,7 @@ public override void BeforeImplicitUpdateRelationship(IRelationshipsDictionary

OnReturn(HashSet resources, ResourcePipeline pipeline) { - return resources.Where(passport => !passport.IsLocked); + return resources.Where(passport => !passport.IsLocked).ToArray(); } } } diff --git a/src/Examples/JsonApiDotNetCoreExample/Definitions/TagHooksDefinition.cs b/src/Examples/JsonApiDotNetCoreExample/Definitions/TagHooksDefinition.cs index b170715e95..891959e00c 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Definitions/TagHooksDefinition.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Definitions/TagHooksDefinition.cs @@ -18,7 +18,7 @@ public TagHooksDefinition(IResourceGraph resourceGraph) public override IEnumerable OnReturn(HashSet resources, ResourcePipeline pipeline) { - return resources.Where(tag => tag.Name != "This should not be included"); + return resources.Where(tag => tag.Name != "This should not be included").ToArray(); } } } diff --git a/src/Examples/JsonApiDotNetCoreExample/Definitions/TodoItemHooksDefinition.cs b/src/Examples/JsonApiDotNetCoreExample/Definitions/TodoItemHooksDefinition.cs index 9e59aa6569..7a22b14eef 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Definitions/TodoItemHooksDefinition.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Definitions/TodoItemHooksDefinition.cs @@ -37,7 +37,7 @@ public override void BeforeImplicitUpdateRelationship(IRelationshipsDictionary OnReturn(HashSet resources, ResourcePipeline pipeline) { - return resources.Where(todoItem => todoItem.Description != "This should not be included"); + return resources.Where(todoItem => todoItem.Description != "This should not be included").ToArray(); } } } diff --git a/src/JsonApiDotNetCore/Configuration/ResourceDescriptorAssemblyCache.cs b/src/JsonApiDotNetCore/Configuration/ResourceDescriptorAssemblyCache.cs index 667d6680fa..3efb5564cc 100644 --- a/src/JsonApiDotNetCore/Configuration/ResourceDescriptorAssemblyCache.cs +++ b/src/JsonApiDotNetCore/Configuration/ResourceDescriptorAssemblyCache.cs @@ -25,7 +25,7 @@ public void RegisterAssembly(Assembly assembly) { EnsureAssembliesScanned(); - return _resourceDescriptorsPerAssembly.Select(pair => (pair.Key, pair.Value)); + return _resourceDescriptorsPerAssembly.Select(pair => (pair.Key, pair.Value)).ToArray(); } private void EnsureAssembliesScanned() From 5068bd759971a30c25c9d472084df6c67ebc0e1c Mon Sep 17 00:00:00 2001 From: Bart Koelman Date: Sat, 6 Mar 2021 18:20:51 +0100 Subject: [PATCH 14/32] AV1706: Don't use single-letter variables --- benchmarks/Query/QueryParserBenchmarks.cs | 2 +- .../Data/AppDbContext.cs | 24 ++++----- .../Definitions/ArticleHooksDefinition.cs | 2 +- .../Configuration/ResourceGraph.cs | 13 ++--- .../Configuration/ResourceGraphBuilder.cs | 17 ++++--- .../Configuration/ServiceDiscoveryFacade.cs | 4 +- .../Configuration/TypeLocator.cs | 4 +- .../Internal/Discovery/HooksDiscovery.cs | 2 +- .../Execution/DiffableResourceHashSet.cs | 2 +- .../Internal/Execution/HookExecutorHelper.cs | 5 +- .../Execution/RelationshipsDictionary.cs | 4 +- .../Hooks/Internal/ResourceHookExecutor.cs | 8 +-- .../Hooks/Internal/Traversal/NodeLayer.cs | 2 +- .../Hooks/Internal/Traversal/RootNode.cs | 4 +- .../Internal/Traversal/TraversalHelper.cs | 2 +- .../Middleware/JsonApiMiddleware.cs | 2 +- .../Middleware/JsonApiRoutingConvention.cs | 3 +- .../Parsing/ResourceFieldChainResolver.cs | 6 +-- .../QueryableBuilding/QueryClauseBuilder.cs | 4 +- .../QueryableBuilding/SelectClauseBuilder.cs | 2 +- .../Internal/QueryStringReader.cs | 2 +- .../Resources/ResourceFactory.cs | 6 +-- .../Client/Internal/ResponseDeserializer.cs | 7 +-- .../Serialization/JsonApiReader.cs | 2 +- .../Serialization/Objects/ErrorDocument.cs | 2 +- .../ServiceDiscoveryFacadeTests.cs | 2 +- .../ExampleFakers.cs | 20 ++++---- .../AtomicOperations/OperationsFakers.cs | 22 ++++---- .../CustomRoutes/CustomRouteFakers.cs | 8 +-- .../EagerLoading/EagerLoadingFakers.cs | 14 +++--- .../HostingInIIS/HostingFakers.cs | 4 +- .../IdObfuscation/ObfuscationFakers.cs | 6 +-- .../IntegrationTests/Links/LinksFakers.cs | 10 ++-- .../IntegrationTests/Logging/AuditFakers.cs | 4 +- .../IntegrationTests/Meta/SupportFakers.cs | 4 +- .../ModelStateDbContext.cs | 2 +- .../NamingConventions/SwimmingFakers.cs | 6 +-- .../QueryStrings/QueryStringFakers.cs | 38 +++++++------- .../SparseFieldSets/SparseFieldSetTests.cs | 28 +++++------ .../ReadWrite/ReadWriteFakers.cs | 22 ++++---- .../DefaultBehaviorFakers.cs | 8 +-- .../InjectionFakers.cs | 4 +- .../CallableResourceDefinition.cs | 4 +- .../ResourceHooks/ResourceHookTests.cs | 10 ++-- .../Serialization/SerializationFakers.cs | 12 ++--- .../ZeroKeys/ZeroKeyFakers.cs | 10 ++-- .../QueryStringParameters/FilterParseTests.cs | 4 +- .../IncludeParseTests.cs | 4 +- .../LegacyFilterParseTests.cs | 4 +- .../PaginationParseTests.cs | 4 +- .../QueryStringParameters/SortParseTests.cs | 4 +- .../SparseFieldSetParseTests.cs | 4 +- test/TestBuildingBlocks/FakerContainer.cs | 8 +-- .../Builders/ResourceGraphBuilderTests.cs | 6 +-- .../Controllers/BaseJsonApiControllerTests.cs | 18 +++---- test/UnitTests/Internal/TypeHelperTests.cs | 6 +-- .../Middleware/JsonApiMiddlewareTests.cs | 7 +-- .../Middleware/JsonApiRequestTests.cs | 2 +- .../UnitTests/Models/AttributesEqualsTests.cs | 44 ++++++++-------- .../Executor/ManyToManyOnReturnTests.cs | 12 ++--- .../Executor/Read/BeforeReadTests.cs | 12 ++--- .../Update/BeforeUpdateWithDbValuesTests.cs | 5 +- .../UnitTests/ResourceHooks/HooksDummyData.cs | 36 ++++++------- .../ResourceHooks/HooksTestsSetup.cs | 18 ++++--- .../RelationshipDictionaryTests.cs | 50 +++++++++---------- .../Common/BaseDocumentBuilderTests.cs | 2 +- .../SerializationTestsSetupBase.cs | 20 ++++---- .../Serialization/SerializerTestsSetup.cs | 16 +++--- .../IncludedResourceObjectBuilderTests.cs | 8 +-- .../Server/RequestDeserializerTests.cs | 4 +- .../ResponseResourceObjectBuilderTests.cs | 4 +- .../Server/ResponseSerializerTests.cs | 10 ++-- 72 files changed, 346 insertions(+), 335 deletions(-) diff --git a/benchmarks/Query/QueryParserBenchmarks.cs b/benchmarks/Query/QueryParserBenchmarks.cs index 8ba23d56f0..0b24aea420 100644 --- a/benchmarks/Query/QueryParserBenchmarks.cs +++ b/benchmarks/Query/QueryParserBenchmarks.cs @@ -107,7 +107,7 @@ public void ComplexQuery() private void Run(int iterations, Action action) { - for (int i = 0; i < iterations; i++) + for (int index = 0; index < iterations; index++) { action(); } diff --git a/src/Examples/JsonApiDotNetCoreExample/Data/AppDbContext.cs b/src/Examples/JsonApiDotNetCoreExample/Data/AppDbContext.cs index 9d13b17493..ae3d13d553 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Data/AppDbContext.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Data/AppDbContext.cs @@ -23,12 +23,12 @@ public AppDbContext(DbContextOptions options) protected override void OnModelCreating(ModelBuilder builder) { builder.Entity() - .HasOne(t => t.Assignee) - .WithMany(p => p.AssignedTodoItems); + .HasOne(todoItem => todoItem.Assignee) + .WithMany(person => person.AssignedTodoItems); builder.Entity() - .HasOne(t => t.Owner) - .WithMany(p => p.TodoItems); + .HasOne(todoItem => todoItem.Owner) + .WithMany(person => person.TodoItems); builder.Entity() .HasKey(bc => new @@ -45,23 +45,23 @@ protected override void OnModelCreating(ModelBuilder builder) }); builder.Entity() - .HasOne(t => t.StakeHolderTodoItem) - .WithMany(t => t.StakeHolders) + .HasOne(person => person.StakeHolderTodoItem) + .WithMany(todoItem => todoItem.StakeHolders) .OnDelete(DeleteBehavior.Cascade); builder.Entity() - .HasMany(t => t.ChildTodoItems) - .WithOne(t => t.ParentTodo); + .HasMany(todoItem => todoItem.ChildTodoItems) + .WithOne(todoItem => todoItem.ParentTodo); builder.Entity() - .HasOne(p => p.Person) - .WithOne(p => p.Passport) + .HasOne(passport => passport.Person) + .WithOne(person => person.Passport) .HasForeignKey("PassportKey") .OnDelete(DeleteBehavior.SetNull); builder.Entity() - .HasOne(p => p.OneToOnePerson) - .WithOne(p => p.OneToOneTodoItem) + .HasOne(todoItem => todoItem.OneToOnePerson) + .WithOne(person => person.OneToOneTodoItem) .HasForeignKey("OneToOnePersonKey"); } } diff --git a/src/Examples/JsonApiDotNetCoreExample/Definitions/ArticleHooksDefinition.cs b/src/Examples/JsonApiDotNetCoreExample/Definitions/ArticleHooksDefinition.cs index 03c604e704..cef9af0a74 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Definitions/ArticleHooksDefinition.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Definitions/ArticleHooksDefinition.cs @@ -21,7 +21,7 @@ public ArticleHooksDefinition(IResourceGraph resourceGraph) public override IEnumerable

OnReturn(HashSet
resources, ResourcePipeline pipeline) { - if (pipeline == ResourcePipeline.GetSingle && resources.Any(r => r.Caption == "Classified")) + if (pipeline == ResourcePipeline.GetSingle && resources.Any(article => article.Caption == "Classified")) { throw new JsonApiException(new Error(HttpStatusCode.Forbidden) { diff --git a/src/JsonApiDotNetCore/Configuration/ResourceGraph.cs b/src/JsonApiDotNetCore/Configuration/ResourceGraph.cs index 8689f5a6ac..1fc36ca4a2 100644 --- a/src/JsonApiDotNetCore/Configuration/ResourceGraph.cs +++ b/src/JsonApiDotNetCore/Configuration/ResourceGraph.cs @@ -34,7 +34,7 @@ public ResourceContext GetResourceContext(string resourceName) { ArgumentGuard.NotNullNorEmpty(resourceName, nameof(resourceName)); - return _resources.SingleOrDefault(e => e.PublicName == resourceName); + return _resources.SingleOrDefault(resourceContext => resourceContext.PublicName == resourceName); } /// @@ -43,8 +43,8 @@ public ResourceContext GetResourceContext(Type resourceType) ArgumentGuard.NotNull(resourceType, nameof(resourceType)); return IsLazyLoadingProxyForResourceType(resourceType) - ? _resources.SingleOrDefault(e => e.ResourceType == resourceType.BaseType) - : _resources.SingleOrDefault(e => e.ResourceType == resourceType); + ? _resources.SingleOrDefault(resourceContext => resourceContext.ResourceType == resourceType.BaseType) + : _resources.SingleOrDefault(resourceContext => resourceContext.ResourceType == resourceType); } /// @@ -109,7 +109,8 @@ public RelationshipAttribute GetInverseRelationship(RelationshipAttribute relati return null; } - return GetResourceContext(relationship.RightType).Relationships.SingleOrDefault(r => r.Property == relationship.InverseNavigationProperty); + return GetResourceContext(relationship.RightType).Relationships + .SingleOrDefault(nextRelationship => nextRelationship.Property == relationship.InverseNavigationProperty); } private IReadOnlyCollection Getter(Expression> selector = null, @@ -145,7 +146,7 @@ private IReadOnlyCollection Getter(Expression // model => model.Field1 try { - targeted.Add(available.Single(f => f.Property.Name == memberExpression.Member.Name)); + targeted.Add(available.Single(field => field.Property.Name == memberExpression.Member.Name)); return targeted; } catch (InvalidOperationException) @@ -169,7 +170,7 @@ private IReadOnlyCollection Getter(Expression foreach (MemberInfo member in newExpression.Members) { memberName = member.Name; - targeted.Add(available.Single(f => f.Property.Name == memberName)); + targeted.Add(available.Single(field => field.Property.Name == memberName)); } return targeted; diff --git a/src/JsonApiDotNetCore/Configuration/ResourceGraphBuilder.cs b/src/JsonApiDotNetCore/Configuration/ResourceGraphBuilder.cs index a6bb501ffd..3d5637d2eb 100644 --- a/src/JsonApiDotNetCore/Configuration/ResourceGraphBuilder.cs +++ b/src/JsonApiDotNetCore/Configuration/ResourceGraphBuilder.cs @@ -102,7 +102,7 @@ public ResourceGraphBuilder Add(Type resourceType, Type idType = null, string pu { ArgumentGuard.NotNull(resourceType, nameof(resourceType)); - if (_resources.Any(e => e.ResourceType == resourceType)) + if (_resources.Any(resourceContext => resourceContext.ResourceType == resourceType)) { return this; } @@ -205,7 +205,7 @@ private IReadOnlyCollection GetRelationships(Type resourc if (attribute is HasManyThroughAttribute hasManyThroughAttribute) { - PropertyInfo throughProperty = properties.SingleOrDefault(p => p.Name == hasManyThroughAttribute.ThroughPropertyName); + PropertyInfo throughProperty = properties.SingleOrDefault(property => property.Name == hasManyThroughAttribute.ThroughPropertyName); if (throughProperty == null) { @@ -240,14 +240,15 @@ private IReadOnlyCollection GetRelationships(Type resourc else { // In case of a non-self-referencing many-to-many relationship, we just pick the single compatible type. - hasManyThroughAttribute.LeftProperty = throughProperties.SingleOrDefault(x => x.PropertyType.IsAssignableFrom(resourceType)) ?? + hasManyThroughAttribute.LeftProperty = + throughProperties.SingleOrDefault(property => property.PropertyType.IsAssignableFrom(resourceType)) ?? throw new InvalidConfigurationException($"'{throughType}' does not contain a navigation property to type '{resourceType}'."); } // ArticleTag.ArticleId string leftIdPropertyName = hasManyThroughAttribute.LeftIdPropertyName ?? hasManyThroughAttribute.LeftProperty.Name + "Id"; - hasManyThroughAttribute.LeftIdProperty = throughProperties.SingleOrDefault(x => x.Name == leftIdPropertyName) ?? + hasManyThroughAttribute.LeftIdProperty = throughProperties.SingleOrDefault(property => property.Name == leftIdPropertyName) ?? throw new InvalidConfigurationException( $"'{throughType}' does not contain a relationship ID property to type '{resourceType}' with name '{leftIdPropertyName}'."); @@ -262,7 +263,8 @@ private IReadOnlyCollection GetRelationships(Type resourc else { // In case of a non-self-referencing many-to-many relationship, we just pick the single compatible type. - hasManyThroughAttribute.RightProperty = throughProperties.SingleOrDefault(x => x.PropertyType == hasManyThroughAttribute.RightType) ?? + hasManyThroughAttribute.RightProperty = + throughProperties.SingleOrDefault(property => property.PropertyType == hasManyThroughAttribute.RightType) ?? throw new InvalidConfigurationException( $"'{throughType}' does not contain a navigation property to type '{hasManyThroughAttribute.RightType}'."); } @@ -270,7 +272,7 @@ private IReadOnlyCollection GetRelationships(Type resourc // ArticleTag.TagId string rightIdPropertyName = hasManyThroughAttribute.RightIdPropertyName ?? hasManyThroughAttribute.RightProperty.Name + "Id"; - hasManyThroughAttribute.RightIdProperty = throughProperties.SingleOrDefault(x => x.Name == rightIdPropertyName) ?? + hasManyThroughAttribute.RightIdProperty = throughProperties.SingleOrDefault(property => property.Name == rightIdPropertyName) ?? throw new InvalidConfigurationException( $"'{throughType}' does not contain a relationship ID property to type '{hasManyThroughAttribute.RightType}' with name '{rightIdPropertyName}'."); } @@ -339,7 +341,8 @@ private IReadOnlyCollection GetEagerLoads(Type resourceType, private Type TypeOrElementType(Type type) { - Type[] interfaces = type.GetInterfaces().Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>)).ToArray(); + Type[] interfaces = type.GetInterfaces() + .Where(@interface => @interface.IsGenericType && @interface.GetGenericTypeDefinition() == typeof(IEnumerable<>)).ToArray(); return interfaces.Length == 1 ? interfaces.Single().GenericTypeArguments[0] : type; } diff --git a/src/JsonApiDotNetCore/Configuration/ServiceDiscoveryFacade.cs b/src/JsonApiDotNetCore/Configuration/ServiceDiscoveryFacade.cs index 41e3a390bc..64cf9ef4a1 100644 --- a/src/JsonApiDotNetCore/Configuration/ServiceDiscoveryFacade.cs +++ b/src/JsonApiDotNetCore/Configuration/ServiceDiscoveryFacade.cs @@ -166,10 +166,10 @@ private void AddResourceHookDefinitions(Assembly assembly, ResourceDescriptor id _services.AddScoped(typeof(ResourceHooksDefinition<>).MakeGenericType(identifiable.ResourceType), resourceDefinition); } } - catch (InvalidOperationException e) + catch (InvalidOperationException exception) { throw new InvalidConfigurationException($"Cannot define multiple ResourceHooksDefinition<> implementations for '{identifiable.ResourceType}'", - e); + exception); } } diff --git a/src/JsonApiDotNetCore/Configuration/TypeLocator.cs b/src/JsonApiDotNetCore/Configuration/TypeLocator.cs index 303cb32c43..90febc0ce9 100644 --- a/src/JsonApiDotNetCore/Configuration/TypeLocator.cs +++ b/src/JsonApiDotNetCore/Configuration/TypeLocator.cs @@ -16,8 +16,8 @@ internal static class TypeLocator ///
public static Type TryGetIdType(Type resourceType) { - Type identifiableInterface = resourceType.GetInterfaces() - .FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IIdentifiable<>)); + Type identifiableInterface = resourceType.GetInterfaces().FirstOrDefault(@interface => + @interface.IsGenericType && @interface.GetGenericTypeDefinition() == typeof(IIdentifiable<>)); return identifiableInterface?.GetGenericArguments()[0]; } diff --git a/src/JsonApiDotNetCore/Hooks/Internal/Discovery/HooksDiscovery.cs b/src/JsonApiDotNetCore/Hooks/Internal/Discovery/HooksDiscovery.cs index e09d327fbc..b707e2569f 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/Discovery/HooksDiscovery.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/Discovery/HooksDiscovery.cs @@ -35,7 +35,7 @@ public class HooksDiscovery : IHooksDiscovery public HooksDiscovery(IServiceProvider provider) { - _allHooks = Enum.GetValues(typeof(ResourceHook)).Cast().Where(h => h != ResourceHook.None).ToArray(); + _allHooks = Enum.GetValues(typeof(ResourceHook)).Cast().Where(hook => hook != ResourceHook.None).ToArray(); Type containerType; diff --git a/src/JsonApiDotNetCore/Hooks/Internal/Execution/DiffableResourceHashSet.cs b/src/JsonApiDotNetCore/Hooks/Internal/Execution/DiffableResourceHashSet.cs index 5f71106ad4..2a20c3182f 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/Execution/DiffableResourceHashSet.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/Execution/DiffableResourceHashSet.cs @@ -51,7 +51,7 @@ public IEnumerable> GetDiffs() foreach (TResource resource in this) { - TResource currentValueInDatabase = _databaseValues.Single(e => resource.StringId == e.StringId); + TResource currentValueInDatabase = _databaseValues.Single(databaseResource => resource.StringId == databaseResource.StringId); yield return new ResourceDiffPair(resource, currentValueInDatabase); } } diff --git a/src/JsonApiDotNetCore/Hooks/Internal/Execution/HookExecutorHelper.cs b/src/JsonApiDotNetCore/Hooks/Internal/Execution/HookExecutorHelper.cs index 2a3c44b88f..4fef98240d 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/Execution/HookExecutorHelper.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/Execution/HookExecutorHelper.cs @@ -87,8 +87,7 @@ public IResourceHookContainer GetResourceHookContainer(Res return (IResourceHookContainer)GetResourceHookContainer(typeof(TResource), hook); } - public IEnumerable LoadDbValues(LeftType resourceTypeForRepository, IEnumerable resources, - params RelationshipAttribute[] relationshipsToNextLayer) + public IEnumerable LoadDbValues(LeftType resourceTypeForRepository, IEnumerable resources, params RelationshipAttribute[] relationshipsToNextLayer) { LeftType idType = TypeHelper.GetIdType(resourceTypeForRepository); @@ -97,7 +96,7 @@ public IEnumerable LoadDbValues(LeftType resourceTypeForRepository, IEnumerable idType); IEnumerable cast = ((IEnumerable)resources).Cast(); - IList ids = TypeHelper.CopyToList(cast.Select(i => i.GetTypedId()), idType); + IList ids = TypeHelper.CopyToList(cast.Select(resource => resource.GetTypedId()), idType); var values = (IEnumerable)parameterizedGetWhere.Invoke(this, ArrayFactory.Create(ids, relationshipsToNextLayer)); if (values == null) diff --git a/src/JsonApiDotNetCore/Hooks/Internal/Execution/RelationshipsDictionary.cs b/src/JsonApiDotNetCore/Hooks/Internal/Execution/RelationshipsDictionary.cs index d738a6b162..e8dda3ad04 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/Execution/RelationshipsDictionary.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/Execution/RelationshipsDictionary.cs @@ -47,7 +47,7 @@ public Dictionary> GetByRelationship public Dictionary> GetByRelationship(Type resourceType) { - return this.Where(p => p.Key.RightType == resourceType).ToDictionary(p => p.Key, p => p.Value); + return this.Where(pair => pair.Key.RightType == resourceType).ToDictionary(pair => pair.Key, pair => pair.Value); } /// @@ -56,7 +56,7 @@ public HashSet GetAffected(Expression> naviga ArgumentGuard.NotNull(navigationAction, nameof(navigationAction)); PropertyInfo property = TypeHelper.ParseNavigationExpression(navigationAction); - return this.Where(p => p.Key.Property.Name == property.Name).Select(p => p.Value).SingleOrDefault(); + return this.Where(pair => pair.Key.Property.Name == property.Name).Select(pair => pair.Value).SingleOrDefault(); } } } diff --git a/src/JsonApiDotNetCore/Hooks/Internal/ResourceHookExecutor.cs b/src/JsonApiDotNetCore/Hooks/Internal/ResourceHookExecutor.cs index 6ee5bad873..75c97d1bcf 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/ResourceHookExecutor.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/ResourceHookExecutor.cs @@ -69,7 +69,7 @@ public IEnumerable BeforeUpdate(IEnumerable res { if (GetHook(ResourceHook.BeforeUpdate, resources, out IResourceHookContainer container, out RootNode node)) { - RelationshipAttribute[] relationships = node.RelationshipsToNextLayer.Select(p => p.Attribute).ToArray(); + RelationshipAttribute[] relationships = node.RelationshipsToNextLayer.Select(proxy => proxy.Attribute).ToArray(); IEnumerable dbValues = LoadDbValues(typeof(TResource), (IEnumerable)node.UniqueResources, ResourceHook.BeforeUpdate, relationships); var diff = new DiffableResourceHashSet(node.UniqueResources, dbValues, node.LeftsToNextLayer(), _targetedFields); IEnumerable updated = container.BeforeUpdate(diff, pipeline); @@ -103,7 +103,7 @@ public IEnumerable BeforeDelete(IEnumerable res { if (GetHook(ResourceHook.BeforeDelete, resources, out IResourceHookContainer container, out RootNode node)) { - RelationshipAttribute[] relationships = node.RelationshipsToNextLayer.Select(p => p.Attribute).ToArray(); + RelationshipAttribute[] relationships = node.RelationshipsToNextLayer.Select(proxy => proxy.Attribute).ToArray(); IEnumerable targetResources = LoadDbValues(typeof(TResource), (IEnumerable)node.UniqueResources, ResourceHook.BeforeDelete, relationships) ?? @@ -312,7 +312,7 @@ private void FireNestedBeforeUpdateHooks(ResourcePipeline pipeline, NodeLayer la { if (uniqueResources.Cast().Any()) { - RelationshipAttribute[] relationships = node.RelationshipsToNextLayer.Select(p => p.Attribute).ToArray(); + RelationshipAttribute[] relationships = node.RelationshipsToNextLayer.Select(proxy => proxy.Attribute).ToArray(); IEnumerable dbValues = LoadDbValues(resourceType, uniqueResources, ResourceHook.BeforeUpdateRelationship, relationships); // these are the resources of the current node grouped by @@ -575,7 +575,7 @@ private void FireAfterUpdateRelationship(IResourceHookContainer container, IReso /// private HashSet GetIds(IEnumerable resources) { - return new HashSet(resources.Cast().Select(e => e.StringId)); + return new HashSet(resources.Cast().Select(resource => resource.StringId)); } } } diff --git a/src/JsonApiDotNetCore/Hooks/Internal/Traversal/NodeLayer.cs b/src/JsonApiDotNetCore/Hooks/Internal/Traversal/NodeLayer.cs index bad0938a20..216f928560 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/Traversal/NodeLayer.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/Traversal/NodeLayer.cs @@ -20,7 +20,7 @@ public NodeLayer(List nodes) public bool AnyResources() { - return _collection.Any(n => n.UniqueResources.Cast().Any()); + return _collection.Any(node => node.UniqueResources.Cast().Any()); } public IEnumerator GetEnumerator() diff --git a/src/JsonApiDotNetCore/Hooks/Internal/Traversal/RootNode.cs b/src/JsonApiDotNetCore/Hooks/Internal/Traversal/RootNode.cs index 14b6296f6f..3f31e14331 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/Traversal/RootNode.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/Traversal/RootNode.cs @@ -36,7 +36,7 @@ public RootNode(IEnumerable uniqueResources, RelationshipProxy[] popu public Dictionary> LeftsToNextLayerByRelationships() { return _allRelationshipsToNextLayer.GroupBy(proxy => proxy.RightType) - .ToDictionary(gdc => gdc.Key, gdc => gdc.ToDictionary(p => p.Attribute, _ => UniqueResources)); + .ToDictionary(gdc => gdc.Key, gdc => gdc.ToDictionary(proxy => proxy.Attribute, _ => UniqueResources)); } /// @@ -44,7 +44,7 @@ public Dictionary> LeftsToN /// public Dictionary LeftsToNextLayer() { - return RelationshipsToNextLayer.ToDictionary(p => p.Attribute, _ => UniqueResources); + return RelationshipsToNextLayer.ToDictionary(proxy => proxy.Attribute, _ => UniqueResources); } /// diff --git a/src/JsonApiDotNetCore/Hooks/Internal/Traversal/TraversalHelper.cs b/src/JsonApiDotNetCore/Hooks/Internal/Traversal/TraversalHelper.cs index 16fd700cd6..f679fc71ca 100644 --- a/src/JsonApiDotNetCore/Hooks/Internal/Traversal/TraversalHelper.cs +++ b/src/JsonApiDotNetCore/Hooks/Internal/Traversal/TraversalHelper.cs @@ -216,7 +216,7 @@ private RelationshipProxy[] GetPopulatedRelationships(LeftType leftType, IEnumer IEnumerable relationshipsFromLeftToRight = _relationshipProxies.Select(entry => entry.Value).Where(proxy => proxy.LeftType == leftType); - return relationshipsFromLeftToRight.Where(proxy => proxy.IsContextRelation || lefts.Any(p => proxy.GetValue(p) != null)).ToArray(); + return relationshipsFromLeftToRight.Where(proxy => proxy.IsContextRelation || lefts.Any(resource => proxy.GetValue(resource) != null)).ToArray(); } /// diff --git a/src/JsonApiDotNetCore/Middleware/JsonApiMiddleware.cs b/src/JsonApiDotNetCore/Middleware/JsonApiMiddleware.cs index 27f9a2a46d..85796ef54f 100644 --- a/src/JsonApiDotNetCore/Middleware/JsonApiMiddleware.cs +++ b/src/JsonApiDotNetCore/Middleware/JsonApiMiddleware.cs @@ -260,7 +260,7 @@ private static string GetCustomRoute(string resourceName, string apiNamespace, H if (routeAttribute != null) { List trimmedComponents = httpContext.Request.Path.Value.Trim('/').Split('/').ToList(); - int resourceNameIndex = trimmedComponents.FindIndex(c => c == resourceName); + int resourceNameIndex = trimmedComponents.FindIndex(component => component == resourceName); string[] newComponents = trimmedComponents.Take(resourceNameIndex).ToArray(); string customRoute = string.Join('/', newComponents); return customRoute == apiNamespace ? null : customRoute; diff --git a/src/JsonApiDotNetCore/Middleware/JsonApiRoutingConvention.cs b/src/JsonApiDotNetCore/Middleware/JsonApiRoutingConvention.cs index d59e1699c0..468400f070 100644 --- a/src/JsonApiDotNetCore/Middleware/JsonApiRoutingConvention.cs +++ b/src/JsonApiDotNetCore/Middleware/JsonApiRoutingConvention.cs @@ -157,7 +157,8 @@ private Type ExtractResourceTypeFromController(Type type) if ((nextBaseType == aspNetControllerType || nextBaseType == coreControllerType) && currentType.IsGenericType) { - Type resourceType = currentType.GetGenericArguments().FirstOrDefault(t => TypeHelper.IsOrImplementsInterface(t, typeof(IIdentifiable))); + Type resourceType = currentType.GetGenericArguments() + .FirstOrDefault(typeArgument => TypeHelper.IsOrImplementsInterface(typeArgument, typeof(IIdentifiable))); if (resourceType != null) { diff --git a/src/JsonApiDotNetCore/Queries/Internal/Parsing/ResourceFieldChainResolver.cs b/src/JsonApiDotNetCore/Queries/Internal/Parsing/ResourceFieldChainResolver.cs index c4c0d1c546..029c76fcb1 100644 --- a/src/JsonApiDotNetCore/Queries/Internal/Parsing/ResourceFieldChainResolver.cs +++ b/src/JsonApiDotNetCore/Queries/Internal/Parsing/ResourceFieldChainResolver.cs @@ -197,7 +197,7 @@ public IReadOnlyCollection ResolveToOneChainEndingInAttr private RelationshipAttribute GetRelationship(string publicName, ResourceContext resourceContext, string path) { - RelationshipAttribute relationship = resourceContext.Relationships.FirstOrDefault(r => r.PublicName == publicName); + RelationshipAttribute relationship = resourceContext.Relationships.FirstOrDefault(nextRelationship => nextRelationship.PublicName == publicName); if (relationship == null) { @@ -239,7 +239,7 @@ private RelationshipAttribute GetToOneRelationship(string publicName, ResourceCo private AttrAttribute GetAttribute(string publicName, ResourceContext resourceContext, string path) { - AttrAttribute attribute = resourceContext.Attributes.FirstOrDefault(a => a.PublicName == publicName); + AttrAttribute attribute = resourceContext.Attributes.FirstOrDefault(nextAttribute => nextAttribute.PublicName == publicName); if (attribute == null) { @@ -253,7 +253,7 @@ private AttrAttribute GetAttribute(string publicName, ResourceContext resourceCo public ResourceFieldAttribute GetField(string publicName, ResourceContext resourceContext, string path) { - ResourceFieldAttribute field = resourceContext.Fields.FirstOrDefault(a => a.PublicName == publicName); + ResourceFieldAttribute field = resourceContext.Fields.FirstOrDefault(nextField => nextField.PublicName == publicName); if (field == null) { diff --git a/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/QueryClauseBuilder.cs b/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/QueryClauseBuilder.cs index 519a800cc2..e8a8b8a6da 100644 --- a/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/QueryClauseBuilder.cs +++ b/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/QueryClauseBuilder.cs @@ -42,7 +42,7 @@ private static Expression TryGetCollectionCount(Expression collectionExpression) if (collectionExpression.Type.IsInterface) { - foreach (PropertyInfo item in collectionExpression.Type.GetInterfaces().SelectMany(i => i.GetProperties())) + foreach (PropertyInfo item in collectionExpression.Type.GetInterfaces().SelectMany(@interface => @interface.GetProperties())) { properties.Add(item); } @@ -107,7 +107,7 @@ protected Expression CreateTupleAccessExpressionForConstant(object value, Type t // Tuple.Create(value).Item1; MethodInfo tupleCreateMethod = typeof(Tuple).GetMethods() - .Single(m => m.Name == "Create" && m.IsGenericMethod && m.GetGenericArguments().Length == 1); + .Single(method => method.Name == "Create" && method.IsGenericMethod && method.GetGenericArguments().Length == 1); MethodInfo constructedTupleCreateMethod = tupleCreateMethod.MakeGenericMethod(type); diff --git a/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/SelectClauseBuilder.cs b/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/SelectClauseBuilder.cs index 79545277ef..447a47b85a 100644 --- a/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/SelectClauseBuilder.cs +++ b/src/JsonApiDotNetCore/Queries/Internal/QueryableBuilding/SelectClauseBuilder.cs @@ -116,7 +116,7 @@ private ICollection ToPropertySelectors(IDictionary type.ClrType == elementType); - IEnumerable entityProperties = entityModel.GetProperties().Where(p => !p.IsShadowProperty()).ToArray(); + IEnumerable entityProperties = entityModel.GetProperties().Where(property => !property.IsShadowProperty()).ToArray(); foreach (IProperty entityProperty in entityProperties) { diff --git a/src/JsonApiDotNetCore/QueryStrings/Internal/QueryStringReader.cs b/src/JsonApiDotNetCore/QueryStrings/Internal/QueryStringReader.cs index ce7ac0288d..19673f7fb3 100644 --- a/src/JsonApiDotNetCore/QueryStrings/Internal/QueryStringReader.cs +++ b/src/JsonApiDotNetCore/QueryStrings/Internal/QueryStringReader.cs @@ -45,7 +45,7 @@ public virtual void ReadAll(DisableQueryStringAttribute disableQueryStringAttrib $"Missing value for '{parameterName}' query string parameter."); } - IQueryStringParameterReader reader = _parameterReaders.FirstOrDefault(r => r.CanRead(parameterName)); + IQueryStringParameterReader reader = _parameterReaders.FirstOrDefault(nextReader => nextReader.CanRead(parameterName)); if (reader != null) { diff --git a/src/JsonApiDotNetCore/Resources/ResourceFactory.cs b/src/JsonApiDotNetCore/Resources/ResourceFactory.cs index cb802a4b3b..abeabf331e 100644 --- a/src/JsonApiDotNetCore/Resources/ResourceFactory.cs +++ b/src/JsonApiDotNetCore/Resources/ResourceFactory.cs @@ -91,7 +91,7 @@ public NewExpression CreateNewExpression(Type resourceType) private static Expression CreateTupleAccessExpressionForConstant(object value, Type type) { MethodInfo tupleCreateMethod = typeof(Tuple).GetMethods() - .Single(m => m.Name == "Create" && m.IsGenericMethod && m.GetGenericArguments().Length == 1); + .Single(method => method.Name == "Create" && method.IsGenericMethod && method.GetGenericArguments().Length == 1); MethodInfo constructedTupleCreateMethod = tupleCreateMethod.MakeGenericMethod(type); @@ -103,14 +103,14 @@ private static Expression CreateTupleAccessExpressionForConstant(object value, T internal static bool HasSingleConstructorWithoutParameters(Type type) { - ConstructorInfo[] constructors = type.GetConstructors().Where(c => !c.IsStatic).ToArray(); + ConstructorInfo[] constructors = type.GetConstructors().Where(constructor => !constructor.IsStatic).ToArray(); return constructors.Length == 1 && constructors[0].GetParameters().Length == 0; } private static ConstructorInfo GetLongestConstructor(Type type) { - ConstructorInfo[] constructors = type.GetConstructors().Where(c => !c.IsStatic).ToArray(); + ConstructorInfo[] constructors = type.GetConstructors().Where(constructor => !constructor.IsStatic).ToArray(); if (constructors.Length == 0) { diff --git a/src/JsonApiDotNetCore/Serialization/Client/Internal/ResponseDeserializer.cs b/src/JsonApiDotNetCore/Serialization/Client/Internal/ResponseDeserializer.cs index 82cfac8fcb..f7887a677d 100644 --- a/src/JsonApiDotNetCore/Serialization/Client/Internal/ResponseDeserializer.cs +++ b/src/JsonApiDotNetCore/Serialization/Client/Internal/ResponseDeserializer.cs @@ -135,13 +135,14 @@ private ResourceObject GetLinkedResource(ResourceIdentifierObject relatedResourc { try { - return Document.Included.SingleOrDefault(r => r.Type == relatedResourceIdentifier.Type && r.Id == relatedResourceIdentifier.Id); + return Document.Included.SingleOrDefault(resourceObject => + resourceObject.Type == relatedResourceIdentifier.Type && resourceObject.Id == relatedResourceIdentifier.Id); } - catch (InvalidOperationException e) + catch (InvalidOperationException exception) { throw new InvalidOperationException( "A compound document MUST NOT include more than one resource object for each type and ID pair." + - $"The duplicate pair was '{relatedResourceIdentifier.Type}, {relatedResourceIdentifier.Id}'", e); + $"The duplicate pair was '{relatedResourceIdentifier.Type}, {relatedResourceIdentifier.Id}'", exception); } } } diff --git a/src/JsonApiDotNetCore/Serialization/JsonApiReader.cs b/src/JsonApiDotNetCore/Serialization/JsonApiReader.cs index c2b32d0381..9b3626832d 100644 --- a/src/JsonApiDotNetCore/Serialization/JsonApiReader.cs +++ b/src/JsonApiDotNetCore/Serialization/JsonApiReader.cs @@ -181,7 +181,7 @@ private IEnumerable GetResourceTypesFromRequestBody(object model) { if (model is IEnumerable resourceCollection) { - return resourceCollection.Select(r => r.GetType()).Distinct(); + return resourceCollection.Select(resource => resource.GetType()).Distinct(); } return model == null ? Enumerable.Empty() : model.GetType().AsEnumerable(); diff --git a/src/JsonApiDotNetCore/Serialization/Objects/ErrorDocument.cs b/src/JsonApiDotNetCore/Serialization/Objects/ErrorDocument.cs index d558b94186..971fdecce3 100644 --- a/src/JsonApiDotNetCore/Serialization/Objects/ErrorDocument.cs +++ b/src/JsonApiDotNetCore/Serialization/Objects/ErrorDocument.cs @@ -30,7 +30,7 @@ public ErrorDocument(IEnumerable errors) public HttpStatusCode GetErrorStatusCode() { - int[] statusCodes = Errors.Select(e => (int)e.StatusCode).Distinct().ToArray(); + int[] statusCodes = Errors.Select(error => (int)error.StatusCode).Distinct().ToArray(); if (statusCodes.Length == 1) { diff --git a/test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs b/test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs index ecdc3569d6..ef402b78b2 100644 --- a/test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs +++ b/test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs @@ -28,7 +28,7 @@ public sealed class ServiceDiscoveryFacadeTests public ServiceDiscoveryFacadeTests() { var dbResolverMock = new Mock(); - dbResolverMock.Setup(m => m.GetContext()).Returns(new Mock().Object); + dbResolverMock.Setup(resolver => resolver.GetContext()).Returns(new Mock().Object); _services.AddScoped(_ => dbResolverMock.Object); _services.AddSingleton(_options); diff --git a/test/JsonApiDotNetCoreExampleTests/ExampleFakers.cs b/test/JsonApiDotNetCoreExampleTests/ExampleFakers.cs index a67c525537..106eb8fe40 100644 --- a/test/JsonApiDotNetCoreExampleTests/ExampleFakers.cs +++ b/test/JsonApiDotNetCoreExampleTests/ExampleFakers.cs @@ -14,36 +14,36 @@ internal sealed class ExampleFakers : FakerContainer private readonly Lazy> _lazyAuthorFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(author => author.FirstName, f => f.Person.FirstName) - .RuleFor(author => author.LastName, f => f.Person.LastName)); + .RuleFor(author => author.FirstName, faker => faker.Person.FirstName) + .RuleFor(author => author.LastName, faker => faker.Person.LastName)); private readonly Lazy> _lazyArticleFaker = new Lazy>(() => new Faker
() .UseSeed(GetFakerSeed()) - .RuleFor(article => article.Caption, f => f.Lorem.Word()) - .RuleFor(article => article.Url, f => f.Internet.Url())); + .RuleFor(article => article.Caption, faker => faker.Lorem.Word()) + .RuleFor(article => article.Url, faker => faker.Internet.Url())); private readonly Lazy> _lazyUserFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(user => user.UserName, f => f.Person.UserName) - .RuleFor(user => user.Password, f => f.Internet.Password())); + .RuleFor(user => user.UserName, faker => faker.Person.UserName) + .RuleFor(user => user.Password, faker => faker.Internet.Password())); private readonly Lazy> _lazyTodoItemFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(todoItem => todoItem.Description, f => f.Random.Words())); + .RuleFor(todoItem => todoItem.Description, faker => faker.Random.Words())); private readonly Lazy> _lazyPersonFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(person => person.FirstName, f => f.Person.FirstName) - .RuleFor(person => person.LastName, f => f.Person.LastName)); + .RuleFor(person => person.FirstName, faker => faker.Person.FirstName) + .RuleFor(person => person.LastName, faker => faker.Person.LastName)); private readonly Lazy> _lazyTagFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(tag => tag.Name, f => f.Lorem.Word())); + .RuleFor(tag => tag.Name, faker => faker.Lorem.Word())); public Faker Author => _lazyAuthorFaker.Value; public Faker
Article => _lazyArticleFaker.Value; diff --git a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/AtomicOperations/OperationsFakers.cs b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/AtomicOperations/OperationsFakers.cs index d652a8bed5..546cb84b03 100644 --- a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/AtomicOperations/OperationsFakers.cs +++ b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/AtomicOperations/OperationsFakers.cs @@ -22,38 +22,38 @@ internal sealed class OperationsFakers : FakerContainer private readonly Lazy> _lazyPlaylistFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(playlist => playlist.Name, f => f.Lorem.Sentence())); + .RuleFor(playlist => playlist.Name, faker => faker.Lorem.Sentence())); private readonly Lazy> _lazyMusicTrackFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(musicTrack => musicTrack.Title, f => f.Lorem.Word()) - .RuleFor(musicTrack => musicTrack.LengthInSeconds, f => f.Random.Decimal(3 * 60, 5 * 60)) - .RuleFor(musicTrack => musicTrack.Genre, f => f.Lorem.Word()) - .RuleFor(musicTrack => musicTrack.ReleasedAt, f => f.Date.PastOffset())); + .RuleFor(musicTrack => musicTrack.Title, faker => faker.Lorem.Word()) + .RuleFor(musicTrack => musicTrack.LengthInSeconds, faker => faker.Random.Decimal(3 * 60, 5 * 60)) + .RuleFor(musicTrack => musicTrack.Genre, faker => faker.Lorem.Word()) + .RuleFor(musicTrack => musicTrack.ReleasedAt, faker => faker.Date.PastOffset())); private readonly Lazy> _lazyLyricFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(lyric => lyric.Text, f => f.Lorem.Text()) + .RuleFor(lyric => lyric.Text, faker => faker.Lorem.Text()) .RuleFor(lyric => lyric.Format, "LRC")); private readonly Lazy> _lazyTextLanguageFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(textLanguage => textLanguage.IsoCode, f => f.PickRandom(LazyLanguageIsoCodes.Value))); + .RuleFor(textLanguage => textLanguage.IsoCode, faker => faker.PickRandom(LazyLanguageIsoCodes.Value))); private readonly Lazy> _lazyPerformerFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(performer => performer.ArtistName, f => f.Name.FullName()) - .RuleFor(performer => performer.BornAt, f => f.Date.PastOffset())); + .RuleFor(performer => performer.ArtistName, faker => faker.Name.FullName()) + .RuleFor(performer => performer.BornAt, faker => faker.Date.PastOffset())); private readonly Lazy> _lazyRecordCompanyFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(recordCompany => recordCompany.Name, f => f.Company.CompanyName()) - .RuleFor(recordCompany => recordCompany.CountryOfResidence, f => f.Address.Country())); + .RuleFor(recordCompany => recordCompany.Name, faker => faker.Company.CompanyName()) + .RuleFor(recordCompany => recordCompany.CountryOfResidence, faker => faker.Address.Country())); public Faker Playlist => _lazyPlaylistFaker.Value; public Faker MusicTrack => _lazyMusicTrackFaker.Value; diff --git a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/CustomRoutes/CustomRouteFakers.cs b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/CustomRoutes/CustomRouteFakers.cs index 2c15eb3e30..9bd81abec4 100644 --- a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/CustomRoutes/CustomRouteFakers.cs +++ b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/CustomRoutes/CustomRouteFakers.cs @@ -12,14 +12,14 @@ internal sealed class CustomRouteFakers : FakerContainer private readonly Lazy> _lazyTownFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(town => town.Name, f => f.Address.City()) - .RuleFor(town => town.Latitude, f => f.Address.Latitude()) - .RuleFor(town => town.Longitude, f => f.Address.Longitude())); + .RuleFor(town => town.Name, faker => faker.Address.City()) + .RuleFor(town => town.Latitude, faker => faker.Address.Latitude()) + .RuleFor(town => town.Longitude, faker => faker.Address.Longitude())); private readonly Lazy> _lazyCivilianFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(civilian => civilian.Name, f => f.Person.FullName)); + .RuleFor(civilian => civilian.Name, faker => faker.Person.FullName)); public Faker Town => _lazyTownFaker.Value; public Faker Civilian => _lazyCivilianFaker.Value; diff --git a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/EagerLoading/EagerLoadingFakers.cs b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/EagerLoading/EagerLoadingFakers.cs index 5910102644..bb41ba2449 100644 --- a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/EagerLoading/EagerLoadingFakers.cs +++ b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/EagerLoading/EagerLoadingFakers.cs @@ -12,33 +12,33 @@ internal sealed class EagerLoadingFakers : FakerContainer private readonly Lazy> _lazyStateFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(state => state.Name, f => f.Address.City())); + .RuleFor(state => state.Name, faker => faker.Address.City())); private readonly Lazy> _lazyCityFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(city => city.Name, f => f.Address.City())); + .RuleFor(city => city.Name, faker => faker.Address.City())); private readonly Lazy> _lazyStreetFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(street => street.Name, f => f.Address.StreetName())); + .RuleFor(street => street.Name, faker => faker.Address.StreetName())); private readonly Lazy> _lazyBuildingFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(building => building.Number, f => f.Address.BuildingNumber())); + .RuleFor(building => building.Number, faker => faker.Address.BuildingNumber())); private readonly Lazy> _lazyWindowFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(window => window.HeightInCentimeters, f => f.Random.Number(30, 199)) - .RuleFor(window => window.WidthInCentimeters, f => f.Random.Number(30, 199))); + .RuleFor(window => window.HeightInCentimeters, faker => faker.Random.Number(30, 199)) + .RuleFor(window => window.WidthInCentimeters, faker => faker.Random.Number(30, 199))); private readonly Lazy> _lazyDoorFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(door => door.Color, f => f.Commerce.Color())); + .RuleFor(door => door.Color, faker => faker.Commerce.Color())); public Faker State => _lazyStateFaker.Value; public Faker City => _lazyCityFaker.Value; diff --git a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/HostingInIIS/HostingFakers.cs b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/HostingInIIS/HostingFakers.cs index 0bbe24f429..b67b79ab6e 100644 --- a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/HostingInIIS/HostingFakers.cs +++ b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/HostingInIIS/HostingFakers.cs @@ -12,12 +12,12 @@ internal sealed class HostingFakers : FakerContainer private readonly Lazy> _lazyArtGalleryFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(artGallery => artGallery.Theme, f => f.Lorem.Word())); + .RuleFor(artGallery => artGallery.Theme, faker => faker.Lorem.Word())); private readonly Lazy> _lazyPaintingFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(painting => painting.Title, f => f.Lorem.Sentence())); + .RuleFor(painting => painting.Title, faker => faker.Lorem.Sentence())); public Faker ArtGallery => _lazyArtGalleryFaker.Value; public Faker Painting => _lazyPaintingFaker.Value; diff --git a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/IdObfuscation/ObfuscationFakers.cs b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/IdObfuscation/ObfuscationFakers.cs index d6a08114e4..ed064f2956 100644 --- a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/IdObfuscation/ObfuscationFakers.cs +++ b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/IdObfuscation/ObfuscationFakers.cs @@ -12,13 +12,13 @@ internal sealed class ObfuscationFakers : FakerContainer private readonly Lazy> _lazyBankAccountFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(bankAccount => bankAccount.Iban, f => f.Finance.Iban())); + .RuleFor(bankAccount => bankAccount.Iban, faker => faker.Finance.Iban())); private readonly Lazy> _lazyDebitCardFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(debitCard => debitCard.OwnerName, f => f.Name.FullName()) - .RuleFor(debitCard => debitCard.PinCode, f => (short)f.Random.Number(1000, 9999))); + .RuleFor(debitCard => debitCard.OwnerName, faker => faker.Name.FullName()) + .RuleFor(debitCard => debitCard.PinCode, faker => (short)faker.Random.Number(1000, 9999))); public Faker BankAccount => _lazyBankAccountFaker.Value; public Faker DebitCard => _lazyDebitCardFaker.Value; diff --git a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/Links/LinksFakers.cs b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/Links/LinksFakers.cs index b0ade264dc..bd6ee4acb3 100644 --- a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/Links/LinksFakers.cs +++ b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/Links/LinksFakers.cs @@ -12,19 +12,19 @@ internal sealed class LinksFakers : FakerContainer private readonly Lazy> _lazyPhotoAlbumFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(photoAlbum => photoAlbum.Name, f => f.Lorem.Sentence())); + .RuleFor(photoAlbum => photoAlbum.Name, faker => faker.Lorem.Sentence())); private readonly Lazy> _lazyPhotoFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(photo => photo.Url, f => f.Image.PlaceImgUrl())); + .RuleFor(photo => photo.Url, faker => faker.Image.PlaceImgUrl())); private readonly Lazy> _lazyPhotoLocationFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(photoLocation => photoLocation.PlaceName, f => f.Address.FullAddress()) - .RuleFor(photoLocation => photoLocation.Latitude, f => f.Address.Latitude()) - .RuleFor(photoLocation => photoLocation.Longitude, f => f.Address.Longitude())); + .RuleFor(photoLocation => photoLocation.PlaceName, faker => faker.Address.FullAddress()) + .RuleFor(photoLocation => photoLocation.Latitude, faker => faker.Address.Latitude()) + .RuleFor(photoLocation => photoLocation.Longitude, faker => faker.Address.Longitude())); public Faker PhotoAlbum => _lazyPhotoAlbumFaker.Value; public Faker Photo => _lazyPhotoFaker.Value; diff --git a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/Logging/AuditFakers.cs b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/Logging/AuditFakers.cs index ea3e4c79a4..702411dddd 100644 --- a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/Logging/AuditFakers.cs +++ b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/Logging/AuditFakers.cs @@ -12,8 +12,8 @@ internal sealed class AuditFakers : FakerContainer private readonly Lazy> _lazyAuditEntryFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(auditEntry => auditEntry.UserName, f => f.Internet.UserName()) - .RuleFor(auditEntry => auditEntry.CreatedAt, f => f.Date.PastOffset())); + .RuleFor(auditEntry => auditEntry.UserName, faker => faker.Internet.UserName()) + .RuleFor(auditEntry => auditEntry.CreatedAt, faker => faker.Date.PastOffset())); public Faker AuditEntry => _lazyAuditEntryFaker.Value; } diff --git a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/Meta/SupportFakers.cs b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/Meta/SupportFakers.cs index 59de00b55c..797696c8f6 100644 --- a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/Meta/SupportFakers.cs +++ b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/Meta/SupportFakers.cs @@ -12,12 +12,12 @@ internal sealed class SupportFakers : FakerContainer private readonly Lazy> _lazyProductFamilyFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(productFamily => productFamily.Name, f => f.Commerce.ProductName())); + .RuleFor(productFamily => productFamily.Name, faker => faker.Commerce.ProductName())); private readonly Lazy> _lazySupportTicketFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(supportTicket => supportTicket.Description, f => f.Lorem.Paragraph())); + .RuleFor(supportTicket => supportTicket.Description, faker => faker.Lorem.Paragraph())); public Faker ProductFamily => _lazyProductFamilyFaker.Value; public Faker SupportTicket => _lazySupportTicketFaker.Value; diff --git a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/ModelStateValidation/ModelStateDbContext.cs b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/ModelStateValidation/ModelStateDbContext.cs index c130f596b6..7e76eb5617 100644 --- a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/ModelStateValidation/ModelStateDbContext.cs +++ b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/ModelStateValidation/ModelStateDbContext.cs @@ -20,7 +20,7 @@ protected override void OnModelCreating(ModelBuilder builder) { builder.Entity() .HasMany(systemDirectory => systemDirectory.Subdirectories) - .WithOne(x => x.Parent); + .WithOne(systemDirectory => systemDirectory.Parent); builder.Entity() .HasOne(systemDirectory => systemDirectory.Self) diff --git a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/NamingConventions/SwimmingFakers.cs b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/NamingConventions/SwimmingFakers.cs index 86ecc8d1ad..13debc6ca7 100644 --- a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/NamingConventions/SwimmingFakers.cs +++ b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/NamingConventions/SwimmingFakers.cs @@ -12,17 +12,17 @@ internal sealed class SwimmingFakers : FakerContainer private readonly Lazy> _lazySwimmingPoolFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(swimmingPool => swimmingPool.IsIndoor, f => f.Random.Bool())); + .RuleFor(swimmingPool => swimmingPool.IsIndoor, faker => faker.Random.Bool())); private readonly Lazy> _lazyWaterSlideFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(waterSlide => waterSlide.LengthInMeters, f => f.Random.Decimal(3, 100))); + .RuleFor(waterSlide => waterSlide.LengthInMeters, faker => faker.Random.Decimal(3, 100))); private readonly Lazy> _lazyDivingBoardFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(divingBoard => divingBoard.HeightInMeters, f => f.Random.Decimal(1, 15))); + .RuleFor(divingBoard => divingBoard.HeightInMeters, faker => faker.Random.Decimal(1, 15))); public Faker SwimmingPool => _lazySwimmingPoolFaker.Value; public Faker WaterSlide => _lazyWaterSlideFaker.Value; diff --git a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/QueryStrings/QueryStringFakers.cs b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/QueryStrings/QueryStringFakers.cs index b2c878853e..32591440c7 100644 --- a/test/JsonApiDotNetCoreExampleTests/IntegrationTests/QueryStrings/QueryStringFakers.cs +++ b/test/JsonApiDotNetCoreExampleTests/IntegrationTests/QueryStrings/QueryStringFakers.cs @@ -12,53 +12,53 @@ internal sealed class QueryStringFakers : FakerContainer private readonly Lazy> _lazyBlogFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(blog => blog.Title, f => f.Lorem.Word()) - .RuleFor(blog => blog.PlatformName, f => f.Company.CompanyName())); + .RuleFor(blog => blog.Title, faker => faker.Lorem.Word()) + .RuleFor(blog => blog.PlatformName, faker => faker.Company.CompanyName())); private readonly Lazy> _lazyBlogPostFaker = new Lazy>(() => new Faker() .UseSeed(GetFakerSeed()) - .RuleFor(blogPost => blogPost.Caption, f => f.Lorem.Sentence()) - .RuleFor(blogPost => blogPost.Url, f => f.Internet.Url())); + .RuleFor(blogPost => blogPost.Caption, faker => faker.Lorem.Sentence()) + .RuleFor(blogPost => blogPost.Url, faker => faker.Internet.Url())); private readonly Lazy> _lazyLabelFaker = new Lazy>(() => new Faker