diff --git a/JsonApiDotnetCore.sln b/JsonApiDotnetCore.sln index 69b9367d58..769230390d 100644 --- a/JsonApiDotnetCore.sln +++ b/JsonApiDotnetCore.sln @@ -108,6 +108,7 @@ Global {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Debug|x86.ActiveCfg = Debug|Any CPU {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Debug|x86.Build.0 = Debug|Any CPU {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|Any CPU.Build.0 = Release|Any CPU {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|x64.ActiveCfg = Release|Any CPU {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|x64.Build.0 = Release|Any CPU {DF0FCFB2-CB12-44BA-BBB5-1BE0BCFCD14C}.Release|x86.ActiveCfg = Release|Any CPU diff --git a/benchmarks/BenchmarkResource.cs b/benchmarks/BenchmarkResource.cs index 0d3ae2c8bf..6fe5eea7ca 100644 --- a/benchmarks/BenchmarkResource.cs +++ b/benchmarks/BenchmarkResource.cs @@ -2,7 +2,7 @@ namespace Benchmarks { - public class BenchmarkResource : Identifiable + public sealed class BenchmarkResource : Identifiable { [Attr(BenchmarkResourcePublicNames.NameAttr)] public string Name { get; set; } @@ -17,7 +17,7 @@ public class SubResource : Identifiable public string Value { get; set; } } - public static class BenchmarkResourcePublicNames + internal static class BenchmarkResourcePublicNames { public const string NameAttr = "full-name"; public const string Type = "simple-types"; diff --git a/benchmarks/Benchmarks.csproj b/benchmarks/Benchmarks.csproj index 02bfbf378d..72ff3a78cf 100644 --- a/benchmarks/Benchmarks.csproj +++ b/benchmarks/Benchmarks.csproj @@ -6,7 +6,6 @@ - diff --git a/benchmarks/Program.cs b/benchmarks/Program.cs index 474bb5725c..396f8786cb 100644 --- a/benchmarks/Program.cs +++ b/benchmarks/Program.cs @@ -5,9 +5,9 @@ namespace Benchmarks { - class Program + internal class Program { - static void Main(string[] args) + private static void Main(string[] args) { var switcher = new BenchmarkSwitcher(new[] { diff --git a/src/Examples/GettingStarted/Controllers/ArticlesController.cs b/src/Examples/GettingStarted/Controllers/ArticlesController.cs index fec9d3e38d..c25e740825 100644 --- a/src/Examples/GettingStarted/Controllers/ArticlesController.cs +++ b/src/Examples/GettingStarted/Controllers/ArticlesController.cs @@ -6,7 +6,7 @@ namespace GettingStarted { - public class ArticlesController : JsonApiController
+ public sealed class ArticlesController : JsonApiController
{ public ArticlesController( IJsonApiOptions jsonApiOptions, diff --git a/src/Examples/GettingStarted/Controllers/PeopleController.cs b/src/Examples/GettingStarted/Controllers/PeopleController.cs index 68ff5932ea..e6a9a2a4ff 100644 --- a/src/Examples/GettingStarted/Controllers/PeopleController.cs +++ b/src/Examples/GettingStarted/Controllers/PeopleController.cs @@ -6,7 +6,7 @@ namespace GettingStarted { - public class PeopleController : JsonApiController + public sealed class PeopleController : JsonApiController { public PeopleController( IJsonApiOptions jsonApiOptions, diff --git a/src/Examples/GettingStarted/Models/Article.cs b/src/Examples/GettingStarted/Models/Article.cs index f10c3b175f..e8bf99fcaf 100644 --- a/src/Examples/GettingStarted/Models/Article.cs +++ b/src/Examples/GettingStarted/Models/Article.cs @@ -2,7 +2,7 @@ namespace GettingStarted.Models { - public class Article : Identifiable + public sealed class Article : Identifiable { [Attr] public string Title { get; set; } @@ -10,4 +10,4 @@ public class Article : Identifiable public Person Author { get; set; } public int AuthorId { get; set; } } -} \ No newline at end of file +} diff --git a/src/Examples/GettingStarted/Models/Person.cs b/src/Examples/GettingStarted/Models/Person.cs index 39b59a44bb..3c5cff596c 100644 --- a/src/Examples/GettingStarted/Models/Person.cs +++ b/src/Examples/GettingStarted/Models/Person.cs @@ -3,11 +3,11 @@ namespace GettingStarted.Models { - public class Person : Identifiable + public sealed class Person : Identifiable { [Attr] public string Name { get; set; } [HasMany] public List
Articles { get; set; } } -} \ No newline at end of file +} diff --git a/src/Examples/GettingStarted/ResourceDefinitionExample/Model.cs b/src/Examples/GettingStarted/ResourceDefinitionExample/Model.cs index 44a421e112..c12d8946f8 100644 --- a/src/Examples/GettingStarted/ResourceDefinitionExample/Model.cs +++ b/src/Examples/GettingStarted/ResourceDefinitionExample/Model.cs @@ -2,7 +2,7 @@ namespace GettingStarted.ResourceDefinitionExample { - public class Model : Identifiable + public sealed class Model : Identifiable { [Attr] public string DoNotExpose { get; set; } diff --git a/src/Examples/GettingStarted/ResourceDefinitionExample/ModelDefinition.cs b/src/Examples/GettingStarted/ResourceDefinitionExample/ModelDefinition.cs index 1948a13dd7..ac89fc97f2 100644 --- a/src/Examples/GettingStarted/ResourceDefinitionExample/ModelDefinition.cs +++ b/src/Examples/GettingStarted/ResourceDefinitionExample/ModelDefinition.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Models; diff --git a/src/Examples/GettingStarted/ResourceDefinitionExample/ModelsController.cs b/src/Examples/GettingStarted/ResourceDefinitionExample/ModelsController.cs index 52478823f8..3b2d83e8c8 100644 --- a/src/Examples/GettingStarted/ResourceDefinitionExample/ModelsController.cs +++ b/src/Examples/GettingStarted/ResourceDefinitionExample/ModelsController.cs @@ -5,7 +5,7 @@ namespace GettingStarted.ResourceDefinitionExample { - public class ModelsController : JsonApiController + public sealed class ModelsController : JsonApiController { public ModelsController( IJsonApiOptions jsonApiOptions, diff --git a/src/Examples/GettingStarted/Startup.cs b/src/Examples/GettingStarted/Startup.cs index c467b9cccd..6c46707d1d 100644 --- a/src/Examples/GettingStarted/Startup.cs +++ b/src/Examples/GettingStarted/Startup.cs @@ -5,7 +5,7 @@ namespace GettingStarted { - public class Startup + public sealed class Startup { public void ConfigureServices(IServiceCollection services) { diff --git a/src/Examples/JsonApiDotNetCoreExample/Controllers/ArticlesController.cs b/src/Examples/JsonApiDotNetCoreExample/Controllers/ArticlesController.cs index ab64bf2c45..4ae287c670 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Controllers/ArticlesController.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Controllers/ArticlesController.cs @@ -6,7 +6,7 @@ namespace JsonApiDotNetCoreExample.Controllers { - public class ArticlesController : JsonApiController
+ public sealed class ArticlesController : JsonApiController
{ public ArticlesController( IJsonApiOptions jsonApiOptions, diff --git a/src/Examples/JsonApiDotNetCoreExample/Controllers/CamelCasedModelsController.cs b/src/Examples/JsonApiDotNetCoreExample/Controllers/CamelCasedModelsController.cs index 588b474c28..3f1ac5e2ed 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Controllers/CamelCasedModelsController.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Controllers/CamelCasedModelsController.cs @@ -6,7 +6,7 @@ namespace JsonApiDotNetCoreExample.Controllers { - public class KebabCasedModelsController : JsonApiController + public sealed class KebabCasedModelsController : JsonApiController { public KebabCasedModelsController( IJsonApiOptions jsonApiOptions, diff --git a/src/Examples/JsonApiDotNetCoreExample/Controllers/PassportsController.cs b/src/Examples/JsonApiDotNetCoreExample/Controllers/PassportsController.cs index 1f38c6aee6..d2268ac09e 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Controllers/PassportsController.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Controllers/PassportsController.cs @@ -6,7 +6,7 @@ namespace JsonApiDotNetCoreExample.Controllers { - public class PassportsController : JsonApiController + public sealed class PassportsController : JsonApiController { public PassportsController( IJsonApiOptions jsonApiOptions, diff --git a/src/Examples/JsonApiDotNetCoreExample/Controllers/PeopleController.cs b/src/Examples/JsonApiDotNetCoreExample/Controllers/PeopleController.cs index 85a00aaa02..eae404b7bc 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Controllers/PeopleController.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Controllers/PeopleController.cs @@ -6,7 +6,7 @@ namespace JsonApiDotNetCoreExample.Controllers { - public class PeopleController : JsonApiController + public sealed class PeopleController : JsonApiController { public PeopleController( IJsonApiOptions jsonApiOptions, diff --git a/src/Examples/JsonApiDotNetCoreExample/Controllers/PersonRolesController.cs b/src/Examples/JsonApiDotNetCoreExample/Controllers/PersonRolesController.cs index f11e2cee5a..4dfb9232b0 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Controllers/PersonRolesController.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Controllers/PersonRolesController.cs @@ -6,7 +6,7 @@ namespace JsonApiDotNetCoreExample.Controllers { - public class PersonRolesController : JsonApiController + public sealed class PersonRolesController : JsonApiController { public PersonRolesController( IJsonApiOptions jsonApiOptions, diff --git a/src/Examples/JsonApiDotNetCoreExample/Controllers/TagsController.cs b/src/Examples/JsonApiDotNetCoreExample/Controllers/TagsController.cs index 24a5de6931..d9e1382c33 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Controllers/TagsController.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Controllers/TagsController.cs @@ -6,7 +6,7 @@ namespace JsonApiDotNetCoreExample.Controllers { - public class TagsController : JsonApiController + public sealed class TagsController : JsonApiController { public TagsController( IJsonApiOptions jsonApiOptions, diff --git a/src/Examples/JsonApiDotNetCoreExample/Controllers/TestValuesController.cs b/src/Examples/JsonApiDotNetCoreExample/Controllers/TestValuesController.cs index a29295c426..29bb211cfd 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Controllers/TestValuesController.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Controllers/TestValuesController.cs @@ -8,7 +8,7 @@ public class TestValuesController : ControllerBase [HttpGet] public IActionResult Get() { - var result = new string[] { "value" }; + var result = new[] { "value" }; return Ok(result); } } diff --git a/src/Examples/JsonApiDotNetCoreExample/Controllers/TodoCollectionsController.cs b/src/Examples/JsonApiDotNetCoreExample/Controllers/TodoCollectionsController.cs index 8bf3a95539..ccdcb088ca 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Controllers/TodoCollectionsController.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Controllers/TodoCollectionsController.cs @@ -12,9 +12,9 @@ namespace JsonApiDotNetCoreExample.Controllers { - public class TodoCollectionsController : JsonApiController + public sealed class TodoCollectionsController : JsonApiController { - readonly IDbContextResolver _dbResolver; + private readonly IDbContextResolver _dbResolver; public TodoCollectionsController( IJsonApiOptions jsonApiOptions, diff --git a/src/Examples/JsonApiDotNetCoreExample/Controllers/TodoItemsController.cs b/src/Examples/JsonApiDotNetCoreExample/Controllers/TodoItemsController.cs index ea8dbf8359..d21f6c016d 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Controllers/TodoItemsController.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Controllers/TodoItemsController.cs @@ -6,7 +6,7 @@ namespace JsonApiDotNetCoreExample.Controllers { - public class TodoItemsController : JsonApiController + public sealed class TodoItemsController : JsonApiController { public TodoItemsController( IJsonApiOptions jsonApiOptions, diff --git a/src/Examples/JsonApiDotNetCoreExample/Controllers/TodoItemsCustomController.cs b/src/Examples/JsonApiDotNetCoreExample/Controllers/TodoItemsCustomController.cs index 19e16c26ea..476ae4860b 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Controllers/TodoItemsCustomController.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Controllers/TodoItemsCustomController.cs @@ -28,7 +28,7 @@ public CustomJsonApiController( IJsonApiOptions options, IResourceService resourceService, ILoggerFactory loggerFactory) - : base(options, resourceService, loggerFactory) + : base(options, resourceService) { } } @@ -36,23 +36,20 @@ public CustomJsonApiController( public class CustomJsonApiController : ControllerBase where T : class, IIdentifiable { - private readonly ILogger _logger; private readonly IJsonApiOptions _options; private readonly IResourceService _resourceService; - protected IActionResult Forbidden() + private IActionResult Forbidden() { return new StatusCodeResult(403); } public CustomJsonApiController( IJsonApiOptions options, - IResourceService resourceService, - ILoggerFactory loggerFactory) + IResourceService resourceService) { _options = options; _resourceService = resourceService; - _logger = loggerFactory.CreateLogger>(); } public CustomJsonApiController( @@ -62,14 +59,14 @@ public CustomJsonApiController( } [HttpGet] - public virtual async Task GetAsync() + public async Task GetAsync() { var entities = await _resourceService.GetAsync(); return Ok(entities); } [HttpGet("{id}")] - public virtual async Task GetAsync(TId id) + public async Task GetAsync(TId id) { var entity = await _resourceService.GetAsync(id); @@ -80,7 +77,7 @@ public virtual async Task GetAsync(TId id) } [HttpGet("{id}/relationships/{relationshipName}")] - public virtual async Task GetRelationshipsAsync(TId id, string relationshipName) + public async Task GetRelationshipsAsync(TId id, string relationshipName) { var relationship = _resourceService.GetRelationshipAsync(id, relationshipName); if (relationship == null) @@ -90,14 +87,14 @@ public virtual async Task GetRelationshipsAsync(TId id, string re } [HttpGet("{id}/{relationshipName}")] - public virtual async Task GetRelationshipAsync(TId id, string relationshipName) + public async Task GetRelationshipAsync(TId id, string relationshipName) { var relationship = await _resourceService.GetRelationshipAsync(id, relationshipName); return Ok(relationship); } [HttpPost] - public virtual async Task PostAsync([FromBody] T entity) + public async Task PostAsync([FromBody] T entity) { if (entity == null) return UnprocessableEntity(); @@ -111,7 +108,7 @@ public virtual async Task PostAsync([FromBody] T entity) } [HttpPatch("{id}")] - public virtual async Task PatchAsync(TId id, [FromBody] T entity) + public async Task PatchAsync(TId id, [FromBody] T entity) { if (entity == null) return UnprocessableEntity(); @@ -125,14 +122,14 @@ public virtual async Task PatchAsync(TId id, [FromBody] T entity) } [HttpPatch("{id}/relationships/{relationshipName}")] - public virtual async Task PatchRelationshipsAsync(TId id, string relationshipName, [FromBody] List relationships) + public async Task PatchRelationshipsAsync(TId id, string relationshipName, [FromBody] List relationships) { await _resourceService.UpdateRelationshipsAsync(id, relationshipName, relationships); return Ok(); } [HttpDelete("{id}")] - public virtual async Task DeleteAsync(TId id) + public async Task DeleteAsync(TId id) { var wasDeleted = await _resourceService.DeleteAsync(id); diff --git a/src/Examples/JsonApiDotNetCoreExample/Controllers/UsersController.cs b/src/Examples/JsonApiDotNetCoreExample/Controllers/UsersController.cs index e96bed2517..e07456cc90 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Controllers/UsersController.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Controllers/UsersController.cs @@ -6,7 +6,7 @@ namespace JsonApiDotNetCoreExample.Controllers { - public class UsersController : JsonApiController + public sealed class UsersController : JsonApiController { public UsersController( IJsonApiOptions jsonApiOptions, @@ -16,7 +16,7 @@ public UsersController( { } } - public class SuperUsersController : JsonApiController + public sealed class SuperUsersController : JsonApiController { public SuperUsersController( IJsonApiOptions jsonApiOptions, diff --git a/src/Examples/JsonApiDotNetCoreExample/Data/AppDbContext.cs b/src/Examples/JsonApiDotNetCoreExample/Data/AppDbContext.cs index 17815f9778..cb8876b36a 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Data/AppDbContext.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Data/AppDbContext.cs @@ -3,7 +3,7 @@ namespace JsonApiDotNetCoreExample.Data { - public class AppDbContext : DbContext + public sealed class AppDbContext : DbContext { public DbSet TodoItems { get; set; } public DbSet Passports { get; set; } diff --git a/src/Examples/JsonApiDotNetCoreExample/Models/Article.cs b/src/Examples/JsonApiDotNetCoreExample/Models/Article.cs index d8fd68c886..7a4a3ca56b 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Models/Article.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Models/Article.cs @@ -4,7 +4,7 @@ namespace JsonApiDotNetCoreExample.Models { - public class Article : Identifiable + public sealed class Article : Identifiable { [Attr] public string Name { get; set; } diff --git a/src/Examples/JsonApiDotNetCoreExample/Models/ArticleTag.cs b/src/Examples/JsonApiDotNetCoreExample/Models/ArticleTag.cs index 22a63459c7..c1f8ebbf82 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Models/ArticleTag.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Models/ArticleTag.cs @@ -2,7 +2,7 @@ namespace JsonApiDotNetCoreExample.Models { - public class ArticleTag + public sealed class ArticleTag { public int ArticleId { get; set; } public Article Article { get; set; } @@ -24,4 +24,4 @@ public class IdentifiableArticleTag : Identifiable public string SomeMetaData { get; set; } } -} \ No newline at end of file +} diff --git a/src/Examples/JsonApiDotNetCoreExample/Models/Author.cs b/src/Examples/JsonApiDotNetCoreExample/Models/Author.cs index fce4e7f9c3..0696b037e3 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Models/Author.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Models/Author.cs @@ -3,7 +3,7 @@ namespace JsonApiDotNetCoreExample.Models { - public class Author : Identifiable + public sealed class Author : Identifiable { [Attr] public string Name { get; set; } diff --git a/src/Examples/JsonApiDotNetCoreExample/Models/Passport.cs b/src/Examples/JsonApiDotNetCoreExample/Models/Passport.cs index 8775ecbab5..e7d9336ac9 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Models/Passport.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Models/Passport.cs @@ -2,12 +2,12 @@ namespace JsonApiDotNetCoreExample.Models { - public class Passport : Identifiable + public sealed class Passport : Identifiable { - public virtual int? SocialSecurityNumber { get; set; } - public virtual bool IsLocked { get; set; } + public int? SocialSecurityNumber { get; set; } + public bool IsLocked { get; set; } [HasOne] - public virtual Person Person { get; set; } + public Person Person { get; set; } } -} \ No newline at end of file +} diff --git a/src/Examples/JsonApiDotNetCoreExample/Models/Person.cs b/src/Examples/JsonApiDotNetCoreExample/Models/Person.cs index c5182aeb9d..58e2c8c67b 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Models/Person.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Models/Person.cs @@ -4,13 +4,13 @@ namespace JsonApiDotNetCoreExample.Models { - public class PersonRole : Identifiable + public sealed class PersonRole : Identifiable { [HasOne] public Person Person { get; set; } } - public class Person : Identifiable, IIsLockable + public sealed class Person : Identifiable, IIsLockable { public bool IsLocked { get; set; } @@ -24,30 +24,30 @@ public class Person : Identifiable, IIsLockable public int Age { get; set; } [HasMany] - public virtual List TodoItems { get; set; } + public List TodoItems { get; set; } [HasMany] - public virtual List AssignedTodoItems { get; set; } + public List AssignedTodoItems { get; set; } [HasMany] - public virtual List todoCollections { get; set; } + public List todoCollections { get; set; } [HasOne] - public virtual PersonRole Role { get; set; } + public PersonRole Role { get; set; } public int? PersonRoleId { get; set; } [HasOne] - public virtual TodoItem OneToOneTodoItem { get; set; } + public TodoItem OneToOneTodoItem { get; set; } [HasOne] - public virtual TodoItem StakeHolderTodoItem { get; set; } - public virtual int? StakeHolderTodoItemId { get; set; } + public TodoItem StakeHolderTodoItem { get; set; } + public int? StakeHolderTodoItemId { get; set; } [HasOne(links: Link.All, canInclude: false)] - public virtual TodoItem UnIncludeableItem { get; set; } + public TodoItem UnIncludeableItem { get; set; } [HasOne] - public virtual Passport Passport { get; set; } + public Passport Passport { get; set; } public int? PassportId { get; set; } } } diff --git a/src/Examples/JsonApiDotNetCoreExample/Models/TodoItem.cs b/src/Examples/JsonApiDotNetCoreExample/Models/TodoItem.cs index 815bc52675..5358d6cb11 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Models/TodoItem.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Models/TodoItem.cs @@ -32,7 +32,7 @@ public TodoItem() public DateTime? UpdatedDate { get; set; } [Attr(isImmutable: true)] - public string CalculatedValue { get => "calculated"; } + public string CalculatedValue => "calculated"; [Attr] public DateTimeOffset? OffsetDate { get; set; } @@ -44,35 +44,35 @@ public TodoItem() public Guid? CollectionId { get; set; } [HasOne] - public virtual Person Owner { get; set; } + public Person Owner { get; set; } [HasOne] - public virtual Person Assignee { get; set; } + public Person Assignee { get; set; } [HasOne] - public virtual Person OneToOnePerson { get; set; } + public Person OneToOnePerson { get; set; } - public virtual int? OneToOnePersonId { get; set; } + public int? OneToOnePersonId { get; set; } [HasMany] - public virtual List StakeHolders { get; set; } + public List StakeHolders { get; set; } [HasOne] - public virtual TodoItemCollection Collection { get; set; } + public TodoItemCollection Collection { get; set; } // cyclical to-one structure - public virtual int? DependentOnTodoId { get; set; } + public int? DependentOnTodoId { get; set; } [HasOne] - public virtual TodoItem DependentOnTodo { get; set; } + public TodoItem DependentOnTodo { get; set; } // cyclical to-many structure - public virtual int? ParentTodoId {get; set;} + public int? ParentTodoId {get; set;} [HasOne] - public virtual TodoItem ParentTodo { get; set; } + public TodoItem ParentTodo { get; set; } [HasMany] - public virtual List ChildrenTodos { get; set; } + public List ChildrenTodos { get; set; } } } diff --git a/src/Examples/JsonApiDotNetCoreExample/Models/TodoItemCollection.cs b/src/Examples/JsonApiDotNetCoreExample/Models/TodoItemCollection.cs index 2a251581d4..3b33a0fc1f 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Models/TodoItemCollection.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Models/TodoItemCollection.cs @@ -5,16 +5,16 @@ namespace JsonApiDotNetCoreExample.Models { [Resource("todoCollections")] - public class TodoItemCollection : Identifiable + public sealed class TodoItemCollection : Identifiable { [Attr] public string Name { get; set; } [HasMany] - public virtual List TodoItems { get; set; } + public List TodoItems { get; set; } [HasOne] - public virtual Person Owner { get; set; } + public Person Owner { get; set; } public int? OwnerId { get; set; } } diff --git a/src/Examples/JsonApiDotNetCoreExample/Models/User.cs b/src/Examples/JsonApiDotNetCoreExample/Models/User.cs index d0e38b93e7..ef65054c89 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Models/User.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Models/User.cs @@ -1,4 +1,3 @@ -using System; using JsonApiDotNetCore.Models; namespace JsonApiDotNetCoreExample.Models @@ -9,7 +8,7 @@ public class User : Identifiable [Attr] public string Password { get; set; } } - public class SuperUser : User + public sealed class SuperUser : User { [Attr] public int SecurityLevel { get; set; } } diff --git a/src/Examples/JsonApiDotNetCoreExample/Resources/PersonResource.cs b/src/Examples/JsonApiDotNetCoreExample/Resources/PersonResource.cs index 4c786b238c..c1969e9b19 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Resources/PersonResource.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Resources/PersonResource.cs @@ -11,11 +11,6 @@ public class PersonResource : LockableResource, IHasMeta { public PersonResource(IResourceGraph resourceGraph) : base(resourceGraph) { } - public override IEnumerable BeforeUpdate(IDiffableEntityHashSet entities, ResourcePipeline pipeline) - { - return base.BeforeUpdate(entities, pipeline); - } - public override IEnumerable BeforeUpdateRelationship(HashSet ids, IRelationshipsDictionary entitiesByRelationship, ResourcePipeline pipeline) { BeforeImplicitUpdateRelationship(entitiesByRelationship, pipeline); @@ -31,7 +26,7 @@ public Dictionary GetMeta() { return new Dictionary { { "copyright", "Copyright 2015 Example Corp." }, - { "authors", new string[] { "Jared Nance", "Maurits Moeys", "Harro van der Kroft" } } + { "authors", new[] { "Jared Nance", "Maurits Moeys", "Harro van der Kroft" } } }; } } diff --git a/src/Examples/JsonApiDotNetCoreExample/Resources/TagResource.cs b/src/Examples/JsonApiDotNetCoreExample/Resources/TagResource.cs index 1999936e34..f65a0490d0 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Resources/TagResource.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Resources/TagResource.cs @@ -3,7 +3,6 @@ using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Hooks; using JsonApiDotNetCoreExample.Models; -using JsonApiDotNetCore.Internal; using JsonApiDotNetCore.Internal.Contracts; namespace JsonApiDotNetCoreExample.Resources diff --git a/src/Examples/JsonApiDotNetCoreExample/Resources/UserResource.cs b/src/Examples/JsonApiDotNetCoreExample/Resources/UserResource.cs index aa4552cae6..517e9137c0 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Resources/UserResource.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Resources/UserResource.cs @@ -3,7 +3,6 @@ using JsonApiDotNetCoreExample.Models; using JsonApiDotNetCore.Internal.Query; using JsonApiDotNetCore.Internal.Contracts; -using JsonApiDotNetCore.Services; namespace JsonApiDotNetCoreExample.Resources { @@ -18,7 +17,7 @@ public override QueryFilters GetQueryFilters() { return new QueryFilters { - { "firstCharacter", (users, queryFilter) => FirstCharacterFilter(users, queryFilter) } + { "firstCharacter", FirstCharacterFilter } }; } @@ -26,8 +25,8 @@ private IQueryable FirstCharacterFilter(IQueryable users, FilterQuer { switch (filterQuery.Operation) { - /// In EF core >= 3.0 we need to explicitly evaluate the query first. This could probably be translated - /// into a query by building expression trees. + // In EF core >= 3.0 we need to explicitly evaluate the query first. This could probably be translated + // into a query by building expression trees. case "lt": return users.ToList().Where(u => u.Username.First() < filterQuery.Value[0]).AsQueryable(); default: diff --git a/src/Examples/JsonApiDotNetCoreExample/Startups/MetaStartup.cs b/src/Examples/JsonApiDotNetCoreExample/Startups/MetaStartup.cs index 6cc0dd1e81..f074be15bc 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Startups/MetaStartup.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Startups/MetaStartup.cs @@ -2,7 +2,6 @@ using Microsoft.Extensions.DependencyInjection; using JsonApiDotNetCore.Services; using System.Collections.Generic; -using Microsoft.Extensions.Configuration; namespace JsonApiDotNetCoreExample { @@ -10,7 +9,7 @@ namespace JsonApiDotNetCoreExample /// This should be in JsonApiDotNetCoreExampleTests project but changes in .net core 3.0 /// do no longer allow that. See https://github.com/aspnet/AspNetCore/issues/15373. /// - public class MetaStartup : Startup + public sealed class MetaStartup : Startup { public MetaStartup(IWebHostEnvironment env) : base(env) { } @@ -21,7 +20,7 @@ public override void ConfigureServices(IServiceCollection services) } } - public class MetaService : IRequestMeta + public sealed class MetaService : IRequestMeta { public Dictionary GetMeta() { diff --git a/src/Examples/JsonApiDotNetCoreExample/Startups/NoDefaultPageSizeStartup.cs b/src/Examples/JsonApiDotNetCoreExample/Startups/NoDefaultPageSizeStartup.cs index facfd2bb42..2d990ce784 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Startups/NoDefaultPageSizeStartup.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Startups/NoDefaultPageSizeStartup.cs @@ -11,7 +11,7 @@ namespace JsonApiDotNetCoreExample /// This should be in JsonApiDotNetCoreExampleTests project but changes in .net core 3.0 /// do no longer allow that. See https://github.com/aspnet/AspNetCore/issues/15373. /// - public class NoDefaultPageSizeStartup : Startup + public sealed class NoDefaultPageSizeStartup : Startup { public NoDefaultPageSizeStartup(IWebHostEnvironment env) : base(env) { } diff --git a/src/Examples/JsonApiDotNetCoreExample/Startups/Startup.cs b/src/Examples/JsonApiDotNetCoreExample/Startups/Startup.cs index cc5341026a..5c7a7164b2 100644 --- a/src/Examples/JsonApiDotNetCoreExample/Startups/Startup.cs +++ b/src/Examples/JsonApiDotNetCoreExample/Startups/Startup.cs @@ -30,7 +30,7 @@ public virtual void ConfigureServices(IServiceCollection services) { options .EnableSensitiveDataLogging() - .UseNpgsql(GetDbConnectionString(), options => options.SetPostgresVersion(new Version(9,6))); + .UseNpgsql(GetDbConnectionString(), innerOptions => innerOptions.SetPostgresVersion(new Version(9,6))); }, ServiceLifetime.Transient) .AddJsonApi(options => { @@ -44,7 +44,7 @@ public virtual void ConfigureServices(IServiceCollection services) services.AddClientSerialization(); } - public virtual void Configure( + public void Configure( IApplicationBuilder app, AppDbContext context) { diff --git a/src/Examples/NoEntityFrameworkExample/Controllers/TodoItemsController.cs b/src/Examples/NoEntityFrameworkExample/Controllers/TodoItemsController.cs index c21ee5a837..79b487d721 100644 --- a/src/Examples/NoEntityFrameworkExample/Controllers/TodoItemsController.cs +++ b/src/Examples/NoEntityFrameworkExample/Controllers/TodoItemsController.cs @@ -6,7 +6,7 @@ namespace NoEntityFrameworkExample.Controllers { - public class TodoItemsController : JsonApiController + public sealed class TodoItemsController : JsonApiController { public TodoItemsController( IJsonApiOptions jsonApiOptions, diff --git a/src/Examples/NoEntityFrameworkExample/Data/AppDbContext.cs b/src/Examples/NoEntityFrameworkExample/Data/AppDbContext.cs index e7247108dd..383041c6be 100644 --- a/src/Examples/NoEntityFrameworkExample/Data/AppDbContext.cs +++ b/src/Examples/NoEntityFrameworkExample/Data/AppDbContext.cs @@ -3,7 +3,7 @@ namespace NoEntityFrameworkExample.Data { - public class AppDbContext : DbContext + public sealed class AppDbContext : DbContext { public AppDbContext(DbContextOptions options) : base(options) diff --git a/src/Examples/NoEntityFrameworkExample/Models/TodoItem.cs b/src/Examples/NoEntityFrameworkExample/Models/TodoItem.cs index 7836ecdd58..8e9c7c8674 100644 --- a/src/Examples/NoEntityFrameworkExample/Models/TodoItem.cs +++ b/src/Examples/NoEntityFrameworkExample/Models/TodoItem.cs @@ -3,7 +3,7 @@ namespace NoEntityFrameworkExample.Models { - public class TodoItem : Identifiable + public sealed class TodoItem : Identifiable { public TodoItem() { diff --git a/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs b/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs index 09078cda2c..bbf430060f 100644 --- a/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs +++ b/src/Examples/NoEntityFrameworkExample/Services/TodoItemService.cs @@ -11,7 +11,7 @@ namespace NoEntityFrameworkExample.Services { - public class TodoItemService : IResourceService + public sealed class TodoItemService : IResourceService { private readonly string _connectionString; @@ -20,37 +20,27 @@ public TodoItemService(IConfiguration config) _connectionString = config.GetValue("Data:DefaultConnection"); } - private IDbConnection Connection - { - get - { - return new NpgsqlConnection(_connectionString); - } - } + private IDbConnection Connection => new NpgsqlConnection(_connectionString); private async Task> QueryAsync(Func>> query) { - using (IDbConnection dbConnection = Connection) - { - dbConnection.Open(); - return await query(dbConnection); - } + using IDbConnection dbConnection = Connection; + dbConnection.Open(); + return await query(dbConnection); } public async Task> GetAsync() { - return await QueryAsync(async connection => - { - return await connection.QueryAsync("select * from \"TodoItems\""); - }); + return await QueryAsync(async connection => + await connection.QueryAsync("select * from \"TodoItems\"")); } public async Task GetAsync(int id) { - return (await QueryAsync(async connection => - { - return await connection.QueryAsync("select * from \"TodoItems\" where \"Id\"= @id", new { id }); - })).SingleOrDefault(); + var query = await QueryAsync(async connection => + await connection.QueryAsync("select * from \"TodoItems\" where \"Id\"= @id", new {id})); + + return query.SingleOrDefault(); } public Task GetRelationshipAsync(int id, string relationshipName) @@ -65,7 +55,7 @@ public Task GetRelationshipsAsync(int id, string relationshipName) public async Task CreateAsync(TodoItem entity) { - return (await QueryAsync(async connection => + return (await QueryAsync(async connection => { var query = "insert into \"TodoItems\" (\"Description\", \"IsLocked\", \"Ordinal\", \"GuidProperty\") values (@description, @isLocked, @ordinal, @guidProperty) returning \"Id\",\"Description\", \"IsLocked\", \"Ordinal\", \"GuidProperty\""; var result = await connection.QueryAsync(query, new { description = entity.Description, ordinal = entity.Ordinal, guidProperty = entity.GuidProperty, isLocked = entity.IsLocked}); diff --git a/src/Examples/ReportsExample/Models/Report.cs b/src/Examples/ReportsExample/Models/Report.cs index 5bc93edb49..6a682f3dc1 100644 --- a/src/Examples/ReportsExample/Models/Report.cs +++ b/src/Examples/ReportsExample/Models/Report.cs @@ -2,7 +2,7 @@ namespace ReportsExample.Models { - public class Report : Identifiable + public sealed class Report : Identifiable { [Attr] public string Title { get; set; } @@ -11,7 +11,7 @@ public class Report : Identifiable public ComplexType ComplexType { get; set; } } - public class ComplexType + public sealed class ComplexType { public string CompoundPropertyName { get; set; } } diff --git a/src/Examples/ReportsExample/Services/ReportService.cs b/src/Examples/ReportsExample/Services/ReportService.cs index 542b276a5b..f329558648 100644 --- a/src/Examples/ReportsExample/Services/ReportService.cs +++ b/src/Examples/ReportsExample/Services/ReportService.cs @@ -8,7 +8,7 @@ namespace ReportsExample.Services { public class ReportService : IGetAllService { - private ILogger _logger; + private readonly ILogger _logger; public ReportService(ILoggerFactory loggerFactory) { @@ -19,7 +19,7 @@ public Task> GetAsync() { _logger.LogError("GetAsync"); - var task = new Task>(() => Get()); + var task = new Task>(Get); task.RunSynchronously(TaskScheduler.Default); diff --git a/src/Examples/ReportsExample/Startup.cs b/src/Examples/ReportsExample/Startup.cs index bafa6f7689..6940d2f94d 100644 --- a/src/Examples/ReportsExample/Startup.cs +++ b/src/Examples/ReportsExample/Startup.cs @@ -5,7 +5,7 @@ namespace ReportsExample { - public class Startup + public sealed class Startup { public readonly IConfiguration Config; @@ -20,7 +20,7 @@ public Startup(IWebHostEnvironment env) Config = builder.Build(); } - public virtual void ConfigureServices(IServiceCollection services) + public void ConfigureServices(IServiceCollection services) { var mvcBuilder = services.AddMvcCore(); services.AddJsonApi( diff --git a/src/JsonApiDotNetCore/Builders/IResourceGraphBuilder.cs b/src/JsonApiDotNetCore/Builders/IResourceGraphBuilder.cs index 3b38531918..897cc4e47f 100644 --- a/src/JsonApiDotNetCore/Builders/IResourceGraphBuilder.cs +++ b/src/JsonApiDotNetCore/Builders/IResourceGraphBuilder.cs @@ -1,10 +1,8 @@ using System; -using System.Collections.Generic; using JsonApiDotNetCore.Graph; using JsonApiDotNetCore.Internal; using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Models; -using Microsoft.EntityFrameworkCore; namespace JsonApiDotNetCore.Builders { diff --git a/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs b/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs index c2ae694b64..bea0fbc292 100644 --- a/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs +++ b/src/JsonApiDotNetCore/Builders/JsonApiApplicationBuilder.cs @@ -20,7 +20,6 @@ using JsonApiDotNetCore.Serialization.Server.Builders; using JsonApiDotNetCore.Serialization.Server; using Microsoft.Extensions.DependencyInjection.Extensions; -using JsonApiDotNetCore.Extensions; namespace JsonApiDotNetCore.Builders { diff --git a/src/JsonApiDotNetCore/Builders/ResourceGraphBuilder.cs b/src/JsonApiDotNetCore/Builders/ResourceGraphBuilder.cs index f9d8c9da13..2f98f7e6a7 100644 --- a/src/JsonApiDotNetCore/Builders/ResourceGraphBuilder.cs +++ b/src/JsonApiDotNetCore/Builders/ResourceGraphBuilder.cs @@ -16,22 +16,22 @@ namespace JsonApiDotNetCore.Builders { public class ResourceGraphBuilder : IResourceGraphBuilder { - private List _resources { get; set; } = new List(); - private List _validationResults { get; set; } = new List(); - private IResourceNameFormatter _formatter { get; set; } = new CamelCaseFormatter(); + private List Resources { get; } = new List(); + private List ValidationResults { get; } = new List(); + private IResourceNameFormatter Formatter { get; } = new CamelCaseFormatter(); public ResourceGraphBuilder() { } public ResourceGraphBuilder(IResourceNameFormatter formatter) { - _formatter = formatter; + Formatter = formatter; } /// public IResourceGraph Build() { - _resources.ForEach(SetResourceLinksOptions); - var resourceGraph = new ResourceGraph(_resources, _validationResults); + Resources.ForEach(SetResourceLinksOptions); + var resourceGraph = new ResourceGraph(Resources, ValidationResults); return resourceGraph; } @@ -60,13 +60,13 @@ public IResourceGraphBuilder AddResource(Type resourceType, Type idType = null, AssertEntityIsNotAlreadyDefined(resourceType); if (resourceType.Implements()) { - pluralizedTypeName ??= _formatter.FormatResourceName(resourceType); + pluralizedTypeName ??= Formatter.FormatResourceName(resourceType); idType ??= TypeLocator.GetIdType(resourceType); - _resources.Add(GetEntity(pluralizedTypeName, resourceType, idType)); + Resources.Add(GetEntity(pluralizedTypeName, resourceType, idType)); } else { - _validationResults.Add(new ValidationResult(LogLevel.Warning, $"{resourceType} does not implement 'IIdentifiable<>'. ")); + ValidationResults.Add(new ValidationResult(LogLevel.Warning, $"{resourceType} does not implement 'IIdentifiable<>'. ")); } return this; @@ -96,9 +96,9 @@ protected virtual List GetAttributes(Type entityType) // spec point of view. if (prop.Name == nameof(Identifiable.Id)) { - var idAttr = new AttrAttribute() + var idAttr = new AttrAttribute { - PublicAttributeName = _formatter.FormatPropertyName(prop), + PublicAttributeName = Formatter.FormatPropertyName(prop), PropertyInfo = prop }; attributes.Add(idAttr); @@ -109,7 +109,7 @@ protected virtual List GetAttributes(Type entityType) if (attribute == null) continue; - attribute.PublicAttributeName = attribute.PublicAttributeName ?? _formatter.FormatPropertyName(prop); + attribute.PublicAttributeName ??= Formatter.FormatPropertyName(prop); attribute.PropertyInfo = prop; attributes.Add(attribute); @@ -126,7 +126,7 @@ protected virtual List GetRelationships(Type entityType) var attribute = (RelationshipAttribute)prop.GetCustomAttribute(typeof(RelationshipAttribute)); if (attribute == null) continue; - attribute.PublicRelationshipName = attribute.PublicRelationshipName ?? _formatter.FormatPropertyName(prop); + attribute.PublicRelationshipName ??= Formatter.FormatPropertyName(prop); attribute.InternalRelationshipName = prop.Name; attribute.RightType = GetRelationshipType(attribute, prop); attribute.LeftType = entityType; @@ -183,7 +183,7 @@ protected virtual Type GetRelationshipType(RelationshipAttribute relation, Prope private void AssertEntityIsNotAlreadyDefined(Type entityType) { - if (_resources.Any(e => e.ResourceType == entityType)) + if (Resources.Any(e => e.ResourceType == entityType)) throw new InvalidOperationException($"Cannot add entity type {entityType} to context resourceGraph, there is already an entity of that type configured."); } } diff --git a/src/JsonApiDotNetCore/Configuration/JsonApiOptions.cs b/src/JsonApiDotNetCore/Configuration/JsonApiOptions.cs index 88e281fd5f..d63701cc97 100644 --- a/src/JsonApiDotNetCore/Configuration/JsonApiOptions.cs +++ b/src/JsonApiDotNetCore/Configuration/JsonApiOptions.cs @@ -1,6 +1,4 @@ -using System.Collections.Generic; using JsonApiDotNetCore.Graph; -using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Models.Links; using Newtonsoft.Json; @@ -52,7 +50,7 @@ public class JsonApiOptions : IJsonApiOptions /// /// Defaults to . /// - public bool LoadDatabaseValues { get; set; } = false; + public bool LoadDatabaseValues { get; set; } /// /// The base URL Namespace @@ -140,14 +138,9 @@ public class JsonApiOptions : IJsonApiOptions /// public bool ValidateModelState { get; set; } - public JsonSerializerSettings SerializerSettings { get; } = new JsonSerializerSettings() + public JsonSerializerSettings SerializerSettings { get; } = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; - - public void EnableExtension(JsonApiExtension extension) - => EnabledExtensions.Add(extension); - - internal List EnabledExtensions { get; set; } = new List(); } } diff --git a/src/JsonApiDotNetCore/Controllers/DisableQueryAttribute.cs b/src/JsonApiDotNetCore/Controllers/DisableQueryAttribute.cs index d28bd06faf..0dbc45f49a 100644 --- a/src/JsonApiDotNetCore/Controllers/DisableQueryAttribute.cs +++ b/src/JsonApiDotNetCore/Controllers/DisableQueryAttribute.cs @@ -2,7 +2,7 @@ namespace JsonApiDotNetCore.Controllers { - public class DisableQueryAttribute : Attribute + public sealed class DisableQueryAttribute : Attribute { /// /// Disabled one of the native query parameters for a controller. @@ -26,4 +26,4 @@ public DisableQueryAttribute(string customQueryParams) public string QueryParams { get; } } -} \ No newline at end of file +} diff --git a/src/JsonApiDotNetCore/Controllers/DisableRoutingConventionAttribute.cs b/src/JsonApiDotNetCore/Controllers/DisableRoutingConventionAttribute.cs index a0812007e3..8e23b3fb99 100644 --- a/src/JsonApiDotNetCore/Controllers/DisableRoutingConventionAttribute.cs +++ b/src/JsonApiDotNetCore/Controllers/DisableRoutingConventionAttribute.cs @@ -2,6 +2,6 @@ namespace JsonApiDotNetCore.Controllers { - public class DisableRoutingConventionAttribute : Attribute + public sealed class DisableRoutingConventionAttribute : Attribute { } -} \ No newline at end of file +} diff --git a/src/JsonApiDotNetCore/Controllers/HttpMethodRestrictionFilter.cs b/src/JsonApiDotNetCore/Controllers/HttpMethodRestrictionFilter.cs index ca9a2ff138..35341781dc 100644 --- a/src/JsonApiDotNetCore/Controllers/HttpMethodRestrictionFilter.cs +++ b/src/JsonApiDotNetCore/Controllers/HttpMethodRestrictionFilter.cs @@ -5,7 +5,7 @@ namespace JsonApiDotNetCore.Controllers { - public abstract class HttpRestrictAttribute : ActionFilterAttribute, IAsyncActionFilter + public abstract class HttpRestrictAttribute : ActionFilterAttribute { protected abstract string[] Methods { get; } @@ -27,22 +27,22 @@ private bool CanExecuteAction(string requestMethod) } } - public class HttpReadOnlyAttribute : HttpRestrictAttribute + public sealed class HttpReadOnlyAttribute : HttpRestrictAttribute { protected override string[] Methods { get; } = new string[] { "POST", "PATCH", "DELETE" }; } - public class NoHttpPostAttribute : HttpRestrictAttribute + public sealed class NoHttpPostAttribute : HttpRestrictAttribute { protected override string[] Methods { get; } = new string[] { "POST" }; } - public class NoHttpPatchAttribute : HttpRestrictAttribute + public sealed class NoHttpPatchAttribute : HttpRestrictAttribute { protected override string[] Methods { get; } = new string[] { "PATCH" }; } - public class NoHttpDeleteAttribute : HttpRestrictAttribute + public sealed class NoHttpDeleteAttribute : HttpRestrictAttribute { protected override string[] Methods { get; } = new string[] { "DELETE" }; } diff --git a/src/JsonApiDotNetCore/Data/DbContextResolver.cs b/src/JsonApiDotNetCore/Data/DbContextResolver.cs index 3c9e20b9da..628f44e2ca 100644 --- a/src/JsonApiDotNetCore/Data/DbContextResolver.cs +++ b/src/JsonApiDotNetCore/Data/DbContextResolver.cs @@ -2,7 +2,7 @@ namespace JsonApiDotNetCore.Data { - public class DbContextResolver : IDbContextResolver + public sealed class DbContextResolver : IDbContextResolver where TContext : DbContext { private readonly TContext _context; @@ -13,8 +13,5 @@ public DbContextResolver(TContext context) } public DbContext GetContext() => _context; - - public DbSet GetDbSet() where TResource : class => null; - } } diff --git a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs index f03e3e4f24..de6fdeeb0b 100644 --- a/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs +++ b/src/JsonApiDotNetCore/Data/DefaultResourceRepository.cs @@ -27,7 +27,7 @@ public class DefaultResourceRepository : IResourceRepository _dbSet; private readonly IResourceGraph _resourceGraph; private readonly IGenericServiceFactory _genericServiceFactory; - private ILogger> _logger; + private readonly ILogger> _logger; public DefaultResourceRepository( ITargetedFields targetedFields, @@ -235,16 +235,16 @@ private object GetTrackedRelationshipValue(RelationshipAttribute relationshipAtt private IList GetTrackedManyRelationshipValue(IEnumerable relationshipValueList, RelationshipAttribute relationshipAttr, ref bool wasAlreadyAttached) { if (relationshipValueList == null) return null; - bool _wasAlreadyAttached = false; + bool newWasAlreadyAttached = false; var trackedPointerCollection = relationshipValueList.Select(pointer => { // convert each element in the value list to relationshipAttr.DependentType. var tracked = AttachOrGetTracked(pointer); - if (tracked != null) _wasAlreadyAttached = true; + if (tracked != null) newWasAlreadyAttached = true; return Convert.ChangeType(tracked ?? pointer, relationshipAttr.RightType); }) .ToList() .Cast(relationshipAttr.RightType); - if (_wasAlreadyAttached) wasAlreadyAttached = true; + if (newWasAlreadyAttached) wasAlreadyAttached = true; return (IList)trackedPointerCollection; } diff --git a/src/JsonApiDotNetCore/Data/IDbContextResolver.cs b/src/JsonApiDotNetCore/Data/IDbContextResolver.cs index 7d2f5a66dc..f1b4533f26 100644 --- a/src/JsonApiDotNetCore/Data/IDbContextResolver.cs +++ b/src/JsonApiDotNetCore/Data/IDbContextResolver.cs @@ -1,4 +1,3 @@ -using System; using Microsoft.EntityFrameworkCore; namespace JsonApiDotNetCore.Data diff --git a/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs b/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs index bd1f2bc91a..5525e74417 100644 --- a/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs @@ -4,9 +4,7 @@ using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Middleware; using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace JsonApiDotNetCore.Extensions @@ -51,12 +49,12 @@ public static void UseJsonApi(this IApplicationBuilder app, bool skipRegisterMid if (useAuthentication) { app.UseAuthentication(); - }; + } if (useAuthorization) { app.UseAuthorization(); - }; + } // middleware to run after routing occurs. app.UseMiddleware(); @@ -81,9 +79,9 @@ private static void LogResourceGraphValidations(IApplicationBuilder app) var logger = app.ApplicationServices.GetService(typeof(ILogger)) as ILogger; var resourceGraph = app.ApplicationServices.GetService(typeof(IResourceGraph)) as ResourceGraph; - if (logger != null && resourceGraph != null) + if (logger != null) { - resourceGraph.ValidationResults.ForEach((v) => + resourceGraph?.ValidationResults.ForEach((v) => logger.Log( v.LogLevel, new EventId(), diff --git a/src/JsonApiDotNetCore/Extensions/IQueryableExtensions.cs b/src/JsonApiDotNetCore/Extensions/IQueryableExtensions.cs index c52fc88bbc..68505d6c56 100644 --- a/src/JsonApiDotNetCore/Extensions/IQueryableExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/IQueryableExtensions.cs @@ -21,9 +21,8 @@ private static MethodInfo ContainsMethod if (_containsMethod == null) { _containsMethod = typeof(Enumerable) - .GetMethods(BindingFlags.Static | BindingFlags.Public) - .Where(m => m.Name == nameof(Enumerable.Contains) && m.GetParameters().Count() == 2) - .First(); + .GetMethods(BindingFlags.Static | BindingFlags.Public) + .First(m => m.Name == nameof(Enumerable.Contains) && m.GetParameters().Length == 2); } return _containsMethod; } @@ -244,17 +243,16 @@ private static IQueryable CallGenericWhereMethod(IQueryable CallGenericSelectMethod(IQueryable source, List columns) { - var sourceBindings = new List(); var sourceType = typeof(TSource); var parameter = Expression.Parameter(source.ElementType, "x"); - var sourceProperties = new List() { }; + var sourceProperties = new List(); // Store all property names to it's own related property (name as key) var nestedTypesAndProperties = new Dictionary>(); @@ -342,7 +339,7 @@ private static IQueryable CallGenericSelectMethod(IQueryable 1) // Nested property { if (nestedTypesAndProperties.TryGetValue(props[0], out var properties) == false) - nestedTypesAndProperties.Add(props[0], new List() { nameof(Identifiable.Id), props[1] }); + nestedTypesAndProperties.Add(props[0], new List { nameof(Identifiable.Id), props[1] }); else properties.Add(props[1]); } @@ -351,16 +348,16 @@ private static IQueryable CallGenericSelectMethod(IQueryable Expression.Bind(sourceType.GetProperty(prop), Expression.PropertyOrField(parameter, prop))).ToList(); + var sourceBindings = sourceProperties.Select(prop => Expression.Bind(sourceType.GetProperty(prop), Expression.PropertyOrField(parameter, prop))).ToList(); // Bind attributes on nested types var nestedBindings = new List(); - Expression bindExpression; foreach (var item in nestedTypesAndProperties) { var nestedProperty = sourceType.GetProperty(item.Key); var nestedPropertyType = nestedProperty.PropertyType; // [HasMany] attribute + Expression bindExpression; if (nestedPropertyType != typeof(string) && typeof(IEnumerable).IsAssignableFrom(nestedPropertyType)) { // Concrete type of Collection @@ -381,14 +378,14 @@ private static IQueryable CallGenericSelectMethod(IQueryable new Item() {Id = y.Id, Name = y.Name}).ToList() } bindExpression = Expression.Call( typeof(Enumerable), "ToList", - new Type[] { singleType }, + new[] { singleType }, selectMethod); } // [HasOne] attribute diff --git a/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs b/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs index 1b0b6d455d..c09214f120 100644 --- a/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs @@ -5,13 +5,11 @@ using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Graph; using JsonApiDotNetCore.Internal; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using JsonApiDotNetCore.Builders; using JsonApiDotNetCore.Serialization.Client; using JsonApiDotNetCore.Serialization; using JsonApiDotNetCore.Internal.Contracts; -using JsonApiDotNetCore.Serialization.Server; namespace JsonApiDotNetCore.Extensions { @@ -105,7 +103,7 @@ private static HashSet GetResourceTypesFromServiceImplementa if (i.IsGenericType) { var firstGenericArgument = i.GenericTypeArguments.FirstOrDefault(); - if (TypeLocator.TryGetResourceDescriptor(firstGenericArgument, out var resourceDescriptor) == true) + if (TypeLocator.TryGetResourceDescriptor(firstGenericArgument, out var resourceDescriptor)) { resourceDescriptors.Add(resourceDescriptor); } diff --git a/src/JsonApiDotNetCore/Extensions/ModelStateExtensions.cs b/src/JsonApiDotNetCore/Extensions/ModelStateExtensions.cs index 7c2359eb1c..ba5219be99 100644 --- a/src/JsonApiDotNetCore/Extensions/ModelStateExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/ModelStateExtensions.cs @@ -1,4 +1,3 @@ -using System; using System.Linq; using System.Reflection; using JsonApiDotNetCore.Internal; diff --git a/src/JsonApiDotNetCore/Extensions/TypeExtensions.cs b/src/JsonApiDotNetCore/Extensions/TypeExtensions.cs index ea0f7ee4ea..305e7745be 100644 --- a/src/JsonApiDotNetCore/Extensions/TypeExtensions.cs +++ b/src/JsonApiDotNetCore/Extensions/TypeExtensions.cs @@ -17,9 +17,9 @@ public static void AddRange(this IList list, IEnumerable items) if (list == null) throw new ArgumentNullException(nameof(list)); if (items == null) throw new ArgumentNullException(nameof(items)); - if (list is List) + if (list is List genericList) { - ((List)list).AddRange(items); + genericList.AddRange(items); } else { @@ -48,7 +48,7 @@ public static Type GetElementType(this IEnumerable enumerable) { var enumerableTypes = enumerable.GetType() .GetInterfaces() - .Where(t => t.IsGenericType == true && t.GetGenericTypeDefinition() == typeof(IEnumerable<>)) + .Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>)) .ToList(); var numberOfEnumerableTypes = enumerableTypes.Count; @@ -113,7 +113,7 @@ public static bool Implements(this Type concreteType) /// /// Whether or not a type implements an interface. /// - public static bool Implements(this Type concreteType, Type interfaceType) + private static bool Implements(this Type concreteType, Type interfaceType) => interfaceType?.IsAssignableFrom(concreteType) == true; /// diff --git a/src/JsonApiDotNetCore/Formatters/JsonApiInputFormatter.cs b/src/JsonApiDotNetCore/Formatters/JsonApiInputFormatter.cs index f556b7433d..017c5751e0 100644 --- a/src/JsonApiDotNetCore/Formatters/JsonApiInputFormatter.cs +++ b/src/JsonApiDotNetCore/Formatters/JsonApiInputFormatter.cs @@ -6,7 +6,7 @@ namespace JsonApiDotNetCore.Formatters { - public class JsonApiInputFormatter : IInputFormatter + public sealed class JsonApiInputFormatter : IInputFormatter { public bool CanRead(InputFormatterContext context) { diff --git a/src/JsonApiDotNetCore/Formatters/JsonApiOutputFormatter.cs b/src/JsonApiDotNetCore/Formatters/JsonApiOutputFormatter.cs index 6facec6a6a..aed26685d2 100644 --- a/src/JsonApiDotNetCore/Formatters/JsonApiOutputFormatter.cs +++ b/src/JsonApiDotNetCore/Formatters/JsonApiOutputFormatter.cs @@ -6,7 +6,7 @@ namespace JsonApiDotNetCore.Formatters { - public class JsonApiOutputFormatter : IOutputFormatter + public sealed class JsonApiOutputFormatter : IOutputFormatter { public bool CanWriteResult(OutputFormatterCanWriteContext context) { diff --git a/src/JsonApiDotNetCore/Formatters/JsonApiReader.cs b/src/JsonApiDotNetCore/Formatters/JsonApiReader.cs index 784f16fd0b..309705e03d 100644 --- a/src/JsonApiDotNetCore/Formatters/JsonApiReader.cs +++ b/src/JsonApiDotNetCore/Formatters/JsonApiReader.cs @@ -111,13 +111,11 @@ private bool CheckForId(IList modelList) /// String content of body sent to server. private async Task GetRequestBody(Stream body) { - using (var reader = new StreamReader(body)) - { - // This needs to be set to async because - // Synchronous IO operations are - // https://github.com/aspnet/AspNetCore/issues/7644 - return await reader.ReadToEndAsync(); - } + using var reader = new StreamReader(body); + // This needs to be set to async because + // Synchronous IO operations are + // https://github.com/aspnet/AspNetCore/issues/7644 + return await reader.ReadToEndAsync(); } } } diff --git a/src/JsonApiDotNetCore/Formatters/JsonApiWriter.cs b/src/JsonApiDotNetCore/Formatters/JsonApiWriter.cs index 0b2c615581..2620fcdd25 100644 --- a/src/JsonApiDotNetCore/Formatters/JsonApiWriter.cs +++ b/src/JsonApiDotNetCore/Formatters/JsonApiWriter.cs @@ -35,7 +35,7 @@ public async Task WriteAsync(OutputFormatterWriteContext context) throw new ArgumentNullException(nameof(context)); var response = context.HttpContext.Response; - using var writer = context.WriterFactory(response.Body, Encoding.UTF8); + await using var writer = context.WriterFactory(response.Body, Encoding.UTF8); string responseContent; if (_serializer == null) diff --git a/src/JsonApiDotNetCore/Graph/ResourceDescriptor.cs b/src/JsonApiDotNetCore/Graph/ResourceDescriptor.cs index 2cb1a8b812..7fd97d3059 100644 --- a/src/JsonApiDotNetCore/Graph/ResourceDescriptor.cs +++ b/src/JsonApiDotNetCore/Graph/ResourceDescriptor.cs @@ -10,8 +10,8 @@ public ResourceDescriptor(Type resourceType, Type idType) IdType = idType; } - public Type ResourceType { get; set; } - public Type IdType { get; set; } + public Type ResourceType { get; } + public Type IdType { get; } internal static ResourceDescriptor Empty => new ResourceDescriptor(null, null); } diff --git a/src/JsonApiDotNetCore/Graph/ResourceIdMapper.cs b/src/JsonApiDotNetCore/Graph/ResourceIdMapper.cs index 7252d5c710..4aa9f5b010 100644 --- a/src/JsonApiDotNetCore/Graph/ResourceIdMapper.cs +++ b/src/JsonApiDotNetCore/Graph/ResourceIdMapper.cs @@ -19,9 +19,9 @@ public interface IRelatedIdMapper } /// - public class DefaultRelatedIdMapper : IRelatedIdMapper + public sealed class DefaultRelatedIdMapper : IRelatedIdMapper { /// public string GetRelatedIdPropertyName(string propertyName) => propertyName + "Id"; } -} \ No newline at end of file +} diff --git a/src/JsonApiDotNetCore/Graph/ResourceNameFormatters/CamelCaseFormatter.cs b/src/JsonApiDotNetCore/Graph/ResourceNameFormatters/CamelCaseFormatter.cs index 17a94cdcde..8ea50e5dd7 100644 --- a/src/JsonApiDotNetCore/Graph/ResourceNameFormatters/CamelCaseFormatter.cs +++ b/src/JsonApiDotNetCore/Graph/ResourceNameFormatters/CamelCaseFormatter.cs @@ -1,4 +1,4 @@ -using str = JsonApiDotNetCore.Extensions.StringExtensions; +using str = JsonApiDotNetCore.Extensions.StringExtensions; namespace JsonApiDotNetCore.Graph { @@ -31,7 +31,7 @@ namespace JsonApiDotNetCore.Graph /// // > "todoItem" /// /// - public class CamelCaseFormatter: BaseResourceNameFormatter + public sealed class CamelCaseFormatter: BaseResourceNameFormatter { /// public override string ApplyCasingConvention(string properName) => str.Camelize(properName); diff --git a/src/JsonApiDotNetCore/Graph/ResourceNameFormatters/KebabCaseFormatter.cs b/src/JsonApiDotNetCore/Graph/ResourceNameFormatters/KebabCaseFormatter.cs index 42a48a8572..dbf7f1ab86 100644 --- a/src/JsonApiDotNetCore/Graph/ResourceNameFormatters/KebabCaseFormatter.cs +++ b/src/JsonApiDotNetCore/Graph/ResourceNameFormatters/KebabCaseFormatter.cs @@ -1,4 +1,4 @@ -using str = JsonApiDotNetCore.Extensions.StringExtensions; +using str = JsonApiDotNetCore.Extensions.StringExtensions; namespace JsonApiDotNetCore.Graph { @@ -31,7 +31,7 @@ namespace JsonApiDotNetCore.Graph /// // > "todo-item" /// /// - public class KebabCaseFormatter : BaseResourceNameFormatter + public sealed class KebabCaseFormatter : BaseResourceNameFormatter { /// public override string ApplyCasingConvention(string properName) => str.Dasherize(properName); diff --git a/src/JsonApiDotNetCore/Graph/ServiceDiscoveryFacade.cs b/src/JsonApiDotNetCore/Graph/ServiceDiscoveryFacade.cs index ae3fef30f6..a9a4e022d6 100644 --- a/src/JsonApiDotNetCore/Graph/ServiceDiscoveryFacade.cs +++ b/src/JsonApiDotNetCore/Graph/ServiceDiscoveryFacade.cs @@ -14,7 +14,7 @@ namespace JsonApiDotNetCore.Graph { public class ServiceDiscoveryFacade : IServiceDiscoveryFacade { - internal static HashSet ServiceInterfaces = new HashSet { + internal static readonly HashSet ServiceInterfaces = new HashSet { typeof(IResourceService<>), typeof(IResourceService<,>), typeof(IResourceCommandService<>), @@ -37,7 +37,7 @@ public class ServiceDiscoveryFacade : IServiceDiscoveryFacade typeof(IDeleteService<,>) }; - internal static HashSet RepositoryInterfaces = new HashSet { + private static readonly HashSet RepositoryInterfaces = new HashSet { typeof(IResourceRepository<>), typeof(IResourceRepository<,>), typeof(IResourceWriteRepository<>), @@ -47,7 +47,6 @@ public class ServiceDiscoveryFacade : IServiceDiscoveryFacade }; private readonly IServiceCollection _services; private readonly IResourceGraphBuilder _resourceGraphBuilder; - private readonly List _identifiables = new List(); public ServiceDiscoveryFacade(IServiceCollection services, IResourceGraphBuilder resourceGraphBuilder) { @@ -187,7 +186,7 @@ private void AddRepositories(Assembly assembly, ResourceDescriptor resourceDescr RegisterServiceImplementations(assembly, serviceInterface, resourceDescriptor); } } - public int i = 0; + private void RegisterServiceImplementations(Assembly assembly, Type interfaceType, ResourceDescriptor resourceDescriptor) { if (resourceDescriptor.IdType == typeof(Guid) && interfaceType.GetTypeInfo().GenericTypeParameters.Length == 1) diff --git a/src/JsonApiDotNetCore/Graph/TypeLocator.cs b/src/JsonApiDotNetCore/Graph/TypeLocator.cs index d2a5bf1840..9fd4f5a458 100644 --- a/src/JsonApiDotNetCore/Graph/TypeLocator.cs +++ b/src/JsonApiDotNetCore/Graph/TypeLocator.cs @@ -10,11 +10,9 @@ namespace JsonApiDotNetCore.Graph /// /// Used to locate types and facilitate auto-resource discovery /// - static class TypeLocator + internal static class TypeLocator { - private static Dictionary _typeCache = new Dictionary(); - private static Dictionary> _identifiableTypeCache = new Dictionary>(); - + private static readonly Dictionary> _identifiableTypeCache = new Dictionary>(); /// /// Determine whether or not this is a json:api resource by checking if it implements . @@ -30,7 +28,7 @@ public static Type GetIdType(Type resourceType) /// Get all implementations of in the assembly /// public static IEnumerable GetIdentifiableTypes(Assembly assembly) - => (_identifiableTypeCache.TryGetValue(assembly, out var descriptors) == false) + => (_identifiableTypeCache.TryGetValue(assembly, out _) == false) ? FindIdentifiableTypes(assembly) : _identifiableTypeCache[assembly]; diff --git a/src/JsonApiDotNetCore/Hooks/Discovery/HooksDiscovery.cs b/src/JsonApiDotNetCore/Hooks/Discovery/HooksDiscovery.cs index bfade1c50d..6505ccef97 100644 --- a/src/JsonApiDotNetCore/Hooks/Discovery/HooksDiscovery.cs +++ b/src/JsonApiDotNetCore/Hooks/Discovery/HooksDiscovery.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using JsonApiDotNetCore.Internal; @@ -46,7 +46,7 @@ public HooksDiscovery(IServiceProvider provider) /// Discovers the implemented hooks for a model. /// /// The implemented hooks for model. - void DiscoverImplementedHooks(Type containerType) + private void DiscoverImplementedHooks(Type containerType) { if (containerType == null || containerType == _boundResourceDefinitionType) { @@ -69,10 +69,10 @@ void DiscoverImplementedHooks(Type containerType) { if (!_databaseValuesAttributeAllowed.Contains(hook)) { - throw new JsonApiSetupException($"DatabaseValuesAttribute cannot be used on hook" + - $"{hook.ToString("G")} in resource definition {containerType.Name}"); + throw new JsonApiSetupException("DatabaseValuesAttribute cannot be used on hook" + + $"{hook:G} in resource definition {containerType.Name}"); } - var targetList = attr.value ? databaseValuesEnabledHooks : databaseValuesDisabledHooks; + var targetList = attr.Value ? databaseValuesEnabledHooks : databaseValuesDisabledHooks; targetList.Add(hook); } } @@ -82,4 +82,4 @@ void DiscoverImplementedHooks(Type containerType) DatabaseValuesEnabledHooks = databaseValuesEnabledHooks.ToArray(); } } -} \ No newline at end of file +} diff --git a/src/JsonApiDotNetCore/Hooks/Discovery/LoadDatabaseValuesAttribute.cs b/src/JsonApiDotNetCore/Hooks/Discovery/LoadDatabaseValuesAttribute.cs index 6a47e9d2a0..ebf816d3eb 100644 --- a/src/JsonApiDotNetCore/Hooks/Discovery/LoadDatabaseValuesAttribute.cs +++ b/src/JsonApiDotNetCore/Hooks/Discovery/LoadDatabaseValuesAttribute.cs @@ -1,12 +1,13 @@ using System; namespace JsonApiDotNetCore.Hooks { - public class LoadDatabaseValues : Attribute + public sealed class LoadDatabaseValues : Attribute { - public readonly bool value; + public readonly bool Value; + public LoadDatabaseValues(bool mode = true) { - value = mode; + Value = mode; } } } diff --git a/src/JsonApiDotNetCore/Hooks/Execution/DiffableEntityHashSet.cs b/src/JsonApiDotNetCore/Hooks/Execution/DiffableEntityHashSet.cs index e0de8a11ff..cb1ecbdb64 100644 --- a/src/JsonApiDotNetCore/Hooks/Execution/DiffableEntityHashSet.cs +++ b/src/JsonApiDotNetCore/Hooks/Execution/DiffableEntityHashSet.cs @@ -29,11 +29,11 @@ public interface IDiffableEntityHashSet : IEntityHashSet w } /// - public class DiffableEntityHashSet : EntityHashSet, IDiffableEntityHashSet where TResource : class, IIdentifiable + public sealed class DiffableEntityHashSet : EntityHashSet, IDiffableEntityHashSet where TResource : class, IIdentifiable { private readonly HashSet _databaseValues; private readonly bool _databaseValuesLoaded; - private Dictionary> _updatedAttributes; + private readonly Dictionary> _updatedAttributes; public DiffableEntityHashSet(HashSet requestEntities, HashSet databaseEntities, @@ -71,15 +71,15 @@ public IEnumerable> GetDiffs() } /// - public new HashSet GetAffected(Expression> NavigationAction) + public new HashSet GetAffected(Expression> navigationAction) { - var propertyInfo = TypeHelper.ParseNavigationExpression(NavigationAction); + var propertyInfo = TypeHelper.ParseNavigationExpression(navigationAction); var propertyType = propertyInfo.PropertyType; if (propertyType.Inherits(typeof(IEnumerable))) propertyType = TypeHelper.GetTypeOfList(propertyType); if (propertyType.Implements()) { // the navigation action references a relationship. Redirect the call to the relationship dictionary. - return base.GetAffected(NavigationAction); + return base.GetAffected(navigationAction); } else if (_updatedAttributes.TryGetValue(propertyInfo, out HashSet entities)) { @@ -88,7 +88,7 @@ public IEnumerable> GetDiffs() return new HashSet(); } - private HashSet ThrowNoDbValuesError() + private void ThrowNoDbValuesError() { throw new MemberAccessException($"Cannot iterate over the diffs if the ${nameof(LoadDatabaseValues)} option is set to false"); } @@ -98,7 +98,7 @@ private HashSet ThrowNoDbValuesError() /// A wrapper that contains an entity that is affected by the request, /// matched to its current database value /// - public class EntityDiffPair where TResource : class, IIdentifiable + public sealed class EntityDiffPair where TResource : class, IIdentifiable { public EntityDiffPair(TResource entity, TResource databaseValue) { @@ -109,10 +109,10 @@ public EntityDiffPair(TResource entity, TResource databaseValue) /// /// The resource from the request matching the resource from the database. /// - public TResource Entity { get; private set; } + public TResource Entity { get; } /// /// The resource from the database matching the resource from the request. /// - public TResource DatabaseValue { get; private set; } + public TResource DatabaseValue { get; } } } diff --git a/src/JsonApiDotNetCore/Hooks/Execution/EntityHashSet.cs b/src/JsonApiDotNetCore/Hooks/Execution/EntityHashSet.cs index 93ee588a7a..a29b30e391 100644 --- a/src/JsonApiDotNetCore/Hooks/Execution/EntityHashSet.cs +++ b/src/JsonApiDotNetCore/Hooks/Execution/EntityHashSet.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using JsonApiDotNetCore.Models; using System.Collections; using JsonApiDotNetCore.Internal; @@ -26,7 +26,8 @@ public interface IEntityHashSet : IByAffectedRelationships public class EntityHashSet : HashSet, IEntityHashSet where TResource : class, IIdentifiable { /// - public Dictionary> AffectedRelationships { get => _relationships; } + public Dictionary> AffectedRelationships => _relationships; + private readonly RelationshipsDictionary _relationships; public EntityHashSet(HashSet entities, @@ -56,9 +57,9 @@ public Dictionary> GetByRelationship - public HashSet GetAffected(Expression> NavigationAction) + public HashSet GetAffected(Expression> navigationAction) { - return _relationships.GetAffected(NavigationAction); + return _relationships.GetAffected(navigationAction); } } -} \ No newline at end of file +} diff --git a/src/JsonApiDotNetCore/Hooks/Execution/HookExecutorHelper.cs b/src/JsonApiDotNetCore/Hooks/Execution/HookExecutorHelper.cs index d619eacd58..22a0dc9956 100644 --- a/src/JsonApiDotNetCore/Hooks/Execution/HookExecutorHelper.cs +++ b/src/JsonApiDotNetCore/Hooks/Execution/HookExecutorHelper.cs @@ -15,14 +15,14 @@ namespace JsonApiDotNetCore.Hooks { /// - internal class HookExecutorHelper : IHookExecutorHelper + internal sealed class HookExecutorHelper : IHookExecutorHelper { - private readonly IdentifiableComparer _comparer = new IdentifiableComparer(); + private readonly IdentifiableComparer _comparer = IdentifiableComparer.Instance; private readonly IJsonApiOptions _options; - protected readonly IGenericServiceFactory _genericProcessorFactory; - protected readonly Dictionary _hookContainers; - protected readonly Dictionary _hookDiscoveries; - protected readonly List _targetedHooksForRelatedEntities; + private readonly IGenericServiceFactory _genericProcessorFactory; + private readonly Dictionary _hookContainers; + private readonly Dictionary _hookDiscoveries; + private readonly List _targetedHooksForRelatedEntities; public HookExecutorHelper(IGenericServiceFactory genericProcessorFactory, IJsonApiOptions options) @@ -46,7 +46,7 @@ public IResourceHookContainer GetResourceHookContainer(RightType rightType, Reso container = (_genericProcessorFactory.Get(typeof(ResourceDefinition<>), rightType)); _hookContainers[rightType] = container; } - if (container == null) return container; + if (container == null) return null; // if there was a container, first check if it implements the hook we // want to use it for. @@ -58,7 +58,7 @@ public IResourceHookContainer GetResourceHookContainer(RightType rightType, Reso } else { - targetHooks = new List() { hook }; + targetHooks = new List { hook }; } foreach (ResourceHook targetHook in targetHooks) @@ -105,21 +105,20 @@ public bool ShouldLoadDbValues(Type entityType, ResourceHook hook) return _options.LoadDatabaseValues; } - bool ShouldExecuteHook(RightType entityType, ResourceHook hook) + private bool ShouldExecuteHook(RightType entityType, ResourceHook hook) { var discovery = GetHookDiscovery(entityType); return discovery.ImplementedHooks.Contains(hook); } - - void CheckForTargetHookExistence() + private void CheckForTargetHookExistence() { if (!_targetedHooksForRelatedEntities.Any()) throw new InvalidOperationException("Something is not right in the breadth first traversal of resource hook: " + "trying to get meta information when no allowed hooks are set"); } - IHooksDiscovery GetHookDiscovery(Type entityType) + private IHooksDiscovery GetHookDiscovery(Type entityType) { if (!_hookDiscoveries.TryGetValue(entityType, out IHooksDiscovery discovery)) { @@ -129,18 +128,18 @@ IHooksDiscovery GetHookDiscovery(Type entityType) return discovery; } - IEnumerable GetWhereAndInclude(IEnumerable ids, RelationshipAttribute[] relationshipsToNextLayer) where TResource : class, IIdentifiable + private IEnumerable GetWhereAndInclude(IEnumerable ids, RelationshipAttribute[] relationshipsToNextLayer) where TResource : class, IIdentifiable { var repo = GetRepository(); var query = repo.Get().Where(e => ids.Contains(e.Id)); foreach (var inclusionChainElement in relationshipsToNextLayer) { - query = repo.Include(query, new RelationshipAttribute[] { inclusionChainElement }); + query = repo.Include(query, new[] { inclusionChainElement }); } return query.ToList(); } - IResourceReadRepository GetRepository() where TResource : class, IIdentifiable + private IResourceReadRepository GetRepository() where TResource : class, IIdentifiable { return _genericProcessorFactory.Get>(typeof(IResourceReadRepository<,>), typeof(TResource), typeof(TId)); } @@ -160,7 +159,7 @@ public Dictionary LoadImplicitlyAffected( foreach (IIdentifiable ip in includedLefts) { - IList dbRightEntityList = null; + IList dbRightEntityList; var relationshipValue = relationship.GetValue(ip); if (!(relationshipValue is IEnumerable)) { @@ -189,7 +188,7 @@ public Dictionary LoadImplicitlyAffected( return implicitlyAffected.ToDictionary(kvp => kvp.Key, kvp => TypeHelper.CreateHashSetFor(kvp.Key.RightType, kvp.Value)); } - bool IsHasManyThrough(KeyValuePair kvp, + private bool IsHasManyThrough(KeyValuePair kvp, out IEnumerable entities, out RelationshipAttribute attr) { diff --git a/src/JsonApiDotNetCore/Hooks/Execution/RelationshipsDictionary.cs b/src/JsonApiDotNetCore/Hooks/Execution/RelationshipsDictionary.cs index 45b6cd0eca..a40e93a343 100644 --- a/src/JsonApiDotNetCore/Hooks/Execution/RelationshipsDictionary.cs +++ b/src/JsonApiDotNetCore/Hooks/Execution/RelationshipsDictionary.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Collections; using System.Collections.Generic; using System.Linq; @@ -91,9 +91,9 @@ public Dictionary> GetByRelationship(T } /// - public HashSet GetAffected(Expression> NavigationAction) + public HashSet GetAffected(Expression> navigationAction) { - var property = TypeHelper.ParseNavigationExpression(NavigationAction); + var property = TypeHelper.ParseNavigationExpression(navigationAction); return this.Where(p => p.Key.InternalRelationshipName == property.Name).Select(p => p.Value).SingleOrDefault(); } } diff --git a/src/JsonApiDotNetCore/Hooks/ResourceHookExecutor.cs b/src/JsonApiDotNetCore/Hooks/ResourceHookExecutor.cs index 549704d908..54ac1c5053 100644 --- a/src/JsonApiDotNetCore/Hooks/ResourceHookExecutor.cs +++ b/src/JsonApiDotNetCore/Hooks/ResourceHookExecutor.cs @@ -15,13 +15,14 @@ namespace JsonApiDotNetCore.Hooks { /// - internal class ResourceHookExecutor : IResourceHookExecutor + internal sealed class ResourceHookExecutor : IResourceHookExecutor { - internal readonly IHookExecutorHelper _executorHelper; + private readonly IHookExecutorHelper _executorHelper; private readonly ITraversalHelper _traversalHelper; private readonly IIncludeService _includeService; private readonly ITargetedFields _targetedFields; private readonly IResourceGraph _resourceGraph; + public ResourceHookExecutor( IHookExecutorHelper executorHelper, ITraversalHelper traversalHelper, @@ -37,17 +38,17 @@ public ResourceHookExecutor( } /// - public virtual void BeforeRead(ResourcePipeline pipeline, string stringId = null) where TResource : class, IIdentifiable + public void BeforeRead(ResourcePipeline pipeline, string stringId = null) where TResource : class, IIdentifiable { var hookContainer = _executorHelper.GetResourceHookContainer(ResourceHook.BeforeRead); hookContainer?.BeforeRead(pipeline, false, stringId); - var calledContainers = new List() { typeof(TResource) }; + var calledContainers = new List { typeof(TResource) }; foreach (var chain in _includeService.Get()) RecursiveBeforeRead(chain, pipeline, calledContainers); } /// - public virtual IEnumerable BeforeUpdate(IEnumerable entities, ResourcePipeline pipeline) where TResource : class, IIdentifiable + public IEnumerable BeforeUpdate(IEnumerable entities, ResourcePipeline pipeline) where TResource : class, IIdentifiable { if (GetHook(ResourceHook.BeforeUpdate, entities, out var container, out var node)) { @@ -64,7 +65,7 @@ public virtual IEnumerable BeforeUpdate(IEnumerable - public virtual IEnumerable BeforeCreate(IEnumerable entities, ResourcePipeline pipeline) where TResource : class, IIdentifiable + public IEnumerable BeforeCreate(IEnumerable entities, ResourcePipeline pipeline) where TResource : class, IIdentifiable { if (GetHook(ResourceHook.BeforeCreate, entities, out var container, out var node)) { @@ -78,7 +79,7 @@ public virtual IEnumerable BeforeCreate(IEnumerable - public virtual IEnumerable BeforeDelete(IEnumerable entities, ResourcePipeline pipeline) where TResource : class, IIdentifiable + public IEnumerable BeforeDelete(IEnumerable entities, ResourcePipeline pipeline) where TResource : class, IIdentifiable { if (GetHook(ResourceHook.BeforeDelete, entities, out var container, out var node)) { @@ -105,7 +106,7 @@ public virtual IEnumerable BeforeDelete(IEnumerable - public virtual IEnumerable OnReturn(IEnumerable entities, ResourcePipeline pipeline) where TResource : class, IIdentifiable + public IEnumerable OnReturn(IEnumerable entities, ResourcePipeline pipeline) where TResource : class, IIdentifiable { if (GetHook(ResourceHook.OnReturn, entities, out var container, out var node) && pipeline != ResourcePipeline.GetRelationship) { @@ -125,7 +126,7 @@ public virtual IEnumerable OnReturn(IEnumerable } /// - public virtual void AfterRead(IEnumerable entities, ResourcePipeline pipeline) where TResource : class, IIdentifiable + public void AfterRead(IEnumerable entities, ResourcePipeline pipeline) where TResource : class, IIdentifiable { if (GetHook(ResourceHook.AfterRead, entities, out var container, out var node)) { @@ -139,7 +140,7 @@ public virtual void AfterRead(IEnumerable entities, Resour } /// - public virtual void AfterCreate(IEnumerable entities, ResourcePipeline pipeline) where TResource : class, IIdentifiable + public void AfterCreate(IEnumerable entities, ResourcePipeline pipeline) where TResource : class, IIdentifiable { if (GetHook(ResourceHook.AfterCreate, entities, out var container, out var node)) { @@ -152,7 +153,7 @@ public virtual void AfterCreate(IEnumerable entities, Reso } /// - public virtual void AfterUpdate(IEnumerable entities, ResourcePipeline pipeline) where TResource : class, IIdentifiable + public void AfterUpdate(IEnumerable entities, ResourcePipeline pipeline) where TResource : class, IIdentifiable { if (GetHook(ResourceHook.AfterUpdate, entities, out var container, out var node)) { @@ -165,7 +166,7 @@ public virtual void AfterUpdate(IEnumerable entities, Reso } /// - public virtual void AfterDelete(IEnumerable entities, ResourcePipeline pipeline, bool succeeded) where TResource : class, IIdentifiable + public void AfterDelete(IEnumerable entities, ResourcePipeline pipeline, bool succeeded) where TResource : class, IIdentifiable { if (GetHook(ResourceHook.AfterDelete, entities, out var container, out var node)) { @@ -181,7 +182,7 @@ public virtual void AfterDelete(IEnumerable entities, Reso /// Along the way, creates a traversable node from the root entity set. /// /// true, if hook was implemented, false otherwise. - bool GetHook(ResourceHook target, IEnumerable entities, + private bool GetHook(ResourceHook target, IEnumerable entities, out IResourceHookContainer container, out RootNode node) where TResource : class, IIdentifiable { @@ -193,7 +194,7 @@ bool GetHook(ResourceHook target, IEnumerable entities, /// /// Traverses the nodes in a . /// - void Traverse(NodeLayer currentLayer, ResourceHook target, Action action) + private void Traverse(NodeLayer currentLayer, ResourceHook target, Action action) { if (!currentLayer.AnyEntities()) return; foreach (INode node in currentLayer) @@ -212,7 +213,7 @@ void Traverse(NodeLayer currentLayer, ResourceHook target, Action - void RecursiveBeforeRead(List relationshipChain, ResourcePipeline pipeline, List calledContainers) + private void RecursiveBeforeRead(List relationshipChain, ResourcePipeline pipeline, List calledContainers) { var relationship = relationshipChain.First(); if (!calledContainers.Contains(relationship.RightType)) @@ -237,7 +238,7 @@ void RecursiveBeforeRead(List relationshipChain, Resource /// First the BeforeUpdateRelationship should be for owner1, then the /// BeforeImplicitUpdateRelationship hook should be fired for /// owner2, and lastly the BeforeImplicitUpdateRelationship for article2. - void FireNestedBeforeUpdateHooks(ResourcePipeline pipeline, NodeLayer layer) + private void FireNestedBeforeUpdateHooks(ResourcePipeline pipeline, NodeLayer layer) { foreach (INode node in layer) { @@ -317,7 +318,7 @@ void FireNestedBeforeUpdateHooks(ResourcePipeline pipeline, NodeLayer layer) /// with its inverse relationship attribute. /// /// Entities grouped by relationship attribute - Dictionary ReplaceKeysWithInverseRelationships(Dictionary entitiesByRelationship) + private Dictionary ReplaceKeysWithInverseRelationships(Dictionary entitiesByRelationship) { // 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). @@ -331,7 +332,7 @@ Dictionary ReplaceKeysWithInverseRelationshi /// Given a source of entities, gets the implicitly affected entities /// from the database and calls the BeforeImplicitUpdateRelationship hook. /// - void FireForAffectedImplicits(Type entityTypeToInclude, Dictionary implicitsTarget, ResourcePipeline pipeline, IEnumerable existingImplicitEntities = null) + private void FireForAffectedImplicits(Type entityTypeToInclude, Dictionary implicitsTarget, ResourcePipeline pipeline, IEnumerable existingImplicitEntities = null) { var container = _executorHelper.GetResourceHookContainer(entityTypeToInclude, ResourceHook.BeforeImplicitUpdateRelationship); if (container == null) return; @@ -348,7 +349,7 @@ void FireForAffectedImplicits(Type entityTypeToInclude, Dictionary /// The collection returned from the hook /// The pipeline from which the hook was fired - void ValidateHookResponse(IEnumerable returnedList, ResourcePipeline pipeline = 0) + private void ValidateHookResponse(IEnumerable returnedList, ResourcePipeline pipeline = 0) { if (pipeline == ResourcePipeline.GetSingle && returnedList.Count() > 1) { @@ -360,7 +361,7 @@ void ValidateHookResponse(IEnumerable returnedList, ResourcePipeline pipel /// /// A helper method to call a hook on reflectively. /// - IEnumerable CallHook(IResourceHookContainer container, ResourceHook hook, object[] arguments) + private IEnumerable CallHook(IResourceHookContainer container, ResourceHook hook, object[] arguments) { var method = container.GetType().GetMethod(hook.ToString("G")); // note that some of the hooks return "void". When these hooks, the @@ -372,7 +373,7 @@ IEnumerable CallHook(IResourceHookContainer container, ResourceHook hook, object /// /// If the method, unwrap and throw the actual exception. /// - object ThrowJsonApiExceptionOnError(Func action) + private object ThrowJsonApiExceptionOnError(Func action) { try { @@ -389,7 +390,7 @@ object ThrowJsonApiExceptionOnError(Func action) /// If are included, the values of the entries in need to be replaced with these values. /// /// The relationship helper. - IRelationshipsDictionary CreateRelationshipHelper(RightType entityType, Dictionary prevLayerRelationships, IEnumerable dbValues = null) + private IRelationshipsDictionary CreateRelationshipHelper(RightType entityType, Dictionary prevLayerRelationships, IEnumerable dbValues = null) { if (dbValues != null) prevLayerRelationships = ReplaceWithDbValues(prevLayerRelationships, dbValues.Cast()); return (IRelationshipsDictionary)TypeHelper.CreateInstanceOfOpenType(typeof(RelationshipsDictionary<>), entityType, true, prevLayerRelationships); @@ -399,7 +400,7 @@ IRelationshipsDictionary CreateRelationshipHelper(RightType entityType, Dictiona /// Replaces the entities in the values of the prevLayerRelationships dictionary /// with the corresponding entities loaded from the db. /// - Dictionary ReplaceWithDbValues(Dictionary prevLayerRelationships, IEnumerable dbValues) + private Dictionary ReplaceWithDbValues(Dictionary prevLayerRelationships, IEnumerable dbValues) { foreach (var key in prevLayerRelationships.Keys.ToList()) { @@ -413,7 +414,7 @@ Dictionary ReplaceWithDbValues(Dictionary. /// - HashSet GetAllowedEntities(IEnumerable source, IEnumerable allowedIds) + private HashSet GetAllowedEntities(IEnumerable source, IEnumerable allowedIds) { return new HashSet(source.Cast().Where(ue => allowedIds.Contains(ue.StringId))); } @@ -428,7 +429,7 @@ HashSet GetAllowedEntities(IEnumerable source, IEnumerableThe hook in which the db values will be displayed. /// Relationships from to the next layer: /// this indicates which relationships will be included on . - IEnumerable LoadDbValues(Type entityType, IEnumerable uniqueEntities, ResourceHook targetHook, RelationshipAttribute[] relationshipsToNextLayer) + private IEnumerable LoadDbValues(Type entityType, IEnumerable uniqueEntities, ResourceHook targetHook, RelationshipAttribute[] relationshipsToNextLayer) { // We only need to load database values if the target hook of this hook execution // cycle is compatible with displaying database values and has this option enabled. @@ -439,7 +440,7 @@ IEnumerable LoadDbValues(Type entityType, IEnumerable uniqueEntities, ResourceHo /// /// Fires the AfterUpdateRelationship hook /// - void FireAfterUpdateRelationship(IResourceHookContainer container, INode node, ResourcePipeline pipeline) + private void FireAfterUpdateRelationship(IResourceHookContainer container, INode node, ResourcePipeline pipeline) { Dictionary currentEntitiesGrouped = node.RelationshipsFromPreviousLayer.GetRightEntities(); @@ -456,7 +457,7 @@ void FireAfterUpdateRelationship(IResourceHookContainer container, INode node, R /// /// The ids. /// IIdentifiable entities. - HashSet GetIds(IEnumerable entities) + private HashSet GetIds(IEnumerable entities) { return new HashSet(entities.Cast().Select(e => e.StringId)); } diff --git a/src/JsonApiDotNetCore/Hooks/Traversal/ChildNode.cs b/src/JsonApiDotNetCore/Hooks/Traversal/ChildNode.cs index 7d9dd0bd30..80c83b4a34 100644 --- a/src/JsonApiDotNetCore/Hooks/Traversal/ChildNode.cs +++ b/src/JsonApiDotNetCore/Hooks/Traversal/ChildNode.cs @@ -12,13 +12,13 @@ namespace JsonApiDotNetCore.Hooks /// Child node in the tree /// /// - internal class ChildNode : INode where TResource : class, IIdentifiable + internal sealed class ChildNode : INode where TResource : class, IIdentifiable { - private readonly IdentifiableComparer _comparer = new IdentifiableComparer(); + private readonly IdentifiableComparer _comparer = IdentifiableComparer.Instance; /// - public RightType ResourceType { get; private set; } + public RightType ResourceType { get; } /// - public RelationshipProxy[] RelationshipsToNextLayer { get; set; } + public RelationshipProxy[] RelationshipsToNextLayer { get; } /// public IEnumerable UniqueEntities { @@ -29,13 +29,7 @@ public IEnumerable UniqueEntities } /// - public IRelationshipsFromPreviousLayer RelationshipsFromPreviousLayer - { - get - { - return _relationshipsFromPreviousLayer; - } - } + public IRelationshipsFromPreviousLayer RelationshipsFromPreviousLayer => _relationshipsFromPreviousLayer; private readonly RelationshipsFromPreviousLayer _relationshipsFromPreviousLayer; @@ -79,7 +73,7 @@ public void Reassign(IEnumerable updated = null) } else if (currentValue is IIdentifiable relationshipSingle) { - if (!unique.Intersect(new HashSet() { relationshipSingle }, _comparer).Any()) + if (!unique.Intersect(new HashSet { relationshipSingle }, _comparer).Any()) { proxy.SetValue(left, null); } diff --git a/src/JsonApiDotNetCore/Hooks/Traversal/RelationshipGroup.cs b/src/JsonApiDotNetCore/Hooks/Traversal/RelationshipGroup.cs index 6f34f1fb7b..c3febd7a3b 100644 --- a/src/JsonApiDotNetCore/Hooks/Traversal/RelationshipGroup.cs +++ b/src/JsonApiDotNetCore/Hooks/Traversal/RelationshipGroup.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using JsonApiDotNetCore.Models; namespace JsonApiDotNetCore.Hooks @@ -9,7 +9,7 @@ internal interface IRelationshipGroup HashSet LeftEntities { get; } } - internal class RelationshipGroup : IRelationshipGroup where TRight : class, IIdentifiable + internal sealed class RelationshipGroup : IRelationshipGroup where TRight : class, IIdentifiable { public RelationshipProxy Proxy { get; } public HashSet LeftEntities { get; } @@ -21,4 +21,4 @@ public RelationshipGroup(RelationshipProxy proxy, HashSet leftEnt RightEntities = rightEntities; } } -} \ No newline at end of file +} diff --git a/src/JsonApiDotNetCore/Hooks/Traversal/RelationshipProxy.cs b/src/JsonApiDotNetCore/Hooks/Traversal/RelationshipProxy.cs index 14423e6007..8e8201151e 100644 --- a/src/JsonApiDotNetCore/Hooks/Traversal/RelationshipProxy.cs +++ b/src/JsonApiDotNetCore/Hooks/Traversal/RelationshipProxy.cs @@ -17,10 +17,10 @@ namespace JsonApiDotNetCore.Hooks /// it and fire hooks for it, if defined) or not (in which case we skip /// ArticleTags and go directly to Tags. /// - public class RelationshipProxy + internal sealed class RelationshipProxy { - readonly bool _isHasManyThrough; - readonly bool _skipJoinTable; + private readonly bool _isHasManyThrough; + private readonly bool _skipJoinTable; /// /// The target type for this relationship attribute. @@ -28,9 +28,9 @@ public class RelationshipProxy /// For HasManyThrough it is either the ThroughProperty (when the join table is /// Identifiable) or it is the right-hand side (when the join table is not identifiable) /// - public Type RightType { get; private set; } - public Type LeftType { get { return Attribute.LeftType; } } - public bool IsContextRelation { get; private set; } + public Type RightType { get; } + public Type LeftType => Attribute.LeftType; + public bool IsContextRelation { get; } public RelationshipAttribute Attribute { get; set; } public RelationshipProxy(RelationshipAttribute attr, Type relatedType, bool isContextRelation) diff --git a/src/JsonApiDotNetCore/Hooks/Traversal/RelationshipsFromPreviousLayer.cs b/src/JsonApiDotNetCore/Hooks/Traversal/RelationshipsFromPreviousLayer.cs index 2068fa8652..386cf75e9f 100644 --- a/src/JsonApiDotNetCore/Hooks/Traversal/RelationshipsFromPreviousLayer.cs +++ b/src/JsonApiDotNetCore/Hooks/Traversal/RelationshipsFromPreviousLayer.cs @@ -1,4 +1,4 @@ -using System.Collections; +using System.Collections; using System.Collections.Generic; using System.Linq; using JsonApiDotNetCore.Models; @@ -22,9 +22,9 @@ internal interface IRelationshipsFromPreviousLayer Dictionary GetLeftEntities(); } - internal class RelationshipsFromPreviousLayer : IRelationshipsFromPreviousLayer, IEnumerable> where TRightResource : class, IIdentifiable + internal sealed class RelationshipsFromPreviousLayer : IRelationshipsFromPreviousLayer, IEnumerable> where TRightResource : class, IIdentifiable { - readonly IEnumerable> _collection; + private readonly IEnumerable> _collection; public RelationshipsFromPreviousLayer(IEnumerable> collection) { diff --git a/src/JsonApiDotNetCore/Hooks/Traversal/RootNode.cs b/src/JsonApiDotNetCore/Hooks/Traversal/RootNode.cs index 83f485f5a1..f346cdffc7 100644 --- a/src/JsonApiDotNetCore/Hooks/Traversal/RootNode.cs +++ b/src/JsonApiDotNetCore/Hooks/Traversal/RootNode.cs @@ -11,13 +11,13 @@ namespace JsonApiDotNetCore.Hooks /// The root node class of the breadth-first-traversal of entity data structures /// as performed by the /// - internal class RootNode : INode where TResource : class, IIdentifiable + internal sealed class RootNode : INode where TResource : class, IIdentifiable { - private readonly IdentifiableComparer _comparer = new IdentifiableComparer(); + private readonly IdentifiableComparer _comparer = IdentifiableComparer.Instance; private readonly RelationshipProxy[] _allRelationshipsToNextLayer; private HashSet _uniqueEntities; - public Type ResourceType { get; internal set; } - public IEnumerable UniqueEntities { get { return _uniqueEntities; } } + public Type ResourceType { get; } + public IEnumerable UniqueEntities => _uniqueEntities; public RelationshipProxy[] RelationshipsToNextLayer { get; } public Dictionary> LeftsToNextLayerByRelationships() @@ -38,7 +38,7 @@ public Dictionary LeftsToNextLayer() /// /// The root node does not have a parent layer and therefore does not have any relationships to any previous layer /// - public IRelationshipsFromPreviousLayer RelationshipsFromPreviousLayer { get { return null; } } + public IRelationshipsFromPreviousLayer RelationshipsFromPreviousLayer => null; public RootNode(IEnumerable uniqueEntities, RelationshipProxy[] populatedRelationships, RelationshipProxy[] allRelationships) { diff --git a/src/JsonApiDotNetCore/Hooks/Traversal/TraversalHelper.cs b/src/JsonApiDotNetCore/Hooks/Traversal/TraversalHelper.cs index 13591fd926..b380f8f0ae 100644 --- a/src/JsonApiDotNetCore/Hooks/Traversal/TraversalHelper.cs +++ b/src/JsonApiDotNetCore/Hooks/Traversal/TraversalHelper.cs @@ -21,9 +21,9 @@ namespace JsonApiDotNetCore.Hooks /// Typically, the first layer is homogeneous (all entities have the same type), /// and further nodes can be mixed. /// - internal class TraversalHelper : ITraversalHelper + internal sealed class TraversalHelper : ITraversalHelper { - private readonly IdentifiableComparer _comparer = new IdentifiableComparer(); + private readonly IdentifiableComparer _comparer = IdentifiableComparer.Instance; private readonly IResourceGraph _resourceGraph; private readonly ITargetedFields _targetedFields; /// @@ -57,7 +57,7 @@ public RootNode CreateRootNode(IEnumerable root _processedEntities = new Dictionary>(); RegisterRelationshipProxies(typeof(TResource)); var uniqueEntities = ProcessEntities(rootEntities); - var populatedRelationshipsToNextLayer = GetPopulatedRelationships(typeof(TResource), uniqueEntities.Cast()); + var populatedRelationshipsToNextLayer = GetPopulatedRelationships(typeof(TResource), uniqueEntities); var allRelationshipsFromType = _relationshipProxies.Select(entry => entry.Value).Where(proxy => proxy.LeftType == typeof(TResource)).ToArray(); return new RootNode(uniqueEntities, populatedRelationshipsToNextLayer, allRelationshipsFromType); } @@ -69,7 +69,7 @@ public RootNode CreateRootNode(IEnumerable root /// Root node. public NodeLayer CreateNextLayer(INode rootNode) { - return CreateNextLayer(new INode[] { rootNode }); + return CreateNextLayer(new[] { rootNode }); } /// @@ -81,7 +81,7 @@ public NodeLayer CreateNextLayer(IEnumerable nodes) { // first extract entities by parsing populated relationships in the entities // of previous layer - (var lefts, var rights) = ExtractEntities(nodes); + var (lefts, rights) = ExtractEntities(nodes); // group them conveniently so we can make ChildNodes of them: // there might be several relationship attributes in rights dictionary @@ -113,7 +113,7 @@ public NodeLayer CreateNextLayer(IEnumerable nodes) /// iterates through the dictionary and groups the values /// by matching right type of the keys (which are relationship attributes) /// - Dictionary>>> GroupByRightTypeOfRelationship(Dictionary> relationships) + private Dictionary>>> GroupByRightTypeOfRelationship(Dictionary> relationships) { return relationships.GroupBy(kvp => kvp.Key.RightType).ToDictionary(gdc => gdc.Key, gdc => gdc.ToList()); } @@ -122,7 +122,7 @@ Dictionary>> /// Extracts the entities for the current layer by going through all populated relationships /// of the (left entities of the previous layer. /// - (Dictionary>, Dictionary>) ExtractEntities(IEnumerable leftNodes) + private (Dictionary>, Dictionary>) ExtractEntities(IEnumerable leftNodes) { var leftEntitiesGrouped = new Dictionary>(); // RelationshipAttr_prevLayer->currentLayer => prevLayerEntities var rightEntitiesGrouped = new Dictionary>(); // RelationshipAttr_prevLayer->currentLayer => currentLayerEntities @@ -151,7 +151,7 @@ Dictionary>> if (proxy.IsContextRelation || uniqueRightEntities.Any()) { AddToRelationshipGroup(rightEntitiesGrouped, proxy, uniqueRightEntities); - AddToRelationshipGroup(leftEntitiesGrouped, proxy, new IIdentifiable[] { leftEntity }); + AddToRelationshipGroup(leftEntitiesGrouped, proxy, new[] { leftEntity }); } } } @@ -173,7 +173,7 @@ Dictionary>> /// left type to any right type /// /// The relationships. - RelationshipProxy[] GetPopulatedRelationships(LeftType leftType, IEnumerable lefts) + private RelationshipProxy[] GetPopulatedRelationships(LeftType leftType, IEnumerable lefts) { var 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(); @@ -185,7 +185,7 @@ RelationshipProxy[] GetPopulatedRelationships(LeftType leftType, IEnumerableThe entities. /// Incoming entities. /// The 1st type parameter. - HashSet ProcessEntities(IEnumerable incomingEntities) where TResource : class, IIdentifiable + private HashSet ProcessEntities(IEnumerable incomingEntities) where TResource : class, IIdentifiable { Type type = typeof(TResource); var newEntities = UniqueInTree(incomingEntities, type); @@ -198,12 +198,12 @@ HashSet ProcessEntities(IEnumerable incomingEnt /// other models in the resource resourceGraphs by constructing RelationshipProxies . /// /// The type to parse - void RegisterRelationshipProxies(RightType type) + private void RegisterRelationshipProxies(RightType type) { foreach (RelationshipAttribute attr in _resourceGraph.GetRelationships(type)) { if (!attr.CanInclude) continue; - if (!_relationshipProxies.TryGetValue(attr, out RelationshipProxy proxies)) + if (!_relationshipProxies.TryGetValue(attr, out _)) { RightType rightType = GetRightTypeFromRelationship(attr); bool isContextRelation = false; @@ -220,7 +220,7 @@ void RegisterRelationshipProxies(RightType type) /// /// Entities to register /// Entity type. - void RegisterProcessedEntities(IEnumerable entities, Type entityType) + private void RegisterProcessedEntities(IEnumerable entities, Type entityType) { var processedEntities = GetProcessedEntities(entityType); processedEntities.UnionWith(new HashSet(entities)); @@ -231,7 +231,7 @@ void RegisterProcessedEntities(IEnumerable entities, Type entityT /// /// The processed entities. /// Entity type. - HashSet GetProcessedEntities(Type entityType) + private HashSet GetProcessedEntities(Type entityType) { if (!_processedEntities.TryGetValue(entityType, out HashSet processedEntities)) { @@ -248,7 +248,7 @@ HashSet GetProcessedEntities(Type entityType) /// The in tree. /// Entities. /// Entity type. - HashSet UniqueInTree(IEnumerable entities, Type entityType) where TResource : class, IIdentifiable + private HashSet UniqueInTree(IEnumerable entities, Type entityType) where TResource : class, IIdentifiable { var newEntities = entities.Except(GetProcessedEntities(entityType), _comparer).Cast(); return new HashSet(newEntities); @@ -262,7 +262,7 @@ HashSet UniqueInTree(IEnumerable entities, Type /// /// The target type for traversal /// Relationship attribute - RightType GetRightTypeFromRelationship(RelationshipAttribute attr) + private RightType GetRightTypeFromRelationship(RelationshipAttribute attr) { if (attr is HasManyThroughAttribute throughAttr && throughAttr.ThroughType.Inherits(typeof(IIdentifiable))) { @@ -271,7 +271,7 @@ RightType GetRightTypeFromRelationship(RelationshipAttribute attr) return attr.RightType; } - void AddToRelationshipGroup(Dictionary> target, RelationshipProxy proxy, IEnumerable newEntities) + private void AddToRelationshipGroup(Dictionary> target, RelationshipProxy proxy, IEnumerable newEntities) { if (!target.TryGetValue(proxy, out List entities)) { @@ -284,30 +284,29 @@ void AddToRelationshipGroup(Dictionary> t /// /// Reflective helper method to create an instance of ; /// - INode CreateNodeInstance(RightType nodeType, RelationshipProxy[] relationshipsToNext, IEnumerable relationshipsFromPrev) + private INode CreateNodeInstance(RightType nodeType, RelationshipProxy[] relationshipsToNext, IEnumerable relationshipsFromPrev) { IRelationshipsFromPreviousLayer prev = CreateRelationshipsFromInstance(nodeType, relationshipsFromPrev); - return (INode)TypeHelper.CreateInstanceOfOpenType(typeof(ChildNode<>), nodeType, new object[] { relationshipsToNext, prev }); + return (INode)TypeHelper.CreateInstanceOfOpenType(typeof(ChildNode<>), nodeType, relationshipsToNext, prev); } /// /// Reflective helper method to create an instance of ; /// - IRelationshipsFromPreviousLayer CreateRelationshipsFromInstance(RightType nodeType, IEnumerable relationshipsFromPrev) + private IRelationshipsFromPreviousLayer CreateRelationshipsFromInstance(RightType nodeType, IEnumerable relationshipsFromPrev) { var cast = relationshipsFromPrev.Cast(relationshipsFromPrev.First().GetType()); - return (IRelationshipsFromPreviousLayer)TypeHelper.CreateInstanceOfOpenType(typeof(RelationshipsFromPreviousLayer<>), nodeType, new object[] { cast }); + return (IRelationshipsFromPreviousLayer)TypeHelper.CreateInstanceOfOpenType(typeof(RelationshipsFromPreviousLayer<>), nodeType, cast); } /// /// Reflective helper method to create an instance of ; /// - IRelationshipGroup CreateRelationshipGroupInstance(Type thisLayerType, RelationshipProxy proxy, List leftEntities, List rightEntities) + private IRelationshipGroup CreateRelationshipGroupInstance(Type thisLayerType, RelationshipProxy proxy, List leftEntities, List rightEntities) { var rightEntitiesHashed = TypeHelper.CreateInstanceOfOpenType(typeof(HashSet<>), thisLayerType, rightEntities.Cast(thisLayerType)); return (IRelationshipGroup)TypeHelper.CreateInstanceOfOpenType(typeof(RelationshipGroup<>), - thisLayerType, - new object[] { proxy, new HashSet(leftEntities), rightEntitiesHashed }); + thisLayerType, proxy, new HashSet(leftEntities), rightEntitiesHashed); } } @@ -315,9 +314,9 @@ IRelationshipGroup CreateRelationshipGroupInstance(Type thisLayerType, Relations /// A helper class that represents all entities in the current layer that /// are being traversed for which hooks will be executed (see IResourceHookExecutor) /// - internal class NodeLayer : IEnumerable + internal sealed class NodeLayer : IEnumerable { - readonly List _collection; + private readonly List _collection; public bool AnyEntities() { diff --git a/src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs b/src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs index ca84b60a47..1e7ac181ab 100644 --- a/src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs +++ b/src/JsonApiDotNetCore/Internal/DefaultRoutingConvention.cs @@ -33,7 +33,7 @@ namespace JsonApiDotNetCore.Internal /// public class SomeVeryCustomController{SomeResource} : JsonApiMixin { } /// // => /someVeryCustoms/relationship/relatedResource /// - public class DefaultRoutingConvention : IJsonApiRoutingConvention, IControllerResourceMapping + public class DefaultRoutingConvention : IJsonApiRoutingConvention { private readonly string _namespace; private readonly IResourceNameFormatter _formatter; diff --git a/src/JsonApiDotNetCore/Internal/Exceptions/JsonApiSetupException.cs b/src/JsonApiDotNetCore/Internal/Exceptions/JsonApiSetupException.cs index 34765066be..5ab6400b65 100644 --- a/src/JsonApiDotNetCore/Internal/Exceptions/JsonApiSetupException.cs +++ b/src/JsonApiDotNetCore/Internal/Exceptions/JsonApiSetupException.cs @@ -2,7 +2,7 @@ namespace JsonApiDotNetCore.Internal { - public class JsonApiSetupException : Exception + public sealed class JsonApiSetupException : Exception { public JsonApiSetupException(string message) : base(message) { } @@ -10,4 +10,4 @@ public JsonApiSetupException(string message) public JsonApiSetupException(string message, Exception innerException) : base(message, innerException) { } } -} \ No newline at end of file +} diff --git a/src/JsonApiDotNetCore/Internal/Generics/GenericServiceFactory.cs b/src/JsonApiDotNetCore/Internal/Generics/GenericServiceFactory.cs index bc834f4733..acd3f88b06 100644 --- a/src/JsonApiDotNetCore/Internal/Generics/GenericServiceFactory.cs +++ b/src/JsonApiDotNetCore/Internal/Generics/GenericServiceFactory.cs @@ -31,7 +31,7 @@ public interface IGenericServiceFactory TInterface Get(Type openGenericType, Type resourceType, Type keyType); } - public class GenericServiceFactory : IGenericServiceFactory + public sealed class GenericServiceFactory : IGenericServiceFactory { private readonly IServiceProvider _serviceProvider; diff --git a/src/JsonApiDotNetCore/Internal/IdentifiableComparer.cs b/src/JsonApiDotNetCore/Internal/IdentifiableComparer.cs index 60793829b8..fbec8f67cb 100644 --- a/src/JsonApiDotNetCore/Internal/IdentifiableComparer.cs +++ b/src/JsonApiDotNetCore/Internal/IdentifiableComparer.cs @@ -6,9 +6,10 @@ namespace JsonApiDotNetCore.Internal /// /// Compares `IIdentifiable` with each other based on ID /// - public class IdentifiableComparer : IEqualityComparer + public sealed class IdentifiableComparer : IEqualityComparer { internal static readonly IdentifiableComparer Instance = new IdentifiableComparer(); + public bool Equals(IIdentifiable x, IIdentifiable y) { return x.StringId == y.StringId; diff --git a/src/JsonApiDotNetCore/Internal/Query/BaseQueryContext.cs b/src/JsonApiDotNetCore/Internal/Query/BaseQueryContext.cs index c35dd64c88..5ad0d0a386 100644 --- a/src/JsonApiDotNetCore/Internal/Query/BaseQueryContext.cs +++ b/src/JsonApiDotNetCore/Internal/Query/BaseQueryContext.cs @@ -23,7 +23,7 @@ protected BaseQueryContext(TQuery query) public string GetPropertyPath() { if (IsAttributeOfRelationship) - return string.Format("{0}.{1}", Relationship.InternalRelationshipName, Attribute.PropertyInfo.Name); + return $"{Relationship.InternalRelationshipName}.{Attribute.PropertyInfo.Name}"; return Attribute.PropertyInfo.Name; } diff --git a/src/JsonApiDotNetCore/Internal/Query/SortQuery.cs b/src/JsonApiDotNetCore/Internal/Query/SortQuery.cs index 840de80ddb..36c703e71b 100644 --- a/src/JsonApiDotNetCore/Internal/Query/SortQuery.cs +++ b/src/JsonApiDotNetCore/Internal/Query/SortQuery.cs @@ -1,4 +1,4 @@ -namespace JsonApiDotNetCore.Internal.Query +namespace JsonApiDotNetCore.Internal.Query { /// /// Internal representation of the raw articles?sort[field] query from the URL. diff --git a/src/JsonApiDotNetCore/Internal/Query/SortQueryContext.cs b/src/JsonApiDotNetCore/Internal/Query/SortQueryContext.cs index ce1395102d..68d591e5e9 100644 --- a/src/JsonApiDotNetCore/Internal/Query/SortQueryContext.cs +++ b/src/JsonApiDotNetCore/Internal/Query/SortQueryContext.cs @@ -7,6 +7,7 @@ namespace JsonApiDotNetCore.Internal.Query public class SortQueryContext : BaseQueryContext { public SortQueryContext(SortQuery sortQuery) : base(sortQuery) { } + public SortDirection Direction => Query.Direction; } } diff --git a/src/JsonApiDotNetCore/Internal/ResourceContext.cs b/src/JsonApiDotNetCore/Internal/ResourceContext.cs index 15ab4b4c7a..3aaad31f35 100644 --- a/src/JsonApiDotNetCore/Internal/ResourceContext.cs +++ b/src/JsonApiDotNetCore/Internal/ResourceContext.cs @@ -43,7 +43,7 @@ public class ResourceContext public List Relationships { get; set; } private List _fields; - public List Fields { get { return _fields = _fields ?? Attributes.Cast().Concat(Relationships).ToList(); } } + public List Fields { get { return _fields ??= Attributes.Cast().Concat(Relationships).ToList(); } } /// /// Configures which links to show in the diff --git a/src/JsonApiDotNetCore/Internal/ResourceGraph.cs b/src/JsonApiDotNetCore/Internal/ResourceGraph.cs index 2dc5dda57a..b9f89420a4 100644 --- a/src/JsonApiDotNetCore/Internal/ResourceGraph.cs +++ b/src/JsonApiDotNetCore/Internal/ResourceGraph.cs @@ -13,22 +13,22 @@ namespace JsonApiDotNetCore.Internal public class ResourceGraph : IResourceGraph { internal List ValidationResults { get; } - private List _resources { get; } + private List Resources { get; } public ResourceGraph(List entities, List validationResults = null) { - _resources = entities; + Resources = entities; ValidationResults = validationResults; } /// - public ResourceContext[] GetResourceContexts() => _resources.ToArray(); + public ResourceContext[] GetResourceContexts() => Resources.ToArray(); /// public ResourceContext GetResourceContext(string entityName) - => _resources.SingleOrDefault(e => string.Equals(e.ResourceName, entityName, StringComparison.OrdinalIgnoreCase)); + => Resources.SingleOrDefault(e => string.Equals(e.ResourceName, entityName, StringComparison.OrdinalIgnoreCase)); /// public ResourceContext GetResourceContext(Type entityType) - => _resources.SingleOrDefault(e => e.ResourceType == entityType); + => Resources.SingleOrDefault(e => e.ResourceType == entityType); /// public ResourceContext GetResourceContext() where TResource : class, IIdentifiable => GetResourceContext(typeof(TResource)); @@ -75,9 +75,9 @@ private IEnumerable Getter(Expression> selec { IEnumerable available; if (type == FieldFilterType.Attribute) - available = GetResourceContext(typeof(T)).Attributes.Cast(); + available = GetResourceContext(typeof(T)).Attributes; else if (type == FieldFilterType.Relationship) - available = GetResourceContext(typeof(T)).Relationships.Cast(); + available = GetResourceContext(typeof(T)).Relationships; else available = GetResourceContext(typeof(T)).Fields; @@ -128,7 +128,7 @@ private IEnumerable Getter(Expression> selec private void ThrowNotExposedError(string memberName, FieldFilterType type) { - throw new ArgumentException($"{memberName} is not an json:api exposed {type.ToString("g")}."); + throw new ArgumentException($"{memberName} is not an json:api exposed {type:g}."); } /// diff --git a/src/JsonApiDotNetCore/Internal/TypeHelper.cs b/src/JsonApiDotNetCore/Internal/TypeHelper.cs index ec3954b069..4a0be08cb4 100644 --- a/src/JsonApiDotNetCore/Internal/TypeHelper.cs +++ b/src/JsonApiDotNetCore/Internal/TypeHelper.cs @@ -17,14 +17,14 @@ public static IList ConvertCollection(IEnumerable collection, Type targe list.Add(ConvertType(item, targetType)); return list; } - public static bool IsNullable(Type type) + private static bool IsNullable(Type type) { return (!type.IsValueType || Nullable.GetUnderlyingType(type) != null); } public static object ConvertType(object value, Type type) { if (value == null && !IsNullable(type)) - throw new FormatException($"Cannot convert null to a non-nullable type"); + throw new FormatException("Cannot convert null to a non-nullable type"); if (value == null) return null; @@ -38,7 +38,7 @@ public static object ConvertType(object value, Type type) type = Nullable.GetUnderlyingType(type) ?? type; - var stringValue = value?.ToString(); + var stringValue = value.ToString(); if (string.IsNullOrEmpty(stringValue)) return GetDefaultType(type); @@ -91,33 +91,32 @@ public static Type GetTypeOfList(Type type) /// Gets the property info that is referenced in the NavigationAction expression. /// Credits: https://stackoverflow.com/a/17116267/4441216 /// - public static PropertyInfo ParseNavigationExpression(Expression> NavigationExpression) + public static PropertyInfo ParseNavigationExpression(Expression> navigationExpression) { - MemberExpression Exp = null; + MemberExpression exp; //this line is necessary, because sometimes the expression comes in as Convert(originalExpression) - if (NavigationExpression.Body is UnaryExpression) + if (navigationExpression.Body is UnaryExpression unaryExpression) { - var UnExp = (UnaryExpression)NavigationExpression.Body; - if (UnExp.Operand is MemberExpression) + if (unaryExpression.Operand is MemberExpression memberExpression) { - Exp = (MemberExpression)UnExp.Operand; + exp = memberExpression; } else { throw new ArgumentException(); } } - else if (NavigationExpression.Body is MemberExpression) + else if (navigationExpression.Body is MemberExpression memberExpression) { - Exp = (MemberExpression)NavigationExpression.Body; + exp = memberExpression; } else { throw new ArgumentException(); } - return (PropertyInfo)Exp.Member; + return (PropertyInfo)exp.Member; } /// @@ -144,7 +143,7 @@ public static IList ConvertListType(IEnumerable values, Type type) /// Generic type parameters to be used in open type. /// Constructor arguments to be provided in instantiation. /// Open generic type - public static object CreateInstanceOfOpenType(Type openType, Type[] parameters, params object[] constructorArguments) + private static object CreateInstanceOfOpenType(Type openType, Type[] parameters, params object[] constructorArguments) { var parameterizedType = openType.MakeGenericType(parameters); return Activator.CreateInstance(parameterizedType, constructorArguments); @@ -171,7 +170,7 @@ public static Dictionary> ConvertAttributeDicti /// /// Use this overload if you need to instantiate a type that has a internal constructor /// - public static object CreateInstanceOfOpenType(Type openType, Type[] parameters, bool hasInternalConstructor, params object[] constructorArguments) + private static object CreateInstanceOfOpenType(Type openType, Type[] parameters, bool hasInternalConstructor, params object[] constructorArguments) { if (!hasInternalConstructor) return CreateInstanceOfOpenType(openType, parameters, constructorArguments); var parameterizedType = openType.MakeGenericType(parameters); @@ -189,7 +188,7 @@ public static object CreateInstanceOfOpenType(Type openType, Type[] parameters, /// Open generic type public static object CreateInstanceOfOpenType(Type openType, Type parameter, params object[] constructorArguments) { - return CreateInstanceOfOpenType(openType, new Type[] { parameter }, constructorArguments); + return CreateInstanceOfOpenType(openType, new[] { parameter }, constructorArguments); } /// @@ -197,7 +196,7 @@ public static object CreateInstanceOfOpenType(Type openType, Type parameter, par /// public static object CreateInstanceOfOpenType(Type openType, Type parameter, bool hasInternalConstructor, params object[] constructorArguments) { - return CreateInstanceOfOpenType(openType, new Type[] { parameter }, hasInternalConstructor, constructorArguments); + return CreateInstanceOfOpenType(openType, new[] { parameter }, hasInternalConstructor, constructorArguments); } diff --git a/src/JsonApiDotNetCore/Internal/ValidationResults.cs b/src/JsonApiDotNetCore/Internal/ValidationResults.cs index 93fa32c74b..d13b5c65da 100644 --- a/src/JsonApiDotNetCore/Internal/ValidationResults.cs +++ b/src/JsonApiDotNetCore/Internal/ValidationResults.cs @@ -2,7 +2,7 @@ namespace JsonApiDotNetCore.Internal { - public class ValidationResult + public sealed class ValidationResult { public ValidationResult(LogLevel logLevel, string message) { @@ -10,7 +10,7 @@ public ValidationResult(LogLevel logLevel, string message) Message = message; } - public LogLevel LogLevel { get; set; } - public string Message { get; set; } + public LogLevel LogLevel { get; } + public string Message { get; } } } diff --git a/src/JsonApiDotNetCore/Middleware/CurrentRequestMiddleware.cs b/src/JsonApiDotNetCore/Middleware/CurrentRequestMiddleware.cs index 68a169ee0d..6b7adf2c20 100644 --- a/src/JsonApiDotNetCore/Middleware/CurrentRequestMiddleware.cs +++ b/src/JsonApiDotNetCore/Middleware/CurrentRequestMiddleware.cs @@ -1,5 +1,4 @@ using System; -using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using JsonApiDotNetCore.Configuration; @@ -7,7 +6,6 @@ using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Managers.Contracts; using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Primitives; @@ -16,7 +14,7 @@ namespace JsonApiDotNetCore.Middleware /// /// This sets all necessary parameters relating to the HttpContext for JADNC /// - public class CurrentRequestMiddleware + public sealed class CurrentRequestMiddleware { private readonly RequestDelegate _next; private HttpContext _httpContext; @@ -76,7 +74,6 @@ private string GetBaseId() } private string GetRelationshipId() { - var resource = _currentRequest.GetRequestResource(); if (!_currentRequest.IsRelationshipPath) { return null; @@ -84,13 +81,6 @@ private string GetRelationshipId() var components = SplitCurrentPath(); var toReturn = components.ElementAtOrDefault(4); - if (toReturn == null) - { - return null; - } - var relType = _currentRequest.RequestRelationship.RightType; - var relResource = _resourceGraph.GetResourceContext(relType); - var relIdentityType = relResource.IdentityType; return toReturn; } private string[] SplitCurrentPath() @@ -108,9 +98,9 @@ private string GetBasePath(string resourceName = null) var r = _httpContext.Request; if (_options.RelativeLinks) { - return GetNameSpace(resourceName); + return GetNameSpace(); } - var ns = GetNameSpace(resourceName); + var ns = GetNameSpace(); var customRoute = GetCustomRoute(r.Path.Value, resourceName); var toReturn = $"{r.Scheme}://{r.Host}/{ns}"; if (customRoute != null) @@ -137,13 +127,12 @@ private object GetCustomRoute(string path, string resourceName) } } - private string GetNameSpace(string resourceName = null) + private string GetNameSpace() { - return _options.Namespace; } - protected bool PathIsRelationship() + private bool PathIsRelationship() { var actionName = (string)_routeValues["action"]; return actionName.ToLower().Contains("relationships"); @@ -183,7 +172,7 @@ private bool IsValidAcceptHeader(HttpContext context) return true; } - internal static bool ContainsMediaTypeParameters(string mediaType) + private static bool ContainsMediaTypeParameters(string mediaType) { var incomingMediaTypeSpan = mediaType.AsSpan(); @@ -225,7 +214,7 @@ private ResourceContext GetCurrentEntity() var requestResource = _resourceGraph.GetResourceContext(resourceType); if (requestResource == null) { - return requestResource; + return null; } if (_routeValues.TryGetValue("relationshipName", out object relationshipName)) { diff --git a/src/JsonApiDotNetCore/Middleware/DefaultExceptionFilter.cs b/src/JsonApiDotNetCore/Middleware/DefaultExceptionFilter.cs index 195e38a9e4..9ba23becdf 100644 --- a/src/JsonApiDotNetCore/Middleware/DefaultExceptionFilter.cs +++ b/src/JsonApiDotNetCore/Middleware/DefaultExceptionFilter.cs @@ -8,7 +8,7 @@ namespace JsonApiDotNetCore.Middleware /// /// Global exception filter that wraps any thrown error with a JsonApiException. /// - public class DefaultExceptionFilter : ActionFilterAttribute, IExceptionFilter + public sealed class DefaultExceptionFilter : ActionFilterAttribute, IExceptionFilter { private readonly ILogger _logger; diff --git a/src/JsonApiDotNetCore/Middleware/DefaultTypeMatchFilter.cs b/src/JsonApiDotNetCore/Middleware/DefaultTypeMatchFilter.cs index 8ba43dbc26..5e428fa772 100644 --- a/src/JsonApiDotNetCore/Middleware/DefaultTypeMatchFilter.cs +++ b/src/JsonApiDotNetCore/Middleware/DefaultTypeMatchFilter.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Linq; using JsonApiDotNetCore.Internal; using JsonApiDotNetCore.Internal.Contracts; @@ -10,7 +10,7 @@ namespace JsonApiDotNetCore.Middleware /// /// Action filter used to verify the incoming type matches the target type, else return a 409 /// - public class DefaultTypeMatchFilter : IActionFilter + public sealed class DefaultTypeMatchFilter : IActionFilter { private readonly IResourceContextProvider _provider; diff --git a/src/JsonApiDotNetCore/Middleware/QueryParameterFilter.cs b/src/JsonApiDotNetCore/Middleware/QueryParameterFilter.cs index 9e66363da2..863bf7ad3a 100644 --- a/src/JsonApiDotNetCore/Middleware/QueryParameterFilter.cs +++ b/src/JsonApiDotNetCore/Middleware/QueryParameterFilter.cs @@ -6,7 +6,7 @@ namespace JsonApiDotNetCore.Middleware { - public class QueryParameterActionFilter : IAsyncActionFilter, IQueryParameterActionFilter + public sealed class QueryParameterActionFilter : IAsyncActionFilter, IQueryParameterActionFilter { private readonly IQueryParameterDiscovery _queryParser; public QueryParameterActionFilter(IQueryParameterDiscovery queryParser) => _queryParser = queryParser; diff --git a/src/JsonApiDotNetCore/Models/Annotation/AttrAttribute.cs b/src/JsonApiDotNetCore/Models/Annotation/AttrAttribute.cs index 211d94a174..7e7dacbb7d 100644 --- a/src/JsonApiDotNetCore/Models/Annotation/AttrAttribute.cs +++ b/src/JsonApiDotNetCore/Models/Annotation/AttrAttribute.cs @@ -4,7 +4,7 @@ namespace JsonApiDotNetCore.Models { - public class AttrAttribute : Attribute, IResourceField + public sealed class AttrAttribute : Attribute, IResourceField { /// /// Defines a public attribute exposed by the API @@ -123,7 +123,7 @@ private PropertyInfo GetResourceProperty(object resource) /// /// Whether or not the provided exposed name is equivalent to the one defined in on the model /// - public virtual bool Is(string publicRelationshipName) + public bool Is(string publicRelationshipName) => string.Equals(publicRelationshipName, PublicAttributeName, StringComparison.OrdinalIgnoreCase); } } diff --git a/src/JsonApiDotNetCore/Models/Annotation/HasManyAttribute.cs b/src/JsonApiDotNetCore/Models/Annotation/HasManyAttribute.cs index a6b33bb12e..0c04d30fab 100644 --- a/src/JsonApiDotNetCore/Models/Annotation/HasManyAttribute.cs +++ b/src/JsonApiDotNetCore/Models/Annotation/HasManyAttribute.cs @@ -1,4 +1,3 @@ -using System; using JsonApiDotNetCore.Models.Links; namespace JsonApiDotNetCore.Models @@ -36,8 +35,8 @@ public HasManyAttribute(string publicName = null, Link relationshipLinks = Link. /// public override object GetValue(object entity) { - return entity?.GetType()? - .GetProperty(InternalRelationshipName)? + return entity?.GetType() + .GetProperty(InternalRelationshipName)? .GetValue(entity); } diff --git a/src/JsonApiDotNetCore/Models/Annotation/HasManyThroughAttribute.cs b/src/JsonApiDotNetCore/Models/Annotation/HasManyThroughAttribute.cs index f33276cb35..84ff0cfcfa 100644 --- a/src/JsonApiDotNetCore/Models/Annotation/HasManyThroughAttribute.cs +++ b/src/JsonApiDotNetCore/Models/Annotation/HasManyThroughAttribute.cs @@ -26,7 +26,7 @@ namespace JsonApiDotNetCore.Models /// public List<ArticleTag> ArticleTags { get; set; } /// /// - public class HasManyThroughAttribute : HasManyAttribute + public sealed class HasManyThroughAttribute : HasManyAttribute { /// /// Create a HasMany relationship through a many-to-many join relationship. @@ -132,7 +132,7 @@ public override void SetValue(object entity, object newValue) /// In the `[HasManyThrough("tags", nameof(ArticleTags))]` example /// this would be "ArticleTags". /// - public string InternalThroughName { get; private set; } + public string InternalThroughName { get; } /// /// The join type. diff --git a/src/JsonApiDotNetCore/Models/Annotation/HasOneAttribute.cs b/src/JsonApiDotNetCore/Models/Annotation/HasOneAttribute.cs index 183f5b46c3..7e7152f1e8 100644 --- a/src/JsonApiDotNetCore/Models/Annotation/HasOneAttribute.cs +++ b/src/JsonApiDotNetCore/Models/Annotation/HasOneAttribute.cs @@ -4,7 +4,7 @@ namespace JsonApiDotNetCore.Models { - public class HasOneAttribute : RelationshipAttribute + public sealed class HasOneAttribute : RelationshipAttribute { /// /// Create a HasOne relational link to another entity @@ -38,8 +38,8 @@ public HasOneAttribute(string publicName = null, Link links = Link.NotConfigured public override object GetValue(object entity) { - return entity?.GetType()? - .GetProperty(InternalRelationshipName)? + return entity?.GetType() + .GetProperty(InternalRelationshipName)? .GetValue(entity); } @@ -73,23 +73,5 @@ public override void SetValue(object entity, object newValue) } propertyInfo.SetValue(entity, newValue); } - - // HACK: this will likely require boxing - // we should be able to move some of the reflection into the ResourceGraphBuilder - /// - /// Gets the value of the independent identifier (e.g. Article.AuthorId) - /// - /// - /// - /// An instance of dependent resource - /// - /// - /// - /// The property value or null if the property does not exist on the model. - /// - internal object GetIdentifiablePropertyValue(object resource) => resource - .GetType() - .GetProperty(IdentifiablePropertyName) - ?.GetValue(resource); } } diff --git a/src/JsonApiDotNetCore/Models/Annotation/LinksAttribute.cs b/src/JsonApiDotNetCore/Models/Annotation/LinksAttribute.cs index 1c071723f1..b677769744 100644 --- a/src/JsonApiDotNetCore/Models/Annotation/LinksAttribute.cs +++ b/src/JsonApiDotNetCore/Models/Annotation/LinksAttribute.cs @@ -4,18 +4,18 @@ namespace JsonApiDotNetCore.Models.Links { [AttributeUsage(AttributeTargets.Class, Inherited = false)] - public class LinksAttribute : Attribute + public sealed class LinksAttribute : Attribute { public LinksAttribute(Link topLevelLinks = Link.NotConfigured, Link resourceLinks = Link.NotConfigured, Link relationshipLinks = Link.NotConfigured) { if (topLevelLinks == Link.Related) - throw new JsonApiSetupException($"{Link.Related.ToString("g")} not allowed for argument {nameof(topLevelLinks)}"); + throw new JsonApiSetupException($"{Link.Related:g} not allowed for argument {nameof(topLevelLinks)}"); if (resourceLinks == Link.Paging) - throw new JsonApiSetupException($"{Link.Paging.ToString("g")} not allowed for argument {nameof(resourceLinks)}"); + throw new JsonApiSetupException($"{Link.Paging:g} not allowed for argument {nameof(resourceLinks)}"); if (relationshipLinks == Link.Paging) - throw new JsonApiSetupException($"{Link.Paging.ToString("g")} not allowed for argument {nameof(relationshipLinks)}"); + throw new JsonApiSetupException($"{Link.Paging:g} not allowed for argument {nameof(relationshipLinks)}"); TopLevelLinks = topLevelLinks; ResourceLinks = resourceLinks; @@ -26,18 +26,18 @@ public LinksAttribute(Link topLevelLinks = Link.NotConfigured, Link resourceLink /// Configures which links to show in the /// object for this resource. /// - public Link TopLevelLinks { get; private set; } + public Link TopLevelLinks { get; } /// /// Configures which links to show in the /// object for this resource. /// - public Link ResourceLinks { get; private set; } + public Link ResourceLinks { get; } /// /// Configures which links to show in the /// for all relationships of the resource for which this attribute was instantiated. /// - public Link RelationshipLinks { get; private set; } + public Link RelationshipLinks { get; } } } diff --git a/src/JsonApiDotNetCore/Models/Annotation/RelationshipAttribute.cs b/src/JsonApiDotNetCore/Models/Annotation/RelationshipAttribute.cs index 00e348f8c0..a5b61cce62 100644 --- a/src/JsonApiDotNetCore/Models/Annotation/RelationshipAttribute.cs +++ b/src/JsonApiDotNetCore/Models/Annotation/RelationshipAttribute.cs @@ -10,7 +10,7 @@ public abstract class RelationshipAttribute : Attribute, IResourceField protected RelationshipAttribute(string publicName, Link relationshipLinks, bool canInclude) { if (relationshipLinks == Link.Paging) - throw new JsonApiSetupException($"{Link.Paging.ToString("g")} not allowed for argument {nameof(relationshipLinks)}"); + throw new JsonApiSetupException($"{Link.Paging:g} not allowed for argument {nameof(relationshipLinks)}"); PublicRelationshipName = publicName; RelationshipLinks = relationshipLinks; diff --git a/src/JsonApiDotNetCore/Models/JsonApiDocuments/Document.cs b/src/JsonApiDotNetCore/Models/JsonApiDocuments/Document.cs index 0b74574ee9..b42bb75766 100644 --- a/src/JsonApiDotNetCore/Models/JsonApiDocuments/Document.cs +++ b/src/JsonApiDotNetCore/Models/JsonApiDocuments/Document.cs @@ -7,7 +7,7 @@ namespace JsonApiDotNetCore.Models /// /// https://jsonapi.org/format/#document-structure /// - public class Document : ExposableData + public sealed class Document : ExposableData { /// /// see "meta" in https://jsonapi.org/format/#document-top-level diff --git a/src/JsonApiDotNetCore/Models/JsonApiDocuments/ExposableData.cs b/src/JsonApiDotNetCore/Models/JsonApiDocuments/ExposableData.cs index db4b634bd5..567f24e930 100644 --- a/src/JsonApiDotNetCore/Models/JsonApiDocuments/ExposableData.cs +++ b/src/JsonApiDotNetCore/Models/JsonApiDocuments/ExposableData.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; @@ -11,7 +11,11 @@ public class ExposableData where T : class /// see "primary data" in https://jsonapi.org/format/#document-top-level. /// [JsonProperty("data")] - public object Data { get { return GetPrimaryData(); } set { SetPrimaryData(value); } } + public object Data + { + get => GetPrimaryData(); + set => SetPrimaryData(value); + } /// /// see https://www.newtonsoft.com/json/help/html/ConditionalProperties.htm @@ -44,16 +48,16 @@ public bool ShouldSerializeData() /// Internally used to indicate if the document's primary data is /// "single" or "many". /// - internal bool IsManyData { get; private set; } = false; + internal bool IsManyData { get; private set; } /// /// Internally used to indicate if the document's primary data is /// should still be serialized when it's value is null. This is used when /// a single resource is requested but not present (eg /articles/1/author). /// - internal bool IsPopulated { get; private set; } = false; + internal bool IsPopulated { get; private set; } - internal bool HasResource { get { return IsPopulated && ((IsManyData && ManyData.Any()) || SingleData != null); } } + internal bool HasResource => IsPopulated && ((IsManyData && ManyData.Any()) || SingleData != null); /// /// Gets the "single" or "many" data depending on which one was diff --git a/src/JsonApiDotNetCore/Models/JsonApiDocuments/RelationshipEntry.cs b/src/JsonApiDotNetCore/Models/JsonApiDocuments/RelationshipEntry.cs index d0c718b721..5a19067f49 100644 --- a/src/JsonApiDotNetCore/Models/JsonApiDocuments/RelationshipEntry.cs +++ b/src/JsonApiDotNetCore/Models/JsonApiDocuments/RelationshipEntry.cs @@ -3,7 +3,7 @@ namespace JsonApiDotNetCore.Models { - public class RelationshipEntry : ExposableData + public sealed class RelationshipEntry : ExposableData { [JsonProperty("links", NullValueHandling = NullValueHandling.Ignore)] public RelationshipLinks Links { get; set; } diff --git a/src/JsonApiDotNetCore/Models/JsonApiDocuments/RelationshipLinks.cs b/src/JsonApiDotNetCore/Models/JsonApiDocuments/RelationshipLinks.cs index c728df6777..e8076af318 100644 --- a/src/JsonApiDotNetCore/Models/JsonApiDocuments/RelationshipLinks.cs +++ b/src/JsonApiDotNetCore/Models/JsonApiDocuments/RelationshipLinks.cs @@ -2,7 +2,7 @@ namespace JsonApiDotNetCore.Models.Links { - public class RelationshipLinks + public sealed class RelationshipLinks { /// /// see "links" bulletin at https://jsonapi.org/format/#document-resource-object-relationships diff --git a/src/JsonApiDotNetCore/Models/JsonApiDocuments/ResourceLinks.cs b/src/JsonApiDotNetCore/Models/JsonApiDocuments/ResourceLinks.cs index ea701f7681..0ff07ad7e5 100644 --- a/src/JsonApiDotNetCore/Models/JsonApiDocuments/ResourceLinks.cs +++ b/src/JsonApiDotNetCore/Models/JsonApiDocuments/ResourceLinks.cs @@ -1,8 +1,8 @@ -using Newtonsoft.Json; +using Newtonsoft.Json; namespace JsonApiDotNetCore.Models.Links { - public class ResourceLinks + public sealed class ResourceLinks { /// /// https://jsonapi.org/format/#document-resource-object-links @@ -10,4 +10,4 @@ public class ResourceLinks [JsonProperty("self", NullValueHandling = NullValueHandling.Ignore)] public string Self { get; set; } } -} \ No newline at end of file +} diff --git a/src/JsonApiDotNetCore/Models/JsonApiDocuments/ResourceObject.cs b/src/JsonApiDotNetCore/Models/JsonApiDocuments/ResourceObject.cs index 55dc096adb..e46525755b 100644 --- a/src/JsonApiDotNetCore/Models/JsonApiDocuments/ResourceObject.cs +++ b/src/JsonApiDotNetCore/Models/JsonApiDocuments/ResourceObject.cs @@ -4,7 +4,7 @@ namespace JsonApiDotNetCore.Models { - public class ResourceObject : ResourceIdentifierObject + public sealed class ResourceObject : ResourceIdentifierObject { [JsonProperty("attributes", NullValueHandling = NullValueHandling.Ignore)] public Dictionary Attributes { get; set; } diff --git a/src/JsonApiDotNetCore/Models/JsonApiDocuments/ResourceObjectComparer.cs b/src/JsonApiDotNetCore/Models/JsonApiDocuments/ResourceObjectComparer.cs index e7da59bb98..442a918687 100644 --- a/src/JsonApiDotNetCore/Models/JsonApiDocuments/ResourceObjectComparer.cs +++ b/src/JsonApiDotNetCore/Models/JsonApiDocuments/ResourceObjectComparer.cs @@ -1,9 +1,9 @@ -using System.Collections.Generic; +using System.Collections.Generic; using JsonApiDotNetCore.Models; namespace JsonApiDotNetCore.Builders { - class ResourceObjectComparer : IEqualityComparer + internal sealed class ResourceObjectComparer : IEqualityComparer { public bool Equals(ResourceObject x, ResourceObject y) { diff --git a/src/JsonApiDotNetCore/Models/JsonApiExtension.cs b/src/JsonApiDotNetCore/Models/JsonApiExtension.cs deleted file mode 100644 index 7d3b0c87ea..0000000000 --- a/src/JsonApiDotNetCore/Models/JsonApiExtension.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace JsonApiDotNetCore.Models -{ - public enum JsonApiExtension - { - Operations = 0 - } -} diff --git a/src/JsonApiDotNetCore/Models/ResourceAttribute.cs b/src/JsonApiDotNetCore/Models/ResourceAttribute.cs index 9f17883662..7b618ea654 100644 --- a/src/JsonApiDotNetCore/Models/ResourceAttribute.cs +++ b/src/JsonApiDotNetCore/Models/ResourceAttribute.cs @@ -2,13 +2,13 @@ namespace JsonApiDotNetCore.Models { - public class ResourceAttribute : Attribute + public sealed class ResourceAttribute : Attribute { public ResourceAttribute(string resourceName) { ResourceName = resourceName; } - public string ResourceName { get; set; } + public string ResourceName { get; } } } diff --git a/src/JsonApiDotNetCore/Models/ResourceDefinition.cs b/src/JsonApiDotNetCore/Models/ResourceDefinition.cs index 6983cba452..07a71edaf2 100644 --- a/src/JsonApiDotNetCore/Models/ResourceDefinition.cs +++ b/src/JsonApiDotNetCore/Models/ResourceDefinition.cs @@ -1,4 +1,3 @@ -using JsonApiDotNetCore.Internal; using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Internal.Query; using JsonApiDotNetCore.Hooks; @@ -26,19 +25,17 @@ public interface IResourceDefinition /// The resource type public class ResourceDefinition : IResourceDefinition, IResourceHookContainer where TResource : class, IIdentifiable { - private readonly ResourceContext _resourceContext; private readonly IResourceGraph _resourceGraph; private List _allowedAttributes; private List _allowedRelationships; public ResourceDefinition(IResourceGraph resourceGraph) { - _resourceContext = resourceGraph.GetResourceContext(typeof(TResource)); - _allowedAttributes = _resourceContext.Attributes; - _allowedRelationships = _resourceContext.Relationships; + var resourceContext = resourceGraph.GetResourceContext(typeof(TResource)); + _allowedAttributes = resourceContext.Attributes; + _allowedRelationships = resourceContext.Relationships; _resourceGraph = resourceGraph; } - public List GetAllowedRelationships() => _allowedRelationships; public List GetAllowedAttributes() => _allowedAttributes; @@ -130,7 +127,7 @@ public virtual void BeforeImplicitUpdateRelationship(IRelationshipsDictionary for usage details. /// - public class QueryFilters : Dictionary, FilterQuery, IQueryable>> { } + public sealed class QueryFilters : Dictionary, FilterQuery, IQueryable>> { } /// /// Define a the default sort order if no sort key is provided. @@ -169,6 +166,6 @@ public class QueryFilters : Dictionary, Filte /// method signature. /// See for usage details. /// - public class PropertySortOrder : List<(Expression>, SortDirection)> { } + public sealed class PropertySortOrder : List<(Expression>, SortDirection)> { } } } diff --git a/src/JsonApiDotNetCore/QueryParameterServices/Common/QueryParameterService.cs b/src/JsonApiDotNetCore/QueryParameterServices/Common/QueryParameterService.cs index cf363bef65..3bf99c7376 100644 --- a/src/JsonApiDotNetCore/QueryParameterServices/Common/QueryParameterService.cs +++ b/src/JsonApiDotNetCore/QueryParameterServices/Common/QueryParameterService.cs @@ -20,14 +20,9 @@ protected QueryParameterService(IResourceGraph resourceGraph, ICurrentRequest cu { _mainRequestResource = currentRequest.GetRequestResource(); _resourceGraph = resourceGraph; - if (currentRequest.RequestRelationship != null) - { - _requestResource= resourceGraph.GetResourceContext(currentRequest.RequestRelationship.RightType); - } - else - { - _requestResource = _mainRequestResource; - } + _requestResource = currentRequest.RequestRelationship != null + ? resourceGraph.GetResourceContext(currentRequest.RequestRelationship.RightType) + : _mainRequestResource; } protected QueryParameterService() { } @@ -40,7 +35,7 @@ protected QueryParameterService() { } /// `?include=some-relationship` /// public class IncludeService : QueryParameterService { /* ... */ } /// - public virtual string Name { get { return GetParameterNameFromType(); } } + public virtual string Name => GetParameterNameFromType(); /// /// Gets the query parameter name from the implementing class name. Trims "Service" @@ -53,11 +48,9 @@ protected QueryParameterService() { } /// protected AttrAttribute GetAttribute(string target, RelationshipAttribute relationship = null) { - AttrAttribute attribute; - if (relationship != null) - attribute = _resourceGraph.GetAttributes(relationship.RightType).FirstOrDefault(a => a.Is(target)); - else - attribute = _requestResource.Attributes.FirstOrDefault(attr => attr.Is(target)); + var attribute = relationship != null + ? _resourceGraph.GetAttributes(relationship.RightType).FirstOrDefault(a => a.Is(target)) + : _requestResource.Attributes.FirstOrDefault(attr => attr.Is(target)); if (attribute == null) throw new JsonApiException(400, $"'{target}' is not a valid attribute."); diff --git a/src/JsonApiDotNetCore/QueryParameterServices/Contracts/IPageService.cs b/src/JsonApiDotNetCore/QueryParameterServices/Contracts/IPageService.cs index ed840d5694..968ed85958 100644 --- a/src/JsonApiDotNetCore/QueryParameterServices/Contracts/IPageService.cs +++ b/src/JsonApiDotNetCore/QueryParameterServices/Contracts/IPageService.cs @@ -8,19 +8,11 @@ public interface IPageService : IQueryParameterService /// /// Gets the requested or default page size /// - int CurrentPageSize { get; } - /// - /// Default size to be used in pagination - /// - int DefaultPageSize { get; set; } - /// - /// Currently requested page size to be used in pagination - /// - int? RequestedPageSize { get; set; } + int PageSize { get; } /// /// The page requested. Note that the page number is one-based. /// - int CurrentPage { get; set; } + int CurrentPage { get; } /// /// Total amount of pages for request /// diff --git a/src/JsonApiDotNetCore/QueryParameterServices/FilterService.cs b/src/JsonApiDotNetCore/QueryParameterServices/FilterService.cs index bf921383ef..2a10a698c3 100644 --- a/src/JsonApiDotNetCore/QueryParameterServices/FilterService.cs +++ b/src/JsonApiDotNetCore/QueryParameterServices/FilterService.cs @@ -14,7 +14,7 @@ namespace JsonApiDotNetCore.Query public class FilterService : QueryParameterService, IFilterService { private readonly List _filters; - private IResourceDefinition _requestResourceDefinition; + private readonly IResourceDefinition _requestResourceDefinition; public FilterService(IResourceDefinitionProvider resourceDefinitionProvider, IResourceGraph resourceGraph, ICurrentRequest currentRequest) : base(resourceGraph, currentRequest) { @@ -39,15 +39,12 @@ public virtual void Parse(KeyValuePair queryParameter) private FilterQueryContext GetQueryContexts(FilterQuery query) { var queryContext = new FilterQueryContext(query); - if (_requestResourceDefinition != null) + var customQuery = _requestResourceDefinition?.GetCustomQueryFilter(query.Target); + if (customQuery != null) { - var customQuery = _requestResourceDefinition.GetCustomQueryFilter(query.Target); - if (customQuery != null) - { - queryContext.IsCustom = true; - queryContext.CustomQuery = customQuery; - return queryContext; - } + queryContext.IsCustom = true; + queryContext.CustomQuery = customQuery; + return queryContext; } queryContext.Relationship = GetRelationship(query.Relationship); @@ -72,7 +69,7 @@ private List GetFilterQueries(KeyValuePair qu if (string.Equals(op, FilterOperation.@in.ToString(), StringComparison.OrdinalIgnoreCase) || string.Equals(op, FilterOperation.nin.ToString(), StringComparison.OrdinalIgnoreCase)) { - (var _, var filterValue) = ParseFilterOperation(queryParameter.Value); + var (_, filterValue) = ParseFilterOperation(queryParameter.Value); queries.Add(new FilterQuery(propertyName, filterValue, op)); } else @@ -80,7 +77,7 @@ private List GetFilterQueries(KeyValuePair qu var values = ((string)queryParameter.Value).Split(QueryConstants.COMMA); foreach (var val in values) { - (var operation, var filterValue) = ParseFilterOperation(val); + var (operation, filterValue) = ParseFilterOperation(val); queries.Add(new FilterQuery(propertyName, filterValue, operation)); } } @@ -114,7 +111,7 @@ private string GetFilterOperation(string value) var operation = values[0]; // remove prefix from value - if (Enum.TryParse(operation, out FilterOperation op) == false) + if (Enum.TryParse(operation, out FilterOperation _) == false) return string.Empty; return operation; diff --git a/src/JsonApiDotNetCore/QueryParameterServices/PageService.cs b/src/JsonApiDotNetCore/QueryParameterServices/PageService.cs index 95179d85b0..d7da6292ae 100644 --- a/src/JsonApiDotNetCore/QueryParameterServices/PageService.cs +++ b/src/JsonApiDotNetCore/QueryParameterServices/PageService.cs @@ -29,7 +29,7 @@ internal PageService(IJsonApiOptions options) } /// - public int CurrentPageSize + public int PageSize { get { @@ -54,10 +54,10 @@ public int CurrentPageSize public bool Backwards { get; set; } /// - public int TotalPages => (TotalRecords == null || CurrentPageSize == 0) ? -1 : (int)Math.Ceiling(decimal.Divide(TotalRecords.Value, CurrentPageSize)); + public int TotalPages => (TotalRecords == null || PageSize == 0) ? -1 : (int)Math.Ceiling(decimal.Divide(TotalRecords.Value, PageSize)); /// - public bool CanPaginate { get { return TotalPages > 1; } } + public bool CanPaginate => TotalPages > 1; /// public int? TotalRecords { get; set; } diff --git a/src/JsonApiDotNetCore/QueryParameterServices/SortService.cs b/src/JsonApiDotNetCore/QueryParameterServices/SortService.cs index 6373f92ac4..fe136993eb 100644 --- a/src/JsonApiDotNetCore/QueryParameterServices/SortService.cs +++ b/src/JsonApiDotNetCore/QueryParameterServices/SortService.cs @@ -11,7 +11,7 @@ namespace JsonApiDotNetCore.Query /// public class SortService : QueryParameterService, ISortService { - const char DESCENDING_SORT_OPERATOR = '-'; + private const char DESCENDING_SORT_OPERATOR = '-'; private readonly IResourceDefinitionProvider _resourceDefinitionProvider; private List _queries; diff --git a/src/JsonApiDotNetCore/QueryParameterServices/SparseFieldsService.cs b/src/JsonApiDotNetCore/QueryParameterServices/SparseFieldsService.cs index c56319fe93..db6691923b 100644 --- a/src/JsonApiDotNetCore/QueryParameterServices/SparseFieldsService.cs +++ b/src/JsonApiDotNetCore/QueryParameterServices/SparseFieldsService.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using JsonApiDotNetCore.Internal; @@ -51,7 +50,7 @@ public virtual void Parse(KeyValuePair queryParameter) var keySplit = queryParameter.Key.Split(QueryConstants.OPEN_BRACKET, QueryConstants.CLOSE_BRACKET); - if (keySplit.Count() == 1) + if (keySplit.Length == 1) { // input format: fields=prop1,prop2 foreach (var field in fields) RegisterRequestResourceField(field); @@ -64,8 +63,8 @@ public virtual void Parse(KeyValuePair queryParameter) // if not, no longer support this type of sparse field selection. if (navigation == _requestResource.ResourceName && !_requestResource.Relationships.Any(a => a.Is(navigation))) throw new JsonApiException(400, $"Use '?fields=...' instead of 'fields[{navigation}]':" + - $" the square bracket navigations is now reserved " + - $"for relationships only. See https://github.com/json-api-dotnet/JsonApiDotNetCore/issues/555#issuecomment-543100865"); + " the square bracket navigations is now reserved " + + "for relationships only. See https://github.com/json-api-dotnet/JsonApiDotNetCore/issues/555#issuecomment-543100865"); if (navigation.Contains(QueryConstants.DOT)) throw new JsonApiException(400, $"fields[{navigation}] is not valid: deeply nested sparse field selection is not yet supported."); @@ -103,7 +102,7 @@ private void RegisterRequestResourceField(string field) if (attr == null) throw new JsonApiException(400, $"'{_requestResource.ResourceName}' does not contain '{field}'."); - (_selectedFields = _selectedFields ?? new List()).Add(attr); + (_selectedFields ??= new List()).Add(attr); } } } diff --git a/src/JsonApiDotNetCore/RequestServices/CurrentRequest.cs b/src/JsonApiDotNetCore/RequestServices/CurrentRequest.cs index 053cf39cfb..a5bbc31a1b 100644 --- a/src/JsonApiDotNetCore/RequestServices/CurrentRequest.cs +++ b/src/JsonApiDotNetCore/RequestServices/CurrentRequest.cs @@ -4,7 +4,7 @@ namespace JsonApiDotNetCore.Managers { - class CurrentRequest : ICurrentRequest + internal sealed class CurrentRequest : ICurrentRequest { private ResourceContext _resourceContext; public string BasePath { get; set; } diff --git a/src/JsonApiDotNetCore/RequestServices/TargetedFields.cs b/src/JsonApiDotNetCore/RequestServices/TargetedFields.cs index b5a4ee18d8..d5e3d2919a 100644 --- a/src/JsonApiDotNetCore/RequestServices/TargetedFields.cs +++ b/src/JsonApiDotNetCore/RequestServices/TargetedFields.cs @@ -1,10 +1,10 @@ -using System.Collections.Generic; +using System.Collections.Generic; using JsonApiDotNetCore.Models; namespace JsonApiDotNetCore.Serialization { /// - public class TargetedFields : ITargetedFields + public sealed class TargetedFields : ITargetedFields { /// public List Attributes { get; set; } = new List(); diff --git a/src/JsonApiDotNetCore/Serialization/Client/DeserializedResponse.cs b/src/JsonApiDotNetCore/Serialization/Client/DeserializedResponse.cs index 179e62a34f..6bae9a9370 100644 --- a/src/JsonApiDotNetCore/Serialization/Client/DeserializedResponse.cs +++ b/src/JsonApiDotNetCore/Serialization/Client/DeserializedResponse.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Models.Links; @@ -21,7 +20,7 @@ public abstract class DeserializedResponseBase /// Represents a deserialized document with "single data". /// /// Type of the resource in the primary data - public class DeserializedSingleResponse : DeserializedResponseBase where TResource : class, IIdentifiable + public sealed class DeserializedSingleResponse : DeserializedResponseBase where TResource : class, IIdentifiable { public TResource Data { get; set; } } @@ -30,7 +29,7 @@ public class DeserializedSingleResponse : DeserializedResponseBase wh /// Represents a deserialized document with "many data". /// /// Type of the resource(s) in the primary data - public class DeserializedListResponse : DeserializedResponseBase where TResource : class, IIdentifiable + public sealed class DeserializedListResponse : DeserializedResponseBase where TResource : class, IIdentifiable { public List Data { get; set; } } diff --git a/src/JsonApiDotNetCore/Serialization/Client/IRequestSerializer.cs b/src/JsonApiDotNetCore/Serialization/Client/IRequestSerializer.cs index 39dbc5f805..f90e7c041a 100644 --- a/src/JsonApiDotNetCore/Serialization/Client/IRequestSerializer.cs +++ b/src/JsonApiDotNetCore/Serialization/Client/IRequestSerializer.cs @@ -1,6 +1,5 @@ using System.Collections; using System.Collections.Generic; -using System.Linq.Expressions; using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Internal.Contracts; @@ -26,13 +25,13 @@ public interface IRequestSerializer string Serialize(IEnumerable entities); /// /// Sets the attributes that will be included in the serialized payload. - /// You can use + /// You can use /// to conveniently access the desired instances /// public IEnumerable AttributesToSerialize { set; } /// /// Sets the relationships that will be included in the serialized payload. - /// You can use + /// You can use /// to conveniently access the desired instances /// public IEnumerable RelationshipsToSerialize { set; } diff --git a/src/JsonApiDotNetCore/Serialization/Client/RequestSerializer.cs b/src/JsonApiDotNetCore/Serialization/Client/RequestSerializer.cs index 21815794f2..94fd06cb39 100644 --- a/src/JsonApiDotNetCore/Serialization/Client/RequestSerializer.cs +++ b/src/JsonApiDotNetCore/Serialization/Client/RequestSerializer.cs @@ -27,9 +27,9 @@ public RequestSerializer(IResourceGraph resourceGraph, public string Serialize(IIdentifiable entity) { if (entity == null) - return JsonConvert.SerializeObject(Build(entity, new List(), new List())); + return JsonConvert.SerializeObject(Build((IIdentifiable) null, new List(), new List())); - _currentTargetedResource = entity?.GetType(); + _currentTargetedResource = entity.GetType(); var document = Build(entity, GetAttributesToSerialize(entity), GetRelationshipsToSerialize(entity)); _currentTargetedResource = null; return JsonConvert.SerializeObject(document); @@ -47,10 +47,10 @@ public string Serialize(IEnumerable entities) if (entity == null) return JsonConvert.SerializeObject(Build(entities, new List(), new List())); - _currentTargetedResource = entity?.GetType(); + _currentTargetedResource = entity.GetType(); var attributes = GetAttributesToSerialize(entity); var relationships = GetRelationshipsToSerialize(entity); - var document = base.Build(entities, attributes, relationships); + var document = Build(entities, attributes, relationships); _currentTargetedResource = null; return JsonConvert.SerializeObject(document); } diff --git a/src/JsonApiDotNetCore/Serialization/Client/ResponseDeserializer.cs b/src/JsonApiDotNetCore/Serialization/Client/ResponseDeserializer.cs index 38ed9dd1f0..57f1c74ca9 100644 --- a/src/JsonApiDotNetCore/Serialization/Client/ResponseDeserializer.cs +++ b/src/JsonApiDotNetCore/Serialization/Client/ResponseDeserializer.cs @@ -18,12 +18,12 @@ public ResponseDeserializer(IResourceContextProvider provider) : base(provider) /// public DeserializedSingleResponse DeserializeSingle(string body) where TResource : class, IIdentifiable { - var entity = base.Deserialize(body); - return new DeserializedSingleResponse() + var entity = Deserialize(body); + return new DeserializedSingleResponse { Links = _document.Links, Meta = _document.Meta, - Data = entity == null ? null : (TResource)entity, + Data = (TResource) entity, JsonApi = null, Errors = null }; @@ -32,12 +32,12 @@ public DeserializedSingleResponse DeserializeSingle(string /// public DeserializedListResponse DeserializeList(string body) where TResource : class, IIdentifiable { - var entities = base.Deserialize(body); - return new DeserializedListResponse() + var entities = Deserialize(body); + return new DeserializedListResponse { Links = _document.Links, Meta = _document.Meta, - Data = entities == null ? null : ((List)entities).Cast().ToList(), + Data = ((List) entities)?.Cast().ToList(), JsonApi = null, Errors = null }; @@ -62,12 +62,10 @@ protected override void AfterProcessField(IIdentifiable entity, IResourceField f return; if (field is HasOneAttribute hasOneAttr) - { // add attributes and relationships of a parsed HasOne relationship + { + // add attributes and relationships of a parsed HasOne relationship var rio = data.SingleData; - if (rio == null) - hasOneAttr.SetValue(entity, null); - else - hasOneAttr.SetValue(entity, ParseIncludedRelationship(hasOneAttr, rio)); + hasOneAttr.SetValue(entity, rio == null ? null : ParseIncludedRelationship(hasOneAttr, rio)); } else if (field is HasManyAttribute hasManyAttr) { // add attributes and relationships of a parsed HasMany relationship @@ -108,7 +106,7 @@ private ResourceObject GetLinkedResource(ResourceIdentifierObject relatedResourc } catch (InvalidOperationException e) { - throw new InvalidOperationException($"A compound document MUST NOT include more than one resource object for each type and id pair." + 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); } } diff --git a/src/JsonApiDotNetCore/Serialization/Common/BaseDocumentParser.cs b/src/JsonApiDotNetCore/Serialization/Common/BaseDocumentParser.cs index 62cbf096c7..2ab3e47655 100644 --- a/src/JsonApiDotNetCore/Serialization/Common/BaseDocumentParser.cs +++ b/src/JsonApiDotNetCore/Serialization/Common/BaseDocumentParser.cs @@ -101,8 +101,8 @@ protected IIdentifiable SetRelationships(IIdentifiable entity, Dictionary /// /// - /// - private object SetHasOneRelationship(IIdentifiable entity, + private void SetHasOneRelationship(IIdentifiable entity, PropertyInfo[] entityProperties, HasOneAttribute attr, RelationshipEntry relationshipData) { var rio = (ResourceIdentifierObject)relationshipData.Data; - var relatedId = rio?.Id ?? null; + var relatedId = rio?.Id; // this does not make sense in the following case: if we're setting the dependent of a one-to-one relationship, IdentifiablePropertyName should be null. var foreignKeyProperty = entityProperties.FirstOrDefault(p => p.Name == attr.IdentifiablePropertyName); @@ -181,8 +180,6 @@ private object SetHasOneRelationship(IIdentifiable entity, // depending on if this base parser is used client-side or server-side, // different additional processing per field needs to be executed. AfterProcessField(entity, attr, relationshipData); - - return entity; } /// @@ -224,9 +221,10 @@ private void SetNavigation(IIdentifiable entity, HasOneAttribute attr, string re /// /// Sets a HasMany relationship. /// - private object SetHasManyRelationship(IIdentifiable entity, - HasManyAttribute attr, - RelationshipEntry relationshipData) + private void SetHasManyRelationship( + IIdentifiable entity, + HasManyAttribute attr, + RelationshipEntry relationshipData) { if (relationshipData.Data != null) { // if the relationship is set to null, no need to set the navigation property to null: this is the default value. @@ -241,8 +239,6 @@ private object SetHasManyRelationship(IIdentifiable entity, } AfterProcessField(entity, attr, relationshipData); - - return entity; } private object ConvertAttrValue(object newValue, Type targetType) diff --git a/src/JsonApiDotNetCore/Serialization/Common/DocumentBuilder.cs b/src/JsonApiDotNetCore/Serialization/Common/DocumentBuilder.cs index 2e4a2444f4..9f31e18e2c 100644 --- a/src/JsonApiDotNetCore/Serialization/Common/DocumentBuilder.cs +++ b/src/JsonApiDotNetCore/Serialization/Common/DocumentBuilder.cs @@ -1,6 +1,5 @@ using System.Collections; using System.Collections.Generic; -using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Models; namespace JsonApiDotNetCore.Serialization diff --git a/src/JsonApiDotNetCore/Serialization/Common/ResourceObjectBuilder.cs b/src/JsonApiDotNetCore/Serialization/Common/ResourceObjectBuilder.cs index 21aa663844..d62434b8df 100644 --- a/src/JsonApiDotNetCore/Serialization/Common/ResourceObjectBuilder.cs +++ b/src/JsonApiDotNetCore/Serialization/Common/ResourceObjectBuilder.cs @@ -127,7 +127,7 @@ private void ProcessRelationships(IIdentifiable entity, IEnumerable()).Add(rel.PublicRelationshipName, relData); + (ro.Relationships ??= new Dictionary()).Add(rel.PublicRelationshipName, relData); } } diff --git a/src/JsonApiDotNetCore/Serialization/Common/ResourceObjectBuilderSettings.cs b/src/JsonApiDotNetCore/Serialization/Common/ResourceObjectBuilderSettings.cs index e64578e333..2e84b7988e 100644 --- a/src/JsonApiDotNetCore/Serialization/Common/ResourceObjectBuilderSettings.cs +++ b/src/JsonApiDotNetCore/Serialization/Common/ResourceObjectBuilderSettings.cs @@ -6,7 +6,7 @@ namespace JsonApiDotNetCore.Serialization /// Options used to configure how fields of a model get serialized into /// a json:api . /// - public class ResourceObjectBuilderSettings + public sealed class ResourceObjectBuilderSettings { /// Omit null values from attributes /// Omit default values from attributes diff --git a/src/JsonApiDotNetCore/Serialization/Server/Builders/LinkBuilder.cs b/src/JsonApiDotNetCore/Serialization/Server/Builders/LinkBuilder.cs index 5d81048988..cf0aea0d36 100644 --- a/src/JsonApiDotNetCore/Serialization/Server/Builders/LinkBuilder.cs +++ b/src/JsonApiDotNetCore/Serialization/Server/Builders/LinkBuilder.cs @@ -65,19 +65,19 @@ private void SetPageLinks(ResourceContext resourceContext, TopLevelLinks links) { if (_pageService.CurrentPage > 1) { - links.Prev = GetPageLink(resourceContext, _pageService.CurrentPage - 1, _pageService.CurrentPageSize); + links.Prev = GetPageLink(resourceContext, _pageService.CurrentPage - 1, _pageService.PageSize); } if (_pageService.CurrentPage < _pageService.TotalPages) { - links.Next = GetPageLink(resourceContext, _pageService.CurrentPage + 1, _pageService.CurrentPageSize); + links.Next = GetPageLink(resourceContext, _pageService.CurrentPage + 1, _pageService.PageSize); } if (_pageService.TotalPages > 0) { - links.Self = GetPageLink(resourceContext, _pageService.CurrentPage, _pageService.CurrentPageSize); - links.First = GetPageLink(resourceContext, 1, _pageService.CurrentPageSize); - links.Last = GetPageLink(resourceContext, _pageService.TotalPages, _pageService.CurrentPageSize); + links.Self = GetPageLink(resourceContext, _pageService.CurrentPage, _pageService.PageSize); + links.First = GetPageLink(resourceContext, 1, _pageService.PageSize); + links.Last = GetPageLink(resourceContext, _pageService.TotalPages, _pageService.PageSize); } } @@ -140,7 +140,7 @@ public RelationshipLinks GetRelationshipLinks(RelationshipAttribute relationship if (ShouldAddRelationshipLink(parentResourceContext, relationship, Link.Self)) { - links = links ?? new RelationshipLinks(); + links ??= new RelationshipLinks(); links.Self = GetSelfRelationshipLink(parentResourceContext.ResourceName, parent.StringId, childNavigation); } diff --git a/src/JsonApiDotNetCore/Serialization/Server/Builders/ResponseResourceObjectBuilder.cs b/src/JsonApiDotNetCore/Serialization/Server/Builders/ResponseResourceObjectBuilder.cs index 2291610391..7f0b25d09f 100644 --- a/src/JsonApiDotNetCore/Serialization/Server/Builders/ResponseResourceObjectBuilder.cs +++ b/src/JsonApiDotNetCore/Serialization/Server/Builders/ResponseResourceObjectBuilder.cs @@ -7,7 +7,7 @@ namespace JsonApiDotNetCore.Serialization.Server { - public class ResponseResourceObjectBuilder : ResourceObjectBuilder, IResourceObjectBuilder + public class ResponseResourceObjectBuilder : ResourceObjectBuilder { private readonly IIncludedResourceObjectBuilder _includedBuilder; private readonly IIncludeService _includeService; @@ -43,7 +43,7 @@ protected override RelationshipEntry GetRelationshipData(RelationshipAttribute r { RelationshipEntry relationshipEntry = null; List> relationshipChains = null; - if (relationship == _requestRelationship || ShouldInclude(relationship, out relationshipChains )) + if (Equals(relationship, _requestRelationship) || ShouldInclude(relationship, out relationshipChains )) { relationshipEntry = base.GetRelationshipData(relationship, entity); if (relationshipChains != null && relationshipEntry.HasResource) @@ -55,7 +55,7 @@ protected override RelationshipEntry GetRelationshipData(RelationshipAttribute r var links = _linkBuilder.GetRelationshipLinks(relationship, entity); if (links != null) // if links relationshipLinks should be built for this entry, populate the "links" field. - (relationshipEntry = relationshipEntry ?? new RelationshipEntry()).Links = links; + (relationshipEntry ??= new RelationshipEntry()).Links = links; // if neither "links" nor "data" was popupated, return null, which will omit this entry from the output. // (see the NullValueHandling settings on ) diff --git a/src/JsonApiDotNetCore/Serialization/Server/Contracts/IJsonApiSerializer.cs b/src/JsonApiDotNetCore/Serialization/Server/Contracts/IJsonApiSerializer.cs index 46281e1e85..6d056940c0 100644 --- a/src/JsonApiDotNetCore/Serialization/Server/Contracts/IJsonApiSerializer.cs +++ b/src/JsonApiDotNetCore/Serialization/Server/Contracts/IJsonApiSerializer.cs @@ -1,6 +1,4 @@ -using JsonApiDotNetCore.Models; - -namespace JsonApiDotNetCore.Serialization.Server +namespace JsonApiDotNetCore.Serialization.Server { /// /// Serializer used internally in JsonApiDotNetCore to serialize responses. diff --git a/src/JsonApiDotNetCore/Serialization/Server/Contracts/IJsonApiSerializerFactory.cs b/src/JsonApiDotNetCore/Serialization/Server/Contracts/IJsonApiSerializerFactory.cs index ab9502e666..def323437a 100644 --- a/src/JsonApiDotNetCore/Serialization/Server/Contracts/IJsonApiSerializerFactory.cs +++ b/src/JsonApiDotNetCore/Serialization/Server/Contracts/IJsonApiSerializerFactory.cs @@ -1,6 +1,4 @@ -using System; - -namespace JsonApiDotNetCore.Serialization.Server +namespace JsonApiDotNetCore.Serialization.Server { public interface IJsonApiSerializerFactory { diff --git a/src/JsonApiDotNetCore/Serialization/Server/ResourceObjectBuilderSettingsProvider.cs b/src/JsonApiDotNetCore/Serialization/Server/ResourceObjectBuilderSettingsProvider.cs index 9e4541c201..eaddf81891 100644 --- a/src/JsonApiDotNetCore/Serialization/Server/ResourceObjectBuilderSettingsProvider.cs +++ b/src/JsonApiDotNetCore/Serialization/Server/ResourceObjectBuilderSettingsProvider.cs @@ -7,7 +7,7 @@ namespace JsonApiDotNetCore.Serialization.Server /// This implementation of the behaviour provider reads the query params that /// can, if provided, override the settings in . /// - public class ResourceObjectBuilderSettingsProvider : IResourceObjectBuilderSettingsProvider + public sealed class ResourceObjectBuilderSettingsProvider : IResourceObjectBuilderSettingsProvider { private readonly IOmitDefaultService _defaultAttributeValues; private readonly IOmitNullService _nullAttributeValues; diff --git a/src/JsonApiDotNetCore/Serialization/Server/ResponseSerializer.cs b/src/JsonApiDotNetCore/Serialization/Server/ResponseSerializer.cs index 4c86f29e2e..cca8487f15 100644 --- a/src/JsonApiDotNetCore/Serialization/Server/ResponseSerializer.cs +++ b/src/JsonApiDotNetCore/Serialization/Server/ResponseSerializer.cs @@ -1,9 +1,7 @@ -using System; +using System; using System.Collections; using System.Collections.Generic; -using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Models; -using JsonApiDotNetCore.Query; using Newtonsoft.Json; using JsonApiDotNetCore.Managers.Contracts; using JsonApiDotNetCore.Serialization.Server.Builders; diff --git a/src/JsonApiDotNetCore/Services/Contract/IUpdateRelationshipService.cs b/src/JsonApiDotNetCore/Services/Contract/IUpdateRelationshipService.cs index 188e827701..44b45222f4 100644 --- a/src/JsonApiDotNetCore/Services/Contract/IUpdateRelationshipService.cs +++ b/src/JsonApiDotNetCore/Services/Contract/IUpdateRelationshipService.cs @@ -1,4 +1,3 @@ -using System.Collections.Generic; using System.Threading.Tasks; using JsonApiDotNetCore.Models; diff --git a/src/JsonApiDotNetCore/Services/DefaultResourceService.cs b/src/JsonApiDotNetCore/Services/DefaultResourceService.cs index d7eaed4001..d1c7c1553a 100644 --- a/src/JsonApiDotNetCore/Services/DefaultResourceService.cs +++ b/src/JsonApiDotNetCore/Services/DefaultResourceService.cs @@ -178,7 +178,7 @@ public virtual async Task UpdateAsync(TId id, TResource entity) public virtual async Task UpdateRelationshipsAsync(TId id, string relationshipName, object related) { var relationship = GetRelationship(relationshipName); - var entityQuery = _repository.Include(_repository.Get(id), new RelationshipAttribute[] { relationship }); + var entityQuery = _repository.Include(_repository.Get(id), new[] { relationship }); var entity = await _repository.FirstOrDefaultAsync(entityQuery); if (entity == null) throw new JsonApiException(404, $"Entity with id {id} could not be found."); @@ -188,10 +188,9 @@ public virtual async Task UpdateRelationshipsAsync(TId id, string relationshipNa string[] relationshipIds = null; if (related != null) { - if (relationship is HasOneAttribute) - relationshipIds = new string[] { ((IIdentifiable)related).StringId }; - else - relationshipIds = ((IEnumerable)related).Select(e => e.StringId).ToArray(); + relationshipIds = relationship is HasOneAttribute + ? new[] {((IIdentifiable) related).StringId} + : ((IEnumerable) related).Select(e => e.StringId).ToArray(); } await _repository.UpdateRelationshipsAsync(entity, relationship, relationshipIds ?? new string[0] ); @@ -201,10 +200,9 @@ public virtual async Task UpdateRelationshipsAsync(TId id, string relationshipNa protected virtual async Task> ApplyPageQueryAsync(IQueryable entities) { - if (!(_pageService.CurrentPageSize > 0)) + if (!(_pageService.PageSize > 0)) { - var allEntities = await _repository.ToListAsync(entities); - return allEntities as IEnumerable; + return await _repository.ToListAsync(entities); } int pageOffset = _pageService.CurrentPage; @@ -214,9 +212,9 @@ protected virtual async Task> ApplyPageQueryAsync(IQuerya } _logger.LogInformation($"Applying paging query. Fetching page {pageOffset} " + - $"with {_pageService.CurrentPageSize} entities"); + $"with {_pageService.PageSize} entities"); - return await _repository.PageAsync(entities, _pageService.CurrentPageSize, pageOffset); + return await _repository.PageAsync(entities, _pageService.PageSize, pageOffset); } /// diff --git a/src/JsonApiDotNetCore/Services/ResourceDefinitionProvider.cs b/src/JsonApiDotNetCore/Services/ResourceDefinitionProvider.cs index 5a9e4b655c..32005a984d 100644 --- a/src/JsonApiDotNetCore/Services/ResourceDefinitionProvider.cs +++ b/src/JsonApiDotNetCore/Services/ResourceDefinitionProvider.cs @@ -1,4 +1,4 @@ -using System; +using System; using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Services; @@ -6,7 +6,7 @@ namespace JsonApiDotNetCore.Query { /// - internal class ResourceDefinitionProvider : IResourceDefinitionProvider + internal sealed class ResourceDefinitionProvider : IResourceDefinitionProvider { private readonly IResourceGraph _resourceContextProvider; private readonly IScopedServiceProvider _serviceProvider; diff --git a/src/JsonApiDotNetCore/Services/ScopedServiceProvider.cs b/src/JsonApiDotNetCore/Services/ScopedServiceProvider.cs index 51248f7593..975c87029c 100644 --- a/src/JsonApiDotNetCore/Services/ScopedServiceProvider.cs +++ b/src/JsonApiDotNetCore/Services/ScopedServiceProvider.cs @@ -14,7 +14,7 @@ public interface IScopedServiceProvider : IServiceProvider { } /// /// A service provider that uses the current HttpContext request scope /// - public class RequestScopedServiceProvider : IScopedServiceProvider + public sealed class RequestScopedServiceProvider : IScopedServiceProvider { private readonly IHttpContextAccessor _httpContextAccessor; diff --git a/test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs b/test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs index c4a7ba4644..9a62c99457 100644 --- a/test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs +++ b/test/DiscoveryTests/ServiceDiscoveryFacadeTests.cs @@ -22,14 +22,13 @@ namespace DiscoveryTests { - public class ServiceDiscoveryFacadeTests + public sealed class ServiceDiscoveryFacadeTests { private readonly IServiceCollection _services = new ServiceCollection(); private readonly ResourceGraphBuilder _resourceGraphBuilder = new ResourceGraphBuilder(); public ServiceDiscoveryFacadeTests() { - var contextMock = new Mock(); var dbResolverMock = new Mock(); dbResolverMock.Setup(m => m.GetContext()).Returns(new Mock().Object); TestModelRepository._dbContextResolver = dbResolverMock.Object; @@ -43,13 +42,13 @@ public ServiceDiscoveryFacadeTests() _services.AddScoped((_) => new Mock().Object); } - private ServiceDiscoveryFacade _facade => new ServiceDiscoveryFacade(_services, _resourceGraphBuilder); + private ServiceDiscoveryFacade Facade => new ServiceDiscoveryFacade(_services, _resourceGraphBuilder); [Fact] public void AddAssembly_Adds_All_Resources_To_Graph() { // Arrange, act - _facade.AddAssembly(typeof(Person).Assembly); + Facade.AddAssembly(typeof(Person).Assembly); // Assert var resourceGraph = _resourceGraphBuilder.Build(); @@ -66,7 +65,7 @@ public void AddAssembly_Adds_All_Resources_To_Graph() public void AddCurrentAssembly_Adds_Resources_To_Graph() { // Arrange, act - _facade.AddCurrentAssembly(); + Facade.AddCurrentAssembly(); // Assert var resourceGraph = _resourceGraphBuilder.Build(); @@ -78,7 +77,7 @@ public void AddCurrentAssembly_Adds_Resources_To_Graph() public void AddCurrentAssembly_Adds_Services_To_Container() { // Arrange, act - _facade.AddCurrentAssembly(); + Facade.AddCurrentAssembly(); // Assert var services = _services.BuildServiceProvider(); @@ -90,19 +89,17 @@ public void AddCurrentAssembly_Adds_Services_To_Container() public void AddCurrentAssembly_Adds_Repositories_To_Container() { // Arrange, act - _facade.AddCurrentAssembly(); + Facade.AddCurrentAssembly(); // Assert var services = _services.BuildServiceProvider(); Assert.IsType(services.GetService>()); } - public class TestModel : Identifiable { } + public sealed class TestModel : Identifiable { } public class TestModelService : DefaultResourceService { - private static IResourceRepository _repo = new Mock>().Object; - public TestModelService( IEnumerable queryParameters, IJsonApiOptions options, diff --git a/test/IntegrationTests/Data/EntityRepositoryTests.cs b/test/IntegrationTests/Data/EntityRepositoryTests.cs index 35dbbe878c..033cd3a399 100644 --- a/test/IntegrationTests/Data/EntityRepositoryTests.cs +++ b/test/IntegrationTests/Data/EntityRepositoryTests.cs @@ -15,7 +15,7 @@ namespace JADNC.IntegrationTests.Data { - public class EntityRepositoryTests + public sealed class EntityRepositoryTests { [Fact] public async Task UpdateAsync_AttributesUpdated_ShouldHaveSpecificallyThoseAttributesUpdated() @@ -23,7 +23,7 @@ public async Task UpdateAsync_AttributesUpdated_ShouldHaveSpecificallyThoseAttri // Arrange var itemId = 213; var seed = Guid.NewGuid(); - using (var arrangeContext = GetContext(seed)) + await using (var arrangeContext = GetContext(seed)) { var (repository, targetedFields) = Setup(arrangeContext); var todoItemUpdates = new TodoItem @@ -42,13 +42,13 @@ public async Task UpdateAsync_AttributesUpdated_ShouldHaveSpecificallyThoseAttri targetedFields.Setup(m => m.Relationships).Returns(new List()); // Act - var updatedItem = await repository.UpdateAsync(todoItemUpdates); + await repository.UpdateAsync(todoItemUpdates); } // Assert - in different context - using var assertContext = GetContext(seed); + await using var assertContext = GetContext(seed); { - var (repository, targetedFields) = Setup(assertContext); + var (repository, _) = Setup(assertContext); var fetchedTodo = repository.Get(itemId).First(); Assert.NotNull(fetchedTodo); @@ -65,9 +65,9 @@ public async Task UpdateAsync_AttributesUpdated_ShouldHaveSpecificallyThoseAttri public async Task Paging_PageNumberIsPositive_ReturnCorrectIdsAtTheFront(int pageSize, int pageNumber, int[] expectedResult) { // Arrange - using var context = GetContext(); - var (repository, targetedFields) = Setup(context); - context.AddRange(TodoItems(1, 2, 3, 4, 5, 6, 7, 8, 9)); + await using var context = GetContext(); + var (repository, _) = Setup(context); + context.AddRange(TodoItems(1, 2, 3, 4, 5, 6, 7, 8, 9).Cast()); await context.SaveChangesAsync(); // Act @@ -84,10 +84,10 @@ public async Task Paging_PageNumberIsPositive_ReturnCorrectIdsAtTheFront(int pag public async Task Paging_PageSizeNonPositive_DoNothing(int pageSize) { // Arrange - using var context = GetContext(); - var (repository, targetedFields) = Setup(context); + await using var context = GetContext(); + var (repository, _) = Setup(context); var items = TodoItems(2, 3, 1); - context.AddRange(items); + context.AddRange(items.Cast()); await context.SaveChangesAsync(); // Act @@ -102,9 +102,9 @@ public async Task Paging_PageNumberDoesNotExist_ReturnEmptyAQueryable() { // Arrange var items = TodoItems(2, 3, 1); - using var context = GetContext(); - var (repository, targetedFields) = Setup(context); - context.AddRange(items); + await using var context = GetContext(); + var (repository, _) = Setup(context); + context.AddRange(items.Cast()); // Act var result = await repository.PageAsync(context.Set(), 2, 3); @@ -117,9 +117,9 @@ public async Task Paging_PageNumberDoesNotExist_ReturnEmptyAQueryable() public async Task Paging_PageNumberIsZero_PretendsItsOne() { // Arrange - using var context = GetContext(); - var (repository, targetedFields) = Setup(context); - context.AddRange(TodoItems(2, 3, 4, 5, 6, 7, 8, 9)); + await using var context = GetContext(); + var (repository, _) = Setup(context); + context.AddRange(TodoItems(2, 3, 4, 5, 6, 7, 8, 9).Cast()); await context.SaveChangesAsync(); // Act @@ -136,9 +136,9 @@ public async Task Paging_PageNumberIsZero_PretendsItsOne() public async Task Paging_PageNumberIsNegative_GiveBackReverseAmountOfIds(int pageSize, int pageNumber, int[] expectedIds) { // Arrange - using var context = GetContext(); + await using var context = GetContext(); var repository = Setup(context).Repository; - context.AddRange(TodoItems(1, 2, 3, 4, 5, 6, 7, 8, 9)); + context.AddRange(TodoItems(1, 2, 3, 4, 5, 6, 7, 8, 9).Cast()); context.SaveChanges(); // Act @@ -161,7 +161,7 @@ public async Task Paging_PageNumberIsNegative_GiveBackReverseAmountOfIds(int pag private AppDbContext GetContext(Guid? seed = null) { - Guid actualSeed = seed == null ? Guid.NewGuid() : seed.GetValueOrDefault(); + Guid actualSeed = seed ?? Guid.NewGuid(); var options = new DbContextOptionsBuilder() .UseInMemoryDatabase(databaseName: $"IntegrationDatabaseRepository{actualSeed}") .Options; @@ -176,12 +176,12 @@ private static TodoItem[] TodoItems(params int[] ids) return ids.Select(id => new TodoItem { Id = id }).ToArray(); } - private class IdComparer : IEqualityComparer + private sealed class IdComparer : IEqualityComparer where T : IIdentifiable { public bool Equals(T x, T y) => x?.StringId == y?.StringId; - public int GetHashCode(T obj) => obj?.StringId?.GetHashCode() ?? 0; + public int GetHashCode(T obj) => obj.StringId?.GetHashCode() ?? 0; } } } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/CustomControllerTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/CustomControllerTests.cs index a03a213534..a5dacd3921 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/CustomControllerTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/CustomControllerTests.cs @@ -15,11 +15,11 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Extensibility { [Collection("WebHostCollection")] - public class CustomControllerTests + public sealed class CustomControllerTests { - private TestFixture _fixture; - private Faker _todoItemFaker; - private Faker _personFaker; + private readonly TestFixture _fixture; + private readonly Faker _todoItemFaker; + private readonly Faker _personFaker; public CustomControllerTests(TestFixture fixture) { @@ -39,7 +39,7 @@ public async Task NonJsonApiControllers_DoNotUse_Dasherized_Routes() var builder = new WebHostBuilder() .UseStartup(); var httpMethod = new HttpMethod("GET"); - var route = $"testValues"; + var route = "testValues"; var server = new TestServer(builder); var client = server.CreateClient(); @@ -59,7 +59,7 @@ public async Task CustomRouteControllers_Uses_Dasherized_Collection_Route() var builder = new WebHostBuilder() .UseStartup(); var httpMethod = new HttpMethod("GET"); - var route = $"/custom/route/todoItems"; + var route = "/custom/route/todoItems"; var server = new TestServer(builder); var client = server.CreateClient(); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/NullValuedAttributeHandlingTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/NullValuedAttributeHandlingTests.cs index baeb5deef7..1aaa56a309 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/NullValuedAttributeHandlingTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/NullValuedAttributeHandlingTests.cs @@ -12,7 +12,7 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Extensibility { [Collection("WebHostCollection")] - public class NullValuedAttributeHandlingTests : IAsyncLifetime + public sealed class NullValuedAttributeHandlingTests : IAsyncLifetime { private readonly TestFixture _fixture; private readonly AppDbContext _dbContext; diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/RequestMetaTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/RequestMetaTests.cs index 5f31c447b6..46128676c5 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/RequestMetaTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Extensibility/RequestMetaTests.cs @@ -12,9 +12,9 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Extensibility { [Collection("WebHostCollection")] - public class RequestMetaTests + public sealed class RequestMetaTests { - private TestFixture _fixture; + private readonly TestFixture _fixture; public RequestMetaTests(TestFixture fixture) { @@ -29,7 +29,7 @@ public async Task Injecting_IRequestMeta_Adds_Meta_Data() .UseStartup(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/people"; + var route = "/api/v1/people"; var server = new TestServer(builder); var client = server.CreateClient(); @@ -49,9 +49,8 @@ public async Task Injecting_IRequestMeta_Adds_Meta_Data() foreach (var hash in expectedMeta) { - if (hash.Value is IList) + if (hash.Value is IList listValue) { - var listValue = (IList)hash.Value; for (var i = 0; i < listValue.Count; i++) Assert.Equal(listValue[i].ToString(), ((IList)meta[hash.Key])[i].ToString()); } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/HttpReadOnlyTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/HttpReadOnlyTests.cs index 0d3de444ee..3171eddace 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/HttpReadOnlyTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/HttpReadOnlyTests.cs @@ -9,7 +9,7 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance { [Collection("WebHostCollection")] - public class HttpReadOnlyTests + public sealed class HttpReadOnlyTests { [Fact] public async Task Allows_GET_Requests() diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpDeleteTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpDeleteTests.cs index e7aa542d9a..0702a77c25 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpDeleteTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpDeleteTests.cs @@ -1,4 +1,4 @@ -using System.Net; +using System.Net; using System.Net.Http; using System.Threading.Tasks; using JsonApiDotNetCoreExample; @@ -9,7 +9,7 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance { [Collection("WebHostCollection")] - public class nohttpdeleteTests + public sealed class NoHttpDeleteTests { [Fact] public async Task Allows_GET_Requests() diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpPatchTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpPatchTests.cs index 573b8dccf7..97975c505a 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpPatchTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpPatchTests.cs @@ -1,4 +1,4 @@ -using System.Net; +using System.Net; using System.Net.Http; using System.Threading.Tasks; using JsonApiDotNetCoreExample; @@ -9,7 +9,7 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance { [Collection("WebHostCollection")] - public class nohttppatchTests + public sealed class NoHttpPatchTests { [Fact] public async Task Allows_GET_Requests() diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpPostTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpPostTests.cs index b1dda90c29..8aa2be9c0f 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpPostTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/HttpMethodRestrictions/NoHttpPostTests.cs @@ -1,4 +1,4 @@ -using System.Net; +using System.Net; using System.Net.Http; using System.Threading.Tasks; using JsonApiDotNetCoreExample; @@ -9,7 +9,7 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance { [Collection("WebHostCollection")] - public class NoHttpPostTests + public sealed class NoHttpPostTests { [Fact] public async Task Allows_GET_Requests() diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/KebabCaseFormatterTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/KebabCaseFormatterTests.cs index 842e533d36..2aaf4ef4dd 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/KebabCaseFormatterTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/KebabCaseFormatterTests.cs @@ -1,4 +1,3 @@ -using System.Linq; using System.Net; using System.Threading.Tasks; using Bogus; @@ -8,7 +7,7 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance { - public class KebabCaseFormatterTests : FunctionalTestCollection + public sealed class KebabCaseFormatterTests : FunctionalTestCollection { private readonly Faker _faker; @@ -20,15 +19,15 @@ public KebabCaseFormatterTests(KebabCaseApplicationFactory factory) : base(facto [Fact] public async Task KebabCaseFormatter_GetAll_IsReturned() { - /// Arrange + // Arrange var model = _faker.Generate(); _dbContext.KebabCasedModels.Add(model); _dbContext.SaveChanges(); - /// Act + // Act var (body, response) = await Get("api/v1/kebab-cased-models"); - /// Assert + // Assert AssertEqualStatusCode(HttpStatusCode.OK, response); var responseItem = _deserializer.DeserializeList(body).Data; Assert.True(responseItem.Count > 0); @@ -37,15 +36,15 @@ public async Task KebabCaseFormatter_GetAll_IsReturned() [Fact] public async Task KebabCaseFormatter_GetSingle_IsReturned() { - /// Arrange + // Arrange var model = _faker.Generate(); _dbContext.KebabCasedModels.Add(model); _dbContext.SaveChanges(); - /// Act + // Act var (body, response) = await Get($"api/v1/kebab-cased-models/{model.Id}"); - /// Assert + // Assert AssertEqualStatusCode(HttpStatusCode.OK, response); var responseItem = _deserializer.DeserializeSingle(body).Data; Assert.Equal(model.Id, responseItem.Id); @@ -54,34 +53,33 @@ public async Task KebabCaseFormatter_GetSingle_IsReturned() [Fact] public async Task KebabCaseFormatter_Create_IsCreated() { - /// Arrange + // Arrange var model = _faker.Generate(); var serializer = GetSerializer(kcm => new { kcm.CompoundAttr }); - /// Act - var (body, response) = await Post($"api/v1/kebab-cased-models", serializer.Serialize(model)); + // Act + var (body, response) = await Post("api/v1/kebab-cased-models", serializer.Serialize(model)); - /// Assert + // Assert AssertEqualStatusCode(HttpStatusCode.Created, response); var responseItem = _deserializer.DeserializeSingle(body).Data; - var x = _dbContext.KebabCasedModels.Where(kcm => kcm.Id.Equals(responseItem.Id)).Single(); Assert.Equal(model.CompoundAttr, responseItem.CompoundAttr); } [Fact] public async Task KebabCaseFormatter_Update_IsUpdated() { - /// Arrange + // Arrange var model = _faker.Generate(); _dbContext.KebabCasedModels.Add(model); _dbContext.SaveChanges(); model.CompoundAttr = _faker.Generate().CompoundAttr; var serializer = GetSerializer(kcm => new { kcm.CompoundAttr }); - /// Act + // Act var (body, response) = await Patch($"api/v1/kebab-cased-models/{model.Id}", serializer.Serialize(model)); - /// Assert + // Assert AssertEqualStatusCode(HttpStatusCode.OK, response); var responseItem = _deserializer.DeserializeSingle(body).Data; Assert.Equal(model.CompoundAttr, responseItem.CompoundAttr); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs index 1ef254b8dd..0a2a86afd5 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/ManyToManyTests.cs @@ -18,7 +18,7 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance { [Collection("WebHostCollection")] - public class ManyToManyTests + public sealed class ManyToManyTests { private static readonly Faker
_articleFaker = new Faker
() .RuleFor(a => a.Name, f => f.Random.AlphaNumeric(10)) @@ -26,7 +26,7 @@ public class ManyToManyTests private static readonly Faker _tagFaker = new Faker().RuleFor(a => a.Name, f => f.Random.AlphaNumeric(10)); - private TestFixture _fixture; + private readonly TestFixture _fixture; public ManyToManyTests(TestFixture fixture) { _fixture = fixture; @@ -50,7 +50,7 @@ public async Task Can_Fetch_Many_To_Many_Through_All() }; context.ArticleTags.Add(articleTag); await context.SaveChangesAsync(); - var route = $"/api/v1/articles?include=tags"; + var route = "/api/v1/articles?include=tags"; // @TODO - Use fixture var builder = new WebHostBuilder() @@ -281,8 +281,6 @@ public async Task Can_Create_Many_To_Many() context.AuthorDifferentDbContextName.Add(author); await context.SaveChangesAsync(); - var article = _articleFaker.Generate(); - var route = "/api/v1/articles"; var request = new HttpRequestMessage(new HttpMethod("POST"), route); var content = new diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/ResourceDefinitions/QueryFiltersTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/ResourceDefinitions/QueryFiltersTests.cs index 1f4c426b55..6c312ddd3d 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/ResourceDefinitions/QueryFiltersTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/ResourceDefinitions/QueryFiltersTests.cs @@ -13,11 +13,11 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance { [Collection("WebHostCollection")] - public class QueryFiltersTests + public sealed class QueryFiltersTests { - private TestFixture _fixture; - private AppDbContext _context; - private Faker _userFaker; + private readonly TestFixture _fixture; + private readonly AppDbContext _context; + private readonly Faker _userFaker; public QueryFiltersTests(TestFixture fixture) { @@ -53,7 +53,6 @@ public async Task FiltersWithCustomQueryFiltersEquals() Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var deserializedBody = _fixture.GetDeserializer().DeserializeList(body).Data; - var usersWithFirstCharacter = _context.Users.Where(u => u.Username[0] == firstUsernameCharacter); Assert.True(deserializedBody.All(u => u.Username[0] == firstUsernameCharacter)); } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/ResourceDefinitions/ResourceDefinitionTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/ResourceDefinitions/ResourceDefinitionTests.cs index 0fbace3280..4dc6c68228 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/ResourceDefinitions/ResourceDefinitionTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/ResourceDefinitions/ResourceDefinitionTests.cs @@ -17,13 +17,13 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance { [Collection("WebHostCollection")] - public class ResourceDefinitionTests + public sealed class ResourceDefinitionTests { - private TestFixture _fixture; - private AppDbContext _context; - private Faker _userFaker; - private Faker _todoItemFaker; - private Faker _personFaker; + private readonly TestFixture _fixture; + private readonly AppDbContext _context; + private readonly Faker _userFaker; + private readonly Faker _todoItemFaker; + private readonly Faker _personFaker; private static readonly Faker
_articleFaker = new Faker
() .RuleFor(a => a.Name, f => f.Random.AlphaNumeric(10)) .RuleFor(a => a.Author, f => new Author()); @@ -77,10 +77,12 @@ public async Task Can_Create_User_With_Password() var httpMethod = new HttpMethod("POST"); - var route = $"/api/v1/users"; + var route = "/api/v1/users"; - var request = new HttpRequestMessage(httpMethod, route); - request.Content = new StringContent(serializer.Serialize(user)); + var request = new HttpRequestMessage(httpMethod, route) + { + Content = new StringContent(serializer.Serialize(user)) + }; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); // Act @@ -113,8 +115,10 @@ public async Task Can_Update_User_Password() var serializer = _fixture.GetSerializer(p => new { p.Password }); var httpMethod = new HttpMethod("PATCH"); var route = $"/api/v1/users/{user.Id}"; - var request = new HttpRequestMessage(httpMethod, route); - request.Content = new StringContent(serializer.Serialize(user)); + var request = new HttpRequestMessage(httpMethod, route) + { + Content = new StringContent(serializer.Serialize(user)) + }; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); // Act @@ -125,7 +129,6 @@ public async Task Can_Update_User_Password() // response assertions var body = await response.Content.ReadAsStringAsync(); - var returnedUser = _fixture.GetDeserializer().DeserializeSingle(body).Data; var document = JsonConvert.DeserializeObject(body); Assert.False(document.SingleData.Attributes.ContainsKey("password")); Assert.Equal(user.Username, document.SingleData.Attributes["username"]); @@ -139,9 +142,7 @@ public async Task Can_Update_User_Password() public async Task Unauthorized_TodoItem() { // Arrange - var route = $"/api/v1/todoItems/1337"; - var httpMethod = new HttpMethod("GET"); - var request = new HttpRequestMessage(httpMethod, route); + var route = "/api/v1/todoItems/1337"; // Act var response = await _fixture.Client.GetAsync(route); @@ -155,9 +156,7 @@ public async Task Unauthorized_TodoItem() public async Task Unauthorized_Passport() { // Arrange - var route = $"/api/v1/people/1?include=passport"; - var httpMethod = new HttpMethod("GET"); - var request = new HttpRequestMessage(httpMethod, route); + var route = "/api/v1/people/1?include=passport"; // Act var response = await _fixture.Client.GetAsync(route); @@ -204,11 +203,7 @@ public async Task Article_Is_Hidden() context.Articles.AddRange(articles); await context.SaveChangesAsync(); - var route = $"/api/v1/articles"; - - var httpMethod = new HttpMethod("GET"); - var request = new HttpRequestMessage(httpMethod, route); - + var route = "/api/v1/articles"; // Act var response = await _fixture.Client.GetAsync(route); @@ -231,7 +226,7 @@ public async Task Tag_Is_Hidden() string toBeExcluded = "This should be not be included"; tags[0].Name = toBeExcluded; - var articleTags = new ArticleTag[] + var articleTags = new[] { new ArticleTag { @@ -247,11 +242,7 @@ public async Task Tag_Is_Hidden() context.ArticleTags.AddRange(articleTags); await context.SaveChangesAsync(); - var route = $"/api/v1/articles?include=tags"; - - var httpMethod = new HttpMethod("GET"); - var request = new HttpRequestMessage(httpMethod, route); - + var route = "/api/v1/articles?include=tags"; // Act var response = await _fixture.Client.GetAsync(route); @@ -297,7 +288,7 @@ public async Task Cascade_Permission_Error_Create_ToOne_Relationship() }; var httpMethod = new HttpMethod("POST"); - var route = $"/api/v1/people"; + var route = "/api/v1/people"; var request = new HttpRequestMessage(httpMethod, route); string serializedContent = JsonConvert.SerializeObject(content); @@ -320,10 +311,10 @@ public async Task Cascade_Permission_Error_Updating_ToOne_Relationship() // Arrange var context = _fixture.GetService(); var person = _personFaker.Generate(); - var passport = new Passport() { IsLocked = true }; + var passport = new Passport { IsLocked = true }; person.Passport = passport; context.People.AddRange(person); - var newPassport = new Passport() { }; + var newPassport = new Passport(); context.Passports.Add(newPassport); await context.SaveChangesAsync(); @@ -367,10 +358,10 @@ public async Task Cascade_Permission_Error_Updating_ToOne_Relationship_Deletion( // Arrange var context = _fixture.GetService(); var person = _personFaker.Generate(); - var passport = new Passport() { IsLocked = true }; + var passport = new Passport { IsLocked = true }; person.Passport = passport; context.People.AddRange(person); - var newPassport = new Passport() { }; + var newPassport = new Passport(); context.Passports.Add(newPassport); await context.SaveChangesAsync(); @@ -470,7 +461,7 @@ public async Task Cascade_Permission_Error_Create_ToMany_Relationship() }; var httpMethod = new HttpMethod("POST"); - var route = $"/api/v1/todoItems"; + var route = "/api/v1/todoItems"; var request = new HttpRequestMessage(httpMethod, route); string serializedContent = JsonConvert.SerializeObject(content); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeFilterTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeFilterTests.cs index 49472014f1..2f77e2f9bb 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeFilterTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeFilterTests.cs @@ -16,10 +16,10 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec { [Collection("WebHostCollection")] - public class AttributeFilterTests + public sealed class AttributeFilterTests { - private TestFixture _fixture; - private Faker _todoItemFaker; + private readonly TestFixture _fixture; + private readonly Faker _todoItemFaker; private readonly Faker _personFaker; public AttributeFilterTests(TestFixture fixture) @@ -139,14 +139,13 @@ public async Task Can_Filter_On_In_Array_Values() { context.TodoItems.Add(item); // Exclude 2 items - if (guids.Count < (todoItems.Count() - 2)) + if (guids.Count < (todoItems.Count - 2)) guids.Add(item.GuidProperty); else notInGuids.Add(item.GuidProperty); } context.SaveChanges(); - var totalCount = context.TodoItems.Count(); var httpMethod = new HttpMethod("GET"); var route = $"/api/v1/todoItems?filter[guidProperty]=in:{string.Join(",", guids)}"; var request = new HttpRequestMessage(httpMethod, route); @@ -160,7 +159,7 @@ public async Task Can_Filter_On_In_Array_Values() // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(guids.Count(), deserializedTodoItems.Count()); + Assert.Equal(guids.Count, deserializedTodoItems.Count); foreach (var item in deserializedTodoItems) { Assert.Contains(item.GuidProperty, guids); @@ -191,12 +190,12 @@ public async Task Can_Filter_On_Related_In_Array_Values() // Act var response = await _fixture.Client.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); - var documents = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); + var documents = JsonConvert.DeserializeObject(body); var included = documents.Included; // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(ownerFirstNames.Count(), documents.ManyData.Count()); + Assert.Equal(ownerFirstNames.Count, documents.ManyData.Count); Assert.NotNull(included); Assert.NotEmpty(included); foreach (var item in included) @@ -218,7 +217,7 @@ public async Task Can_Filter_On_Not_In_Array_Values() { context.TodoItems.Add(item); // Exclude 2 items - if (guids.Count < (todoItems.Count() - 2)) + if (guids.Count < (todoItems.Count - 2)) guids.Add(item.GuidProperty); else notInGuids.Add(item.GuidProperty); @@ -239,7 +238,7 @@ public async Task Can_Filter_On_Not_In_Array_Values() // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(totalCount - notInGuids.Count(), deserializedTodoItems.Count()); + Assert.Equal(totalCount - notInGuids.Count, deserializedTodoItems.Count); foreach (var item in deserializedTodoItems) { Assert.DoesNotContain(item.GuidProperty, notInGuids); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeSortTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeSortTests.cs index 6b387fed64..7998df3431 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeSortTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/AttributeSortTests.cs @@ -7,9 +7,9 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec { [Collection("WebHostCollection")] - public class AttributeSortTests + public sealed class AttributeSortTests { - private TestFixture _fixture; + private readonly TestFixture _fixture; public AttributeSortTests(TestFixture fixture) { @@ -21,7 +21,7 @@ public async Task Cannot_Sort_If_Explicitly_Forbidden() { // Arrange var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/todoItems?include=owner&sort=achievedDate"; + var route = "/api/v1/todoItems?include=owner&sort=achievedDate"; var request = new HttpRequestMessage(httpMethod, route); // Act diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/ContentNegotiation.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/ContentNegotiation.cs index bccb8ebf83..dc026a6fd1 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/ContentNegotiation.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/ContentNegotiation.cs @@ -10,14 +10,8 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec { [Collection("WebHostCollection")] - public class ContentNegotiation + public sealed class ContentNegotiation { - private TestFixture _fixture; - public ContentNegotiation(TestFixture fixture) - { - _fixture = fixture; - } - [Fact] public async Task Server_Sends_Correct_ContentType_Header() { @@ -48,10 +42,9 @@ public async Task Server_Responds_415_With_MediaType_Parameters() var route = "/api/v1/todoItems"; var server = new TestServer(builder); var client = server.CreateClient(); - var request = new HttpRequestMessage(httpMethod, route); - request.Content = new StringContent(string.Empty); - request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); - request.Content.Headers.ContentType.CharSet = "ISO-8859-4"; + var request = new HttpRequestMessage(httpMethod, route) {Content = new StringContent(string.Empty)}; + request.Content.Headers.ContentType = + new MediaTypeHeaderValue("application/vnd.api+json") {CharSet = "ISO-8859-4"}; // Act var response = await client.SendAsync(request); @@ -70,8 +63,7 @@ public async Task ServerResponds_406_If_RequestAcceptHeader_Contains_MediaTypePa var route = "/api/v1/todoItems"; var server = new TestServer(builder); var client = server.CreateClient(); - var acceptHeader = new MediaTypeWithQualityHeaderValue("application/vnd.api+json"); - acceptHeader.CharSet = "ISO-8859-4"; + var acceptHeader = new MediaTypeWithQualityHeaderValue("application/vnd.api+json") {CharSet = "ISO-8859-4"}; client.DefaultRequestHeaders .Accept .Add(acceptHeader); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs index b5a0ef5140..d1acf36c65 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/CreatingDataTests.cs @@ -4,8 +4,6 @@ using System.Net; using System.Threading.Tasks; using Bogus; -using JsonApiDotNetCore.Builders; -using JsonApiDotNetCore.Serialization.Client; using JsonApiDotNetCoreExample.Models; using JsonApiDotNetCoreExampleTests.Helpers.Models; using Microsoft.EntityFrameworkCore; @@ -14,7 +12,7 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec { - public class CreatingDataTests : FunctionalTestCollection + public sealed class CreatingDataTests : FunctionalTestCollection { private readonly Faker _todoItemFaker; private readonly Faker _personFaker; @@ -43,7 +41,8 @@ public async Task CreateResource_ModelWithEntityFrameworkInheritance_IsCreated() // Assert AssertEqualStatusCode(HttpStatusCode.Created, response); var createdSuperUser = _deserializer.DeserializeSingle(body).Data; - var created = _dbContext.SuperUsers.Where(e => e.Id.Equals(createdSuperUser.Id)).First(); + var first = _dbContext.SuperUsers.FirstOrDefault(e => e.Id.Equals(createdSuperUser.Id)); + Assert.NotNull(first); } [Fact] @@ -57,7 +56,7 @@ public async Task CreateResource_GuidResource_IsCreated() var todoItemCollection = new TodoItemCollection { Owner = owner }; // Act - var (body, response) = await Post("/api/v1/todoCollections", serializer.Serialize(todoItemCollection)); + var (_, response) = await Post("/api/v1/todoCollections", serializer.Serialize(todoItemCollection)); // Assert AssertEqualStatusCode(HttpStatusCode.Created, response); @@ -73,7 +72,7 @@ public async Task ClientGeneratedId_IntegerIdAndNotEnabled_IsForbidden() todoItem.Id = clientDefinedId; // Act - var (body, response) = await Post("/api/v1/todoItems", serializer.Serialize(todoItem)); + var (_, response) = await Post("/api/v1/todoItems", serializer.Serialize(todoItem)); // Assert AssertEqualStatusCode(HttpStatusCode.Forbidden, response); @@ -216,12 +215,10 @@ public async Task CreateResource_EntityTypeMismatch_IsConflict() { // Arrange var serializer = GetSerializer(e => new { }, e => new { e.Owner }); - var resourceGraph = new ResourceGraphBuilder().AddResource("todoItems").AddResource().AddResource().Build(); - var _deserializer = new ResponseDeserializer(resourceGraph); var content = serializer.Serialize(_todoItemFaker.Generate()).Replace("todoItems", "people"); // Act - var (body, response) = await Post("/api/v1/todoItems", content); + var (_, response) = await Post("/api/v1/todoItems", content); // Assert AssertEqualStatusCode(HttpStatusCode.Conflict, response); @@ -285,7 +282,7 @@ public async Task CreateRelationship_ToManyWithImplicitRemove_IsCreated() } - public class CreatingDataWithClientEnabledIdTests : FunctionalTestCollection + public sealed class CreatingDataWithClientEnabledIdTests : FunctionalTestCollection { private readonly Faker _todoItemFaker; diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeeplyNestedInclusionTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeeplyNestedInclusionTests.cs index 6130e81e45..4a2dd5a3ed 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeeplyNestedInclusionTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeeplyNestedInclusionTests.cs @@ -17,9 +17,9 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec { [Collection("WebHostCollection")] - public class DeeplyNestedInclusionTests + public sealed class DeeplyNestedInclusionTests { - private TestFixture _fixture; + private readonly TestFixture _fixture; public DeeplyNestedInclusionTests(TestFixture fixture) { diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeletingDataTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeletingDataTests.cs index 099128e71c..eb18ce542d 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeletingDataTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DeletingDataTests.cs @@ -2,32 +2,22 @@ using System.Net; using System.Net.Http; using System.Threading.Tasks; -using Bogus; using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Data; -using JsonApiDotNetCoreExample.Models; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; -using Microsoft.EntityFrameworkCore; using Xunit; namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec { [Collection("WebHostCollection")] - public class DeletingDataTests + public sealed class DeletingDataTests { - private TestFixture _fixture; - private AppDbContext _context; - private Faker _todoItemFaker; + private readonly AppDbContext _context; public DeletingDataTests(TestFixture fixture) { - _fixture = fixture; _context = fixture.GetService(); - _todoItemFaker = new Faker() - .RuleFor(t => t.Description, f => f.Lorem.Sentence()) - .RuleFor(t => t.Ordinal, f => f.Random.Number()) - .RuleFor(t => t.CreatedDate, f => f.Date.Past()); } [Fact] diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Included.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Included.cs index 5c98837e1d..0c844e0d23 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Included.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Included.cs @@ -17,10 +17,10 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec.DocumentTests { [Collection("WebHostCollection")] - public class Included + public sealed class Included { private readonly AppDbContext _context; - private readonly Bogus.Faker _personFaker; + private readonly Faker _personFaker; private readonly Faker _todoItemFaker; private readonly Faker _todoItemCollectionFaker; @@ -54,7 +54,7 @@ public async Task GET_Included_Contains_SideLoadedData_ForManyToOne() var builder = new WebHostBuilder().UseStartup(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/todoItems?include=owner"; + var route = "/api/v1/todoItems?include=owner"; var server = new TestServer(builder); var client = server.CreateClient(); @@ -132,7 +132,7 @@ public async Task GET_Included_Contains_SideLoadedData_OneToMany() .UseStartup(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/people?include=todoItems"; + var route = "/api/v1/people?include=todoItems"; var server = new TestServer(builder); var client = server.CreateClient(); @@ -203,14 +203,14 @@ public async Task GET_Included_DoesNot_Duplicate_Records_If_HasOne_Exists_Twice( var todoItem2 = _todoItemFaker.Generate(); todoItem1.Owner = person; todoItem2.Owner = person; - _context.TodoItems.AddRange(new[] { todoItem1, todoItem2 }); + _context.TodoItems.AddRange(todoItem1, todoItem2); _context.SaveChanges(); var builder = new WebHostBuilder() .UseStartup(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/todoItems?include=owner"; + var route = "/api/v1/todoItems?include=owner"; var server = new TestServer(builder); var client = server.CreateClient(); @@ -419,7 +419,7 @@ public async Task Can_Ignore_Null_Parent_In_Nested_Include() var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/todoItems?sort=-createdDate&page[size]=2&include=owner.role"; // last two todoItems + var route = "/api/v1/todoItems?sort=-createdDate&page[size]=2&include=owner.role"; // last two todoItems var server = new TestServer(builder); var client = server.CreateClient(); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Meta.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Meta.cs index 59928ffccd..71b3559965 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Meta.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Meta.cs @@ -15,10 +15,10 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec.DocumentTests { [Collection("WebHostCollection")] - public class Meta + public sealed class Meta { - private TestFixture _fixture; - private AppDbContext _context; + private readonly TestFixture _fixture; + private readonly AppDbContext _context; public Meta(TestFixture fixture) { _fixture = fixture; @@ -37,7 +37,7 @@ public async Task Total_Record_Count_Included() .UseStartup(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/todoItems"; + var route = "/api/v1/todoItems"; var server = new TestServer(builder); var client = server.CreateClient(); @@ -51,7 +51,7 @@ public async Task Total_Record_Count_Included() // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(documents.Meta); - Assert.Equal((long)expectedCount, (long)documents.Meta["total-records"]); + Assert.Equal(expectedCount, (long)documents.Meta["total-records"]); } [Fact] @@ -64,7 +64,7 @@ public async Task Total_Record_Count_Included_When_None() .UseStartup(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/todoItems"; + var route = "/api/v1/todoItems"; var server = new TestServer(builder); var client = server.CreateClient(); @@ -91,7 +91,7 @@ public async Task Total_Record_Count_Not_Included_In_POST_Response() .UseStartup(); var httpMethod = new HttpMethod("POST"); - var route = $"/api/v1/todoItems"; + var route = "/api/v1/todoItems"; var server = new TestServer(builder); var client = server.CreateClient(); @@ -172,7 +172,7 @@ public async Task EntityThatImplements_IHasMeta_Contains_MetaData() .UseStartup(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/people"; + var route = "/api/v1/people"; var server = new TestServer(builder); var client = server.CreateClient(); @@ -191,9 +191,8 @@ public async Task EntityThatImplements_IHasMeta_Contains_MetaData() foreach (var hash in expectedMeta) { - if (hash.Value is IList) + if (hash.Value is IList listValue) { - var listValue = (IList)hash.Value; for (var i = 0; i < listValue.Count; i++) Assert.Equal(listValue[i].ToString(), ((IList)documents.Meta[hash.Key])[i].ToString()); } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Relationships.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Relationships.cs index 3d1097a3be..96b6d3d6fa 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Relationships.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/DocumentTests/Relationships.cs @@ -1,4 +1,4 @@ -using System.Net; +using System.Net; using System.Net.Http; using System.Threading.Tasks; using JsonApiDotNetCoreExample; @@ -15,15 +15,13 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec.DocumentTests { [Collection("WebHostCollection")] - public class Relationships + public sealed class Relationships { - private TestFixture _fixture; - private AppDbContext _context; - private Faker _todoItemFaker; + private readonly AppDbContext _context; + private readonly Faker _todoItemFaker; public Relationships(TestFixture fixture) { - _fixture = fixture; _context = fixture.GetService(); _todoItemFaker = new Faker() .RuleFor(t => t.Description, f => f.Lorem.Sentence()) @@ -101,7 +99,7 @@ public async Task Correct_RelationshipObjects_For_OneToMany_Relationships() .UseStartup(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/people"; + var route = "/api/v1/people"; var server = new TestServer(builder); var client = server.CreateClient(); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingDataTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingDataTests.cs index c58fc94663..40b5bd0f71 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingDataTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingDataTests.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; @@ -16,11 +16,11 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec { [Collection("WebHostCollection")] - public class FetchingDataTests + public sealed class FetchingDataTests { - private TestFixture _fixture; - private Faker _todoItemFaker; - private Faker _personFaker; + private readonly TestFixture _fixture; + private readonly Faker _todoItemFaker; + private readonly Faker _personFaker; public FetchingDataTests(TestFixture fixture) { @@ -110,7 +110,7 @@ public async Task GetResources_NoDefaultPageSize_ReturnsResources() var builder = new WebHostBuilder() .UseStartup(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/todoItems"; + var route = "/api/v1/todoItems"; var server = new TestServer(builder); var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); @@ -135,7 +135,7 @@ public async Task GetSingleResource_ResourceDoesNotExist_ReturnsNotFoundWithNull var builder = new WebHostBuilder() .UseStartup(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/todoItems/123"; + var route = "/api/v1/todoItems/123"; var server = new TestServer(builder); var client = server.CreateClient(); var request = new HttpRequestMessage(httpMethod, route); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingRelationshipsTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingRelationshipsTests.cs index a3ec7d83d0..3c816d1ec4 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingRelationshipsTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/FetchingRelationshipsTests.cs @@ -12,10 +12,10 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec { [Collection("WebHostCollection")] - public class FetchingRelationshipsTests + public sealed class FetchingRelationshipsTests { - private TestFixture _fixture; - private Faker _todoItemFaker; + private readonly TestFixture _fixture; + private readonly Faker _todoItemFaker; public FetchingRelationshipsTests(TestFixture fixture) { diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/NestedResourceTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/NestedResourceTests.cs index e023590da5..222ec684cd 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/NestedResourceTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/NestedResourceTests.cs @@ -1,4 +1,4 @@ -using System.Linq; +using System.Linq; using System.Net; using System.Threading.Tasks; using Bogus; @@ -9,7 +9,7 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec { - public class NestedResourceTests : FunctionalTestCollection + public sealed class NestedResourceTests : FunctionalTestCollection { private readonly Faker _todoItemFaker; private readonly Faker _personFaker; diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/PagingTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/PagingTests.cs index 3ff55bf427..d7fb0d11fc 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/PagingTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/PagingTests.cs @@ -6,7 +6,6 @@ using JsonApiDotNetCore.Models; using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Models; -using JsonApiDotNetCoreExampleTests.Helpers.Models; using Newtonsoft.Json; using Xunit; using Person = JsonApiDotNetCoreExample.Models.Person; @@ -14,9 +13,9 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec { [Collection("WebHostCollection")] - public class PagingTests : TestFixture + public sealed class PagingTests : TestFixture { - private TestFixture _fixture; + private readonly TestFixture _fixture; private readonly Faker _todoItemFaker; public PagingTests(TestFixture fixture) @@ -88,7 +87,7 @@ public async Task Pagination_OnGivenPage_DisplaysCorrectTopLevelLinks(int pageNu Context.TodoItems.AddRange(todoItems); Context.SaveChanges(); - string route = $"/api/v1/todoItems"; + string route = "/api/v1/todoItems"; if (pageNum != 1) { route += $"?page[size]=5&page[number]={pageNum}"; @@ -139,12 +138,12 @@ public async Task Pagination_OnGivenPage_DisplaysCorrectTopLevelLinks(int pageNu } } - private class IdComparer : IEqualityComparer + private sealed class IdComparer : IEqualityComparer where T : IIdentifiable { public bool Equals(T x, T y) => x?.StringId == y?.StringId; - public int GetHashCode(T obj) => obj?.StringId?.GetHashCode() ?? 0; + public int GetHashCode(T obj) => obj.StringId?.GetHashCode() ?? 0; } } } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/QueryParameters.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/QueryParameters.cs index 1c64f41dab..2cacb7c302 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/QueryParameters.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/QueryParameters.cs @@ -11,14 +11,8 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec { [Collection("WebHostCollection")] - public class QueryParameters + public sealed class QueryParameters { - private TestFixture _fixture; - public QueryParameters(TestFixture fixture) - { - _fixture = fixture; - } - [Fact] public async Task Server_Returns_400_ForUnknownQueryParam() { diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/SparseFieldSetTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/SparseFieldSetTests.cs index a3acd23ce2..558268aa44 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/SparseFieldSetTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/SparseFieldSetTests.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; @@ -9,25 +8,22 @@ using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; -using JsonApiDotNetCoreExampleTests.Helpers.Extensions; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using Xunit; -using StringExtensions = JsonApiDotNetCoreExampleTests.Helpers.Extensions.StringExtensions; using Person = JsonApiDotNetCoreExample.Models.Person; using System.Net; using JsonApiDotNetCore.Serialization.Client; using JsonApiDotNetCore.Builders; using JsonApiDotNetCoreExampleTests.Helpers.Models; -using JsonApiDotNetCore.Services; using JsonApiDotNetCore.Internal.Contracts; namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec { [Collection("WebHostCollection")] - public class SparseFieldSetTests + public sealed class SparseFieldSetTests { private readonly AppDbContext _dbContext; private readonly IResourceGraph _resourceGraph; @@ -53,7 +49,6 @@ public SparseFieldSetTests(TestFixture fixture) public async Task Can_Select_Sparse_Fieldsets() { // Arrange - var fields = new List { "Id", "Description", "CreatedDate", "AchievedDate" }; var todoItem = new TodoItem { Description = "description", @@ -63,9 +58,6 @@ public async Task Can_Select_Sparse_Fieldsets() }; _dbContext.TodoItems.Add(todoItem); await _dbContext.SaveChangesAsync(); - var expectedSql = StringExtensions.Normalize($@"SELECT 't'.'Id', 't'.'Description', 't'.'CreatedDate', 't'.'AchievedDate' - FROM 'TodoItems' AS 't' - WHERE 't'.'Id' = {todoItem.Id}"); // Act var query = _dbContext @@ -170,7 +162,7 @@ public async Task Fields_Query_Selects_All_Fieldset_With_HasOne() using var server = new TestServer(builder); var client = server.CreateClient(); - var route = $"/api/v1/todoItems?include=owner&fields[owner]=firstName,age"; + var route = "/api/v1/todoItems?include=owner&fields[owner]=firstName,age"; var request = new HttpRequestMessage(httpMethod, route); var resourceGraph = new ResourceGraphBuilder().AddResource().AddResource("todoItems").Build(); var deserializer = new ResponseDeserializer(resourceGraph); diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingDataTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingDataTests.cs index ea9ea6004c..bbe645d17c 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingDataTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingDataTests.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; @@ -20,11 +19,11 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec { [Collection("WebHostCollection")] - public class UpdatingDataTests : EndToEndTest + public sealed class UpdatingDataTests : EndToEndTest { - private AppDbContext _context; - private Faker _todoItemFaker; - private Faker _personFaker; + private readonly AppDbContext _context; + private readonly Faker _todoItemFaker; + private readonly Faker _personFaker; public UpdatingDataTests(TestFixture fixture) : base(fixture) { @@ -79,7 +78,6 @@ public async Task Response400IfUpdatingNotSettableAttribute() var response = await client.SendAsync(request); // Assert - var body = await response.Content.ReadAsStringAsync(); Assert.Equal(422, Convert.ToInt32(response.StatusCode)); } @@ -249,9 +247,8 @@ public async Task Can_Patch_Entity_And_HasOne_Relationships() private HttpRequestMessage PrepareRequest(string method, string route, string content) { var httpMethod = new HttpMethod(method); - var request = new HttpRequestMessage(httpMethod, route); + var request = new HttpRequestMessage(httpMethod, route) {Content = new StringContent(content)}; - request.Content = new StringContent(content); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); return request; } diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingRelationshipsTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingRelationshipsTests.cs index e3c9c9e3f4..d2c0a46ba0 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingRelationshipsTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/Spec/UpdatingRelationshipsTests.cs @@ -1,12 +1,10 @@ using System.Collections.Generic; -using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Bogus; -using JsonApiDotNetCore.Models; using JsonApiDotNetCoreExample; using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; @@ -14,19 +12,18 @@ using Microsoft.AspNetCore.TestHost; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; -using Newtonsoft.Json.Linq; using Xunit; using Person = JsonApiDotNetCoreExample.Models.Person; namespace JsonApiDotNetCoreExampleTests.Acceptance.Spec { [Collection("WebHostCollection")] - public class UpdatingRelationshipsTests + public sealed class UpdatingRelationshipsTests { - private TestFixture _fixture; + private readonly TestFixture _fixture; private AppDbContext _context; - private Bogus.Faker _personFaker; - private Faker _todoItemFaker; + private readonly Faker _personFaker; + private readonly Faker _todoItemFaker; public UpdatingRelationshipsTests(TestFixture fixture) { @@ -94,16 +91,14 @@ public async Task Can_Update_Cyclic_ToMany_Relationship_By_Patching_Resource() // Act - var response = await client.SendAsync(request); - var body = await response.Content.ReadAsStringAsync(); + await client.SendAsync(request); _context = _fixture.GetService(); var updatedTodoItem = _context.TodoItems.AsNoTracking() .Where(ti => ti.Id == todoItem.Id) .Include(ti => ti.ChildrenTodos).First(); - updatedTodoItem.ChildrenTodos.Any((ti) => ti.Id == todoItem.Id); - Assert.Contains(updatedTodoItem.ChildrenTodos, (ti) => ti.Id == todoItem.Id); + Assert.Contains(updatedTodoItem.ChildrenTodos, ti => ti.Id == todoItem.Id); } [Fact] @@ -111,7 +106,6 @@ public async Task Can_Update_Cyclic_ToOne_Relationship_By_Patching_Resource() { // Arrange var todoItem = _todoItemFaker.Generate(); - var strayTodoItem = _todoItemFaker.Generate(); _context.TodoItems.Add(todoItem); _context.SaveChanges(); @@ -150,11 +144,9 @@ public async Task Can_Update_Cyclic_ToOne_Relationship_By_Patching_Resource() // Act - var response = await client.SendAsync(request); - var body = await response.Content.ReadAsStringAsync(); + await client.SendAsync(request); _context = _fixture.GetService(); - var updatedTodoItem = _context.TodoItems.AsNoTracking() .Where(ti => ti.Id == todoItem.Id) .Include(ti => ti.DependentOnTodo).First(); @@ -216,11 +208,9 @@ public async Task Can_Update_Both_Cyclic_ToOne_And_ToMany_Relationship_By_Patchi // Act - var response = await client.SendAsync(request); - var body = await response.Content.ReadAsStringAsync(); + await client.SendAsync(request); _context = _fixture.GetService(); - var updatedTodoItem = _context.TodoItems.AsNoTracking() .Where(ti => ti.Id == todoItem.Id) .Include(ti => ti.ParentTodo).First(); @@ -232,8 +222,7 @@ public async Task Can_Update_Both_Cyclic_ToOne_And_ToMany_Relationship_By_Patchi public async Task Can_Update_ToMany_Relationship_By_Patching_Resource() { // Arrange - var todoCollection = new TodoItemCollection(); - todoCollection.TodoItems = new List(); + var todoCollection = new TodoItemCollection {TodoItems = new List()}; var person = _personFaker.Generate(); var todoItem = _todoItemFaker.Generate(); todoCollection.Owner = person; @@ -243,7 +232,7 @@ public async Task Can_Update_ToMany_Relationship_By_Patching_Resource() var newTodoItem1 = _todoItemFaker.Generate(); var newTodoItem2 = _todoItemFaker.Generate(); - _context.AddRange(new TodoItem[] { newTodoItem1, newTodoItem2 }); + _context.AddRange(newTodoItem1, newTodoItem2); _context.SaveChanges(); var builder = new WebHostBuilder() @@ -291,8 +280,8 @@ public async Task Can_Update_ToMany_Relationship_By_Patching_Resource() Assert.Equal(HttpStatusCode.OK, response.StatusCode); - /// we are expecting two, not three, because the request does - /// a "complete replace". + // we are expecting two, not three, because the request does + // a "complete replace". Assert.Equal(2, updatedTodoItems.Count); } @@ -306,8 +295,7 @@ public async Task Can_Update_ToMany_Relationship_By_Patching_Resource_When_Targe // this user may not be reattached to the db context in the repository. // Arrange - var todoCollection = new TodoItemCollection(); - todoCollection.TodoItems = new List(); + var todoCollection = new TodoItemCollection {TodoItems = new List()}; var person = _personFaker.Generate(); var todoItem = _todoItemFaker.Generate(); todoCollection.Owner = person; @@ -318,7 +306,7 @@ public async Task Can_Update_ToMany_Relationship_By_Patching_Resource_When_Targe var newTodoItem1 = _todoItemFaker.Generate(); var newTodoItem2 = _todoItemFaker.Generate(); - _context.AddRange(new TodoItem[] { newTodoItem1, newTodoItem2 }); + _context.AddRange(newTodoItem1, newTodoItem2); _context.SaveChanges(); var builder = new WebHostBuilder() @@ -370,8 +358,8 @@ public async Task Can_Update_ToMany_Relationship_By_Patching_Resource_When_Targe Assert.Equal(HttpStatusCode.OK, response.StatusCode); - /// we are expecting two, not three, because the request does - /// a "complete replace". + // we are expecting two, not three, because the request does + // a "complete replace". Assert.Equal(2, updatedTodoItems.Count); } @@ -379,8 +367,7 @@ public async Task Can_Update_ToMany_Relationship_By_Patching_Resource_When_Targe public async Task Can_Update_ToMany_Relationship_By_Patching_Resource_With_Overlap() { // Arrange - var todoCollection = new TodoItemCollection(); - todoCollection.TodoItems = new List(); + var todoCollection = new TodoItemCollection {TodoItems = new List()}; var person = _personFaker.Generate(); var todoItem1 = _todoItemFaker.Generate(); var todoItem2 = _todoItemFaker.Generate(); @@ -472,9 +459,11 @@ public async Task Can_Update_ToMany_Relationship_ThroughLink() var httpMethod = new HttpMethod("PATCH"); var route = $"/api/v1/people/{person.Id}/relationships/todoItems"; - var request = new HttpRequestMessage(httpMethod, route); + var request = new HttpRequestMessage(httpMethod, route) + { + Content = new StringContent(JsonConvert.SerializeObject(content)) + }; - request.Content = new StringContent(JsonConvert.SerializeObject(content)); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); // Act @@ -510,9 +499,8 @@ public async Task Can_Update_ToOne_Relationship_ThroughLink() var httpMethod = new HttpMethod("PATCH"); var route = $"/api/v1/todoItems/{todoItem.Id}/relationships/owner"; - var request = new HttpRequestMessage(httpMethod, route); + var request = new HttpRequestMessage(httpMethod, route) {Content = new StringContent(content)}; - request.Content = new StringContent(content); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); // Act @@ -560,8 +548,10 @@ public async Task Can_Delete_ToOne_Relationship_By_Patching_Resource() var httpMethod = new HttpMethod("PATCH"); var route = $"/api/v1/todoItems/{todoItem.Id}"; - var request = new HttpRequestMessage(httpMethod, route); - request.Content = new StringContent(JsonConvert.SerializeObject(content)); + var request = new HttpRequestMessage(httpMethod, route) + { + Content = new StringContent(JsonConvert.SerializeObject(content)) + }; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); // Act @@ -584,16 +574,10 @@ public async Task Can_Delete_ToMany_Relationship_By_Patching_Resource() // Arrange var person = _personFaker.Generate(); var todoItem = _todoItemFaker.Generate(); - person.TodoItems = new List() { todoItem }; + person.TodoItems = new List { todoItem }; _context.People.Add(person); _context.SaveChanges(); - var builder = new WebHostBuilder() - .UseStartup(); - - var server = new TestServer(builder); - var client = server.CreateClient(); - var content = new { data = new @@ -604,10 +588,7 @@ public async Task Can_Delete_ToMany_Relationship_By_Patching_Resource() { { "todoItems", new { - data = new List - { - - } + data = new List() } } } @@ -660,9 +641,11 @@ public async Task Can_Delete_Relationship_By_Patching_Relationship() var httpMethod = new HttpMethod("PATCH"); var route = $"/api/v1/todoItems/{todoItem.Id}/relationships/owner"; - var request = new HttpRequestMessage(httpMethod, route); + var request = new HttpRequestMessage(httpMethod, route) + { + Content = new StringContent(JsonConvert.SerializeObject(content)) + }; - request.Content = new StringContent(JsonConvert.SerializeObject(content)); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); // Act @@ -687,7 +670,7 @@ public async Task Updating_ToOne_Relationship_With_Implicit_Remove() var person1 = _personFaker.Generate(); person1.Passport = passport; var person2 = _personFaker.Generate(); - context.People.AddRange(new List() { person1, person2 }); + context.People.AddRange(new List { person1, person2 }); await context.SaveChangesAsync(); var passportId = person1.PassportId; var content = new @@ -735,7 +718,7 @@ public async Task Updating_ToMany_Relationship_With_Implicit_Remove() person1.TodoItems = _todoItemFaker.Generate(3).ToList(); var person2 = _personFaker.Generate(); person2.TodoItems = _todoItemFaker.Generate(2).ToList(); - context.People.AddRange(new List() { person1, person2 }); + context.People.AddRange(new List { person1, person2 }); await context.SaveChangesAsync(); var todoItem1Id = person1.TodoItems[0].Id; var todoItem2Id = person1.TodoItems[1].Id; diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/TestFixture.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/TestFixture.cs index 79a19c8c9a..4c4b75e3b6 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/TestFixture.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/TestFixture.cs @@ -18,7 +18,7 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance public class TestFixture : IDisposable where TStartup : class { private readonly TestServer _server; - private IServiceProvider _services; + private readonly IServiceProvider _services; public TestFixture() { var builder = new WebHostBuilder() @@ -68,8 +68,9 @@ public void ReloadDbContext() Context = new AppDbContext(GetService>()); } - private bool disposedValue = false; - protected virtual void Dispose(bool disposing) + private bool disposedValue; + + private void Dispose(bool disposing) { if (!disposedValue) { @@ -88,4 +89,4 @@ public void Dispose() Dispose(true); } } -} \ No newline at end of file +} diff --git a/test/JsonApiDotNetCoreExampleTests/Acceptance/TodoItemsControllerTests.cs b/test/JsonApiDotNetCoreExampleTests/Acceptance/TodoItemsControllerTests.cs index 63b88a311c..2825371b7a 100644 --- a/test/JsonApiDotNetCoreExampleTests/Acceptance/TodoItemsControllerTests.cs +++ b/test/JsonApiDotNetCoreExampleTests/Acceptance/TodoItemsControllerTests.cs @@ -20,12 +20,12 @@ namespace JsonApiDotNetCoreExampleTests.Acceptance { [Collection("WebHostCollection")] - public class TodoItemControllerTests + public sealed class TodoItemControllerTests { - private TestFixture _fixture; - private AppDbContext _context; - private Faker _todoItemFaker; - private Faker _personFaker; + private readonly TestFixture _fixture; + private readonly AppDbContext _context; + private readonly Faker _todoItemFaker; + private readonly Faker _personFaker; public TodoItemControllerTests(TestFixture fixture) { @@ -161,11 +161,11 @@ public async Task Can_Filter_TodoItems_Using_IsNotNull_Operator() var otherTodoItem = _todoItemFaker.Generate(); otherTodoItem.UpdatedDate = null; - _context.TodoItems.AddRange(new[] { todoItem, otherTodoItem }); + _context.TodoItems.AddRange(todoItem, otherTodoItem); _context.SaveChanges(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/todoItems?filter[updatedDate]=isnotnull:"; + var route = "/api/v1/todoItems?filter[updatedDate]=isnotnull:"; var request = new HttpRequestMessage(httpMethod, route); // Act @@ -192,11 +192,11 @@ public async Task Can_Filter_TodoItems_ByParent_Using_IsNotNull_Operator() otherTodoItem.Assignee = null; _context.RemoveRange(_context.TodoItems); - _context.TodoItems.AddRange(new[] { todoItem, otherTodoItem }); + _context.TodoItems.AddRange(todoItem, otherTodoItem); _context.SaveChanges(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/todoItems?filter[assignee.id]=isnotnull:"; + var route = "/api/v1/todoItems?filter[assignee.id]=isnotnull:"; var request = new HttpRequestMessage(httpMethod, route); // Act @@ -220,11 +220,11 @@ public async Task Can_Filter_TodoItems_Using_IsNull_Operator() var otherTodoItem = _todoItemFaker.Generate(); otherTodoItem.UpdatedDate = new DateTime(); - _context.TodoItems.AddRange(new[] { todoItem, otherTodoItem }); + _context.TodoItems.AddRange(todoItem, otherTodoItem); _context.SaveChanges(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/todoItems?filter[updatedDate]=isnull:"; + var route = "/api/v1/todoItems?filter[updatedDate]=isnull:"; var request = new HttpRequestMessage(httpMethod, route); // Act @@ -250,11 +250,11 @@ public async Task Can_Filter_TodoItems_ByParent_Using_IsNull_Operator() var otherTodoItem = _todoItemFaker.Generate(); otherTodoItem.Assignee = new Person(); - _context.TodoItems.AddRange(new[] { todoItem, otherTodoItem }); + _context.TodoItems.AddRange(todoItem, otherTodoItem); _context.SaveChanges(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/todoItems?filter[assignee.id]=isnull:"; + var route = "/api/v1/todoItems?filter[assignee.id]=isnull:"; var request = new HttpRequestMessage(httpMethod, route); // Act @@ -316,7 +316,7 @@ public async Task Can_Sort_TodoItems_By_Ordinal_Ascending() _context.SaveChanges(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/todoItems?sort=ordinal"; + var route = "/api/v1/todoItems?sort=ordinal"; var request = new HttpRequestMessage(httpMethod, route); // Act @@ -431,7 +431,7 @@ public async Task Can_Sort_TodoItems_By_Ordinal_Descending() _context.SaveChanges(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/todoItems?sort=-ordinal"; + var route = "/api/v1/todoItems?sort=-ordinal"; var request = new HttpRequestMessage(httpMethod, route); // Act @@ -524,10 +524,12 @@ public async Task Can_Post_TodoItem() todoItem.OffsetDate = nowOffset; var httpMethod = new HttpMethod("POST"); - var route = $"/api/v1/todoItems"; + var route = "/api/v1/todoItems"; - var request = new HttpRequestMessage(httpMethod, route); - request.Content = new StringContent(serializer.Serialize(todoItem)); + var request = new HttpRequestMessage(httpMethod, route) + { + Content = new StringContent(serializer.Serialize(todoItem)) + }; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); // Act @@ -561,7 +563,7 @@ public async Task Can_Post_TodoItem_With_Different_Owner_And_Assignee() data = new { type = "todoItems", - attributes = new Dictionary() + attributes = new Dictionary { { "description", todoItem.Description }, { "ordinal", todoItem.Ordinal }, @@ -590,10 +592,12 @@ public async Task Can_Post_TodoItem_With_Different_Owner_And_Assignee() }; var httpMethod = new HttpMethod("POST"); - var route = $"/api/v1/todoItems"; + var route = "/api/v1/todoItems"; - var request = new HttpRequestMessage(httpMethod, route); - request.Content = new StringContent(JsonConvert.SerializeObject(content)); + var request = new HttpRequestMessage(httpMethod, route) + { + Content = new StringContent(JsonConvert.SerializeObject(content)) + }; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); // Act @@ -633,7 +637,7 @@ public async Task Can_Patch_TodoItem() { id = todoItem.Id, type = "todoItems", - attributes = new Dictionary() + attributes = new Dictionary { { "description", newTodoItem.Description }, { "ordinal", newTodoItem.Ordinal }, @@ -645,8 +649,10 @@ public async Task Can_Patch_TodoItem() var httpMethod = new HttpMethod("PATCH"); var route = $"/api/v1/todoItems/{todoItem.Id}"; - var request = new HttpRequestMessage(httpMethod, route); - request.Content = new StringContent(JsonConvert.SerializeObject(content)); + var request = new HttpRequestMessage(httpMethod, route) + { + Content = new StringContent(JsonConvert.SerializeObject(content)) + }; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); // Act @@ -671,13 +677,13 @@ public async Task Can_Patch_TodoItemWithNullable() _context.SaveChanges(); var todoItem = _todoItemFaker.Generate(); - todoItem.AchievedDate = System.DateTime.Now; + todoItem.AchievedDate = DateTime.Now; todoItem.Owner = person; _context.TodoItems.Add(todoItem); _context.SaveChanges(); var newTodoItem = _todoItemFaker.Generate(); - newTodoItem.AchievedDate = System.DateTime.Now.AddDays(2); + newTodoItem.AchievedDate = DateTime.Now.AddDays(2); var content = new { @@ -685,7 +691,7 @@ public async Task Can_Patch_TodoItemWithNullable() { id = todoItem.Id, type = "todoItems", - attributes = new Dictionary() + attributes = new Dictionary { { "description", newTodoItem.Description }, { "ordinal", newTodoItem.Ordinal }, @@ -698,8 +704,10 @@ public async Task Can_Patch_TodoItemWithNullable() var httpMethod = new HttpMethod("PATCH"); var route = $"/api/v1/todoItems/{todoItem.Id}"; - var request = new HttpRequestMessage(httpMethod, route); - request.Content = new StringContent(JsonConvert.SerializeObject(content)); + var request = new HttpRequestMessage(httpMethod, route) + { + Content = new StringContent(JsonConvert.SerializeObject(content)) + }; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); // Act @@ -724,7 +732,7 @@ public async Task Can_Patch_TodoItemWithNullValue() _context.SaveChanges(); var todoItem = _todoItemFaker.Generate(); - todoItem.AchievedDate = System.DateTime.Now; + todoItem.AchievedDate = DateTime.Now; todoItem.Owner = person; _context.TodoItems.Add(todoItem); _context.SaveChanges(); @@ -737,7 +745,7 @@ public async Task Can_Patch_TodoItemWithNullValue() { id = todoItem.Id, type = "todoItems", - attributes = new Dictionary() + attributes = new Dictionary { { "description", newTodoItem.Description }, { "ordinal", newTodoItem.Ordinal }, @@ -750,8 +758,10 @@ public async Task Can_Patch_TodoItemWithNullValue() var httpMethod = new HttpMethod("PATCH"); var route = $"/api/v1/todoItems/{todoItem.Id}"; - var request = new HttpRequestMessage(httpMethod, route); - request.Content = new StringContent(JsonConvert.SerializeObject(content)); + var request = new HttpRequestMessage(httpMethod, route) + { + Content = new StringContent(JsonConvert.SerializeObject(content)) + }; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); // Act @@ -783,8 +793,7 @@ public async Task Can_Delete_TodoItem() var httpMethod = new HttpMethod("DELETE"); var route = $"/api/v1/todoItems/{todoItem.Id}"; - var request = new HttpRequestMessage(httpMethod, route); - request.Content = new StringContent(string.Empty); + var request = new HttpRequestMessage(httpMethod, route) {Content = new StringContent(string.Empty)}; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); // Act diff --git a/test/JsonApiDotNetCoreExampleTests/Helpers/Extensions/DocumentExtensions.cs b/test/JsonApiDotNetCoreExampleTests/Helpers/Extensions/DocumentExtensions.cs index 298b86812c..0255fb7e36 100644 --- a/test/JsonApiDotNetCoreExampleTests/Helpers/Extensions/DocumentExtensions.cs +++ b/test/JsonApiDotNetCoreExampleTests/Helpers/Extensions/DocumentExtensions.cs @@ -1,13 +1,6 @@ -using System; using System.Collections.Generic; using System.Linq; -using System.Reflection; using JsonApiDotNetCore.Models; -using Microsoft.EntityFrameworkCore.Internal; -using Microsoft.EntityFrameworkCore.Query; -using Microsoft.EntityFrameworkCore.Query.Internal; -using Microsoft.EntityFrameworkCore.Storage; -using Database = Microsoft.EntityFrameworkCore.Storage.Database; namespace JsonApiDotNetCoreExampleTests.Helpers.Extensions { @@ -15,16 +8,14 @@ public static class DocumentExtensions { public static ResourceObject FindResource(this List included, string type, TId id) { - var document = included.Where(documentData => ( - documentData.Type == type - && documentData.Id == id.ToString() - )).FirstOrDefault(); + var document = included.FirstOrDefault(documentData => + documentData.Type == type && documentData.Id == id.ToString()); return document; } public static int CountOfType(this List included, string type) { - return included.Where(documentData => documentData.Type == type).Count(); + return included.Count(documentData => documentData.Type == type); } } } diff --git a/test/JsonApiDotNetCoreExampleTests/Helpers/Extensions/StringExtensions.cs b/test/JsonApiDotNetCoreExampleTests/Helpers/Extensions/StringExtensions.cs deleted file mode 100644 index dbe6b19feb..0000000000 --- a/test/JsonApiDotNetCoreExampleTests/Helpers/Extensions/StringExtensions.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Text.RegularExpressions; - -namespace JsonApiDotNetCoreExampleTests.Helpers.Extensions -{ - public static class StringExtensions - { - public static string Normalize(this string input) - { - return Regex.Replace(input, @"\s+", string.Empty) - .ToUpper() - .Replace("\"", string.Empty) - .Replace("'", string.Empty); - } - } -} diff --git a/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs b/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs index dc6506afdc..ca21468d76 100644 --- a/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs +++ b/test/NoEntityFrameworkTests/Acceptance/Extensibility/NoEntityFrameworkTests.cs @@ -12,7 +12,7 @@ namespace NoEntityFrameworkTests.Acceptance.Extensibility { - public class NoEntityFrameworkTests : IClassFixture + public sealed class NoEntityFrameworkTests : IClassFixture { private readonly TestFixture _fixture; @@ -31,7 +31,7 @@ public async Task Can_Get_TodoItems() var client = _fixture.Server.CreateClient(); var httpMethod = new HttpMethod("GET"); - var route = $"/api/v1/todoItems"; + var route = "/api/v1/todoItems"; var request = new HttpRequestMessage(httpMethod, route); @@ -78,7 +78,7 @@ public async Task Can_Create_TodoItems() // Arrange var description = Guid.NewGuid().ToString(); var httpMethod = new HttpMethod("POST"); - var route = $"/api/v1/todoItems/"; + var route = "/api/v1/todoItems/"; var content = new { data = new @@ -92,8 +92,10 @@ public async Task Can_Create_TodoItems() } }; - var request = new HttpRequestMessage(httpMethod, route); - request.Content = new StringContent(JsonConvert.SerializeObject(content)); + var request = new HttpRequestMessage(httpMethod, route) + { + Content = new StringContent(JsonConvert.SerializeObject(content)) + }; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); var builder = new WebHostBuilder() diff --git a/test/NoEntityFrameworkTests/TestFixture.cs b/test/NoEntityFrameworkTests/TestFixture.cs index 6a5f294a94..5196a1d7a8 100644 --- a/test/NoEntityFrameworkTests/TestFixture.cs +++ b/test/NoEntityFrameworkTests/TestFixture.cs @@ -14,9 +14,9 @@ namespace NoEntityFrameworkTests { public class TestFixture : IDisposable { - public AppDbContext Context { get; private set; } - public TestServer Server { get; private set; } - private IServiceProvider _services; + public AppDbContext Context { get; } + public TestServer Server { get; } + private readonly IServiceProvider _services; public TestFixture() { var builder = new WebHostBuilder().UseStartup(); diff --git a/test/NoEntityFrameworkTests/TestScopedServiceProvider.cs b/test/NoEntityFrameworkTests/TestScopedServiceProvider.cs index 69628ff8f1..6d209dc491 100644 --- a/test/NoEntityFrameworkTests/TestScopedServiceProvider.cs +++ b/test/NoEntityFrameworkTests/TestScopedServiceProvider.cs @@ -5,10 +5,10 @@ namespace NoEntityFrameworkTests { - public class TestScopedServiceProvider : IScopedServiceProvider + public sealed class TestScopedServiceProvider : IScopedServiceProvider { private readonly IServiceProvider _serviceProvider; - private Mock _httpContextAccessorMock = new Mock(); + private readonly Mock _httpContextAccessorMock = new Mock(); public TestScopedServiceProvider(IServiceProvider serviceProvider) { diff --git a/test/NoEntityFrameworkTests/TestStartup.cs b/test/NoEntityFrameworkTests/TestStartup.cs index ad0022a197..986706c9db 100644 --- a/test/NoEntityFrameworkTests/TestStartup.cs +++ b/test/NoEntityFrameworkTests/TestStartup.cs @@ -5,7 +5,7 @@ namespace NoEntityFrameworkTests { - public class TestStartup : Startup + public sealed class TestStartup : Startup { public TestStartup(IWebHostEnvironment env) : base(env) { } diff --git a/test/UnitTests/Builders/ContextGraphBuilder_Tests.cs b/test/UnitTests/Builders/ContextGraphBuilder_Tests.cs index 434f2ba27d..ccb8eb2ad9 100644 --- a/test/UnitTests/Builders/ContextGraphBuilder_Tests.cs +++ b/test/UnitTests/Builders/ContextGraphBuilder_Tests.cs @@ -4,7 +4,6 @@ using System.Reflection; using Humanizer; using JsonApiDotNetCore.Builders; -using JsonApiDotNetCore.Extensions; using JsonApiDotNetCore.Extensions.EntityFrameworkCore; using JsonApiDotNetCore.Graph; using JsonApiDotNetCore.Internal.Contracts; @@ -15,11 +14,13 @@ namespace UnitTests { - public class ResourceGraphBuilder_Tests + public sealed class ResourceGraphBuilder_Tests { - class NonDbResource : Identifiable { } - class DbResource : Identifiable { } - class TestContext : DbContext + private sealed class NonDbResource : Identifiable { } + + private sealed class DbResource : Identifiable { } + + private class TestContext : DbContext { public DbSet DbResources { get; set; } } @@ -119,7 +120,7 @@ public void Relationships_Without_Names_Specified_Will_Use_Default_Formatter() Assert.Equal("relatedResources", resource.Relationships.Single(r => r.IsHasMany).PublicRelationshipName); } - public class TestResource : Identifiable + public sealed class TestResource : Identifiable { [Attr] public string CompoundAttribute { get; set; } [HasOne] public RelatedResource RelatedResource { get; set; } @@ -128,7 +129,7 @@ public class TestResource : Identifiable public class RelatedResource : Identifiable { } - public class CamelCaseNameFormatter : IResourceNameFormatter + public sealed class CamelCaseNameFormatter : IResourceNameFormatter { public string ApplyCasingConvention(string properName) => ToCamelCase(properName); diff --git a/test/UnitTests/Builders/LinkBuilderTests.cs b/test/UnitTests/Builders/LinkBuilderTests.cs index 5408fbf809..1867c31b08 100644 --- a/test/UnitTests/Builders/LinkBuilderTests.cs +++ b/test/UnitTests/Builders/LinkBuilderTests.cs @@ -1,4 +1,3 @@ -using System; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Internal; using JsonApiDotNetCore.Internal.Contracts; @@ -14,7 +13,7 @@ namespace UnitTests { - public class LinkBuilderTests + public sealed class LinkBuilderTests { private readonly IPageService _pageService; private readonly Mock _provider = new Mock(); @@ -213,7 +212,7 @@ private IPageService GetPageManager() mock.Setup(m => m.CanPaginate).Returns(true); mock.Setup(m => m.CurrentPage).Returns(2); mock.Setup(m => m.TotalPages).Returns(3); - mock.Setup(m => m.CurrentPageSize).Returns(10); + mock.Setup(m => m.PageSize).Returns(10); return mock.Object; } diff --git a/test/UnitTests/Builders/LinkTests.cs b/test/UnitTests/Builders/LinkTests.cs index 96d49b2f22..df1504930c 100644 --- a/test/UnitTests/Builders/LinkTests.cs +++ b/test/UnitTests/Builders/LinkTests.cs @@ -3,7 +3,7 @@ namespace UnitTests.Builders { - public class LinkTests + public sealed class LinkTests { [Theory] [InlineData(Link.All, Link.Self, true)] diff --git a/test/UnitTests/Controllers/BaseJsonApiController_Tests.cs b/test/UnitTests/Controllers/BaseJsonApiController_Tests.cs index 2044ca72dd..aec9a5a438 100644 --- a/test/UnitTests/Controllers/BaseJsonApiController_Tests.cs +++ b/test/UnitTests/Controllers/BaseJsonApiController_Tests.cs @@ -13,14 +13,14 @@ namespace UnitTests { - public class BaseJsonApiController_Tests + public sealed class BaseJsonApiController_Tests { - public class Resource : Identifiable + public sealed class Resource : Identifiable { [Attr] public string TestAttribute { get; set; } } - public class ResourceController : BaseJsonApiController + public sealed class ResourceController : BaseJsonApiController { public ResourceController( IJsonApiOptions jsonApiOptions, @@ -92,7 +92,7 @@ public async Task GetAsyncById_Throws_405_If_No_Service() { // Arrange const int id = 0; - var controller = new ResourceController(new Mock().Object, NullLoggerFactory.Instance, getById: null); + var controller = new ResourceController(new Mock().Object, NullLoggerFactory.Instance); // Act var exception = await Assert.ThrowsAsync(() => controller.GetAsync(id)); @@ -121,7 +121,7 @@ public async Task GetRelationshipsAsync_Throws_405_If_No_Service() { // Arrange const int id = 0; - var controller = new ResourceController(new Mock().Object, NullLoggerFactory.Instance, getRelationships: null); + var controller = new ResourceController(new Mock().Object, NullLoggerFactory.Instance); // Act var exception = await Assert.ThrowsAsync(() => controller.GetRelationshipsAsync(id, string.Empty)); @@ -150,7 +150,7 @@ public async Task GetRelationshipAsync_Throws_405_If_No_Service() { // Arrange const int id = 0; - var controller = new ResourceController(new Mock().Object, NullLoggerFactory.Instance, getRelationship: null); + var controller = new ResourceController(new Mock().Object, NullLoggerFactory.Instance); // Act var exception = await Assert.ThrowsAsync(() => controller.GetRelationshipAsync(id, string.Empty)); @@ -218,7 +218,7 @@ public async Task PatchAsync_Throws_405_If_No_Service() { // Arrange const int id = 0; - var controller = new ResourceController(new Mock().Object, NullLoggerFactory.Instance, update: null); + var controller = new ResourceController(new Mock().Object, NullLoggerFactory.Instance); // Act var exception = await Assert.ThrowsAsync(() => controller.PatchAsync(id, It.IsAny())); @@ -236,7 +236,7 @@ public async Task PostAsync_Calls_Service() var controller = new ResourceController(new JsonApiOptions(), NullLoggerFactory.Instance, create: serviceMock.Object); serviceMock.Setup(m => m.CreateAsync(It.IsAny())).ReturnsAsync(resource); - controller.ControllerContext = new Microsoft.AspNetCore.Mvc.ControllerContext { HttpContext = new DefaultHttpContext() }; + controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }; // Act await controller.PostAsync(resource); @@ -251,8 +251,14 @@ public async Task PostAsync_ModelStateInvalid_ValidateModelStateDisabled() // Arrange var resource = new Resource(); var serviceMock = new Mock>(); - var controller = new ResourceController(new JsonApiOptions { ValidateModelState = false }, NullLoggerFactory.Instance, create: serviceMock.Object); - controller.ControllerContext = new Microsoft.AspNetCore.Mvc.ControllerContext { HttpContext = new DefaultHttpContext() }; + var controller = new ResourceController(new JsonApiOptions {ValidateModelState = false}, + NullLoggerFactory.Instance, create: serviceMock.Object) + { + ControllerContext = new ControllerContext + { + HttpContext = new DefaultHttpContext() + } + }; serviceMock.Setup(m => m.CreateAsync(It.IsAny())).ReturnsAsync(resource); // Act @@ -269,8 +275,11 @@ public async Task PostAsync_ModelStateInvalid_ValidateModelStateEnabled() // Arrange var resource = new Resource(); var serviceMock = new Mock>(); - var controller = new ResourceController(new JsonApiOptions { ValidateModelState = true }, NullLoggerFactory.Instance, create: serviceMock.Object); - controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() }; + var controller = new ResourceController(new JsonApiOptions {ValidateModelState = true}, + NullLoggerFactory.Instance, create: serviceMock.Object) + { + ControllerContext = new ControllerContext {HttpContext = new DefaultHttpContext()} + }; controller.ModelState.AddModelError("TestAttribute", "Failed Validation"); serviceMock.Setup(m => m.CreateAsync(It.IsAny())).ReturnsAsync(resource); @@ -303,7 +312,7 @@ public async Task PatchRelationshipsAsync_Throws_405_If_No_Service() { // Arrange const int id = 0; - var controller = new ResourceController(new Mock().Object, NullLoggerFactory.Instance, updateRelationships: null); + var controller = new ResourceController(new Mock().Object, NullLoggerFactory.Instance); // Act var exception = await Assert.ThrowsAsync(() => controller.PatchRelationshipsAsync(id, string.Empty, null)); @@ -332,8 +341,7 @@ public async Task DeleteAsync_Throws_405_If_No_Service() { // Arrange const int id = 0; - var controller = new ResourceController(new Mock().Object, NullLoggerFactory.Instance, - delete: null); + var controller = new ResourceController(new Mock().Object, NullLoggerFactory.Instance); // Act var exception = await Assert.ThrowsAsync(() => controller.DeleteAsync(id)); diff --git a/test/UnitTests/Controllers/JsonApiControllerMixin_Tests.cs b/test/UnitTests/Controllers/JsonApiControllerMixin_Tests.cs index 00f265daed..51fb451c42 100644 --- a/test/UnitTests/Controllers/JsonApiControllerMixin_Tests.cs +++ b/test/UnitTests/Controllers/JsonApiControllerMixin_Tests.cs @@ -6,7 +6,7 @@ namespace UnitTests { - public class JsonApiControllerMixin_Tests : JsonApiControllerMixin + public sealed class JsonApiControllerMixin_Tests : JsonApiControllerMixin { [Fact] diff --git a/test/UnitTests/Data/DefaultEntityRepositoryTest.cs b/test/UnitTests/Data/DefaultEntityRepositoryTest.cs index 3c9fca2951..3633000a70 100644 --- a/test/UnitTests/Data/DefaultEntityRepositoryTest.cs +++ b/test/UnitTests/Data/DefaultEntityRepositoryTest.cs @@ -1,22 +1,18 @@ -using JsonApiDotNetCore.Builders; using JsonApiDotNetCore.Data; using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Serialization; -using JsonApiDotNetCoreExample.Data; using JsonApiDotNetCoreExample.Models; using Microsoft.EntityFrameworkCore; using Moq; -using System; using System.Collections.Generic; using System.Linq; -using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Logging.Abstractions; using Xunit; namespace UnitTests.Data { - public class DefaultEntityRepositoryTest + public sealed class DefaultEntityRepositoryTest { [Fact] @@ -27,7 +23,8 @@ public async Task PageAsync_IQueryableIsAListAndPageNumberPositive_CanStillCount // Arrange var repository = Setup(); - var todoItems = new List() { + var todoItems = new List + { new TodoItem{ Id = 1 }, new TodoItem{ Id = 2 } }; @@ -47,7 +44,8 @@ public async Task PageAsync_IQueryableIsAListAndPageNumberNegative_CanStillCount // Arrange var repository = Setup(); - var todoItems = new List() { + var todoItems = new List + { new TodoItem{ Id = 1 }, new TodoItem{ Id = 2 }, new TodoItem{ Id = 3 }, diff --git a/test/UnitTests/DbSetMock.cs b/test/UnitTests/DbSetMock.cs index f6ad7a2915..2921a8247b 100644 --- a/test/UnitTests/DbSetMock.cs +++ b/test/UnitTests/DbSetMock.cs @@ -37,7 +37,7 @@ public static Mock> AsDbSetMock(this List list) where T : class } } -internal class TestAsyncQueryProvider : IAsyncQueryProvider +internal sealed class TestAsyncQueryProvider : IAsyncQueryProvider { private readonly IQueryProvider _inner; @@ -83,12 +83,8 @@ TResult IAsyncQueryProvider.ExecuteAsync(Expression expression, Cancell } } -internal class TestAsyncEnumerable : EnumerableQuery, IAsyncEnumerable, IQueryable +internal sealed class TestAsyncEnumerable : EnumerableQuery, IAsyncEnumerable, IQueryable { - public TestAsyncEnumerable(IEnumerable enumerable) - : base(enumerable) - { } - public TestAsyncEnumerable(Expression expression) : base(expression) { } @@ -103,13 +99,10 @@ public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToke throw new System.NotImplementedException(); } - IQueryProvider IQueryable.Provider - { - get { return new TestAsyncQueryProvider(this); } - } + IQueryProvider IQueryable.Provider => new TestAsyncQueryProvider(this); } -internal class TestAsyncEnumerator : IAsyncEnumerator +internal sealed class TestAsyncEnumerator : IAsyncEnumerator { private readonly IEnumerator _inner; @@ -123,13 +116,7 @@ public void Dispose() _inner.Dispose(); } - public T Current - { - get - { - return _inner.Current; - } - } + public T Current => _inner.Current; public Task MoveNext(CancellationToken cancellationToken) { diff --git a/test/UnitTests/Extensions/IServiceCollectionExtensionsTests.cs b/test/UnitTests/Extensions/IServiceCollectionExtensionsTests.cs index 2b9f3c2cb8..d42be16de5 100644 --- a/test/UnitTests/Extensions/IServiceCollectionExtensionsTests.cs +++ b/test/UnitTests/Extensions/IServiceCollectionExtensionsTests.cs @@ -1,4 +1,3 @@ -using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Data; using JsonApiDotNetCore.Extensions; using JsonApiDotNetCore.Formatters; @@ -23,7 +22,7 @@ namespace UnitTests.Extensions { - public class IServiceCollectionExtensionsTests + public sealed class IServiceCollectionExtensionsTests { [Fact] public void AddJsonApiInternals_Adds_All_Required_Services() @@ -155,7 +154,7 @@ public void AddJsonApi_With_Context_Uses_Resource_Type_Name_If_NoOtherSpecified( Assert.Equal("intResources", resource.ResourceName); } - public class IntResource : Identifiable { } + public sealed class IntResource : Identifiable { } public class GuidResource : Identifiable { } private class IntResourceService : IResourceService diff --git a/test/UnitTests/Extensions/TypeExtensions_Tests.cs b/test/UnitTests/Extensions/TypeExtensions_Tests.cs index b473ceb5e3..849b80d1f6 100644 --- a/test/UnitTests/Extensions/TypeExtensions_Tests.cs +++ b/test/UnitTests/Extensions/TypeExtensions_Tests.cs @@ -6,7 +6,7 @@ namespace UnitTests.Extensions { - public class TypeExtensions_Tests + public sealed class TypeExtensions_Tests { [Fact] public void GetCollection_Creates_List_If_T_Implements_Interface() @@ -63,7 +63,7 @@ public void Implements_Returns_False_If_Type_DoesNot_Implement_Interface() Assert.False(result); } - private class Model : IIdentifiable + private sealed class Model : IIdentifiable { public string StringId { get; set; } } diff --git a/test/UnitTests/Graph/TypeLocator_Tests.cs b/test/UnitTests/Graph/TypeLocator_Tests.cs index ca70b32581..dfd4e723c4 100644 --- a/test/UnitTests/Graph/TypeLocator_Tests.cs +++ b/test/UnitTests/Graph/TypeLocator_Tests.cs @@ -5,7 +5,7 @@ namespace UnitTests.Internal { - public class TypeLocator_Tests + public sealed class TypeLocator_Tests { [Fact] public void GetGenericInterfaceImplementation_Gets_Implementation() @@ -139,11 +139,11 @@ public void TryGetResourceDescriptor_Returns_False_If_Type_Is_IIdentifiable() public interface IGenericInterface { } - public class Implementation : IGenericInterface { } + public sealed class Implementation : IGenericInterface { } public class BaseType { } - public class DerivedType : BaseType { } + public sealed class DerivedType : BaseType { } - public class Model : Identifiable { } + public sealed class Model : Identifiable { } } diff --git a/test/UnitTests/Internal/JsonApiException_Test.cs b/test/UnitTests/Internal/JsonApiException_Test.cs index 57ac29d480..989db27ef3 100644 --- a/test/UnitTests/Internal/JsonApiException_Test.cs +++ b/test/UnitTests/Internal/JsonApiException_Test.cs @@ -3,7 +3,7 @@ namespace UnitTests.Internal { - public class JsonApiException_Test + public sealed class JsonApiException_Test { [Fact] public void Can_GetStatusCode() diff --git a/test/UnitTests/Internal/ResourceGraphBuilder_Tests.cs b/test/UnitTests/Internal/ResourceGraphBuilder_Tests.cs index e765004ac5..e6475f242d 100644 --- a/test/UnitTests/Internal/ResourceGraphBuilder_Tests.cs +++ b/test/UnitTests/Internal/ResourceGraphBuilder_Tests.cs @@ -7,7 +7,7 @@ namespace UnitTests.Internal { - public class ResourceGraphBuilder_Tests + public sealed class ResourceGraphBuilder_Tests { [Fact] public void AddDbContext_Does_Not_Throw_If_Context_Contains_Members_That_DoNot_Implement_IIdentifiable() diff --git a/test/UnitTests/Internal/TypeHelper_Tests.cs b/test/UnitTests/Internal/TypeHelper_Tests.cs index 287444aea4..387d0cfdc3 100644 --- a/test/UnitTests/Internal/TypeHelper_Tests.cs +++ b/test/UnitTests/Internal/TypeHelper_Tests.cs @@ -5,7 +5,7 @@ namespace UnitTests.Internal { - public class TypeHelper_Tests + public sealed class TypeHelper_Tests { [Fact] public void Can_Convert_DateTimeOffsets() @@ -136,7 +136,7 @@ private enum TestEnum Test = 1 } - private class ComplexType : BaseType + private sealed class ComplexType : BaseType { public int Property { get; set; } } diff --git a/test/UnitTests/Middleware/CurrentRequestMiddlewareTests.cs b/test/UnitTests/Middleware/CurrentRequestMiddlewareTests.cs index c224207a5d..120c0cd41d 100644 --- a/test/UnitTests/Middleware/CurrentRequestMiddlewareTests.cs +++ b/test/UnitTests/Middleware/CurrentRequestMiddlewareTests.cs @@ -1,26 +1,21 @@ using JsonApiDotNetCore.Configuration; -using JsonApiDotNetCore.Controllers; using JsonApiDotNetCore.Internal; using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Managers; using JsonApiDotNetCore.Middleware; using JsonApiDotNetCore.Models; -using JsonApiDotNetCoreExample.Models; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; -using Microsoft.AspNetCore.Routing; using Moq; using System; -using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; using System.Threading.Tasks; using Xunit; namespace UnitTests.Middleware { - public class CurrentRequestMiddlewareTests + public sealed class CurrentRequestMiddlewareTests { [Fact] public async Task ParseUrlBase_ObfuscatedIdClass_ShouldSetIdCorrectly() @@ -97,7 +92,7 @@ public async Task ParseUrlBase_UrlHasIncorrectBaseIdSet_ShouldThrowException(str Assert.Contains(baseId, exception.Message); } - class InvokeConfiguration + private sealed class InvokeConfiguration { public CurrentRequestMiddleware MiddleWare; public HttpContext HttpContext; @@ -121,7 +116,7 @@ private InvokeConfiguration GetConfiguration(string path, string resourceName = { throw new ArgumentException("Path should start with a '/'"); } - var middleware = new CurrentRequestMiddleware((context) => + var middleware = new CurrentRequestMiddleware(httpContext => { return Task.Run(() => Console.WriteLine("finished")); }); @@ -161,9 +156,10 @@ private static DefaultHttpContext CreateHttpContext(string path, bool isRelation var context = new DefaultHttpContext(); context.Request.Path = new PathString(path); context.Response.Body = new MemoryStream(); - var feature = new RouteValuesFeature(); - feature.RouteValues["controller"] = "fake!"; - feature.RouteValues["action"] = isRelationship ? "GetRelationship" : action; + var feature = new RouteValuesFeature + { + RouteValues = {["controller"] = "fake!", ["action"] = isRelationship ? "GetRelationship" : action} + }; if(id != null) { feature.RouteValues["id"] = id; diff --git a/test/UnitTests/Models/AttributesEqualsTests.cs b/test/UnitTests/Models/AttributesEqualsTests.cs index 297216db61..5aa4ba1bd1 100644 --- a/test/UnitTests/Models/AttributesEqualsTests.cs +++ b/test/UnitTests/Models/AttributesEqualsTests.cs @@ -1,10 +1,9 @@ -using System.Collections.Generic; using JsonApiDotNetCore.Models; using Xunit; namespace UnitTests.Models { - public class AttributesEqualsTests + public sealed class AttributesEqualsTests { [Fact] public void HasManyAttribute_Equals_Returns_True_When_Same_Name() diff --git a/test/UnitTests/Models/IdentifiableTests.cs b/test/UnitTests/Models/IdentifiableTests.cs index da4e30360a..971a936e39 100644 --- a/test/UnitTests/Models/IdentifiableTests.cs +++ b/test/UnitTests/Models/IdentifiableTests.cs @@ -3,21 +3,19 @@ namespace UnitTests.Models { - public class IdentifiableTests + public sealed class IdentifiableTests { [Fact] public void Can_Set_StringId_To_Value_Type() { - var resource = new IntId(); - resource.StringId = "1"; + var resource = new IntId {StringId = "1"}; Assert.Equal(1, resource.Id); } [Fact] public void Setting_StringId_To_Null_Sets_Id_As_Default() { - var resource = new IntId(); - resource.StringId = null; + var resource = new IntId {StringId = null}; Assert.Equal(0, resource.Id); } @@ -29,7 +27,7 @@ public void GetStringId_Returns_EmptyString_If_Object_Is_Null() Assert.Equal(string.Empty, stringId); } - private class IntId : Identifiable { + private sealed class IntId : Identifiable { public string ExposedGetStringId(object value) => GetStringId(value); } } diff --git a/test/UnitTests/Models/LinkTests.cs b/test/UnitTests/Models/LinkTests.cs index f8f163fa03..69ef23d577 100644 --- a/test/UnitTests/Models/LinkTests.cs +++ b/test/UnitTests/Models/LinkTests.cs @@ -1,10 +1,9 @@ -using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Models.Links; using Xunit; namespace UnitTests.Models { - public class LinkTests + public sealed class LinkTests { [Fact] public void All_Contains_All_Flags_Except_None() diff --git a/test/UnitTests/Models/RelationshipDataTests.cs b/test/UnitTests/Models/RelationshipDataTests.cs index eaa52440e6..8eb271ff52 100644 --- a/test/UnitTests/Models/RelationshipDataTests.cs +++ b/test/UnitTests/Models/RelationshipDataTests.cs @@ -1,11 +1,11 @@ -using System.Collections.Generic; +using System.Collections.Generic; using JsonApiDotNetCore.Models; using Newtonsoft.Json.Linq; using Xunit; namespace UnitTests.Models { - public class RelationshipDataTests + public sealed class RelationshipDataTests { [Fact] public void Setting_ExposeData_To_List_Sets_ManyData() diff --git a/test/UnitTests/Models/ResourceDefinitionTests.cs b/test/UnitTests/Models/ResourceDefinitionTests.cs index d498042b34..67f7fdf40f 100644 --- a/test/UnitTests/Models/ResourceDefinitionTests.cs +++ b/test/UnitTests/Models/ResourceDefinitionTests.cs @@ -1,24 +1,13 @@ using JsonApiDotNetCore.Builders; -using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Internal.Query; using JsonApiDotNetCore.Models; -using JsonApiDotNetCore.Services; using System.Linq; using Xunit; namespace UnitTests.Models { - public class ResourceDefinition_Scenario_Tests + public sealed class ResourceDefinition_Scenario_Tests { - private readonly IResourceGraph _resourceGraph; - - public ResourceDefinition_Scenario_Tests() - { - _resourceGraph = new ResourceGraphBuilder() - .AddResource("models") - .Build(); - } - [Fact] public void Request_Filter_Uses_Member_Expression() { @@ -54,7 +43,7 @@ public class Model : Identifiable [Attr] public string Prop { get; set; } } - public class RequestFilteredResource : ResourceDefinition + public sealed class RequestFilteredResource : ResourceDefinition { // this constructor will be resolved from the container // that means you can take on any dependency that is also defined in the container diff --git a/test/UnitTests/QueryParameters/FilterServiceTests.cs b/test/UnitTests/QueryParameters/FilterServiceTests.cs index 68937ee793..df7390124a 100644 --- a/test/UnitTests/QueryParameters/FilterServiceTests.cs +++ b/test/UnitTests/QueryParameters/FilterServiceTests.cs @@ -7,7 +7,7 @@ namespace UnitTests.QueryParameters { - public class FilterServiceTests : QueryParametersUnitTestCollection + public sealed class FilterServiceTests : QueryParametersUnitTestCollection { public FilterService GetService() { diff --git a/test/UnitTests/QueryParameters/IncludeServiceTests.cs b/test/UnitTests/QueryParameters/IncludeServiceTests.cs index 5c98aa2f04..d2eef40f9c 100644 --- a/test/UnitTests/QueryParameters/IncludeServiceTests.cs +++ b/test/UnitTests/QueryParameters/IncludeServiceTests.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using JsonApiDotNetCore.Internal; @@ -9,7 +8,7 @@ namespace UnitTests.QueryParameters { - public class IncludeServiceTests : QueryParametersUnitTestCollection + public sealed class IncludeServiceTests : QueryParametersUnitTestCollection { public IncludeService GetService(ResourceContext resourceContext = null) diff --git a/test/UnitTests/QueryParameters/OmitDefaultService.cs b/test/UnitTests/QueryParameters/OmitDefaultService.cs index 522c15049c..32b5aa0976 100644 --- a/test/UnitTests/QueryParameters/OmitDefaultService.cs +++ b/test/UnitTests/QueryParameters/OmitDefaultService.cs @@ -6,7 +6,7 @@ namespace UnitTests.QueryParameters { - public class OmitDefaultServiceTests : QueryParametersUnitTestCollection + public sealed class OmitDefaultServiceTests : QueryParametersUnitTestCollection { public OmitDefaultService GetService(bool @default, bool @override) { @@ -39,7 +39,7 @@ public void Name_OmitNullService_IsCorrect() public void Parse_QueryConfigWithApiSettings_CanParse(string queryConfig, bool @default, bool @override, bool expected) { // Arrange - var query = new KeyValuePair($"omitNull", new StringValues(queryConfig)); + var query = new KeyValuePair("omitNull", new StringValues(queryConfig)); var service = GetService(@default, @override); // Act diff --git a/test/UnitTests/QueryParameters/OmitNullService.cs b/test/UnitTests/QueryParameters/OmitNullService.cs index f4ec0e0ed5..98758cd171 100644 --- a/test/UnitTests/QueryParameters/OmitNullService.cs +++ b/test/UnitTests/QueryParameters/OmitNullService.cs @@ -6,7 +6,7 @@ namespace UnitTests.QueryParameters { - public class OmitNullServiceTests : QueryParametersUnitTestCollection + public sealed class OmitNullServiceTests : QueryParametersUnitTestCollection { public OmitNullService GetService(bool @default, bool @override) { @@ -39,7 +39,7 @@ public void Name_OmitNullService_IsCorrect() public void Parse_QueryConfigWithApiSettings_CanParse(string queryConfig, bool @default, bool @override, bool expected) { // Arrange - var query = new KeyValuePair($"omitNull", new StringValues(queryConfig)); + var query = new KeyValuePair("omitNull", new StringValues(queryConfig)); var service = GetService(@default, @override); // Act diff --git a/test/UnitTests/QueryParameters/PageServiceTests.cs b/test/UnitTests/QueryParameters/PageServiceTests.cs index c59b8a6e82..d157d1efda 100644 --- a/test/UnitTests/QueryParameters/PageServiceTests.cs +++ b/test/UnitTests/QueryParameters/PageServiceTests.cs @@ -7,9 +7,9 @@ namespace UnitTests.QueryParameters { - public class PageServiceTests : QueryParametersUnitTestCollection + public sealed class PageServiceTests : QueryParametersUnitTestCollection { - public PageService GetService(int? maximumPageSize = null, int? maximumPageNumber = null) + public IPageService GetService(int? maximumPageSize = null, int? maximumPageNumber = null) { return new PageService(new JsonApiOptions { @@ -40,7 +40,7 @@ public void Name_PageService_IsCorrect() public void Parse_PageSize_CanParse(string value, int expectedValue, int? maximumPageSize, bool shouldThrow) { // Arrange - var query = new KeyValuePair($"page[size]", new StringValues(value)); + var query = new KeyValuePair("page[size]", new StringValues(value)); var service = GetService(maximumPageSize: maximumPageSize); // Act @@ -52,7 +52,7 @@ public void Parse_PageSize_CanParse(string value, int expectedValue, int? maximu else { service.Parse(query); - Assert.Equal(expectedValue, service.CurrentPageSize); + Assert.Equal(expectedValue, service.PageSize); } } @@ -65,7 +65,7 @@ public void Parse_PageSize_CanParse(string value, int expectedValue, int? maximu public void Parse_PageNumber_CanParse(string value, int expectedValue, int? maximumPageNumber, bool shouldThrow) { // Arrange - var query = new KeyValuePair($"page[number]", new StringValues(value)); + var query = new KeyValuePair("page[number]", new StringValues(value)); var service = GetService(maximumPageNumber: maximumPageNumber); // Act diff --git a/test/UnitTests/QueryParameters/SortServiceTests.cs b/test/UnitTests/QueryParameters/SortServiceTests.cs index 4284b89790..ca86183626 100644 --- a/test/UnitTests/QueryParameters/SortServiceTests.cs +++ b/test/UnitTests/QueryParameters/SortServiceTests.cs @@ -6,7 +6,7 @@ namespace UnitTests.QueryParameters { - public class SortServiceTests : QueryParametersUnitTestCollection + public sealed class SortServiceTests : QueryParametersUnitTestCollection { public SortService GetService() { @@ -33,7 +33,7 @@ public void Name_SortService_IsCorrect() public void Parse_InvalidSortQuery_ThrowsJsonApiException(string stringSortQuery) { // Arrange - var query = new KeyValuePair($"sort", stringSortQuery); + var query = new KeyValuePair("sort", stringSortQuery); var sortService = GetService(); // Act, assert diff --git a/test/UnitTests/QueryParameters/SparseFieldsServiceTests.cs b/test/UnitTests/QueryParameters/SparseFieldsServiceTests.cs index 6b0df9e779..c615854066 100644 --- a/test/UnitTests/QueryParameters/SparseFieldsServiceTests.cs +++ b/test/UnitTests/QueryParameters/SparseFieldsServiceTests.cs @@ -8,7 +8,7 @@ namespace UnitTests.QueryParameters { - public class SparseFieldsServiceTests : QueryParametersUnitTestCollection + public sealed class SparseFieldsServiceTests : QueryParametersUnitTestCollection { public SparseFieldsService GetService(ResourceContext resourceContext = null) { diff --git a/test/UnitTests/ResourceHooks/AffectedEntitiesHelperTests.cs b/test/UnitTests/ResourceHooks/AffectedEntitiesHelperTests.cs index 972442b155..34be2b6ea8 100644 --- a/test/UnitTests/ResourceHooks/AffectedEntitiesHelperTests.cs +++ b/test/UnitTests/ResourceHooks/AffectedEntitiesHelperTests.cs @@ -7,7 +7,7 @@ namespace UnitTests.ResourceHooks.AffectedEntities { - public class Dummy : Identifiable + public sealed class Dummy : Identifiable { public string SomeUpdatedProperty { get; set; } public string SomeNotUpdatedProperty { get; set; } @@ -21,20 +21,20 @@ public class Dummy : Identifiable } public class NotTargeted : Identifiable { } - public class ToMany : Identifiable { } - public class ToOne : Identifiable { } + public sealed class ToMany : Identifiable { } + public sealed class ToOne : Identifiable { } - public class RelationshipDictionaryTests + public sealed class RelationshipDictionaryTests { public readonly HasOneAttribute FirstToOneAttr; public readonly HasOneAttribute SecondToOneAttr; public readonly HasManyAttribute ToManyAttr; public readonly Dictionary> Relationships = new Dictionary>(); - public readonly HashSet FirstToOnesEntities = new HashSet { new Dummy() { Id = 1 }, new Dummy() { Id = 2 }, new Dummy() { Id = 3 } }; - public readonly HashSet SecondToOnesEntities = new HashSet { new Dummy() { Id = 4 }, new Dummy() { Id = 5 }, new Dummy() { Id = 6 } }; - public readonly HashSet ToManiesEntities = new HashSet { new Dummy() { Id = 7 }, new Dummy() { Id = 8 }, new Dummy() { Id = 9 } }; - public readonly HashSet NoRelationshipsEntities = new HashSet { new Dummy() { Id = 10 }, new Dummy() { Id = 11 }, new Dummy() { Id = 12 } }; + public readonly HashSet FirstToOnesEntities = new HashSet { new Dummy { Id = 1 }, new Dummy { Id = 2 }, new Dummy { Id = 3 } }; + public readonly HashSet SecondToOnesEntities = new HashSet { new Dummy { Id = 4 }, new Dummy { Id = 5 }, new Dummy { Id = 6 } }; + public readonly HashSet ToManiesEntities = new HashSet { new Dummy { Id = 7 }, new Dummy { Id = 8 }, new Dummy { Id = 9 } }; + public readonly HashSet NoRelationshipsEntities = new HashSet { new Dummy { Id = 10 }, new Dummy { Id = 11 }, new Dummy { Id = 12 } }; public readonly HashSet AllEntities; public RelationshipDictionaryTests() { diff --git a/test/UnitTests/ResourceHooks/DiscoveryTests.cs b/test/UnitTests/ResourceHooks/DiscoveryTests.cs index 1ff192f691..de8319c314 100644 --- a/test/UnitTests/ResourceHooks/DiscoveryTests.cs +++ b/test/UnitTests/ResourceHooks/DiscoveryTests.cs @@ -10,10 +10,10 @@ namespace UnitTests.ResourceHooks { - public class DiscoveryTests + public sealed class DiscoveryTests { public class Dummy : Identifiable { } - public class DummyResourceDefinition : ResourceDefinition + public sealed class DummyResourceDefinition : ResourceDefinition { public DummyResourceDefinition() : base(new ResourceGraphBuilder().AddResource().Build()) { } @@ -41,12 +41,12 @@ public void HookDiscovery_StandardResourceDefinition_CanDiscover() public class AnotherDummy : Identifiable { } public abstract class ResourceDefinitionBase : ResourceDefinition where T : class, IIdentifiable { - public ResourceDefinitionBase(IResourceGraph resourceGraph) : base(resourceGraph) { } + protected ResourceDefinitionBase(IResourceGraph resourceGraph) : base(resourceGraph) { } public override IEnumerable BeforeDelete(IEntityHashSet entities, ResourcePipeline pipeline) { return entities; } public override void AfterDelete(HashSet entities, ResourcePipeline pipeline, bool succeeded) { } } - public class AnotherDummyResourceDefinition : ResourceDefinitionBase + public sealed class AnotherDummyResourceDefinition : ResourceDefinitionBase { public AnotherDummyResourceDefinition() : base(new ResourceGraphBuilder().AddResource().Build()) { } } @@ -62,7 +62,7 @@ public void HookDiscovery_InheritanceSubclass_CanDiscover() } public class YetAnotherDummy : Identifiable { } - public class YetAnotherDummyResourceDefinition : ResourceDefinition + public sealed class YetAnotherDummyResourceDefinition : ResourceDefinition { public YetAnotherDummyResourceDefinition() : base(new ResourceGraphBuilder().AddResource().Build()) { } @@ -79,7 +79,7 @@ public void HookDiscovery_WronglyUsedLoadDatabaseValueAttribute_ThrowsJsonApiSet Assert.Throws(() => { // Arrange & act - var hookConfig = new HooksDiscovery(MockProvider(new YetAnotherDummyResourceDefinition())); + new HooksDiscovery(MockProvider(new YetAnotherDummyResourceDefinition())); }); } @@ -94,7 +94,7 @@ public void HookDiscovery_InheritanceWithGenericSubclass_CanDiscover() Assert.Contains(ResourceHook.AfterDelete, hookConfig.ImplementedHooks); } - public class GenericDummyResourceDefinition : ResourceDefinition where TResource : class, IIdentifiable + public sealed class GenericDummyResourceDefinition : ResourceDefinition where TResource : class, IIdentifiable { public GenericDummyResourceDefinition() : base(new ResourceGraphBuilder().AddResource().Build()) { } diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/AfterCreateTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/AfterCreateTests.cs index d91231280e..4dafef66a4 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/AfterCreateTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/AfterCreateTests.cs @@ -1,4 +1,4 @@ -using JsonApiDotNetCore.Hooks; +using JsonApiDotNetCore.Hooks; using JsonApiDotNetCoreExample.Models; using Moq; using System.Collections.Generic; @@ -6,7 +6,7 @@ namespace UnitTests.ResourceHooks { - public class AfterCreateTests : HooksTestsSetup + public sealed class AfterCreateTests : HooksTestsSetup { private readonly ResourceHook[] targetHooks = { ResourceHook.AfterCreate, ResourceHook.AfterUpdateRelationship }; diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreateTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreateTests.cs index a5438b624d..64c2e24e9b 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreateTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreateTests.cs @@ -1,4 +1,4 @@ -using JsonApiDotNetCore.Hooks; +using JsonApiDotNetCore.Hooks; using JsonApiDotNetCoreExample.Models; using Moq; using System.Collections.Generic; @@ -6,7 +6,7 @@ namespace UnitTests.ResourceHooks { - public class BeforeCreateTests : HooksTestsSetup + public sealed class BeforeCreateTests : HooksTestsSetup { private readonly ResourceHook[] targetHooks = { ResourceHook.BeforeCreate, ResourceHook.BeforeUpdateRelationship }; diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreate_WithDbValues_Tests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreate_WithDbValues_Tests.cs index 31246bb210..c5ca7ac86f 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreate_WithDbValues_Tests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Create/BeforeCreate_WithDbValues_Tests.cs @@ -9,7 +9,7 @@ namespace UnitTests.ResourceHooks { - public class BeforeCreate_WithDbValues_Tests : HooksTestsSetup + public sealed class BeforeCreate_WithDbValues_Tests : HooksTestsSetup { private readonly ResourceHook[] targetHooks = { ResourceHook.BeforeCreate, ResourceHook.BeforeImplicitUpdateRelationship, ResourceHook.BeforeUpdateRelationship }; private readonly ResourceHook[] targetHooksNoImplicit = { ResourceHook.BeforeCreate, ResourceHook.BeforeUpdateRelationship }; @@ -177,13 +177,5 @@ private bool PersonIdCheck(IEnumerable ids, string checksum) { return ids.Single() == checksum; } - - private bool PersonCheck(string checksum, IRelationshipsDictionary helper) - { - - var entries = helper.GetByRelationship(); - return entries.Single().Value.Single().LastName == checksum; - } } } - diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/AfterDeleteTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/AfterDeleteTests.cs index 681fa831ef..0da8920138 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/AfterDeleteTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/AfterDeleteTests.cs @@ -6,9 +6,9 @@ namespace UnitTests.ResourceHooks { - public class AfterDeleteTests : HooksTestsSetup + public sealed class AfterDeleteTests : HooksTestsSetup { - readonly ResourceHook[] targetHooks = { ResourceHook.AfterDelete }; + private readonly ResourceHook[] targetHooks = { ResourceHook.AfterDelete }; [Fact] public void AfterDelete() @@ -31,7 +31,7 @@ public void AfterDelete_Without_Any_Hook_Implemented() { // Arrange var discovery = SetDiscoverableHooks(NoHooks, DisableDbValues); - (var _, var hookExecutor, var resourceDefinitionMock) = CreateTestObjects(discovery); + var (_, hookExecutor, resourceDefinitionMock) = CreateTestObjects(discovery); var todoList = CreateTodoWithOwner(); // Act diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/BeforeDeleteTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/BeforeDeleteTests.cs index eda31fe2ac..d6493c2f61 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/BeforeDeleteTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/BeforeDeleteTests.cs @@ -1,12 +1,11 @@ -using JsonApiDotNetCore.Hooks; +using JsonApiDotNetCore.Hooks; using JsonApiDotNetCoreExample.Models; using Moq; -using System.Collections.Generic; using Xunit; namespace UnitTests.ResourceHooks { - public class BeforeDeleteTests : HooksTestsSetup + public sealed class BeforeDeleteTests : HooksTestsSetup { private readonly ResourceHook[] targetHooks = { ResourceHook.BeforeDelete }; @@ -15,7 +14,7 @@ public void BeforeDelete() { // Arrange var discovery = SetDiscoverableHooks(targetHooks, DisableDbValues); - (var _, var hookExecutor, var resourceDefinitionMock) = CreateTestObjects(discovery); + var (_, hookExecutor, resourceDefinitionMock) = CreateTestObjects(discovery); var todoList = CreateTodoWithOwner(); // Act @@ -31,7 +30,7 @@ public void BeforeDelete_Without_Any_Hook_Implemented() { // Arrange var discovery = SetDiscoverableHooks(NoHooks, DisableDbValues); - (var _, var hookExecutor, var resourceDefinitionMock) = CreateTestObjects(discovery); + var (_, hookExecutor, resourceDefinitionMock) = CreateTestObjects(discovery); var todoList = CreateTodoWithOwner(); // Act diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/BeforeDelete_WithDbValue_Tests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/BeforeDelete_WithDbValue_Tests.cs index 0873aee1c9..032af05430 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/BeforeDelete_WithDbValue_Tests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Delete/BeforeDelete_WithDbValue_Tests.cs @@ -7,10 +7,9 @@ using System.Linq; using Xunit; - namespace UnitTests.ResourceHooks { - public class BeforeDelete_WithDbValues_Tests : HooksTestsSetup + public sealed class BeforeDelete_WithDbValues_Tests : HooksTestsSetup { private readonly ResourceHook[] targetHooks = { ResourceHook.BeforeDelete, ResourceHook.BeforeImplicitUpdateRelationship, ResourceHook.BeforeUpdateRelationship }; @@ -42,7 +41,6 @@ public void BeforeDelete() var passportDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var (_, hookExecutor, personResourceMock, todoResourceMock, passportResourceMock) = CreateTestObjects(personDiscovery, todoDiscovery, passportDiscovery, repoDbContextOptions: options); - var todoList = CreateTodoWithOwner(); // Act hookExecutor.BeforeDelete(new List { person }, ResourcePipeline.Delete); @@ -62,7 +60,6 @@ public void BeforeDelete_No_Parent_Hooks() var passportDiscovery = SetDiscoverableHooks(targetHooks, EnableDbValues); var (_, hookExecutor, personResourceMock, todoResourceMock, passportResourceMock) = CreateTestObjects(personDiscovery, todoDiscovery, passportDiscovery, repoDbContextOptions: options); - var todoList = CreateTodoWithOwner(); // Act hookExecutor.BeforeDelete(new List { person }, ResourcePipeline.Delete); @@ -81,7 +78,6 @@ public void BeforeDelete_No_Children_Hooks() var passportDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, hookExecutor, personResourceMock, todoResourceMock, passportResourceMock) = CreateTestObjects(personDiscovery, todoDiscovery, passportDiscovery, repoDbContextOptions: options); - var todoList = CreateTodoWithOwner(); // Act hookExecutor.BeforeDelete(new List { person }, ResourcePipeline.Delete); diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/IdentifiableManyToMany_OnReturnTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/IdentifiableManyToMany_OnReturnTests.cs index 562a65598d..d14dcdc3f5 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/IdentifiableManyToMany_OnReturnTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/IdentifiableManyToMany_OnReturnTests.cs @@ -7,7 +7,7 @@ namespace UnitTests.ResourceHooks { - public class IdentifiableManyToMany_OnReturnTests : HooksTestsSetup + public sealed class IdentifiableManyToMany_OnReturnTests : HooksTestsSetup { private readonly ResourceHook[] targetHooks = { ResourceHook.OnReturn }; @@ -78,7 +78,7 @@ public void OnReturn_Without_Children_Hooks_Implemented() var tagDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); - var (articles, joins, tags) = CreateIdentifiableManyToManyData(); + var (articles, _, tags) = CreateIdentifiableManyToManyData(); // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); @@ -97,7 +97,7 @@ public void OnReturn_Without_Grand_Children_Hooks_Implemented() var joinDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); - var (articles, joins, tags) = CreateIdentifiableManyToManyData(); + var (articles, joins, _) = CreateIdentifiableManyToManyData(); // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); @@ -116,7 +116,7 @@ public void OnReturn_Without_Any_Descendant_Hooks_Implemented() var joinDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); - var (articles, joins, tags) = CreateIdentifiableManyToManyData(); + var (articles, _, _) = CreateIdentifiableManyToManyData(); // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); @@ -134,7 +134,7 @@ public void OnReturn_Without_Any_Hook_Implemented() var joinDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); - var (articles, joins, tags) = CreateIdentifiableManyToManyData(); + var (articles, _, _) = CreateIdentifiableManyToManyData(); // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/ManyToMany_OnReturnTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/ManyToMany_OnReturnTests.cs index cb99e26b93..c1abacdfc2 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/ManyToMany_OnReturnTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/ManyToMany_OnReturnTests.cs @@ -7,11 +7,11 @@ namespace UnitTests.ResourceHooks { - public class ManyToMany_OnReturnTests : HooksTestsSetup + public sealed class ManyToMany_OnReturnTests : HooksTestsSetup { private readonly ResourceHook[] targetHooks = { ResourceHook.OnReturn }; - (List
, List, List) CreateDummyData() + private (List
, List, List) CreateDummyData() { var tagsSubset = _tagFaker.Generate(3).ToList(); var joinsSubSet = _articleTagFaker.Generate(3).ToList(); @@ -37,7 +37,7 @@ public class ManyToMany_OnReturnTests : HooksTestsSetup var allJoins = joinsSubSet.Concat(completeJoin).ToList(); - var articles = new List
() { articleTagsSubset, articleWithAllTags }; + var articles = new List
{ articleTagsSubset, articleWithAllTags }; return (articles, allJoins, allTags); } @@ -48,7 +48,7 @@ public void OnReturn() var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, articleResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, tagDiscovery); - var (articles, joins, tags) = CreateDummyData(); + var (articles, _, tags) = CreateDummyData(); // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); @@ -66,7 +66,7 @@ public void OnReturn_Without_Parent_Hook_Implemented() var articleDiscovery = SetDiscoverableHooks
(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, articleResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, tagDiscovery); - var (articles, joins, tags) = CreateDummyData(); + var (articles, _, tags) = CreateDummyData(); // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); @@ -83,7 +83,7 @@ public void OnReturn_Without_Children_Hooks_Implemented() var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, articleResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, tagDiscovery); - var (articles, joins, tags) = CreateDummyData(); + var (articles, _, _) = CreateDummyData(); // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); @@ -101,7 +101,7 @@ public void OnReturn_Without_Any_Hook_Implemented() var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, articleResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, tagDiscovery); - var (articles, joins, tags) = CreateDummyData(); + var (articles, _, _) = CreateDummyData(); // Act hookExecutor.OnReturn(articles, ResourcePipeline.Get); diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/BeforeReadTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/BeforeReadTests.cs index 3cb8a7dc72..19748c2c0d 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/BeforeReadTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/BeforeReadTests.cs @@ -1,4 +1,4 @@ -using System.Collections.Generic; +using System.Collections.Generic; using JsonApiDotNetCore.Hooks; using JsonApiDotNetCore.Models; using JsonApiDotNetCoreExample.Models; @@ -7,7 +7,7 @@ namespace UnitTests.ResourceHooks { - public class BeforeReadTests : HooksTestsSetup + public sealed class BeforeReadTests : HooksTestsSetup { private readonly ResourceHook[] targetHooks = { ResourceHook.BeforeRead }; @@ -16,9 +16,7 @@ public void BeforeRead() { // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); - var personDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (iqMock, hookExecutor, todoResourceMock) = CreateTestObjects(todoDiscovery); - var todoList = CreateTodoWithOwner(); iqMock.Setup(c => c.Get()).Returns(new List>()); // Act @@ -37,7 +35,6 @@ public void BeforeReadWithInclusion() var personDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (iqMock, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); - var todoList = CreateTodoWithOwner(); // eg a call on api/todoItems?include=owner,assignee,stakeHolders iqMock.Setup(c => c.Get()).Returns(GetIncludedRelationshipsChains("owner", "assignee", "stakeHolders")); @@ -59,7 +56,6 @@ public void BeforeReadWithNestedInclusion() var passportDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (iqMock, hookExecutor, todoResourceMock, ownerResourceMock, passportResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, passportDiscovery); - var todoList = CreateTodoWithOwner(); // eg a call on api/todoItems?include=owner.passport,assignee,stakeHolders iqMock.Setup(c => c.Get()).Returns(GetIncludedRelationshipsChains("owner.passport", "assignee", "stakeHolders")); @@ -83,7 +79,6 @@ public void BeforeReadWithNestedInclusion_No_Parent_Hook_Implemented() var passportDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (iqMock, hookExecutor, todoResourceMock, ownerResourceMock, passportResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, passportDiscovery); - var todoList = CreateTodoWithOwner(); // eg a call on api/todoItems?include=owner.passport,assignee,stakeHolders iqMock.Setup(c => c.Get()).Returns(GetIncludedRelationshipsChains("owner.passport", "assignee", "stakeHolders")); @@ -105,7 +100,6 @@ public void BeforeReadWithNestedInclusion_No_Child_Hook_Implemented() var passportDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (iqMock, hookExecutor, todoResourceMock, ownerResourceMock, passportResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, passportDiscovery); - var todoList = CreateTodoWithOwner(); // eg a call on api/todoItems?include=owner.passport,assignee,stakeHolders iqMock.Setup(c => c.Get()).Returns(GetIncludedRelationshipsChains("owner.passport", "assignee", "stakeHolders")); @@ -127,7 +121,6 @@ public void BeforeReadWithNestedInclusion_No_Grandchild_Hook_Implemented() var passportDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (iqMock, hookExecutor, todoResourceMock, ownerResourceMock, passportResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, passportDiscovery); - var todoList = CreateTodoWithOwner(); // eg a call on api/todoItems?include=owner.passport,assignee,stakeHolders iqMock.Setup(c => c.Get()).Returns(GetIncludedRelationshipsChains("owner.passport", "assignee", "stakeHolders")); @@ -150,7 +143,6 @@ public void BeforeReadWithNestedInclusion_Without_Any_Hook_Implemented() var passportDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (iqMock, hookExecutor, todoResourceMock, ownerResourceMock, passportResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery, passportDiscovery); - var todoList = CreateTodoWithOwner(); // eg a call on api/todoItems?include=owner.passport,assignee,stakeHolders iqMock.Setup(c => c.Get()).Returns(GetIncludedRelationshipsChains("owner.passport", "assignee", "stakeHolders")); diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/IdentifiableManyToMany_AfterReadTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/IdentifiableManyToMany_AfterReadTests.cs index 1f7f5f678f..c2a1fd8e1b 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/IdentifiableManyToMany_AfterReadTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/IdentifiableManyToMany_AfterReadTests.cs @@ -7,7 +7,7 @@ namespace UnitTests.ResourceHooks { - public class IdentifiableManyToMany_AfterReadTests : HooksTestsSetup + public sealed class IdentifiableManyToMany_AfterReadTests : HooksTestsSetup { private readonly ResourceHook[] targetHooks = { ResourceHook.AfterRead }; @@ -60,7 +60,7 @@ public void AfterRead_Without_Children_Hooks_Implemented() var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); - var (articles, joins, tags) = CreateIdentifiableManyToManyData(); + var (articles, _, tags) = CreateIdentifiableManyToManyData(); // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); @@ -79,7 +79,7 @@ public void AfterRead_Without_Grand_Children_Hooks_Implemented() var joinDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); - var (articles, joins, tags) = CreateIdentifiableManyToManyData(); + var (articles, joins, _) = CreateIdentifiableManyToManyData(); // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); @@ -98,7 +98,7 @@ public void AfterRead_Without_Any_Descendant_Hooks_Implemented() var joinDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); - var (articles, joins, tags) = CreateIdentifiableManyToManyData(); + var (articles, _, _) = CreateIdentifiableManyToManyData(); // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); @@ -116,7 +116,7 @@ public void AfterRead_Without_Any_Hook_Implemented() var joinDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, hookExecutor, articleResourceMock, joinResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, joinDiscovery, tagDiscovery); - var (articles, joins, tags) = CreateIdentifiableManyToManyData(); + var (articles, _, _) = CreateIdentifiableManyToManyData(); // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/ManyToMany_AfterReadTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/ManyToMany_AfterReadTests.cs index c3860c935e..19039e2ff2 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/ManyToMany_AfterReadTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Read/ManyToMany_AfterReadTests.cs @@ -7,7 +7,7 @@ namespace UnitTests.ResourceHooks { - public class ManyToMany_AfterReadTests : HooksTestsSetup + public sealed class ManyToMany_AfterReadTests : HooksTestsSetup { private readonly ResourceHook[] targetHooks = { ResourceHook.AfterRead }; @@ -18,7 +18,7 @@ public void AfterRead() var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, articleResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, tagDiscovery); - var (articles, joins, tags) = CreateManyToManyData(); + var (articles, _, tags) = CreateManyToManyData(); // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); @@ -36,7 +36,7 @@ public void AfterRead_Without_Parent_Hook_Implemented() var articleDiscovery = SetDiscoverableHooks
(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); var (_, _, hookExecutor, articleResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, tagDiscovery); - var (articles, joins, tags) = CreateManyToManyData(); + var (articles, _, tags) = CreateManyToManyData(); // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); @@ -53,7 +53,7 @@ public void AfterRead_Without_Children_Hooks_Implemented() var articleDiscovery = SetDiscoverableHooks
(targetHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, articleResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, tagDiscovery); - var (articles, joins, tags) = CreateManyToManyData(); + var (articles, _, _) = CreateManyToManyData(); // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); @@ -70,7 +70,7 @@ public void AfterRead_Without_Any_Hook_Implemented() var articleDiscovery = SetDiscoverableHooks
(NoHooks, DisableDbValues); var tagDiscovery = SetDiscoverableHooks(NoHooks, DisableDbValues); var (_, _, hookExecutor, articleResourceMock, tagResourceMock) = CreateTestObjects(articleDiscovery, tagDiscovery); - var (articles, joins, tags) = CreateManyToManyData(); + var (articles, _, _) = CreateManyToManyData(); // Act hookExecutor.AfterRead(articles, ResourcePipeline.Get); diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/ScenarioTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/ScenarioTests.cs index 544b3df2e0..9cdec75f65 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/ScenarioTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/ScenarioTests.cs @@ -1,4 +1,4 @@ -using JsonApiDotNetCore.Hooks; +using JsonApiDotNetCore.Hooks; using JsonApiDotNetCoreExample.Models; using Moq; using System.Collections.Generic; @@ -6,7 +6,7 @@ namespace UnitTests.ResourceHooks { - public class SameEntityTypeTests : HooksTestsSetup + public sealed class SameEntityTypeTests : HooksTestsSetup { private readonly ResourceHook[] targetHooks = { ResourceHook.OnReturn }; @@ -19,11 +19,11 @@ public void Entity_Has_Multiple_Relations_To_Same_Type() var (_, _, hookExecutor, todoResourceMock, ownerResourceMock) = CreateTestObjects(todoDiscovery, personDiscovery); var person1 = new Person(); var todo = new TodoItem { Owner = person1 }; - var person2 = new Person { AssignedTodoItems = new List() { todo } }; + var person2 = new Person { AssignedTodoItems = new List { todo } }; todo.Assignee = person2; var person3 = new Person { StakeHolderTodoItem = todo }; todo.StakeHolders = new List { person3 }; - var todoList = new List() { todo }; + var todoList = new List { todo }; // Act hookExecutor.OnReturn(todoList, ResourcePipeline.Post); @@ -39,11 +39,11 @@ public void Entity_Has_Cyclic_Relations() { // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); - (var contextMock, var hookExecutor, var todoResourceMock) = CreateTestObjects(todoDiscovery); + var (_, hookExecutor, todoResourceMock) = CreateTestObjects(todoDiscovery); var todo = new TodoItem(); todo.ParentTodo = todo; todo.ChildrenTodos = new List { todo }; - var todoList = new List() { todo }; + var todoList = new List { todo }; // Act hookExecutor.OnReturn(todoList, ResourcePipeline.Post); @@ -58,16 +58,16 @@ public void Entity_Has_Nested_Cyclic_Relations() { // Arrange var todoDiscovery = SetDiscoverableHooks(targetHooks, DisableDbValues); - (var contextMock, var hookExecutor, var todoResourceMock) = CreateTestObjects(todoDiscovery); - var rootTodo = new TodoItem() { Id = 1 }; + var (_, hookExecutor, todoResourceMock) = CreateTestObjects(todoDiscovery); + var rootTodo = new TodoItem { Id = 1 }; var child = new TodoItem { ParentTodo = rootTodo, Id = 2 }; rootTodo.ChildrenTodos = new List { child }; - var grandChild = new TodoItem() { ParentTodo = child, Id = 3 }; + var grandChild = new TodoItem { ParentTodo = child, Id = 3 }; child.ChildrenTodos = new List { grandChild }; - var greatGrandChild = new TodoItem() { ParentTodo = grandChild, Id = 4 }; + var greatGrandChild = new TodoItem { ParentTodo = grandChild, Id = 4 }; grandChild.ChildrenTodos = new List { greatGrandChild }; greatGrandChild.ChildrenTodos = new List { rootTodo }; - var todoList = new List() { rootTodo }; + var todoList = new List { rootTodo }; // Act hookExecutor.OnReturn(todoList, ResourcePipeline.Post); diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/AfterUpdateTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/AfterUpdateTests.cs index 148c80cf68..3979a124e6 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/AfterUpdateTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/AfterUpdateTests.cs @@ -1,4 +1,4 @@ -using JsonApiDotNetCore.Hooks; +using JsonApiDotNetCore.Hooks; using JsonApiDotNetCoreExample.Models; using Moq; using System.Collections.Generic; @@ -6,7 +6,7 @@ namespace UnitTests.ResourceHooks { - public class AfterUpdateTests : HooksTestsSetup + public sealed class AfterUpdateTests : HooksTestsSetup { private readonly ResourceHook[] targetHooks = { ResourceHook.AfterUpdate, ResourceHook.AfterUpdateRelationship }; diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/BeforeUpdateTests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/BeforeUpdateTests.cs index 65047e81c2..a4fcdd22e2 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/BeforeUpdateTests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/BeforeUpdateTests.cs @@ -1,4 +1,4 @@ -using JsonApiDotNetCore.Hooks; +using JsonApiDotNetCore.Hooks; using JsonApiDotNetCoreExample.Models; using Moq; using System.Collections.Generic; @@ -6,7 +6,7 @@ namespace UnitTests.ResourceHooks { - public class BeforeUpdateTests : HooksTestsSetup + public sealed class BeforeUpdateTests : HooksTestsSetup { private readonly ResourceHook[] targetHooks = { ResourceHook.BeforeUpdate, ResourceHook.BeforeUpdateRelationship }; diff --git a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/BeforeUpdate_WithDbValues_Tests.cs b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/BeforeUpdate_WithDbValues_Tests.cs index 156aa3c99a..05f6108041 100644 --- a/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/BeforeUpdate_WithDbValues_Tests.cs +++ b/test/UnitTests/ResourceHooks/ResourceHookExecutor/Update/BeforeUpdate_WithDbValues_Tests.cs @@ -9,7 +9,7 @@ namespace UnitTests.ResourceHooks { - public class BeforeUpdate_WithDbValues_Tests : HooksTestsSetup + public sealed class BeforeUpdate_WithDbValues_Tests : HooksTestsSetup { private readonly ResourceHook[] targetHooks = { ResourceHook.BeforeUpdate, ResourceHook.BeforeImplicitUpdateRelationship, ResourceHook.BeforeUpdateRelationship }; private readonly ResourceHook[] targetHooksNoImplicit = { ResourceHook.BeforeUpdate, ResourceHook.BeforeUpdateRelationship }; @@ -85,7 +85,7 @@ public void BeforeUpdate_Deleting_Relationship() ufMock.Setup(c => c.Relationships).Returns(_resourceGraph.GetRelationships((TodoItem t) => t.OneToOnePerson)); // Act - var _todoList = new List() { new TodoItem { Id = this.todoList[0].Id } }; + var _todoList = new List { new TodoItem { Id = this.todoList[0].Id } }; hookExecutor.BeforeUpdate(_todoList, ResourcePipeline.Patch); // Assert @@ -204,7 +204,6 @@ private bool TodoCheckDiff(IDiffableEntityHashSet entities, string che var diffPair = entities.GetDiffs().Single(); var dbCheck = diffPair.DatabaseValue.Description == checksum; var reqCheck = diffPair.Entity.Description == null; - var diffPairCheck = (dbCheck && reqCheck); var updatedRelationship = entities.GetByRelationship().Single(); var diffCheck = updatedRelationship.Key.PublicRelationshipName == "oneToOnePerson"; diff --git a/test/UnitTests/ResourceHooks/ResourceHooksTestsSetup.cs b/test/UnitTests/ResourceHooks/ResourceHooksTestsSetup.cs index 28f35f2c83..a040c72551 100644 --- a/test/UnitTests/ResourceHooks/ResourceHooksTestsSetup.cs +++ b/test/UnitTests/ResourceHooks/ResourceHooksTestsSetup.cs @@ -64,7 +64,7 @@ protected List CreateTodoWithToOnePerson() { var todoItem = _todoFaker.Generate(); var person = _personFaker.Generate(); - var todoList = new List() { todoItem }; + var todoList = new List { todoItem }; person.OneToOneTodoItem = todoItem; todoItem.OneToOnePerson = person; return todoList; @@ -74,7 +74,7 @@ protected List CreateTodoWithOwner() { var todoItem = _todoFaker.Generate(); var person = _personFaker.Generate(); - var todoList = new List() { todoItem }; + var todoList = new List { todoItem }; person.AssignedTodoItems = todoList; todoItem.Owner = person; return todoList; @@ -106,7 +106,7 @@ protected List CreateTodoWithOwner() var allJoins = joinsSubSet.Concat(completeJoin).ToList(); - var articles = new List
() { articleTagsSubset, articleWithAllTags }; + var articles = new List
{ articleTagsSubset, articleWithAllTags }; return (articles, allJoins, allTags); } @@ -134,14 +134,14 @@ protected List CreateTodoWithOwner() } var allJoins = joinsSubSet.Concat(completeJoin).ToList(); - var articles = new List
() { articleTagsSubset, articleWithAllTags }; + var articles = new List
{ articleTagsSubset, articleWithAllTags }; return (articles, allJoins, allTags); } } public class HooksTestsSetup : HooksDummyData { - (Mock, Mock, Mock, IJsonApiOptions) CreateMocks() + private (Mock, Mock, Mock, IJsonApiOptions) CreateMocks() { var pfMock = new Mock(); var ufMock = new Mock(); @@ -159,7 +159,7 @@ public class HooksTestsSetup : HooksDummyData // mocking the genericServiceFactory and JsonApiContext and wiring them up. var (ufMock, iqMock, gpfMock, options) = CreateMocks(); - SetupProcessorFactoryForResourceDefinition(gpfMock, mainResource.Object, mainDiscovery, null); + SetupProcessorFactoryForResourceDefinition(gpfMock, mainResource.Object, mainDiscovery); var execHelper = new HookExecutorHelper(gpfMock.Object, options); var traversalHelper = new TraversalHelper(_resourceGraph, ufMock.Object); @@ -241,7 +241,7 @@ protected IHooksDiscovery SetDiscoverableHooks(ResourceHoo .Returns(enableDbValuesHooks); } mock.Setup(discovery => discovery.DatabaseValuesEnabledHooks) - .Returns(new ResourceHook[] { ResourceHook.BeforeImplicitUpdateRelationship }.Concat(enableDbValuesHooks).ToArray()); + .Returns(new[] { ResourceHook.BeforeImplicitUpdateRelationship }.Concat(enableDbValuesHooks).ToArray()); return mock.Object; } @@ -268,7 +268,7 @@ protected DbContextOptions InitInMemoryDb(Action seeder return options; } - void MockHooks(Mock> resourceDefinition) where TModel : class, IIdentifiable + private void MockHooks(Mock> resourceDefinition) where TModel : class, IIdentifiable { resourceDefinition .Setup(rd => rd.BeforeCreate(It.IsAny>(), It.IsAny())) @@ -310,7 +310,7 @@ void MockHooks(Mock> resourceDefinition) .Verifiable(); } - void SetupProcessorFactoryForResourceDefinition( + private void SetupProcessorFactoryForResourceDefinition( Mock processorFactory, IResourceHookContainer modelResource, IHooksDiscovery discovery, @@ -340,7 +340,7 @@ void SetupProcessorFactoryForResourceDefinition( } } - IResourceReadRepository CreateTestRepository( + private IResourceReadRepository CreateTestRepository( AppDbContext dbContext ) where TModel : class, IIdentifiable { @@ -348,19 +348,19 @@ AppDbContext dbContext return new DefaultResourceRepository(null, resolver, null, null, NullLoggerFactory.Instance); } - IDbContextResolver CreateTestDbResolver(AppDbContext dbContext) where TModel : class, IIdentifiable + private IDbContextResolver CreateTestDbResolver(AppDbContext dbContext) where TModel : class, IIdentifiable { var mock = new Mock(); mock.Setup(r => r.GetContext()).Returns(dbContext); return mock.Object; } - void ResolveInverseRelationships(AppDbContext context) + private void ResolveInverseRelationships(AppDbContext context) { new InverseRelationships(_resourceGraph, new DbContextResolver(context)).Resolve(); } - Mock> CreateResourceDefinition + private Mock> CreateResourceDefinition (IHooksDiscovery discovery ) where TModel : class, IIdentifiable diff --git a/test/UnitTests/Serialization/Client/RequestSerializerTests.cs b/test/UnitTests/Serialization/Client/RequestSerializerTests.cs index ce4e2ad578..783c49c11a 100644 --- a/test/UnitTests/Serialization/Client/RequestSerializerTests.cs +++ b/test/UnitTests/Serialization/Client/RequestSerializerTests.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Text.RegularExpressions; using JsonApiDotNetCore.Models; @@ -6,11 +5,10 @@ using JsonApiDotNetCore.Serialization.Client; using Xunit; using UnitTests.TestModels; -using Person = UnitTests.TestModels.Person; namespace UnitTests.Serialization.Client { - public class RequestSerializerTests : SerializerTestsSetup + public sealed class RequestSerializerTests : SerializerTestsSetup { private readonly RequestSerializer _serializer; @@ -24,7 +22,7 @@ public RequestSerializerTests() public void SerializeSingle_ResourceWithDefaultTargetFields_CanBuild() { // Arrange - var entity = new TestResource() { Id = 1, StringField = "value", NullableIntField = 123 }; + var entity = new TestResource { Id = 1, StringField = "value", NullableIntField = 123 }; // Act string serialized = _serializer.Serialize(entity); @@ -55,7 +53,7 @@ public void SerializeSingle_ResourceWithDefaultTargetFields_CanBuild() public void SerializeSingle_ResourceWithTargetedSetAttributes_CanBuild() { // Arrange - var entity = new TestResource() { Id = 1, StringField = "value", NullableIntField = 123 }; + var entity = new TestResource { Id = 1, StringField = "value", NullableIntField = 123 }; _serializer.AttributesToSerialize = _resourceGraph.GetAttributes(tr => tr.StringField); // Act @@ -80,7 +78,7 @@ public void SerializeSingle_ResourceWithTargetedSetAttributes_CanBuild() public void SerializeSingle_NoIdWithTargetedSetAttributes_CanBuild() { // Arrange - var entityNoId = new TestResource() { Id = 0, StringField = "value", NullableIntField = 123 }; + var entityNoId = new TestResource { Id = 0, StringField = "value", NullableIntField = 123 }; _serializer.AttributesToSerialize = _resourceGraph.GetAttributes(tr => tr.StringField); // Act @@ -105,7 +103,7 @@ public void SerializeSingle_NoIdWithTargetedSetAttributes_CanBuild() public void SerializeSingle_ResourceWithoutTargetedAttributes_CanBuild() { // Arrange - var entity = new TestResource() { Id = 1, StringField = "value", NullableIntField = 123 }; + var entity = new TestResource { Id = 1, StringField = "value", NullableIntField = 123 }; _serializer.AttributesToSerialize = _resourceGraph.GetAttributes(tr => new { }); // Act @@ -179,8 +177,8 @@ public void SerializeMany_ResourcesWithTargetedAttributes_CanBuild() // Arrange var entities = new List { - new TestResource() { Id = 1, StringField = "value1", NullableIntField = 123 }, - new TestResource() { Id = 2, StringField = "value2", NullableIntField = 123 } + new TestResource { Id = 1, StringField = "value1", NullableIntField = 123 }, + new TestResource { Id = 2, StringField = "value2", NullableIntField = 123 } }; _serializer.AttributesToSerialize = _resourceGraph.GetAttributes(tr => tr.StringField); @@ -218,8 +216,7 @@ public void SerializeSingle_Null_CanBuild() _serializer.AttributesToSerialize = _resourceGraph.GetAttributes(tr => tr.StringField); // Act - IIdentifiable obj = null; - string serialized = _serializer.Serialize(obj); + string serialized = _serializer.Serialize((IIdentifiable) null); // Assert var expectedFormatted = @@ -234,7 +231,7 @@ public void SerializeSingle_Null_CanBuild() public void SerializeMany_EmptyList_CanBuild() { // Arrange - var entities = new List { }; + var entities = new List(); _serializer.AttributesToSerialize = _resourceGraph.GetAttributes(tr => tr.StringField); // Act diff --git a/test/UnitTests/Serialization/Client/ResponseDeserializerTests.cs b/test/UnitTests/Serialization/Client/ResponseDeserializerTests.cs index 0ffdc6f5ef..fa9436d699 100644 --- a/test/UnitTests/Serialization/Client/ResponseDeserializerTests.cs +++ b/test/UnitTests/Serialization/Client/ResponseDeserializerTests.cs @@ -9,7 +9,7 @@ namespace UnitTests.Serialization.Client { - public class ResponseDeserializerTests : DeserializerTestsSetup + public sealed class ResponseDeserializerTests : DeserializerTestsSetup { private readonly Dictionary _linkValues = new Dictionary(); private readonly ResponseDeserializer _deserializer; @@ -57,7 +57,7 @@ public void DeserializeSingle_EmptyResponseWithTopLevelLinks_CanDeserialize() // Assert Assert.Null(result.Data); Assert.NotNull(result.Links); - TopLevelLinks links = (TopLevelLinks)result.Links; + TopLevelLinks links = result.Links; Assert.Equal(_linkValues["self"], links.Self); Assert.Equal(_linkValues["next"], links.Next); Assert.Equal(_linkValues["last"], links.Last); @@ -80,7 +80,7 @@ public void DeserializeList_EmptyResponseWithTopLevelLinks_CanDeserialize() // Assert Assert.Empty(result.Data); Assert.NotNull(result.Links); - TopLevelLinks links = (TopLevelLinks)result.Links; + TopLevelLinks links = result.Links; Assert.Equal(_linkValues["self"], links.Self); Assert.Equal(_linkValues["next"], links.Next); Assert.Equal(_linkValues["last"], links.Last); @@ -115,19 +115,19 @@ public void DeserializeSingle_MultipleDependentRelationshipsWithIncluded_CanDese content.SingleData.Relationships.Add("emptyToManies", CreateRelationshipData(isToManyData: true)); var toOneAttributeValue = "populatedToOne member content"; var toManyAttributeValue = "populatedToManies member content"; - content.Included = new List() + content.Included = new List { - new ResourceObject() + new ResourceObject { Type = "oneToOneDependents", Id = "10", - Attributes = new Dictionary() { {"attributeMember", toOneAttributeValue } } + Attributes = new Dictionary { {"attributeMember", toOneAttributeValue } } }, - new ResourceObject() + new ResourceObject { Type = "oneToManyDependents", Id = "10", - Attributes = new Dictionary() { {"attributeMember", toManyAttributeValue } } + Attributes = new Dictionary { {"attributeMember", toManyAttributeValue } } } }; var body = JsonConvert.SerializeObject(content); @@ -158,19 +158,19 @@ public void DeserializeSingle_MultiplePrincipalRelationshipsWithIncluded_CanDese content.SingleData.Relationships.Add("emptyToMany", CreateRelationshipData()); var toOneAttributeValue = "populatedToOne member content"; var toManyAttributeValue = "populatedToManies member content"; - content.Included = new List() + content.Included = new List { - new ResourceObject() + new ResourceObject { Type = "oneToOnePrincipals", Id = "10", - Attributes = new Dictionary() { {"attributeMember", toOneAttributeValue } } + Attributes = new Dictionary { {"attributeMember", toOneAttributeValue } } }, - new ResourceObject() + new ResourceObject { Type = "oneToManyPrincipals", Id = "10", - Attributes = new Dictionary() { {"attributeMember", toManyAttributeValue } } + Attributes = new Dictionary { {"attributeMember", toManyAttributeValue } } } }; var body = JsonConvert.SerializeObject(content); @@ -197,20 +197,20 @@ public void DeserializeSingle_NestedIncluded_CanDeserialize() content.SingleData.Relationships.Add("populatedToManies", CreateRelationshipData("oneToManyDependents", isToManyData: true)); var toManyAttributeValue = "populatedToManies member content"; var nestedIncludeAttributeValue = "nested include member content"; - content.Included = new List() + content.Included = new List { - new ResourceObject() + new ResourceObject { Type = "oneToManyDependents", Id = "10", - Attributes = new Dictionary() { {"attributeMember", toManyAttributeValue } }, + Attributes = new Dictionary { {"attributeMember", toManyAttributeValue } }, Relationships = new Dictionary { { "principal", CreateRelationshipData("oneToManyPrincipals") } } }, - new ResourceObject() + new ResourceObject { Type = "oneToManyPrincipals", Id = "10", - Attributes = new Dictionary() { {"attributeMember", nestedIncludeAttributeValue } } + Attributes = new Dictionary { {"attributeMember", nestedIncludeAttributeValue } } } }; var body = JsonConvert.SerializeObject(content); @@ -241,27 +241,27 @@ public void DeserializeSingle_DeeplyNestedIncluded_CanDeserialize() var includedAttributeValue = "multi member content"; var nestedIncludedAttributeValue = "nested include member content"; var deeplyNestedIncludedAttributeValue = "deeply nested member content"; - content.Included = new List() + content.Included = new List { - new ResourceObject() + new ResourceObject { Type = "multiPrincipals", Id = "10", - Attributes = new Dictionary() { {"attributeMember", includedAttributeValue } }, + Attributes = new Dictionary { {"attributeMember", includedAttributeValue } }, Relationships = new Dictionary { { "populatedToManies", CreateRelationshipData("oneToManyDependents", isToManyData: true) } } }, - new ResourceObject() + new ResourceObject { Type = "oneToManyDependents", Id = "10", - Attributes = new Dictionary() { {"attributeMember", nestedIncludedAttributeValue } }, + Attributes = new Dictionary { {"attributeMember", nestedIncludedAttributeValue } }, Relationships = new Dictionary { { "principal", CreateRelationshipData("oneToManyPrincipals") } } }, - new ResourceObject() + new ResourceObject { Type = "oneToManyPrincipals", Id = "10", - Attributes = new Dictionary() { {"attributeMember", deeplyNestedIncludedAttributeValue } } + Attributes = new Dictionary { {"attributeMember", deeplyNestedIncludedAttributeValue } } }, }; var body = JsonConvert.SerializeObject(content); @@ -293,27 +293,27 @@ public void DeserializeList_DeeplyNestedIncluded_CanDeserialize() var includedAttributeValue = "multi member content"; var nestedIncludedAttributeValue = "nested include member content"; var deeplyNestedIncludedAttributeValue = "deeply nested member content"; - content.Included = new List() + content.Included = new List { - new ResourceObject() + new ResourceObject { Type = "multiPrincipals", Id = "10", - Attributes = new Dictionary() { {"attributeMember", includedAttributeValue } }, + Attributes = new Dictionary { {"attributeMember", includedAttributeValue } }, Relationships = new Dictionary { { "populatedToManies", CreateRelationshipData("oneToManyDependents", isToManyData: true) } } }, - new ResourceObject() + new ResourceObject { Type = "oneToManyDependents", Id = "10", - Attributes = new Dictionary() { {"attributeMember", nestedIncludedAttributeValue } }, + Attributes = new Dictionary { {"attributeMember", nestedIncludedAttributeValue } }, Relationships = new Dictionary { { "principal", CreateRelationshipData("oneToManyPrincipals") } } }, - new ResourceObject() + new ResourceObject { Type = "oneToManyPrincipals", Id = "10", - Attributes = new Dictionary() { {"attributeMember", deeplyNestedIncludedAttributeValue } } + Attributes = new Dictionary { {"attributeMember", deeplyNestedIncludedAttributeValue } } }, }; var body = JsonConvert.SerializeObject(content); diff --git a/test/UnitTests/Serialization/Common/DocumentBuilderTests.cs b/test/UnitTests/Serialization/Common/DocumentBuilderTests.cs index 75cc825ad3..69b7f17d75 100644 --- a/test/UnitTests/Serialization/Common/DocumentBuilderTests.cs +++ b/test/UnitTests/Serialization/Common/DocumentBuilderTests.cs @@ -1,16 +1,13 @@ -using System; -using System.Collections; using System.Collections.Generic; -using System.Linq; using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Serialization; using Moq; using Xunit; using UnitTests.TestModels; -using Person = UnitTests.TestModels.Person; + namespace UnitTests.Serialization.Serializer { - public class BaseDocumentBuilderTests : SerializerTestsSetup + public sealed class BaseDocumentBuilderTests : SerializerTestsSetup { private readonly TestDocumentBuilder _builder; @@ -25,11 +22,8 @@ public BaseDocumentBuilderTests() [Fact] public void EntityToDocument_NullEntity_CanBuild() { - // Arrange - TestResource entity = null; - // Act - var document = _builder.Build(entity, null, null); + var document = _builder.Build((TestResource) null); // Assert Assert.Null(document.Data); @@ -44,7 +38,7 @@ public void EntityToDocument_EmptyList_CanBuild() var entities = new List(); // Act - var document = _builder.Build(entities, null, null); + var document = _builder.Build(entities); // Assert Assert.NotNull(document.Data); @@ -59,7 +53,7 @@ public void EntityToDocument_SingleEntity_CanBuild() IIdentifiable dummy = new Identifiable(); // Act - var document = _builder.Build(dummy, null, null); + var document = _builder.Build(dummy); // Assert Assert.NotNull(document.Data); @@ -70,10 +64,10 @@ public void EntityToDocument_SingleEntity_CanBuild() public void EntityToDocument_EntityList_CanBuild() { // Arrange - var entities = new List() { new Identifiable(), new Identifiable() }; + var entities = new List { new Identifiable(), new Identifiable() }; // Act - var document = _builder.Build(entities, null, null); + var document = _builder.Build(entities); var data = (List)document.Data; // Assert diff --git a/test/UnitTests/Serialization/Common/DocumentParserTests.cs b/test/UnitTests/Serialization/Common/DocumentParserTests.cs index 68a1d6f62f..360cb2c775 100644 --- a/test/UnitTests/Serialization/Common/DocumentParserTests.cs +++ b/test/UnitTests/Serialization/Common/DocumentParserTests.cs @@ -6,11 +6,10 @@ using Newtonsoft.Json; using Xunit; using UnitTests.TestModels; -using Person = UnitTests.TestModels.Person; namespace UnitTests.Serialization.Deserializer { - public class BaseDocumentParserTests : DeserializerTestsSetup + public sealed class BaseDocumentParserTests : DeserializerTestsSetup { private readonly TestDocumentParser _deserializer; @@ -44,7 +43,7 @@ public void DeserializeResourceIdentifiers_SingleData_CanDeserialize() public void DeserializeResourceIdentifiers_EmptySingleData_CanDeserialize() { // Arrange - var content = new Document { }; + var content = new Document(); var body = JsonConvert.SerializeObject(content); // Act @@ -81,7 +80,7 @@ public void DeserializeResourceIdentifiers_ArrayData_CanDeserialize() [Fact] public void DeserializeResourceIdentifiers_EmptyArrayData_CanDeserialize() { - var content = new Document { Data = new List { } }; + var content = new Document { Data = new List()}; var body = JsonConvert.SerializeObject(content); // Act diff --git a/test/UnitTests/Serialization/Common/ResourceObjectBuilderTests.cs b/test/UnitTests/Serialization/Common/ResourceObjectBuilderTests.cs index 46304c5e9d..0aded6e7f9 100644 --- a/test/UnitTests/Serialization/Common/ResourceObjectBuilderTests.cs +++ b/test/UnitTests/Serialization/Common/ResourceObjectBuilderTests.cs @@ -6,11 +6,10 @@ using JsonApiDotNetCore.Serialization; using Xunit; using UnitTests.TestModels; -using Person = UnitTests.TestModels.Person; namespace UnitTests.Serialization.Serializer { - public class ResourceObjectBuilderTests : SerializerTestsSetup + public sealed class ResourceObjectBuilderTests : SerializerTestsSetup { private readonly ResourceObjectBuilder _builder; @@ -39,7 +38,7 @@ public void EntityToResourceObject_EmptyResource_CanBuild() public void EntityToResourceObject_ResourceWithId_CanBuild() { // Arrange - var entity = new TestResource() { Id = 1 }; + var entity = new TestResource { Id = 1 }; // Act var resourceObject = _builder.Build(entity); @@ -57,7 +56,7 @@ public void EntityToResourceObject_ResourceWithId_CanBuild() public void EntityToResourceObject_ResourceWithIncludedAttrs_CanBuild(string stringFieldValue, int? intFieldValue) { // Arrange - var entity = new TestResource() { StringField = stringFieldValue, NullableIntField = intFieldValue }; + var entity = new TestResource { StringField = stringFieldValue, NullableIntField = intFieldValue }; var attrs = _resourceGraph.GetAttributes(tr => new { tr.StringField, tr.NullableIntField }); // Act diff --git a/test/UnitTests/Serialization/DeserializerTestsSetup.cs b/test/UnitTests/Serialization/DeserializerTestsSetup.cs index bfdfdacfee..79d1a83666 100644 --- a/test/UnitTests/Serialization/DeserializerTestsSetup.cs +++ b/test/UnitTests/Serialization/DeserializerTestsSetup.cs @@ -1,4 +1,4 @@ -using JsonApiDotNetCore.Internal.Contracts; +using JsonApiDotNetCore.Internal.Contracts; using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Serialization; using System.Collections.Generic; @@ -7,7 +7,7 @@ namespace UnitTests.Serialization { public class DeserializerTestsSetup : SerializationTestsSetupBase { - protected class TestDocumentParser : BaseDocumentParser + protected sealed class TestDocumentParser : BaseDocumentParser { public TestDocumentParser(IResourceGraph resourceGraph) : base(resourceGraph) { } @@ -34,7 +34,7 @@ protected Document CreateDocumentWithRelationships(string mainType) { Id = "1", Type = mainType, - Relationships = new Dictionary { } + Relationships = new Dictionary() } }; } diff --git a/test/UnitTests/Serialization/SerializerTestsSetup.cs b/test/UnitTests/Serialization/SerializerTestsSetup.cs index de4f00825c..3b7ac36d81 100644 --- a/test/UnitTests/Serialization/SerializerTestsSetup.cs +++ b/test/UnitTests/Serialization/SerializerTestsSetup.cs @@ -1,16 +1,12 @@ -using System; -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; -using JsonApiDotNetCore.Internal.Contracts; -using JsonApiDotNetCore.Managers.Contracts; using JsonApiDotNetCore.Models; using JsonApiDotNetCore.Models.Links; using JsonApiDotNetCore.Query; using JsonApiDotNetCore.Serialization; using JsonApiDotNetCore.Serialization.Server; using JsonApiDotNetCore.Serialization.Server.Builders; -using JsonApiDotNetCore.Services; -using JsonApiDotNetCoreExample.Models; using Moq; namespace UnitTests.Serialization @@ -79,13 +75,6 @@ protected IMetaBuilder GetMetaBuilder(Dictionary meta = nu return mock.Object; } - protected ICurrentRequest GetRequestManager() where T : class, IIdentifiable - { - var mock = new Mock(); - mock.Setup(m => m.GetRequestResource()).Returns(_resourceGraph.GetResourceContext()); - return mock.Object; - } - protected ILinkBuilder GetLinkBuilder(TopLevelLinks top = null, ResourceLinks resource = null, RelationshipLinks relationship = null) { var mock = new Mock(); @@ -95,12 +84,6 @@ protected ILinkBuilder GetLinkBuilder(TopLevelLinks top = null, ResourceLinks re return mock.Object; } - protected ISparseFieldsService GetFieldsQuery() - { - var mock = new Mock(); - return mock.Object; - } - protected IFieldsToSerialize GetSerializableFields() { var mock = new Mock(); @@ -122,19 +105,19 @@ protected IIncludeService GetIncludedRelationships(List - protected class TestDocumentBuilder : BaseDocumentBuilder + protected sealed class TestDocumentBuilder : BaseDocumentBuilder { public TestDocumentBuilder(IResourceObjectBuilder resourceObjectBuilder) : base(resourceObjectBuilder) { } public new Document Build(IIdentifiable entity, List attributes = null, List relationships = null) { - return base.Build(entity, attributes ?? null, relationships ?? null); + return base.Build(entity, attributes, relationships); } public new Document Build(IEnumerable entities, List attributes = null, List relationships = null) { - return base.Build(entities, attributes ?? null, relationships ?? null); + return base.Build(entities, attributes, relationships); } } } -} \ No newline at end of file +} diff --git a/test/UnitTests/Serialization/Server/IncludedResourceObjectBuilderTests.cs b/test/UnitTests/Serialization/Server/IncludedResourceObjectBuilderTests.cs index f2e5e65929..e0dca46bd8 100644 --- a/test/UnitTests/Serialization/Server/IncludedResourceObjectBuilderTests.cs +++ b/test/UnitTests/Serialization/Server/IncludedResourceObjectBuilderTests.cs @@ -9,13 +9,13 @@ namespace UnitTests.Serialization.Server { - public class IncludedResourceObjectBuilderTests : SerializerTestsSetup + public sealed class IncludedResourceObjectBuilderTests : SerializerTestsSetup { [Fact] public void BuildIncluded_DeeplyNestedCircularChainOfSingleData_CanBuild() { // Arrange - var (article, author, authorFood, reviewer, reviewerFood) = GetAuthorChainInstances(); + var (article, author, _, reviewer, _) = GetAuthorChainInstances(); var authorChain = GetIncludedRelationshipsChain("author.blogs.reviewer.favoriteFood"); var builder = GetBuilder(); @@ -59,10 +59,10 @@ public void BuildIncluded_OverlappingDeeplyNestedCircularChains_CanBuild() { // Arrange var authorChain = GetIncludedRelationshipsChain("author.blogs.reviewer.favoriteFood"); - var (article, author, authorFood, reviewer, reviewerFood) = GetAuthorChainInstances(); + var (article, author, _, reviewer, reviewerFood) = GetAuthorChainInstances(); var sharedBlog = author.Blogs.First(); var sharedBlogAuthor = reviewer; - var (_reviewer, _reviewerSong, _author, _authorSong) = GetReviewerChainInstances(article, sharedBlog, sharedBlogAuthor); + var (_, _, _, authorSong) = GetReviewerChainInstances(article, sharedBlog, sharedBlogAuthor); var reviewerChain = GetIncludedRelationshipsChain("reviewer.blogs.author.favoriteSong"); var builder = GetBuilder(); @@ -81,10 +81,7 @@ public void BuildIncluded_OverlappingDeeplyNestedCircularChains_CanBuild() foreach (var blog in nonOverlappingBlogs) Assert.Single(blog.Relationships.Keys.ToList()); - var sharedAuthorResourceObject = result.Single((ro) => ro.Type == "people" && ro.Id == sharedBlogAuthor.StringId); - var sharedAuthorSongRelation = sharedAuthorResourceObject.Relationships["favoriteSong"].SingleData; - Assert.Equal(_authorSong.StringId, sharedBlogAuthor.FavoriteSong.StringId); - var sharedAuthorFoodRelation = sharedAuthorResourceObject.Relationships["favoriteFood"].SingleData; + Assert.Equal(authorSong.StringId, sharedBlogAuthor.FavoriteSong.StringId); Assert.Equal(reviewerFood.StringId, sharedBlogAuthor.FavoriteFood.StringId); } diff --git a/test/UnitTests/Serialization/Server/RequestDeserializerTests.cs b/test/UnitTests/Serialization/Server/RequestDeserializerTests.cs index faef53944e..d1c47e6dca 100644 --- a/test/UnitTests/Serialization/Server/RequestDeserializerTests.cs +++ b/test/UnitTests/Serialization/Server/RequestDeserializerTests.cs @@ -5,18 +5,16 @@ using JsonApiDotNetCore.Serialization.Server; using Moq; using Newtonsoft.Json; -using UnitTests.TestModels; -using Person = UnitTests.TestModels.Person; using Xunit; namespace UnitTests.Serialization.Server { - public class RequestDeserializerTests : DeserializerTestsSetup + public sealed class RequestDeserializerTests : DeserializerTestsSetup { private readonly RequestDeserializer _deserializer; private readonly Mock _fieldsManagerMock = new Mock(); - public RequestDeserializerTests() : base() + public RequestDeserializerTests() { _deserializer = new RequestDeserializer(_resourceGraph, _fieldsManagerMock.Object); } @@ -41,7 +39,7 @@ public void DeserializeAttributes_VariousUpdatedMembers_RegistersTargetedFields( public void DeserializeAttributes_UpdatedImmutableMember_ThrowsInvalidOperationException() { // Arrange - SetupFieldsManager(out List attributesToUpdate, out List relationshipsToUpdate); + SetupFieldsManager(out _, out _); var content = new Document { Data = new ResourceObject diff --git a/test/UnitTests/Serialization/Server/ResponseResourceObjectBuilderTests.cs b/test/UnitTests/Serialization/Server/ResponseResourceObjectBuilderTests.cs index c6fa74e7b1..f26d6234a7 100644 --- a/test/UnitTests/Serialization/Server/ResponseResourceObjectBuilderTests.cs +++ b/test/UnitTests/Serialization/Server/ResponseResourceObjectBuilderTests.cs @@ -3,11 +3,10 @@ using JsonApiDotNetCore.Models; using Xunit; using UnitTests.TestModels; -using Person = UnitTests.TestModels.Person; namespace UnitTests.Serialization.Server { - public class ResponseResourceObjectBuilderTests : SerializerTestsSetup + public sealed class ResponseResourceObjectBuilderTests : SerializerTestsSetup { private readonly List _relationshipsForBuild; private const string _relationshipName = "dependents"; diff --git a/test/UnitTests/Serialization/Server/ResponseSerializerTests.cs b/test/UnitTests/Serialization/Server/ResponseSerializerTests.cs index 200c8e273f..a93e2a242d 100644 --- a/test/UnitTests/Serialization/Server/ResponseSerializerTests.cs +++ b/test/UnitTests/Serialization/Server/ResponseSerializerTests.cs @@ -1,4 +1,3 @@ -using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; @@ -10,13 +9,13 @@ namespace UnitTests.Serialization.Server { - public class ResponseSerializerTests : SerializerTestsSetup + public sealed class ResponseSerializerTests : SerializerTestsSetup { [Fact] public void SerializeSingle_ResourceWithDefaultTargetFields_CanSerialize() { // Arrange - var entity = new TestResource() { Id = 1, StringField = "value", NullableIntField = 123 }; + var entity = new TestResource { Id = 1, StringField = "value", NullableIntField = 123 }; var serializer = GetResponseSerializer(); // Act @@ -50,7 +49,7 @@ public void SerializeSingle_ResourceWithDefaultTargetFields_CanSerialize() public void SerializeMany_ResourceWithDefaultTargetFields_CanSerialize() { // Arrange - var entity = new TestResource() { Id = 1, StringField = "value", NullableIntField = 123 }; + var entity = new TestResource { Id = 1, StringField = "value", NullableIntField = 123 }; var serializer = GetResponseSerializer(); // Act @@ -234,9 +233,9 @@ public void SerializeSingle_Null_CanSerialize() { // Arrange var serializer = GetResponseSerializer(); - TestResource entity = null; + // Act - string serialized = serializer.SerializeSingle(entity); + string serialized = serializer.SerializeSingle(null); // Assert var expectedFormatted = @"{ ""data"": null }"; @@ -335,10 +334,11 @@ public void SerializeSingle_NullWithLinksAndMeta_StillShowsLinksAndMeta() { // Arrange var meta = new Dictionary { { "test", "meta" } }; - OneToManyPrincipal entity = null; var serializer = GetResponseSerializer(metaDict: meta, topLinks: _dummyTopLevelLinks, relationshipLinks: _dummyRelationshipLinks, resourceLinks: _dummyResourceLinks); + // Act - string serialized = serializer.SerializeSingle(entity); + string serialized = serializer.SerializeSingle(null); + // Assert var expectedFormatted = @"{ @@ -361,7 +361,7 @@ public void SerializeSingle_NullWithLinksAndMeta_StillShowsLinksAndMeta() public void SerializeSingleWithRequestRelationship_NullToOneRelationship_CanSerialize() { // Arrange - var entity = new OneToOnePrincipal() { Id = 2, Dependent = null }; + var entity = new OneToOnePrincipal { Id = 2, Dependent = null }; var serializer = GetResponseSerializer(); var requestRelationship = _resourceGraph.GetRelationships((OneToOnePrincipal t) => t.Dependent).First(); serializer.RequestRelationship = requestRelationship; @@ -379,7 +379,7 @@ public void SerializeSingleWithRequestRelationship_NullToOneRelationship_CanSeri public void SerializeSingleWithRequestRelationship_PopulatedToOneRelationship_CanSerialize() { // Arrange - var entity = new OneToOnePrincipal() { Id = 2, Dependent = new OneToOneDependent { Id = 1 } }; + var entity = new OneToOnePrincipal { Id = 2, Dependent = new OneToOneDependent { Id = 1 } }; var serializer = GetResponseSerializer(); var requestRelationship = _resourceGraph.GetRelationships((OneToOnePrincipal t) => t.Dependent).First(); serializer.RequestRelationship = requestRelationship; @@ -406,7 +406,7 @@ public void SerializeSingleWithRequestRelationship_PopulatedToOneRelationship_Ca public void SerializeSingleWithRequestRelationship_EmptyToManyRelationship_CanSerialize() { // Arrange - var entity = new OneToManyPrincipal() { Id = 2, Dependents = new List() }; + var entity = new OneToManyPrincipal { Id = 2, Dependents = new List() }; var serializer = GetResponseSerializer(); var requestRelationship = _resourceGraph.GetRelationships((OneToManyPrincipal t) => t.Dependents).First(); serializer.RequestRelationship = requestRelationship; @@ -425,7 +425,7 @@ public void SerializeSingleWithRequestRelationship_EmptyToManyRelationship_CanSe public void SerializeSingleWithRequestRelationship_PopulatedToManyRelationship_CanSerialize() { // Arrange - var entity = new OneToManyPrincipal() { Id = 2, Dependents = new List { new OneToManyDependent { Id = 1 } } }; + var entity = new OneToManyPrincipal { Id = 2, Dependents = new List { new OneToManyDependent { Id = 1 } } }; var serializer = GetResponseSerializer(); var requestRelationship = _resourceGraph.GetRelationships((OneToManyPrincipal t) => t.Dependents).First(); serializer.RequestRelationship = requestRelationship; @@ -476,7 +476,7 @@ public void SerializeError_CustomError_CanSerialize() Assert.Equal(expectedJson, result); } - class CustomError : Error + private sealed class CustomError : Error { public CustomError(int status, string title, string detail, string myProp) : base(status, title, detail) diff --git a/test/UnitTests/Services/EntityResourceService_Tests.cs b/test/UnitTests/Services/EntityResourceService_Tests.cs index f0a99df980..7f0cedffd6 100644 --- a/test/UnitTests/Services/EntityResourceService_Tests.cs +++ b/test/UnitTests/Services/EntityResourceService_Tests.cs @@ -16,7 +16,7 @@ namespace UnitTests.Services { - public class EntityResourceService_Tests + public sealed class EntityResourceService_Tests { private readonly Mock> _repositoryMock = new Mock>(); private readonly IResourceGraph _resourceGraph; diff --git a/test/UnitTests/TestModels.cs b/test/UnitTests/TestModels.cs index 8abcc84b8e..208c323e61 100644 --- a/test/UnitTests/TestModels.cs +++ b/test/UnitTests/TestModels.cs @@ -4,8 +4,7 @@ namespace UnitTests.TestModels { - - public class TestResource : Identifiable + public sealed class TestResource : Identifiable { [Attr] public string StringField { get; set; } [Attr] public DateTime DateTimeField { get; set; } @@ -27,24 +26,24 @@ public class ComplexType public string CompoundName { get; set; } } - public class OneToOnePrincipal : IdentifiableWithAttribute + public sealed class OneToOnePrincipal : IdentifiableWithAttribute { [HasOne] public OneToOneDependent Dependent { get; set; } } - public class OneToOneDependent : IdentifiableWithAttribute + public sealed class OneToOneDependent : IdentifiableWithAttribute { [HasOne] public OneToOnePrincipal Principal { get; set; } public int? PrincipalId { get; set; } } - public class OneToOneRequiredDependent : IdentifiableWithAttribute + public sealed class OneToOneRequiredDependent : IdentifiableWithAttribute { [HasOne] public OneToOnePrincipal Principal { get; set; } public int PrincipalId { get; set; } } - public class OneToManyDependent : IdentifiableWithAttribute + public sealed class OneToManyDependent : IdentifiableWithAttribute { [HasOne] public OneToManyPrincipal Principal { get; set; } public int? PrincipalId { get; set; } @@ -56,7 +55,7 @@ public class OneToManyRequiredDependent : IdentifiableWithAttribute public int PrincipalId { get; set; } } - public class OneToManyPrincipal : IdentifiableWithAttribute + public sealed class OneToManyPrincipal : IdentifiableWithAttribute { [HasMany] public List Dependents { get; set; } } @@ -66,7 +65,7 @@ public class IdentifiableWithAttribute : Identifiable [Attr] public string AttributeMember { get; set; } } - public class MultipleRelationshipsPrincipalPart : IdentifiableWithAttribute + public sealed class MultipleRelationshipsPrincipalPart : IdentifiableWithAttribute { [HasOne] public OneToOneDependent PopulatedToOne { get; set; } [HasOne] public OneToOneDependent EmptyToOne { get; set; } diff --git a/test/UnitTests/TestScopedServiceProvider.cs b/test/UnitTests/TestScopedServiceProvider.cs index af68e340b9..c770ce681e 100644 --- a/test/UnitTests/TestScopedServiceProvider.cs +++ b/test/UnitTests/TestScopedServiceProvider.cs @@ -5,10 +5,10 @@ namespace UnitTests { - public class TestScopedServiceProvider : IScopedServiceProvider + public sealed class TestScopedServiceProvider : IScopedServiceProvider { private readonly IServiceProvider _serviceProvider; - private Mock _httpContextAccessorMock = new Mock(); + private readonly Mock _httpContextAccessorMock = new Mock(); public TestScopedServiceProvider(IServiceProvider serviceProvider) {