diff --git a/.gitignore b/.gitignore index f22fd045..3636aa8a 100644 --- a/.gitignore +++ b/.gitignore @@ -109,3 +109,5 @@ /BlogWebApp/Blog.Web/ClientApp/.angular/cache/20.0.1/BlogAngular /BlogWebApp/Blog.Web/ClientApp/dist/BlogAngular /Clients/BlogRazor/bin/Debug/net9.0 +/BlogWebApp/BlogBlazor/bin/Debug/net9.0 +/BlogWebApp/BlogBlazor/obj diff --git a/BlogWebApp/Blog.Web/Cache/CachedAttribute.cs b/BlogWebApp/Blog.Web/Cache/CachedAttribute.cs index 34c7b8e6..498a8ab6 100644 --- a/BlogWebApp/Blog.Web/Cache/CachedAttribute.cs +++ b/BlogWebApp/Blog.Web/Cache/CachedAttribute.cs @@ -19,13 +19,13 @@ /// /// Initializes a new instance of the class. /// -/// The life time seconds. +/// The lifetime seconds. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class CachedAttribute(int lifeTimeSeconds) : Attribute, IAsyncActionFilter { /// - /// The life time seconds. + /// The lifetime seconds. /// private readonly int _lifeTimeSeconds = lifeTimeSeconds; diff --git a/BlogWebApp/Blog.Web/Controllers/V1/AccountsController.cs b/BlogWebApp/Blog.Web/Controllers/V1/AccountsController.cs index 7093b72d..c65286a7 100644 --- a/BlogWebApp/Blog.Web/Controllers/V1/AccountsController.cs +++ b/BlogWebApp/Blog.Web/Controllers/V1/AccountsController.cs @@ -222,7 +222,7 @@ public async Task CreateAsync([FromBody] RegistrationRequest mode return Bad(result); } - model.Roles ??= new[] {"User"}; + model.Roles ??= ["User"]; foreach(var role in model.Roles) { diff --git a/BlogWebApp/Blog.Web/Controllers/V1/CommentsController.cs b/BlogWebApp/Blog.Web/Controllers/V1/CommentsController.cs index 88815c55..a383646b 100644 --- a/BlogWebApp/Blog.Web/Controllers/V1/CommentsController.cs +++ b/BlogWebApp/Blog.Web/Controllers/V1/CommentsController.cs @@ -183,7 +183,7 @@ public async Task CreateAsync([FromBody] CreateCommentRequest req comment.CreatedAt = Now; await _commentService.InsertAsync(comment); var response = new CreatedResponse {Id = comment.Id}; - var baseUrl = $@"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}"; + var baseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}"; var locationUrl = baseUrl + "/" + ApiRoutes.CommentsController.Comments + "/" + ApiRoutes.CommentsController.GetComment + "/" + comment.Id; diff --git a/BlogWebApp/Blog.Web/Controllers/V1/PostsController.cs b/BlogWebApp/Blog.Web/Controllers/V1/PostsController.cs index 5b38f15b..796930a3 100644 --- a/BlogWebApp/Blog.Web/Controllers/V1/PostsController.cs +++ b/BlogWebApp/Blog.Web/Controllers/V1/PostsController.cs @@ -223,7 +223,7 @@ public async Task CreateAsync([FromBody] CreatePostRequest model) var response = new CreatedResponse { Id = postToCreate.Id }; - var baseUrl = $@"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}"; + var baseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}"; var locationUrl = baseUrl + "/" + ApiRoutes.PostsController.Show.Replace("{id}", postToCreate.Id.ToString()); return Created(locationUrl, response); diff --git a/BlogWebApp/Blog.Web/Controllers/V1/TagsController.cs b/BlogWebApp/Blog.Web/Controllers/V1/TagsController.cs index c67f32f0..69bb53e5 100644 --- a/BlogWebApp/Blog.Web/Controllers/V1/TagsController.cs +++ b/BlogWebApp/Blog.Web/Controllers/V1/TagsController.cs @@ -85,6 +85,9 @@ public async Task GetTags() [Cached(600)] public async Task GetTagsByFilter([FromBody] SearchParametersRequest searchParameters = null) { + if (searchParameters == null) + return BadRequest(); + searchParameters.SortParameters ??= new SortParametersRequest(); searchParameters.SortParameters.OrderBy ??= "asc"; @@ -179,12 +182,7 @@ public async Task TagsActivity() [Authorize] public async Task CreateAsync([FromBody] CreateTagRequest model) { - if (!ModelState.IsValid) - { - return Bad(ModelState); - } - - if (await _tagsService.AnyAsync(new TagSpecification(x => x.Title.ToLower().Equals(model.Title.ToLower())))) + if (!ModelState.IsValid || await _tagsService.AnyAsync(new TagSpecification(x => x.Title.ToLower().Equals(model.Title.ToLower())))) { return Bad(ModelState); } @@ -194,7 +192,7 @@ public async Task CreateAsync([FromBody] CreateTagRequest model) var response = new CreatedResponse { Id = tag.Id }; - var baseUrl = $@"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}"; + var baseUrl = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host.ToUriComponent()}"; var locationUrl = baseUrl + "/" + ApiRoutes.TagsController.GetTag.Replace("{id}", tag.Id.ToString()); return Created(locationUrl, response); diff --git a/BlogWebApp/Blog.Web/Factories/CategoryRequestFactory.cs b/BlogWebApp/Blog.Web/Factories/CategoryRequestFactory.cs index 22facc14..27ed9f81 100644 --- a/BlogWebApp/Blog.Web/Factories/CategoryRequestFactory.cs +++ b/BlogWebApp/Blog.Web/Factories/CategoryRequestFactory.cs @@ -49,7 +49,7 @@ public override CreateCategoryRequest GenerateForCreate() => public override UpdateCategoryRequest GenerateForUpdate(int id) { var category = _unitOfWork.GetRepository().FirstOrDefault(new CategorySpecification(x => x.Id == id)) - ?? throw new MicroserviceArgumentNullException();; + ?? throw new MicroserviceArgumentNullException(); var mapped = _mapper.Map(category); diff --git a/BlogWebApp/Blog.Web/Filters/SwaggerFilters/LowercaseDocumentFilter.cs b/BlogWebApp/Blog.Web/Filters/SwaggerFilters/LowercaseDocumentFilter.cs index 80cd74d0..e4ca9b3c 100644 --- a/BlogWebApp/Blog.Web/Filters/SwaggerFilters/LowercaseDocumentFilter.cs +++ b/BlogWebApp/Blog.Web/Filters/SwaggerFilters/LowercaseDocumentFilter.cs @@ -17,7 +17,7 @@ public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) } /// - /// Lowercase the everything but parameters. + /// Lowercase everything but parameters. /// /// The key. /// string. diff --git a/BlogWebApp/Blog.Web/Filters/SwaggerFilters/SwaggerGroupOperationFilter.cs b/BlogWebApp/Blog.Web/Filters/SwaggerFilters/SwaggerGroupOperationFilter.cs index 1d7294cd..ad40481f 100644 --- a/BlogWebApp/Blog.Web/Filters/SwaggerFilters/SwaggerGroupOperationFilter.cs +++ b/BlogWebApp/Blog.Web/Filters/SwaggerFilters/SwaggerGroupOperationFilter.cs @@ -24,11 +24,11 @@ public void Apply(OpenApiOperation operation, OperationFilterContext context) if (attributes.Any()) { var groupNameAttribute = attributes.First(); - operation.Tags = new[] { new OpenApiTag { Name = groupNameAttribute.GroupName } }; + operation.Tags = [new OpenApiTag { Name = groupNameAttribute.GroupName }]; } else { - operation.Tags = new[] { new OpenApiTag { Name = controllerActionDescriptor.RouteValues["controller"] } }; + operation.Tags = [new OpenApiTag { Name = controllerActionDescriptor.RouteValues["controller"] }]; } } } \ No newline at end of file diff --git a/BlogWebApp/Blog.Web/StartupConfigureServicesInstallers/AuthenticationAndAuthorizationInstaller.cs b/BlogWebApp/Blog.Web/StartupConfigureServicesInstallers/AuthenticationAndAuthorizationInstaller.cs index ee6177ab..51fe24f0 100644 --- a/BlogWebApp/Blog.Web/StartupConfigureServicesInstallers/AuthenticationAndAuthorizationInstaller.cs +++ b/BlogWebApp/Blog.Web/StartupConfigureServicesInstallers/AuthenticationAndAuthorizationInstaller.cs @@ -102,15 +102,15 @@ public void InstallServices(IServiceCollection services, IConfiguration configur }); services.AddCors(options => { - options.AddPolicy("AllowAll", bilder => + options.AddPolicy("AllowAll", builder => { - bilder.AllowAnyOrigin() + builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); - options.AddPolicy("AllowAllBlazor", bilder => + options.AddPolicy("AllowAllBlazor", builder => { - bilder.WithOrigins("https://localhost:44390").AllowAnyOrigin() + builder.WithOrigins("https://localhost:44390").AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); diff --git a/BlogWebApp/Blog.Web/StartupConfigureServicesInstallers/CorsInstaller.cs b/BlogWebApp/Blog.Web/StartupConfigureServicesInstallers/CorsInstaller.cs index fc0c77e2..121e4ac6 100644 --- a/BlogWebApp/Blog.Web/StartupConfigureServicesInstallers/CorsInstaller.cs +++ b/BlogWebApp/Blog.Web/StartupConfigureServicesInstallers/CorsInstaller.cs @@ -29,7 +29,7 @@ public void InstallServices(IServiceCollection services, IConfiguration configur { builder.AllowAnyHeader(); builder.AllowAnyMethod(); - builder.SetIsOriginAllowed(host => true); + builder.SetIsOriginAllowed(_ => true); builder.AllowCredentials(); } else diff --git a/BlogWebApp/Blog.Web/StartupConfigures/ConfigureSpa.cs b/BlogWebApp/Blog.Web/StartupConfigures/ConfigureSpa.cs index 06e60c8e..e19f9016 100644 --- a/BlogWebApp/Blog.Web/StartupConfigures/ConfigureSpa.cs +++ b/BlogWebApp/Blog.Web/StartupConfigures/ConfigureSpa.cs @@ -26,7 +26,7 @@ public static void Configure(IApplicationBuilder app, IWebHostEnvironment env) if (env.IsDevelopment()) { - spa.UseProxyToSpaDevelopmentServer("http://localhost:4200"); ; + spa.UseProxyToSpaDevelopmentServer("http://localhost:4200"); } else { diff --git a/BlogWebApp/Blog.Web/SwaggerExamples/Responses/CreatedResponseExample.cs b/BlogWebApp/Blog.Web/SwaggerExamples/Responses/CreatedResponseExample.cs index 28205945..a5e62539 100644 --- a/BlogWebApp/Blog.Web/SwaggerExamples/Responses/CreatedResponseExample.cs +++ b/BlogWebApp/Blog.Web/SwaggerExamples/Responses/CreatedResponseExample.cs @@ -6,7 +6,9 @@ /// /// Created response example. /// -/// +/// +/// IExamplesProvider{CreatedResponse{int}} +/// public class CreatedResponseExample : IExamplesProvider> { /// diff --git a/BlogWebApp/Blog.Web/VIewModels/AspNetUser/TwoFactorAuthenticationViewModel.cs b/BlogWebApp/Blog.Web/VIewModels/AspNetUser/TwoFactorAuthenticationViewModel.cs index d9d00036..43635da8 100644 --- a/BlogWebApp/Blog.Web/VIewModels/AspNetUser/TwoFactorAuthenticationViewModel.cs +++ b/BlogWebApp/Blog.Web/VIewModels/AspNetUser/TwoFactorAuthenticationViewModel.cs @@ -1,7 +1,7 @@ namespace BLog.Web.ViewModels.AspNetUser; /// -/// Two factor authentication view model +/// Two-factor authentication view model /// public class TwoFactorAuthenticationViewModel { diff --git a/BlogWebApp/Blog.sln.DotSettings.user b/BlogWebApp/Blog.sln.DotSettings.user index f0d73571..419787f0 100644 --- a/BlogWebApp/Blog.sln.DotSettings.user +++ b/BlogWebApp/Blog.sln.DotSettings.user @@ -1,4 +1,7 @@  + <AssemblyExplorer> + <Assembly Path="C:\Users\user\.nuget\packages\microsoft.aspnetcore.mvc.core\2.2.5\lib\netstandard2.0\Microsoft.AspNetCore.Mvc.Core.dll" /> +</AssemblyExplorer> <SessionState ContinuousTestingMode="0" Name="PostTagRelationsServiceTests" xmlns="urn:schemas-jetbrains-com:jetbrains-ut-session"> <TestAncestor> <TestId>xUnit::8AE98490-2264-4CBC-8B61-62DA16A2EC82::net5.0::Blog.ServicesTests.EntityServices.PostTagRelationsServiceTests</TestId> diff --git a/BlogWebApp/Blog.slnLaunch.user b/BlogWebApp/Blog.slnLaunch.user new file mode 100644 index 00000000..2890067f --- /dev/null +++ b/BlogWebApp/Blog.slnLaunch.user @@ -0,0 +1,15 @@ +[ + { + "Name": "New Profile", + "Projects": [ + { + "Path": "Blog.Web\\Blog.Web.csproj", + "Action": "Start" + }, + { + "Path": "BlogBlazor\\BlogBlazor.csproj", + "Action": "Start" + } + ] + } +] \ No newline at end of file diff --git a/BlogWebApp/Data/Blog.Data.Core/Entity.cs b/BlogWebApp/Data/Blog.Data.Core/Entity.cs index 7320381b..b3457a07 100644 --- a/BlogWebApp/Data/Blog.Data.Core/Entity.cs +++ b/BlogWebApp/Data/Blog.Data.Core/Entity.cs @@ -4,8 +4,8 @@ namespace Blog.Data.Core; -using System; using Blog.Core; +using System; /// /// Entity. @@ -74,13 +74,13 @@ public virtual bool Equals(Entity other) var otherType = other.GetUnproxiedType(); var thisType = this.GetUnproxiedType(); - return thisType.IsAssignableFrom(otherType) || otherType.IsAssignableFrom(thisType); + return otherType != null && (thisType.IsAssignableFrom(otherType) || otherType.IsAssignableFrom(thisType)); } /// public override int GetHashCode() { - return Equals(this.Id, default(int)) ? base.GetHashCode() : this.Id.GetHashCode(); + return Equals(this.Id, 0) ? base.GetHashCode() : this.Id.GetHashCode(); } /// @@ -90,7 +90,7 @@ public override int GetHashCode() /// bool. private static bool IsTransient(Entity obj) { - return obj != null && Equals(obj.Id, default(int)); + return obj != null && Equals(obj.Id, 0); } /// diff --git a/BlogWebApp/Data/Blog.Data.Core/Models/BaseDeletableModel.cs b/BlogWebApp/Data/Blog.Data.Core/Models/BaseDeletableModel.cs index f4f2f8f0..ff974d05 100644 --- a/BlogWebApp/Data/Blog.Data.Core/Models/BaseDeletableModel.cs +++ b/BlogWebApp/Data/Blog.Data.Core/Models/BaseDeletableModel.cs @@ -4,9 +4,9 @@ namespace Blog.Data.Core.Models; -using System; using Blog.Core; using Interfaces; +using System; /// /// Base deletable model. @@ -89,13 +89,13 @@ public virtual bool Equals(BaseDeletableModel other) var otherType = other.GetUnproxiedType(); var thisType = this.GetUnproxiedType(); - return thisType.IsAssignableFrom(otherType) || otherType.IsAssignableFrom(thisType); + return otherType != null && (thisType.IsAssignableFrom(otherType) || otherType.IsAssignableFrom(thisType)); } /// public override int GetHashCode() { - return Equals(this.Id, default(int)) ? base.GetHashCode() : this.Id.GetHashCode(); + return Equals(this.Id, 0) ? base.GetHashCode() : this.Id.GetHashCode(); } /// @@ -105,7 +105,7 @@ public override int GetHashCode() /// bool. private static bool IsTransient(BaseDeletableModel obj) { - return obj != null && Equals(obj.Id, default(int)); + return obj != null && Equals(obj.Id, 0); } /// diff --git a/BlogWebApp/Data/Blog.Data.Core/Models/BaseModel.cs b/BlogWebApp/Data/Blog.Data.Core/Models/BaseModel.cs index 659fea0a..b26295a6 100644 --- a/BlogWebApp/Data/Blog.Data.Core/Models/BaseModel.cs +++ b/BlogWebApp/Data/Blog.Data.Core/Models/BaseModel.cs @@ -4,26 +4,22 @@ namespace Blog.Data.Core.Models; +using Interfaces; using System; using System.ComponentModel.DataAnnotations; -using Interfaces; /// /// Base model. /// /// TKey. -public abstract class BaseModel : IAuditInfo +public abstract class BaseModel(TKey id) + : IAuditInfo { - protected BaseModel(TKey id) - { - Id = id; - } - /// /// Gets or sets id. /// [Key] - public TKey Id { get; } + public TKey Id { get; } = id; /// /// Gets or sets created on. diff --git a/BlogWebApp/Data/Blog.Data.Models/ApplicationUser.cs b/BlogWebApp/Data/Blog.Data.Models/ApplicationUser.cs index 7c560108..3280dd5b 100644 --- a/BlogWebApp/Data/Blog.Data.Models/ApplicationUser.cs +++ b/BlogWebApp/Data/Blog.Data.Models/ApplicationUser.cs @@ -4,11 +4,11 @@ namespace Blog.Data.Models; -using System; -using System.Collections.Generic; using Blog.Core; using Blog.Data.Core.Models.Interfaces; using Microsoft.AspNetCore.Identity; +using System; +using System.Collections.Generic; /// /// Application user entity. diff --git a/BlogWebApp/Data/Blog.Data.Models/Message.cs b/BlogWebApp/Data/Blog.Data.Models/Message.cs index 0879c24b..8be9cf9f 100644 --- a/BlogWebApp/Data/Blog.Data.Models/Message.cs +++ b/BlogWebApp/Data/Blog.Data.Models/Message.cs @@ -2,10 +2,9 @@ // Copyright (c) PlaceholderCompany. All rights reserved. // -using Blog.Core.Enums; - namespace Blog.Data.Models; +using Blog.Core.Enums; using Core; /// diff --git a/BlogWebApp/Data/Blog.Data.Models/Post.cs b/BlogWebApp/Data/Blog.Data.Models/Post.cs index 19b189a7..3f898cfd 100644 --- a/BlogWebApp/Data/Blog.Data.Models/Post.cs +++ b/BlogWebApp/Data/Blog.Data.Models/Post.cs @@ -2,8 +2,8 @@ namespace Blog.Data.Models; -using System; using Core; +using System; /// /// Post entity. diff --git a/BlogWebApp/Data/Blog.Data.Models/PostsTagsRelations.cs b/BlogWebApp/Data/Blog.Data.Models/PostsTagsRelations.cs index 1326b2f1..af99f115 100644 --- a/BlogWebApp/Data/Blog.Data.Models/PostsTagsRelations.cs +++ b/BlogWebApp/Data/Blog.Data.Models/PostsTagsRelations.cs @@ -7,7 +7,7 @@ namespace Blog.Data.Models; using Core; /// -/// Posts Tags Many to Many Relations entity. +/// Posts Tags Many-to-Many Relations entity. /// /// public class PostsTagsRelations : Entity diff --git a/BlogWebApp/Data/Blog.Data.Models/Setting.cs b/BlogWebApp/Data/Blog.Data.Models/Setting.cs index d84e2326..9aafa547 100644 --- a/BlogWebApp/Data/Blog.Data.Models/Setting.cs +++ b/BlogWebApp/Data/Blog.Data.Models/Setting.cs @@ -9,7 +9,6 @@ namespace Blog.Data.Models; /// /// Setting. /// - public class Setting : Entity { /// diff --git a/BlogWebApp/Data/Blog.Data/ApplicationDbContext.cs b/BlogWebApp/Data/Blog.Data/ApplicationDbContext.cs index fab6f270..8d7ceb3d 100644 --- a/BlogWebApp/Data/Blog.Data/ApplicationDbContext.cs +++ b/BlogWebApp/Data/Blog.Data/ApplicationDbContext.cs @@ -4,15 +4,15 @@ namespace Blog.Data; +using Blog.Data.Core.Models.Interfaces; +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; +using Models; using System; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; -using Blog.Data.Core.Models.Interfaces; -using Models; -using Microsoft.AspNetCore.Identity.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore; /// /// Application database context. @@ -159,7 +159,7 @@ protected override void OnModelCreating(ModelBuilder builder) foreach (var deletableEntityType in deletableEntityTypes) { var method = SetIsDeletedQueryFilterMethod.MakeGenericMethod(deletableEntityType.ClrType); - method.Invoke(null, new object[] { builder }); + method.Invoke(null, [builder]); } // Disable cascade delete diff --git a/BlogWebApp/Data/Blog.Data/ApplicationDbContextSeeder.cs b/BlogWebApp/Data/Blog.Data/ApplicationDbContextSeeder.cs index 19de9e5d..c31f4db0 100644 --- a/BlogWebApp/Data/Blog.Data/ApplicationDbContextSeeder.cs +++ b/BlogWebApp/Data/Blog.Data/ApplicationDbContextSeeder.cs @@ -2,14 +2,16 @@ // Copyright (c) BLog. All rights reserved. // +using static System.ArgumentNullException; + namespace Blog.Data; -using System; -using System.Linq; using Blog.Core; -using Models; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; +using Models; +using System; +using System.Linq; /// /// Application database context seeder. @@ -23,15 +25,8 @@ public static class ApplicationDbContextSeeder /// serviceProvider. public static void Seed(ApplicationDbContext dbContext, IServiceProvider serviceProvider) { - if (dbContext == null) - { - throw new ArgumentNullException(nameof(dbContext)); - } - - if (serviceProvider == null) - { - throw new ArgumentNullException(nameof(serviceProvider)); - } + ThrowIfNull(nameof(dbContext)); + ThrowIfNull(nameof(serviceProvider)); var roleManager = serviceProvider.GetRequiredService>(); Seed(dbContext, roleManager); @@ -44,15 +39,8 @@ public static void Seed(ApplicationDbContext dbContext, IServiceProvider service /// roleManager. public static void Seed(ApplicationDbContext dbContext, RoleManager roleManager) { - if (dbContext == null) - { - throw new ArgumentNullException(nameof(dbContext)); - } - - if (roleManager == null) - { - throw new ArgumentNullException(nameof(roleManager)); - } + ThrowIfNull(nameof(dbContext)); + ThrowIfNull(nameof(roleManager)); SeedRoles(roleManager); } diff --git a/BlogWebApp/Data/Blog.Data/ApplicationUserStore.cs b/BlogWebApp/Data/Blog.Data/ApplicationUserStore.cs index ae28a811..8899f7c9 100644 --- a/BlogWebApp/Data/Blog.Data/ApplicationUserStore.cs +++ b/BlogWebApp/Data/Blog.Data/ApplicationUserStore.cs @@ -4,10 +4,10 @@ namespace Blog.Data; -using System.Security.Claims; -using Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Models; +using System.Security.Claims; /// /// Application user store. @@ -64,7 +64,7 @@ protected override IdentityUserClaim CreateUserClaim(ApplicationUser use /// login. /// IdentityUserLogin. protected override IdentityUserLogin CreateUserLogin(ApplicationUser user, UserLoginInfo login) => - new () + new() { UserId = user.Id, ProviderKey = login.ProviderKey, @@ -93,6 +93,7 @@ protected override IdentityUserToken CreateUserToken( Name = name, Value = value, }; + return token; } } \ No newline at end of file diff --git a/BlogWebApp/Data/Blog.Data/Repositories/EfRepository.cs b/BlogWebApp/Data/Blog.Data/Repositories/EfRepository.cs index 1916585e..10733dfb 100644 --- a/BlogWebApp/Data/Blog.Data/Repositories/EfRepository.cs +++ b/BlogWebApp/Data/Blog.Data/Repositories/EfRepository.cs @@ -89,7 +89,7 @@ public Task> SearchAsync(SearchQuery searchQue throw new NotImplementedException(); } - public Task> SearchBySquenceAsync(SearchQuery searchQuery, IQueryable sequence) + public Task> SearchBySequenceAsync(SearchQuery searchQuery, IQueryable sequence) { throw new NotImplementedException(); } diff --git a/BlogWebApp/Data/Blog.Data/Repository.cs b/BlogWebApp/Data/Blog.Data/Repository.cs index 5e92b157..d2566254 100644 --- a/BlogWebApp/Data/Blog.Data/Repository.cs +++ b/BlogWebApp/Data/Blog.Data/Repository.cs @@ -4,17 +4,17 @@ namespace Blog.Data; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; using Blog.Core; using Blog.Core.Infrastructure; using Blog.Core.Infrastructure.Pagination; using Blog.Core.TableFilters; -using Specifications.Base; +using Microsoft.EntityFrameworkCore; using Repository; +using Specifications.Base; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; /// /// Table methods. @@ -40,7 +40,7 @@ public class Repository : IRepository public virtual IQueryable TableNoTracking => // AsNoTracking method temporarily doesn't work, it's a bug in EF Core 2.1 (details in https://github.com/aspnet/EntityFrameworkCore/issues/11689) - // Update - I checked this functionality and it is working fine, that's why I returned + // Update - I checked this functionality, and it is working fine, that's why I returned this.Entities.AsNoTracking(); /// @@ -109,7 +109,7 @@ public virtual async Task> SearchAsync(SearchQuery - public virtual async Task> SearchBySquenceAsync(SearchQuery searchQuery, IQueryable sequence) + public virtual async Task> SearchBySequenceAsync(SearchQuery searchQuery, IQueryable sequence) { // Applying filters sequence = this.ManageFilters(searchQuery, sequence); @@ -350,10 +350,7 @@ public async Task DeleteAsync(IEnumerable entities) /// public bool Any(ISpecification specification) { - if (specification.Filter == null) - { - throw new ArgumentNullException(nameof(specification)); - } + ArgumentNullException.ThrowIfNull(nameof(specification)); return this.Entities.Any(specification.Filter); } diff --git a/BlogWebApp/Data/Blog.Data/Repository/IRepository.cs b/BlogWebApp/Data/Blog.Data/Repository/IRepository.cs index 45e1bc33..c1c2d258 100644 --- a/BlogWebApp/Data/Blog.Data/Repository/IRepository.cs +++ b/BlogWebApp/Data/Blog.Data/Repository/IRepository.cs @@ -4,13 +4,13 @@ namespace Blog.Data.Repository; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Blog.Core; using Blog.Core.Infrastructure.Pagination; using Blog.Core.TableFilters; using Specifications.Base; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; /// /// Repository interface. @@ -82,7 +82,7 @@ public interface IRepository /// searchQuery. /// sequence. /// Task. - Task> SearchBySquenceAsync(SearchQuery searchQuery, IQueryable sequence); + Task> SearchBySequenceAsync(SearchQuery searchQuery, IQueryable sequence); /// /// Generate query. diff --git a/BlogWebApp/Data/Blog.Data/Specifications/Base/ISpecification.cs b/BlogWebApp/Data/Blog.Data/Specifications/Base/ISpecification.cs index 1c8663c1..589ead1b 100644 --- a/BlogWebApp/Data/Blog.Data/Specifications/Base/ISpecification.cs +++ b/BlogWebApp/Data/Blog.Data/Specifications/Base/ISpecification.cs @@ -28,5 +28,5 @@ public interface ISpecification /// /// The includes. /// - List>> Includes { get; } + List>> Includes { get; } } \ No newline at end of file diff --git a/BlogWebApp/Data/Blog.Data/Specifications/MessageSpecification.cs b/BlogWebApp/Data/Blog.Data/Specifications/MessageSpecification.cs index a5fe72fe..1faa3a61 100644 --- a/BlogWebApp/Data/Blog.Data/Specifications/MessageSpecification.cs +++ b/BlogWebApp/Data/Blog.Data/Specifications/MessageSpecification.cs @@ -4,10 +4,10 @@ namespace Blog.Data.Specifications; +using Base; +using Models; using System; using System.Linq.Expressions; -using Models; -using Base; /// /// Message specification. @@ -15,13 +15,6 @@ namespace Blog.Data.Specifications; /// public class MessageSpecification : BaseSpecification { - /// - /// Initializes a new instance of the class. - /// - public MessageSpecification() - { - } - /// /// Initializes a new instance of the class. /// diff --git a/BlogWebApp/Data/Blog.Data/Specifications/ProfileSpecification.cs b/BlogWebApp/Data/Blog.Data/Specifications/ProfileSpecification.cs index 3cd534de..30d733a4 100644 --- a/BlogWebApp/Data/Blog.Data/Specifications/ProfileSpecification.cs +++ b/BlogWebApp/Data/Blog.Data/Specifications/ProfileSpecification.cs @@ -4,10 +4,10 @@ namespace Blog.Data.Specifications; +using Base; +using Models; using System; using System.Linq.Expressions; -using Models; -using Base; /// /// Profile specification. @@ -15,13 +15,6 @@ namespace Blog.Data.Specifications; /// public class ProfileSpecification : BaseSpecification { - /// - /// Initializes a new instance of the class. - /// - public ProfileSpecification() - { - } - /// /// Initializes a new instance of the class. /// diff --git a/BlogWebApp/Data/Blog.Data/Specifications/TagSpecification.cs b/BlogWebApp/Data/Blog.Data/Specifications/TagSpecification.cs index be61de09..018a4a3a 100644 --- a/BlogWebApp/Data/Blog.Data/Specifications/TagSpecification.cs +++ b/BlogWebApp/Data/Blog.Data/Specifications/TagSpecification.cs @@ -4,10 +4,10 @@ namespace Blog.Data.Specifications; +using Base; +using Models; using System; using System.Linq.Expressions; -using Models; -using Base; /// /// Tag specification. @@ -15,13 +15,6 @@ namespace Blog.Data.Specifications; /// public class TagSpecification : BaseSpecification { - /// - /// Initializes a new instance of the class. - /// - public TagSpecification() - { - } - /// /// Initializes a new instance of the class. /// diff --git a/BlogWebApp/Data/Blog.Data/UnitOfWork/IUnitOfWork.cs b/BlogWebApp/Data/Blog.Data/UnitOfWork/IUnitOfWork.cs index 97bb782e..3f5c1592 100644 --- a/BlogWebApp/Data/Blog.Data/UnitOfWork/IUnitOfWork.cs +++ b/BlogWebApp/Data/Blog.Data/UnitOfWork/IUnitOfWork.cs @@ -1,12 +1,12 @@ namespace Blog.Data.UnitOfWork; -using System; -using System.Linq; -using System.Threading.Tasks; +using Blog.Core; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Storage; -using Blog.Core; using Repository; +using System; +using System.Linq; +using System.Threading.Tasks; /// /// Unit of work interface. @@ -96,7 +96,7 @@ IQueryable FromSqlRaw(string sql, params object[] parameters) /// /// The type of the context. /// -public interface IUnitOfWork : IUnitOfWork +public interface IUnitOfWork : IUnitOfWork where TContext : Microsoft.EntityFrameworkCore.DbContext { /// diff --git a/BlogWebApp/Data/Blog.Data/UnitOfWork/UnitOfWork.cs b/BlogWebApp/Data/Blog.Data/UnitOfWork/UnitOfWork.cs index 85029cae..960899fa 100644 --- a/BlogWebApp/Data/Blog.Data/UnitOfWork/UnitOfWork.cs +++ b/BlogWebApp/Data/Blog.Data/UnitOfWork/UnitOfWork.cs @@ -1,18 +1,18 @@ namespace Blog.Data.UnitOfWork; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; +using Blog.Core; using EntityFrameworkCore.AutoHistory.Extensions; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage; -using Blog.Core; using Repository; using RepositoryFactory; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; /// /// Unit of work. @@ -41,7 +41,7 @@ public sealed class UnitOfWork : /// Initializes a new instance of the class. /// /// The context. - /// context + /// context. public UnitOfWork(TContext context) { var context1 = context; @@ -98,7 +98,7 @@ public IDbContextTransaction BeginTransaction(bool useIfExists = false) /// Sets the automatic detect changes. /// /// if set to true [value]. - public void SetAutoDetectChanges(bool value) + public void SetAutoDetectChanges(bool value) => this.DbContext.ChangeTracker.AutoDetectChangesEnabled = value; /// @@ -107,7 +107,7 @@ public void SetAutoDetectChanges(bool value) /// /// The last save changes result. /// - public SaveChangesResult LastSaveChangesResult { get; private set; } + public SaveChangesResult LastSaveChangesResult { get; } /// /// Executes the SQL command. @@ -248,15 +248,15 @@ public IRepository GetRepository(bool hasCustomRepository) whe } var key = typeof(TEntity); - if (_repositories.ContainsKey(key)) + if (_repositories.TryGetValue(key, out var repository)) { - return (IRepository)_repositories[key]; + return (IRepository)repository; } var dbContext = this.DbContext; if (dbContext != null) { - this._repositories[key] = new Repository((DbContext)dbContext) as object; + this._repositories[key] = new Repository((DbContext)dbContext); } return (IRepository)this._repositories[key]; diff --git a/BlogWebApp/Services/Blog.CommonServices/ActiveDirectoryService.cs b/BlogWebApp/Services/Blog.CommonServices/ActiveDirectoryService.cs index fa70b62e..2c820bf2 100644 --- a/BlogWebApp/Services/Blog.CommonServices/ActiveDirectoryService.cs +++ b/BlogWebApp/Services/Blog.CommonServices/ActiveDirectoryService.cs @@ -1,21 +1,28 @@ -using System.Collections.Generic; -using Blog.CommonServices.Interfaces; +using Blog.CommonServices.Interfaces; using Blog.Services.Core.Dtos.User; +using System.Collections.Generic; namespace Blog.CommonServices; +/// +/// Active Directory service. +/// +/// public class ActiveDirectoryService : IActiveDirectoryService { + /// public ActiveDirectoryUserDto GetActiveDirectoryUserByIdentity(string identity) { throw new System.NotImplementedException(); } + /// public ActiveDirectoryUserDto GetActiveDirectoryUserByEmployeeId(string employeeId) { throw new System.NotImplementedException(); } + /// public List GetActiveDirectoryUsersByGroup(string groupName) { throw new System.NotImplementedException(); diff --git a/BlogWebApp/Services/Blog.CommonServices/Interfaces/IActiveDirectoryService.cs b/BlogWebApp/Services/Blog.CommonServices/Interfaces/IActiveDirectoryService.cs index 5d889c25..b17b4ede 100644 --- a/BlogWebApp/Services/Blog.CommonServices/Interfaces/IActiveDirectoryService.cs +++ b/BlogWebApp/Services/Blog.CommonServices/Interfaces/IActiveDirectoryService.cs @@ -4,12 +4,32 @@ namespace Blog.CommonServices.Interfaces; -using System.Collections.Generic; using Blog.Services.Core.Dtos.User; +using System.Collections.Generic; +/// +/// The Active Directory service interface. +/// public interface IActiveDirectoryService { + /// + /// Gets Active Directory User by identity. + /// + /// The identity. + /// ActiveDirectoryUserDto. ActiveDirectoryUserDto GetActiveDirectoryUserByIdentity(string identity); + + /// + /// Gets Active Directory User by employee id. + /// + /// The employee id. + /// ActiveDirectoryUserDto. ActiveDirectoryUserDto GetActiveDirectoryUserByEmployeeId(string employeeId); + + /// + /// Gets Active Directory Users by group. + /// + /// The group name. + /// ActiveDirectoryUserDto. List GetActiveDirectoryUsersByGroup(string groupName); } \ No newline at end of file diff --git a/BlogWebApp/Services/Blog.Services.Core/Caching/MemoryCacheManager.cs b/BlogWebApp/Services/Blog.Services.Core/Caching/MemoryCacheManager.cs index 42144c0d..1faad455 100644 --- a/BlogWebApp/Services/Blog.Services.Core/Caching/MemoryCacheManager.cs +++ b/BlogWebApp/Services/Blog.Services.Core/Caching/MemoryCacheManager.cs @@ -4,13 +4,13 @@ namespace Blog.Services.Core.Caching; +using Interfaces; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Primitives; using System; using System.Collections.Concurrent; using System.Linq; using System.Threading; -using Microsoft.Extensions.Caching.Memory; -using Microsoft.Extensions.Primitives; -using Interfaces; /// /// Memory cache manager. @@ -145,7 +145,7 @@ protected static string AddKey(string key) protected static void TryRemoveKey(string key) { // try to remove key from dictionary - if (!AllKeys.TryRemove(key, out var _)) + if (!AllKeys.TryRemove(key, out _)) { // if not possible to remove key from dictionary, then try to mark key as not existing in cache AllKeys.TryUpdate(key, false, false); diff --git a/BlogWebApp/Services/Blog.Services.Core/Caching/RedisCacheManager.cs b/BlogWebApp/Services/Blog.Services.Core/Caching/RedisCacheManager.cs index 72e18b4f..70dbd56e 100644 --- a/BlogWebApp/Services/Blog.Services.Core/Caching/RedisCacheManager.cs +++ b/BlogWebApp/Services/Blog.Services.Core/Caching/RedisCacheManager.cs @@ -4,13 +4,13 @@ namespace Blog.Services.Core.Caching; -using System; -using System.Linq; -using System.Threading.Tasks; using Blog.Core.Configuration; +using Interfaces; using Newtonsoft.Json; using StackExchange.Redis; -using Interfaces; +using System; +using System.Linq; +using System.Threading.Tasks; /// /// Redis cache manager. @@ -143,14 +143,14 @@ protected virtual async Task GetAsync(string key) var serializedItem = await this.db.StringGetAsync(key); if (!serializedItem.HasValue) { - return default(T); + return default; } // deserialize item var item = JsonConvert.DeserializeObject(serializedItem); if (item == null) { - return default(T); + return default; } // set item in the per-request cache diff --git a/BlogWebApp/Services/Blog.Services.Core/Caching/RedisConnectionWrapper.cs b/BlogWebApp/Services/Blog.Services.Core/Caching/RedisConnectionWrapper.cs index eedf9cbb..1502da09 100644 --- a/BlogWebApp/Services/Blog.Services.Core/Caching/RedisConnectionWrapper.cs +++ b/BlogWebApp/Services/Blog.Services.Core/Caching/RedisConnectionWrapper.cs @@ -4,14 +4,15 @@ namespace Blog.Services.Core.Caching; -using System; -using System.Linq; -using System.Net; +using Blog.Core.Configuration; +using Interfaces; using RedLockNet.SERedis; using RedLockNet.SERedis.Configuration; using StackExchange.Redis; -using Blog.Core.Configuration; -using Interfaces; +using System; +using System.Linq; +using System.Net; +using System.Threading; /// /// Redis connection wrapper. @@ -31,7 +32,7 @@ public class RedisConnectionWrapper : IRedisConnectionWrapper, ILocker /// /// Lock object. /// - private readonly object @lock = new (); + private readonly Lock @lock = new(); /// /// RedLock factory. @@ -110,6 +111,7 @@ public bool PerformActionWithLock(string resource, TimeSpan expirationTime, Acti { // use RedLock library using var redisLock = this.redisLockFactory.CreateLock(resource, expirationTime); + // ensure that lock is acquired if (!redisLock.IsAcquired) { diff --git a/BlogWebApp/Services/Blog.Services.Core/Dtos/User/ActiveDirectoryUserDto.cs b/BlogWebApp/Services/Blog.Services.Core/Dtos/User/ActiveDirectoryUserDto.cs index 5d07796d..98e6161b 100644 --- a/BlogWebApp/Services/Blog.Services.Core/Dtos/User/ActiveDirectoryUserDto.cs +++ b/BlogWebApp/Services/Blog.Services.Core/Dtos/User/ActiveDirectoryUserDto.cs @@ -1,13 +1,43 @@ -using System.Collections.Generic; +// +// Copyright (c) PlaceholderCompany. All rights reserved. +// namespace Blog.Services.Core.Dtos.User; +using System.Collections.Generic; + +/// +/// The Active directory user dto. +/// public class ActiveDirectoryUserDto { + /// + /// The gets or sets first name. + /// public string FirstName { get; set; } + + /// + /// The gets or sets last name. + /// public string LastName { get; set; } + + /// + /// The gets or sets email. + /// public string Email { get; set; } + + /// + /// The gets or sets identity. + /// public string Identity { get; set; } + + /// + /// The gets or sets display name. + /// public string DisplayName { get; set; } + + /// + /// The gets or sets groups. + /// public List Groups { get; set; } = []; } \ No newline at end of file diff --git a/BlogWebApp/Services/Blog.Services.Core/Identity/Auth/JwtFactory.cs b/BlogWebApp/Services/Blog.Services.Core/Identity/Auth/JwtFactory.cs index 5528dc6c..e01c27b1 100644 --- a/BlogWebApp/Services/Blog.Services.Core/Identity/Auth/JwtFactory.cs +++ b/BlogWebApp/Services/Blog.Services.Core/Identity/Auth/JwtFactory.cs @@ -4,6 +4,10 @@ namespace Blog.Services.Core.Identity.Auth; +using Blog.Core; +using Data.Models; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; @@ -11,10 +15,6 @@ namespace Blog.Services.Core.Identity.Auth; using System.Security.Cryptography; using System.Security.Principal; using System.Threading.Tasks; -using Microsoft.AspNetCore.Identity; -using Microsoft.Extensions.Options; -using Blog.Core; -using Data.Models; using Utilities; /// @@ -57,8 +57,7 @@ public JwtFactory( /// public async Task GenerateEncodedToken(string userName, ClaimsIdentity identity) { - var claims = new List(new[] - { + var claims = new List([ new Claim(JwtRegisteredClaimNames.Sub, userName), new Claim(JwtRegisteredClaimNames.Jti, await this.jwtOptions.JtiGenerator()), new Claim( @@ -72,8 +71,8 @@ public async Task GenerateEncodedToken(string userName, ClaimsIdentity i identity.FindFirst(JwtClaimTypes.Email), identity.FindFirst(JwtClaimTypes.PhoneNumber), identity.FindFirst(JwtClaimTypes.IsEmailVerified), - identity.FindFirst(JwtClaimTypes.ProfileId), - }); + identity.FindFirst(JwtClaimTypes.ProfileId) + ]); var user = await this.userManager.FindByNameAsync(userName); @@ -160,14 +159,7 @@ private static void ThrowIfInvalidOptions(JwtIssuerOptions options) throw new ArgumentException("Must be a non-zero TimeSpan.", nameof(JwtIssuerOptions.ValidFor)); } - if (options.SigningCredentials == null) - { - throw new ArgumentNullException(nameof(JwtIssuerOptions.SigningCredentials)); - } - - if (options.JtiGenerator == null) - { - throw new ArgumentNullException(nameof(JwtIssuerOptions.JtiGenerator)); - } + ArgumentNullException.ThrowIfNull(nameof(JwtIssuerOptions.SigningCredentials)); + ArgumentNullException.ThrowIfNull(nameof(JwtIssuerOptions.JtiGenerator)); } } \ No newline at end of file diff --git a/BlogWebApp/Services/Blog.Services.Core/Identity/Auth/Tokens.cs b/BlogWebApp/Services/Blog.Services.Core/Identity/Auth/Tokens.cs index cff90a31..bf6083e6 100644 --- a/BlogWebApp/Services/Blog.Services.Core/Identity/Auth/Tokens.cs +++ b/BlogWebApp/Services/Blog.Services.Core/Identity/Auth/Tokens.cs @@ -4,9 +4,9 @@ namespace Blog.Services.Core.Identity.Auth; +using Newtonsoft.Json; using System.Security.Claims; using System.Threading.Tasks; -using Newtonsoft.Json; /// /// Tokens. @@ -34,6 +34,7 @@ public static async Task GenerateJwt(ClaimsIdentity identity, IJwtFactor }; var json = JsonConvert.SerializeObject(response, serializerSettings); + return json; } } \ No newline at end of file diff --git a/BlogWebApp/Services/Blog.Services.Core/Identity/User/ViewModelToEntityMappingUser.cs b/BlogWebApp/Services/Blog.Services.Core/Identity/User/ViewModelToEntityMappingUser.cs index 08b9cddd..f807696c 100644 --- a/BlogWebApp/Services/Blog.Services.Core/Identity/User/ViewModelToEntityMappingUser.cs +++ b/BlogWebApp/Services/Blog.Services.Core/Identity/User/ViewModelToEntityMappingUser.cs @@ -4,11 +4,11 @@ namespace Blog.Services.Core.Identity.User; -using System.Linq; +using Blog.Services.Core.Dtos.User; using Contracts.V1.Requests.UsersRequests; using Contracts.V1.Responses.UsersResponses; using Data.Models; -using Blog.Services.Core.Dtos.User; +using System.Linq; /// /// View model to entity mapping user. diff --git a/BlogWebApp/Services/Blog.Services.Core/QueryableExtensions.cs b/BlogWebApp/Services/Blog.Services.Core/QueryableExtensions.cs index 3c3b7d7a..acdb33d3 100644 --- a/BlogWebApp/Services/Blog.Services.Core/QueryableExtensions.cs +++ b/BlogWebApp/Services/Blog.Services.Core/QueryableExtensions.cs @@ -4,13 +4,13 @@ namespace Blog.Services.Core; +using Dtos; using System; using System.Linq; using System.Linq.Expressions; -using Dtos; /// -/// Queriable extensions. +/// Queryable extensions. /// public static class QueryableExtensions { @@ -36,6 +36,7 @@ public static IQueryable OrderBy(this IQueryable source, SortParameters [source.ElementType, selector.Type], expression, Expression.Quote(Expression.Lambda(selector, parameter))); + return source.Provider.CreateQuery(expression); } } \ No newline at end of file diff --git a/BlogWebApp/Services/Blog.Services.Core/Security/HasScopeHandler.cs b/BlogWebApp/Services/Blog.Services.Core/Security/HasScopeHandler.cs index 1b3acaed..1ecb3ca2 100644 --- a/BlogWebApp/Services/Blog.Services.Core/Security/HasScopeHandler.cs +++ b/BlogWebApp/Services/Blog.Services.Core/Security/HasScopeHandler.cs @@ -4,9 +4,9 @@ namespace Blog.Services.Core.Security; +using Microsoft.AspNetCore.Authorization; using System.Linq; using System.Threading.Tasks; -using Microsoft.AspNetCore.Authorization; /// /// Has scope handler. @@ -26,7 +26,7 @@ protected override Task HandleRequirementAsync(AuthorizationHandlerContext conte var scopes = context.User.FindFirst(c => c.Type == "scope" && c.Issuer == requirement.Issuer)?.Value.Split(' '); // Succeed if the scope array contains the required scope - if (scopes.Any(s => s == requirement.Scope)) + if (scopes != null && scopes.Any(s => s == requirement.Scope)) { context.Succeed(requirement); } diff --git a/BlogWebApp/Services/Blog.Services.Core/Security/HasScopeRequirement.cs b/BlogWebApp/Services/Blog.Services.Core/Security/HasScopeRequirement.cs index af08106e..e0b9b468 100644 --- a/BlogWebApp/Services/Blog.Services.Core/Security/HasScopeRequirement.cs +++ b/BlogWebApp/Services/Blog.Services.Core/Security/HasScopeRequirement.cs @@ -1,11 +1,11 @@ -// +// // Copyright (c) PlaceholderCompany. All rights reserved. // namespace Blog.Services.Core.Security; -using System; using Microsoft.AspNetCore.Authorization; +using System; /// /// Has scope requirement. diff --git a/BlogWebApp/Services/Blog.Services.Core/Utilities/Extensions.DateTime.cs b/BlogWebApp/Services/Blog.Services.Core/Utilities/Extensions.DateTime.cs index 564770c7..00d365a0 100644 --- a/BlogWebApp/Services/Blog.Services.Core/Utilities/Extensions.DateTime.cs +++ b/BlogWebApp/Services/Blog.Services.Core/Utilities/Extensions.DateTime.cs @@ -22,11 +22,12 @@ public static long ToUnixTimeStamp(this DateTime dateTime) var universalTime = dateTime.ToUniversalTime(); var delta = Math.Round((universalTime - offset).TotalSeconds); + return (long)delta; } /// - /// Convert DateTime to To user time. + /// Convert DateTime to user time. /// /// dt. /// sourceDateTimeKind. @@ -51,6 +52,6 @@ public static DateTime ConvertToUserTime(this DateTime dt, DateTimeKind sourceDa /// string. public static string ToSafeFileName(this DateTime dateTime) { - return $"{dateTime.Day.ToString("00")}{dateTime.Month.ToString("00")}{dateTime.Year}"; + return $"{dateTime.Day:00}{dateTime.Month:00}{dateTime.Year}"; } } \ No newline at end of file diff --git a/BlogWebApp/Services/Blog.Services.Core/Utilities/Extensions.String.cs b/BlogWebApp/Services/Blog.Services.Core/Utilities/Extensions.String.cs index 1850760a..5708bcae 100644 --- a/BlogWebApp/Services/Blog.Services.Core/Utilities/Extensions.String.cs +++ b/BlogWebApp/Services/Blog.Services.Core/Utilities/Extensions.String.cs @@ -14,9 +14,9 @@ namespace Blog.Services.Core.Utilities; /// public static partial class Extensions { - private static readonly Regex WebUrlExpression = new Regex(@"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)", RegexOptions.Singleline | RegexOptions.Compiled); - private static readonly Regex EmailExpression = new Regex(@"^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$", RegexOptions.Singleline | RegexOptions.Compiled); - private static readonly Regex StripHtmlExpression = new Regex("<\\S[^><]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled); + private static readonly Regex WebUrlExpression = new(@"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(:[0-9]+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)", RegexOptions.Singleline | RegexOptions.Compiled); + private static readonly Regex EmailExpression = new("^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$", RegexOptions.Singleline | RegexOptions.Compiled); + private static readonly Regex StripHtmlExpression = new("<\\S[^><]*>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled); /// /// Convert string to int. @@ -27,6 +27,7 @@ public static int ToInt(this string input) { // int result = 0; int.TryParse(input, out var result); + return result; } @@ -39,6 +40,7 @@ public static bool ToBool(this string input) { // int result = 0; bool.TryParse(input, out var result); + return result; } @@ -51,6 +53,7 @@ public static bool ToBool(this string input) public static Guid ToGuid(this string value) { Guid.TryParse(value, out var result); + return result; } diff --git a/BlogWebApp/Services/Blog.Services/CommentsService.cs b/BlogWebApp/Services/Blog.Services/CommentsService.cs index 38a3d207..cf528de8 100644 --- a/BlogWebApp/Services/Blog.Services/CommentsService.cs +++ b/BlogWebApp/Services/Blog.Services/CommentsService.cs @@ -135,11 +135,9 @@ public async Task GetPagedCommentsByPostId(int postId, SortPara /// public async Task GetCommentAsync(int id) - { - return await this.Repository.Table + => await this.Repository.Table .Where(new CommentSpecification(x => x.Id.Equals(id)).Filter) .FirstOrDefaultAsync(); - } /// public async Task GetCommentsActivity() diff --git a/BlogWebApp/Services/Blog.Services/ControllerContext/IControllerContext.cs b/BlogWebApp/Services/Blog.Services/ControllerContext/IControllerContext.cs index 960234d1..6f97f735 100644 --- a/BlogWebApp/Services/Blog.Services/ControllerContext/IControllerContext.cs +++ b/BlogWebApp/Services/Blog.Services/ControllerContext/IControllerContext.cs @@ -2,10 +2,10 @@ // Copyright (c) PlaceholderCompany. All rights reserved. // -using Blog.Data.Models; - namespace Blog.EntityServices.ControllerContext; +using Data.Models; + /// /// Controller context interface. /// diff --git a/BlogWebApp/Services/Blog.Services/GeneralService/GeneralService.cs b/BlogWebApp/Services/Blog.Services/GeneralService/GeneralService.cs index d0d10fcd..404bddb5 100644 --- a/BlogWebApp/Services/Blog.Services/GeneralService/GeneralService.cs +++ b/BlogWebApp/Services/Blog.Services/GeneralService/GeneralService.cs @@ -4,16 +4,16 @@ namespace Blog.EntityServices.GeneralService; +using Blog.Data.Core; +using Core.Infrastructure.Pagination; +using Core.TableFilters; +using Data.Repository; +using Data.Specifications.Base; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; -using Core.Infrastructure.Pagination; -using Core.TableFilters; -using Blog.Data.Core; -using Data.Repository; -using Data.Specifications.Base; /// /// General service. @@ -114,7 +114,7 @@ public async Task> SearchAsync(SearchQuery searchQuery) public async Task> SearchBySequenceAsync( SearchQuery searchQuery, IQueryable sequence) - => await this.Repository.SearchBySquenceAsync(searchQuery, sequence); + => await this.Repository.SearchBySequenceAsync(searchQuery, sequence); /// public ICollection GetAll() diff --git a/BlogWebApp/Services/Blog.Services/GeneralService/IGeneralService.cs b/BlogWebApp/Services/Blog.Services/GeneralService/IGeneralService.cs index 734e75b8..204e00d3 100644 --- a/BlogWebApp/Services/Blog.Services/GeneralService/IGeneralService.cs +++ b/BlogWebApp/Services/Blog.Services/GeneralService/IGeneralService.cs @@ -2,14 +2,14 @@ // Copyright (c) PlaceholderCompany. All rights reserved. // +namespace Blog.EntityServices.GeneralService; + +using Core.Infrastructure.Pagination; +using Core.TableFilters; +using Data.Specifications.Base; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Blog.Core.Infrastructure.Pagination; -using Blog.Core.TableFilters; -using Blog.Data.Specifications.Base; - -namespace Blog.EntityServices.GeneralService; /// /// General service interface. @@ -195,7 +195,7 @@ Task> SearchBySequenceAsync( T FirstOrDefault(ISpecification specification); /// - /// Lasts the or default. + /// Last or default. /// /// The specification. /// T. diff --git a/BlogWebApp/Services/Blog.Services/Identity/Auth/IAuthService.cs b/BlogWebApp/Services/Blog.Services/Identity/Auth/IAuthService.cs index f79a05c8..207647af 100644 --- a/BlogWebApp/Services/Blog.Services/Identity/Auth/IAuthService.cs +++ b/BlogWebApp/Services/Blog.Services/Identity/Auth/IAuthService.cs @@ -2,12 +2,12 @@ // Copyright (c) PlaceholderCompany. All rights reserved. // +namespace Blog.EntityServices.Identity.Auth; + +using Data.Models; +using Microsoft.AspNetCore.Identity; using System.Security.Claims; using System.Threading.Tasks; -using Blog.Data.Models; -using Microsoft.AspNetCore.Identity; - -namespace Blog.EntityServices.Identity.Auth; /// /// Auth service. diff --git a/BlogWebApp/Services/Blog.Services/Identity/Registration/IRegistrationService.cs b/BlogWebApp/Services/Blog.Services/Identity/Registration/IRegistrationService.cs index ef8b972a..890e8a45 100644 --- a/BlogWebApp/Services/Blog.Services/Identity/Registration/IRegistrationService.cs +++ b/BlogWebApp/Services/Blog.Services/Identity/Registration/IRegistrationService.cs @@ -2,12 +2,12 @@ // Copyright (c) PlaceholderCompany. All rights reserved. // -using System.Threading.Tasks; -using Blog.Data.Models; -using Microsoft.AspNetCore.Identity; - namespace Blog.EntityServices.Identity.Registration; +using Data.Models; +using Microsoft.AspNetCore.Identity; +using System.Threading.Tasks; + /// /// Registration service interface. /// diff --git a/BlogWebApp/Services/Blog.Services/Identity/User/IUserService.cs b/BlogWebApp/Services/Blog.Services/Identity/User/IUserService.cs index bc166626..1d40ef9a 100644 --- a/BlogWebApp/Services/Blog.Services/Identity/User/IUserService.cs +++ b/BlogWebApp/Services/Blog.Services/Identity/User/IUserService.cs @@ -2,15 +2,15 @@ // Copyright (c) PlaceholderCompany. All rights reserved. // +namespace Blog.EntityServices.Identity.User; + +using Contracts.V1.Responses.Chart; +using Core.Infrastructure.Pagination; +using Core.TableFilters; +using Data.Models; +using Microsoft.AspNetCore.Identity; using System.Collections.Generic; using System.Threading.Tasks; -using Blog.Contracts.V1.Responses.Chart; -using Blog.Core.Infrastructure.Pagination; -using Blog.Core.TableFilters; -using Blog.Data.Models; -using Microsoft.AspNetCore.Identity; - -namespace Blog.EntityServices.Identity.User; /// /// User service interface. diff --git a/BlogWebApp/Services/Blog.Services/Identity/User/UserService.cs b/BlogWebApp/Services/Blog.Services/Identity/User/UserService.cs index 255fa167..1fa7fa2f 100644 --- a/BlogWebApp/Services/Blog.Services/Identity/User/UserService.cs +++ b/BlogWebApp/Services/Blog.Services/Identity/User/UserService.cs @@ -4,9 +4,6 @@ namespace Blog.EntityServices.Identity.User; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using AutoMapper; using Contracts.V1.Responses.Chart; using Core.Infrastructure.Pagination; @@ -15,6 +12,9 @@ namespace Blog.EntityServices.Identity.User; using Data.Repository; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; /// /// User service. @@ -214,12 +214,12 @@ public async Task> GetAllFilteredUsersAsync(Tab { var sequence = this.applicationUserRepository.Table; - return await this.applicationUserRepository.SearchBySquenceAsync(this.AddFilter(tableFilter), sequence); + return await this.applicationUserRepository.SearchBySequenceAsync(this.AddFilter(tableFilter), sequence); } /// public async Task GetUsersActivity() - => new () + => new() { Name = "Posts", Series = await applicationUserRepository.TableNoTracking diff --git a/BlogWebApp/Services/Blog.Services/PostsService.cs b/BlogWebApp/Services/Blog.Services/PostsService.cs index ef22ba61..3189c506 100644 --- a/BlogWebApp/Services/Blog.Services/PostsService.cs +++ b/BlogWebApp/Services/Blog.Services/PostsService.cs @@ -4,27 +4,25 @@ namespace Blog.EntityServices; -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Data; -using System.Linq; -using System.Threading.Tasks; using AutoMapper; -using Blog.CommonServices.Interfaces; +using Blog.Services.Core; +using Blog.Services.Core.Dtos; +using Blog.Services.Core.Dtos.Posts; +using Blog.Services.Core.Dtos.User; using Contracts.V1.Responses.Chart; using Core.Helpers; using Data.Models; using Data.Repository; using Data.Specifications; -using Blog.Services.Core; -using Blog.Services.Core.Dtos; -using Blog.Services.Core.Dtos.Exports; -using Blog.Services.Core.Dtos.Posts; -using Blog.Services.Core.Dtos.User; using GeneralService; using Interfaces; using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Data; +using System.Linq; +using System.Threading.Tasks; /// /// Posts service. @@ -278,7 +276,7 @@ public async Task InsertAsync(Post post, IEnumerable tags) /// public async Task GetPostsActivity() - => new () + => new() { Name = "Posts", Series = await Repository.TableNoTracking diff --git a/BlogWebApp/Services/Blog.Services/Security/Authorization/PermissionsPolicyProvider.cs b/BlogWebApp/Services/Blog.Services/Security/Authorization/PermissionsPolicyProvider.cs index 83bf69e6..4eb7d29b 100644 --- a/BlogWebApp/Services/Blog.Services/Security/Authorization/PermissionsPolicyProvider.cs +++ b/BlogWebApp/Services/Blog.Services/Security/Authorization/PermissionsPolicyProvider.cs @@ -4,11 +4,11 @@ namespace Blog.EntityServices.Security.Authorization; -using System; -using System.Threading.Tasks; +using Core.Consts; using Microsoft.AspNetCore.Authorization; using Microsoft.Extensions.Options; -using Core.Consts; +using System; +using System.Threading.Tasks; /// /// Permissions policy provider. @@ -44,7 +44,7 @@ public class PermissionsPolicyProvider(IOptions options) public Task GetPolicyAsync(string policyName) { if (!policyName.StartsWith(this.policyPrefix, StringComparison.OrdinalIgnoreCase) || - string.IsNullOrWhiteSpace(policyName.Substring(this.policyPrefix.Length))) + string.IsNullOrWhiteSpace(policyName[this.policyPrefix.Length..])) { return this.FallbackPolicyProvider.GetPolicyAsync(policyName); } diff --git a/BlogWebApp/Services/Blog.Services/Security/Authorization/PermissionsRequirement.cs b/BlogWebApp/Services/Blog.Services/Security/Authorization/PermissionsRequirement.cs index 171baf05..13efa42e 100644 --- a/BlogWebApp/Services/Blog.Services/Security/Authorization/PermissionsRequirement.cs +++ b/BlogWebApp/Services/Blog.Services/Security/Authorization/PermissionsRequirement.cs @@ -2,10 +2,10 @@ // Copyright (c) PlaceholderCompany. All rights reserved. // -using Microsoft.AspNetCore.Authorization; - namespace Blog.EntityServices.Security.Authorization; +using Microsoft.AspNetCore.Authorization; + /// /// Permissions requirement. /// diff --git a/BlogWebApp/Services/Blog.Services/Security/EncryptionService.cs b/BlogWebApp/Services/Blog.Services/Security/EncryptionService.cs index 26c65c50..5226b928 100644 --- a/BlogWebApp/Services/Blog.Services/Security/EncryptionService.cs +++ b/BlogWebApp/Services/Blog.Services/Security/EncryptionService.cs @@ -21,25 +21,24 @@ public class EncryptionService : IEncryptionService public virtual string CreateSaltKey(int size) { // generate a cryptographic random number - using (var provider = new RNGCryptoServiceProvider()) - { - var buff = new byte[size]; - provider.GetBytes(buff); + using var provider = new RNGCryptoServiceProvider(); - // Return a Base64 string representation of the random number - return Convert.ToBase64String(buff); - } + var buff = new byte[size]; + provider.GetBytes(buff); + + // Return a Base64 string representation of the random number + return Convert.ToBase64String(buff); } /// /// Create a password hash. /// /// Password. - /// Salk key. + /// Salt key. /// Password format (hash algorithm). /// Password hash - public virtual string CreatePasswordHash(string password, string saltkey, string passwordFormat) - => this.CreateHash(Encoding.UTF8.GetBytes(string.Concat(password, saltkey)), passwordFormat); + public virtual string CreatePasswordHash(string password, string saltKey, string passwordFormat) + => this.CreateHash(Encoding.UTF8.GetBytes(string.Concat(password, saltKey)), passwordFormat); /// /// Create a data hash. diff --git a/BlogWebApp/Services/Blog.Services/Security/IEncryptionService.cs b/BlogWebApp/Services/Blog.Services/Security/IEncryptionService.cs index e73148bd..1f7c4770 100644 --- a/BlogWebApp/Services/Blog.Services/Security/IEncryptionService.cs +++ b/BlogWebApp/Services/Blog.Services/Security/IEncryptionService.cs @@ -5,47 +5,47 @@ namespace Blog.EntityServices.Security; /// -/// Encryption service +/// Encryption service. /// public interface IEncryptionService { /// - /// Create salt key + /// Create salt key. /// - /// Key size - /// Salt key + /// Key size. + /// Salt key. string CreateSaltKey(int size); /// - /// Create a password hash + /// Create a password hash. /// - /// Password - /// Salk key - /// Password format (hash algorithm) - /// Password hash - string CreatePasswordHash(string password, string saltkey, string passwordFormat); + /// Password. + /// Salt key. + /// Password format (hash algorithm). + /// Password hash. + string CreatePasswordHash(string password, string saltKey, string passwordFormat); /// - /// Create a data hash + /// Create a data hash. /// - /// The data for calculating the hash - /// Hash algorithm - /// Data hash + /// The data for calculating the hash. + /// Hash algorithm. + /// Data hash. string CreateHash(byte[] data, string hashAlgorithm); /// - /// Encrypt text + /// Encrypt text. /// - /// Text to encrypt - /// Encryption private key - /// Encrypted text + /// Text to encrypt. + /// Encryption private key. + /// Encrypted text. string EncryptText(string plainText, string encryptionPrivateKey = ""); /// - /// Decrypt text + /// Decrypt text. /// - /// Text to decrypt - /// Encryption private key - /// Decrypted text + /// Text to decrypt. + /// Encryption private key. + /// Decrypted text. string DecryptText(string cipherText, string encryptionPrivateKey = ""); } \ No newline at end of file diff --git a/BlogWebApp/Services/Blog.Services/Security/PermissionService.cs b/BlogWebApp/Services/Blog.Services/Security/PermissionService.cs index 337fd4d6..6ffc20f3 100644 --- a/BlogWebApp/Services/Blog.Services/Security/PermissionService.cs +++ b/BlogWebApp/Services/Blog.Services/Security/PermissionService.cs @@ -52,16 +52,15 @@ public bool Authorize() return this.Authorize(this.workContext.CurrentUser); } + /// + /// The authorization. + /// private bool Authorize(ApplicationUser user) - { - if (this.CheckIsUserAdmin(user)) - { - return true; - } - - return true; - } + => this.CheckIsUserAdmin(user) || true; + /// + /// The check if user is admin. + /// private bool CheckIsUserAdmin(ApplicationUser user) { var systemAdminKey = string.Format("Admin", user.Id); diff --git a/BlogWebApp/TestResults/2715d5b6-d117-4900-b1f8-ae27b053d7fb/user_USER_2023-12-08.23_04_51.coverage b/BlogWebApp/TestResults/2715d5b6-d117-4900-b1f8-ae27b053d7fb/user_USER_2023-12-08.23_04_51.coverage new file mode 100644 index 00000000..b207bffa Binary files /dev/null and b/BlogWebApp/TestResults/2715d5b6-d117-4900-b1f8-ae27b053d7fb/user_USER_2023-12-08.23_04_51.coverage differ diff --git a/BlogWebApp/TestResults/c10d3eb3-22ff-4902-9617-2d2c6c43059c/user_USER_2025-03-07.10_09_36.coverage b/BlogWebApp/TestResults/c10d3eb3-22ff-4902-9617-2d2c6c43059c/user_USER_2025-03-07.10_09_36.coverage new file mode 100644 index 00000000..58e786f5 Binary files /dev/null and b/BlogWebApp/TestResults/c10d3eb3-22ff-4902-9617-2d2c6c43059c/user_USER_2025-03-07.10_09_36.coverage differ diff --git a/BlogWebApp/TestResults/f8a3d9fb-e298-40fd-8dd7-d2e3b9010615/user_USER_2023-09-22.11_56_30.coverage b/BlogWebApp/TestResults/f8a3d9fb-e298-40fd-8dd7-d2e3b9010615/user_USER_2023-09-22.11_56_30.coverage new file mode 100644 index 00000000..005697ff Binary files /dev/null and b/BlogWebApp/TestResults/f8a3d9fb-e298-40fd-8dd7-d2e3b9010615/user_USER_2023-09-22.11_56_30.coverage differ diff --git a/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/CommentsServiceTests.cs b/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/CommentsServiceTests.cs index 7dec1841..9689e487 100644 --- a/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/CommentsServiceTests.cs +++ b/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/CommentsServiceTests.cs @@ -152,7 +152,7 @@ public void GetAll_WhenCommentsExists_ShouldReturnComments(int notEqualCount) /// /// Get all comments. - /// Should return nothing when comments does not exists. + /// Should return nothing when comments does not exist. /// [Fact] public void GetAll_WhenCommentsDoesNotExists_ShouldReturnNothing() @@ -238,7 +238,7 @@ public async Task GetAllAsync_WhenCommentsExists_ShouldReturnComments(int notEqu /// /// Get all async comments. - /// Should return nothing when comments does not exists. + /// Should return nothing when comments does not exist. /// [Fact] public async Task GetAllAsync_WhenCommentsDoesNotExists_ShouldReturnNothing() @@ -359,7 +359,7 @@ public void GetAll_WithEqualsSpecification_WhenCommentsExists_ShouldReturnCommen /// /// Get all comments with specification. - /// Should return nothing with when comments does not exists. + /// Should return nothing with when comments does not exist. /// /// The equal count. /// The CommentBody search. @@ -389,7 +389,7 @@ public void GetAll_WithEqualSpecification_WhenCommentsExists_ShouldReturnNothing /// /// Get all comments. - /// Should return nothing with when comments does not exists. + /// Should return nothing with when comments does not exist. /// /// The CommentBody search. [Theory] @@ -451,12 +451,11 @@ public void GetAll_WithContainsSpecification_WhenSpecificationIsNull_ShouldRetur .With(x => x.CommentBody, commentBodySearch) .CreateMany(random.Next(100)); - CommentSpecification specification = null; _commentsRepositoryMock.Setup(x => x.GetAll(It.IsAny())) .Returns(() => commentsList.Where(x => x.CommentBody.Contains(commentBodySearch)).AsQueryable()); //Act - var comments = _commentsService.GetAll(specification); + var comments = _commentsService.GetAll(null); //Assert Assert.NotNull(comments); @@ -572,7 +571,7 @@ public async Task GetAllAsync_WithEqualsSpecification_WhenCommentsExists_ShouldR /// /// Get all async comments with specification. - /// Should return nothing with when comments does not exists. + /// Should return nothing with when comments does not exist. /// /// The equal count. /// The CommentBody search. @@ -602,7 +601,7 @@ public async Task GetAllAsync_WithEqualSpecification_WhenCommentsExists_ShouldRe /// /// Get all async comments. - /// Should return nothing with when comments does not exists. + /// Should return nothing with when comments does not exist. /// /// The CommentBody search. [Theory] @@ -666,12 +665,11 @@ public async Task GetAllAsync_WithContainsSpecification_WhenSpecificationIsNull_ .With(x => x.CommentBody, commentBodySearch) .CreateMany(random.Next(100)); - CommentSpecification specification = null; _commentsRepositoryMock.Setup(x => x.GetAllAsync(It.IsAny())) .ReturnsAsync(() => commentsList.Where(x => x.CommentBody.Contains(commentBodySearch)).ToList()); //Act - var comments = await _commentsService.GetAllAsync(specification); + var comments = await _commentsService.GetAllAsync(null); //Assert Assert.NotNull(comments); @@ -744,7 +742,7 @@ public void Find_WhenCommentExists_ShouldReturnComment() /// /// Find comment. - /// Should return nothing when comment does not exists. + /// Should return nothing when comment does not exist. /// [Fact] public void Find_WhenCommentDoesNotExists_ShouldReturnNothing() @@ -824,7 +822,7 @@ public async Task FindAsync_WhenCommentExists_ShouldReturnComment() /// /// Async find comment. - /// Should return nothing when comment does not exists. + /// Should return nothing when comment does not exist. /// /// Task. [Fact] @@ -978,7 +976,7 @@ public void InsertEnumerable_WhenCommentsExists_ShouldReturnComments() { //Arrange var random = new Random(); - var commentId = _fixture.Create(); ; + var commentId = _fixture.Create(); var itemsCount = random.Next(10); var newComments = SetupCommentFixture() @@ -1583,7 +1581,7 @@ public async Task UpdateAsyncEnumerable_WhenRepositoryThrowsException_ShouldThro #region Delete By Id function /// - /// Verify that function Delete By Id has been called. + /// Verify that function Delete By ID has been called. /// [Fact] public void Verify_FunctionDeleteById_HasBeenCalled() @@ -1596,7 +1594,7 @@ public void Verify_FunctionDeleteById_HasBeenCalled() //Act _commentsService.Insert(newComment); - var comment = _commentsService.Find(commentId); + _commentsService.Find(commentId); _commentsService.Delete(commentId); _commentsRepositoryMock.Setup(x => x.GetById(commentId)) .Returns(() => null); @@ -1607,7 +1605,7 @@ public void Verify_FunctionDeleteById_HasBeenCalled() } /// - /// Delete By Id comment. + /// Delete By ID comment. /// Should return nothing when comment is deleted. /// [Fact] @@ -1627,7 +1625,7 @@ public void DeleteById_WhenCommentIsDeleted_ShouldReturnNothing() //Act _commentsService.Insert(newComment); - var comment = _commentsService.Find(commentId); + _commentsService.Find(commentId); _commentsService.Delete(commentId); _commentsRepositoryMock.Setup(x => x.GetById(commentId)) .Returns(() => null); @@ -1637,6 +1635,24 @@ public void DeleteById_WhenCommentIsDeleted_ShouldReturnNothing() Assert.Null(deletedComment); } + /// + /// Delete By ID comment. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteById_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var comment = SetupCommentFixture().Create(); + _commentsRepositoryMock.Setup(x => x.GetById(It.IsAny())) + .Returns(comment); + _commentsRepositoryMock.Setup(x => x.Delete(It.IsAny())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _commentsService.Delete(comment.Id)); + } + #endregion #region Delete By Object function @@ -1697,6 +1713,22 @@ public void DeleteByObject_WhenCommentIsDeleted_ShouldReturnNothing() Assert.Null(deletedComment); } + /// + /// Delete By Object comment. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteByObject_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var comment = SetupCommentFixture().Create(); + _commentsRepositoryMock.Setup(x => x.Delete(It.IsAny())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _commentsService.Delete(comment)); + } + #endregion #region Delete By Enumerable function @@ -1769,12 +1801,32 @@ public void DeleteByEnumerable_WhenCommentIsDeleted_ShouldReturnNothing() Assert.Null(newComments); } + /// + /// Delete By Enumerable comment. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteByEnumerable_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var random = new Random(); + var itemsCount = random.Next(10); + var comments = SetupCommentFixture() + .CreateMany(itemsCount) + .ToList(); + _commentsRepositoryMock.Setup(x => x.Delete(It.IsAny>())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _commentsService.Delete(comments)); + } + #endregion #region Delete Async By Id function /// - /// Verify that function Delete Async By Id has been called. + /// Verify that function Delete Async By ID has been called. /// /// Task. [Fact] @@ -1827,6 +1879,24 @@ public async Task DeleteAsyncById_WhenCommentIsDeleted_ShouldReturnNothing() Assert.Null(deletedComment); } + /// + /// Async delete By ID comment. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncById_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var comment = SetupCommentFixture().Create(); + _commentsRepositoryMock.Setup(x => x.GetByIdAsync(It.IsAny())) + .ReturnsAsync(comment); + _commentsRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _commentsService.DeleteAsync(comment.Id)); + } + #endregion #region Delete Async By Object function @@ -1885,6 +1955,22 @@ public async Task DeleteAsyncByObject_WhenCommentIsDeleted_ShouldReturnNothing() Assert.Null(deletedComment); } + /// + /// Async delete By Object comment. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncByObject_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var comment = SetupCommentFixture().Create(); + _commentsRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _commentsService.DeleteAsync(comment)); + } + #endregion #region Delete Async By Enumerable function @@ -1959,6 +2045,26 @@ public async Task DeleteAsyncByEnumerable_WhenCommentIsDeleted_ShouldReturnNothi Assert.Null(newComments); } + /// + /// Async delete By Enumerable comment. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncByEnumerable_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var random = new Random(); + var itemsCount = random.Next(10); + var comments = SetupCommentFixture() + .CreateMany(itemsCount) + .ToList(); + _commentsRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny>())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _commentsService.DeleteAsync(comments)); + } + #endregion #endregion @@ -2049,7 +2155,7 @@ public void Any_WithEqualsSpecification_WhenCommentsExists_ShouldReturnTrue(stri /// /// Check if there are any comments with specification. - /// Should return false with when comments does not exists. + /// Should return false with when comments does not exist. /// /// The CommentBody search. [Theory] @@ -2075,7 +2181,7 @@ public void Any_WithEqualSpecification_WhenCommentsExists_ShouldReturnFalse(stri /// /// Check if there are any comments with specification. - /// Should return false with when comments does not exists. + /// Should return false with when comments does not exist. /// /// The CommentBody search. [Theory] @@ -2184,7 +2290,7 @@ public async Task AnyAsync_WithEqualsSpecification_WhenCommentsExists_ShouldRetu /// /// Async check if there are any comments with specification. - /// Should return false with when comments does not exists. + /// Should return false with when comments does not exist. /// /// The CommentBody search. /// Task. @@ -2211,7 +2317,7 @@ public async Task AnyAsync_WithEqualSpecification_WhenCommentsExists_ShouldRetur /// /// Async check if there are any comments with specification. - /// Should return false with when comments does not exists. + /// Should return false with when comments does not exist. /// /// The CommentBody search. /// Task. @@ -2322,7 +2428,7 @@ public void FirstOrDefault_WithEqualsSpecification_WhenCommentsExists_ShouldRetu /// /// Get first or default comment with specification. - /// Should return nothing with when comment does not exists. + /// Should return nothing with when comment does not exist. /// /// The CommentBody search. [Theory] @@ -2348,7 +2454,7 @@ public void FirstOrDefault_WithEqualSpecification_WhenCommentsExists_ShouldRetur /// /// Get first or default comment with specification. - /// Should return nothing with when comments does not exists. + /// Should return nothing with when comments does not exist. /// /// The CommentBody search. [Theory] @@ -2456,7 +2562,7 @@ public void LastOrDefault_WithEqualsSpecification_WhenCommentsExists_ShouldRetur /// /// Get last or default comment with specification. - /// Should return nothing with when comment does not exists. + /// Should return nothing with when comment does not exist. /// /// The CommentBody search. [Theory] @@ -2482,7 +2588,7 @@ public void LastOrDefault_WithEqualSpecification_WhenCommentsExists_ShouldReturn /// /// Get last or default comment with specification. - /// Should return nothing with when comments does not exists. + /// Should return nothing with when comments does not exist. /// /// The CommentBody search. [Theory] @@ -2531,7 +2637,7 @@ protected static PagedListResult Search(SearchQuery query, Lis } // Resolving Sort Criteria - // This code applies the sorting criterias sent as the parameter + // This code applies the sorting criteria sent as the parameter if (query.SortCriterias is { Count: > 0 }) { var sortCriteria = query.SortCriterias[0]; @@ -2707,7 +2813,7 @@ public async Task SearchAsync_WithEqualsSpecification_WhenCommentsExists_ShouldR /// /// Search async comments with specification. - /// Should return nothing with when comments does not exists. + /// Should return nothing with when comments does not exist. /// /// The search. /// The start. @@ -2750,7 +2856,7 @@ public async Task SearchAsync_WithEqualSpecification_WhenCommentsExists_ShouldRe /// /// Search async comments. - /// Should return nothing when comments does not exists. + /// Should return nothing when comments does not exist. /// /// The search. /// The start. @@ -2800,7 +2906,7 @@ public async Task SearchBySequenceAsync_WhenNoEntitiesExist_ShouldReturnEmpty() var query = new SearchQuery { Skip = 0, Take = 5 }; var expected = new PagedListResult { Entities = new List(), Count = 0 }; - _commentsRepositoryMock.Setup(r => r.SearchBySquenceAsync(query, data)).ReturnsAsync(expected); + _commentsRepositoryMock.Setup(r => r.SearchBySequenceAsync(query, data)).ReturnsAsync(expected); var result = await _commentsService.SearchBySequenceAsync(query, data); @@ -2818,7 +2924,7 @@ public async Task SearchBySequenceAsync_WhenEntitiesExistAndQueryIsNull_ShouldRe var data = SetupCommentFixture().CreateMany(5).AsQueryable(); var expected = new PagedListResult { Entities = data.ToList(), Count = 5 }; - _commentsRepositoryMock.Setup(r => r.SearchBySquenceAsync(null, data)).ReturnsAsync(expected); + _commentsRepositoryMock.Setup(r => r.SearchBySequenceAsync(null, data)).ReturnsAsync(expected); var result = await _commentsService.SearchBySequenceAsync(null, data); @@ -2836,7 +2942,7 @@ public async Task SearchBySequenceAsync_WhenEntitiesExistAndSequenceIsNullIsNull var query = new SearchQuery { Skip = 0, Take = 5 }; var expected = new PagedListResult { Entities = null, Count = 5 }; - _commentsRepositoryMock.Setup(r => r.SearchBySquenceAsync(query, null)).ReturnsAsync(expected); + _commentsRepositoryMock.Setup(r => r.SearchBySequenceAsync(query, null)).ReturnsAsync(expected); var result = await _commentsService.SearchBySequenceAsync(query, null); diff --git a/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/MessagesServiceTests.cs b/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/MessagesServiceTests.cs index a52c5371..ebf06a72 100644 --- a/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/MessagesServiceTests.cs +++ b/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/MessagesServiceTests.cs @@ -158,7 +158,7 @@ public void GetAll_WhenMessagesExists_ShouldReturnMessages(int notEqualCount) /// /// Get all messages. - /// Should return nothing when messages does not exists. + /// Should return nothing when messages does not exist. /// [Fact] public void GetAll_WhenMessagesDoesNotExists_ShouldReturnNothing() @@ -246,7 +246,7 @@ public async Task GetAllAsync_WhenMessagesExists_ShouldReturnMessages(int notEqu /// /// Get all async messages. - /// Should return nothing when messages does not exists. + /// Should return nothing when messages does not exist. /// [Fact] public void GetAllAsync_WhenMessagesDoesNotExists_ShouldReturnNothing() @@ -369,7 +369,7 @@ public void GetAll_WithEqualsSpecification_WhenMessagesExists_ShouldReturnMessag /// /// Get all messages with specification. - /// Should return nothing with when messages does not exists. + /// Should return nothing with when messages does not exist. /// /// The equal count. /// The body search. @@ -398,7 +398,7 @@ public void GetAll_WithEqualSpecification_WhenMessagesExists_ShouldReturnNothing /// /// Get all messages. - /// Should return nothing with when messages does not exists. + /// Should return nothing with when messages does not exist. /// /// The message search. [Theory] @@ -432,7 +432,7 @@ public void GetAll_WithContainsSpecification_WhenSpecificationIsEmpty_ShouldRetu .With(x => x.Body, messageBodySearch) .CreateMany(random.Next(100)); - var specification = new MessageSpecification(); + var specification = new MessageSpecification(null); _messagesRepositoryMock.Setup(x => x.GetAll(It.IsAny())) .Returns(() => messagesList.Where(x => x.Body.Contains(messageBodySearch)).AsQueryable()); @@ -460,12 +460,11 @@ public void GetAll_WithContainsSpecification_WhenSpecificationIsNull_ShouldRetur .With(x => x.Body, messageBodySearch) .CreateMany(random.Next(100)); - MessageSpecification specification = null; _messagesRepositoryMock.Setup(x => x.GetAll(It.IsAny())) .Returns(() => messagesList.Where(x => x.Body.Contains(messageBodySearch)).AsQueryable()); //Act - var messages = _messagesService.GetAll(specification); + var messages = _messagesService.GetAll(null); //Assert Assert.NotNull(messages); @@ -582,7 +581,7 @@ public async Task GetAllAsync_WithEqualsSpecification_WhenMessagesExists_ShouldR /// /// Get all async messages with specification. - /// Should return nothing with when messages does not exists. + /// Should return nothing with when messages does not exist. /// /// The equal count. /// The body search. @@ -611,7 +610,7 @@ public async Task GetAllAsync_WithEqualSpecification_WhenMessagesExists_ShouldRe /// /// Get all async messages. - /// Should return nothing with when messages does not exists. + /// Should return nothing with when messages does not exist. /// /// The message search. [Theory] @@ -645,7 +644,7 @@ public async Task GetAllAsync_WithContainsSpecification_WhenSpecificationIsEmpty .With(x => x.Body, messageBodySearch) .CreateMany(random.Next(100)); - var specification = new MessageSpecification(); + var specification = new MessageSpecification(null); _messagesRepositoryMock.Setup(x => x.GetAllAsync(It.IsAny())) .ReturnsAsync(() => messagesList.Where(x => x.Body.Contains(messageBodySearch)).ToList()); @@ -673,12 +672,11 @@ public async Task GetAllAsync_WithContainsSpecification_WhenSpecificationIsNull_ .With(x => x.Body, messageBodySearch) .CreateMany(random.Next(100)); - MessageSpecification specification = null; _messagesRepositoryMock.Setup(x => x.GetAllAsync(It.IsAny())) .ReturnsAsync(() => messagesList.Where(x => x.Body.Contains(messageBodySearch)).ToList()); //Act - var messages = await _messagesService.GetAllAsync(specification); + var messages = await _messagesService.GetAllAsync(null); //Assert Assert.NotNull(messages); @@ -754,7 +752,7 @@ public void Find_WhenMessageExists_ShouldReturnMessage() /// /// Find message. - /// Should return nothing when message does not exists. + /// Should return nothing when message does not exist. /// [Fact] public void Find_WhenMessageDoesNotExists_ShouldReturnNothing() @@ -838,7 +836,7 @@ public async Task FindAsync_WhenMessageExists_ShouldReturnMessage() /// /// Async find message. - /// Should return nothing when message does not exists. + /// Should return nothing when message does not exist. /// /// Task. [Fact] @@ -1611,7 +1609,7 @@ public async Task UpdateAsyncEnumerable_WhenRepositoryThrowsException_ShouldThro #region Delete By Id function /// - /// Verify that function Delete By Id has been called. + /// Verify that function Delete By ID has been called. /// [Fact] public void Verify_FunctionDeleteById_HasBeenCalled() @@ -1632,7 +1630,7 @@ public void Verify_FunctionDeleteById_HasBeenCalled() //Act _messagesService.Insert(newMessage); - var message = _messagesService.Find(messageId); + _messagesService.Find(messageId); _messagesService.Delete(messageId); _messagesRepositoryMock.Setup(x => x.GetById(messageId)) .Returns(() => null); @@ -1643,7 +1641,7 @@ public void Verify_FunctionDeleteById_HasBeenCalled() } /// - /// Delete By Id message. + /// Delete By ID message. /// Should return nothing when message is deleted. /// [Fact] @@ -1665,7 +1663,7 @@ public void DeleteById_WhenMessageDeleted_ShouldReturnNothing() //Act _messagesService.Insert(newMessage); - var message = _messagesService.Find(messageId); + _messagesService.Find(messageId); _messagesService.Delete(messageId); _messagesRepositoryMock.Setup(x => x.GetById(messageId)) .Returns(() => null); @@ -1675,6 +1673,24 @@ public void DeleteById_WhenMessageDeleted_ShouldReturnNothing() Assert.Null(deletedMessage); } + /// + /// Delete By ID message. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteById_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var message = SetupMessageFixture().Create(); + _messagesRepositoryMock.Setup(x => x.GetById(It.IsAny())) + .Returns(message); + _messagesRepositoryMock.Setup(x => x.Delete(It.IsAny())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _messagesService.Delete(message.Id)); + } + #endregion #region Delete By Object function @@ -1744,6 +1760,22 @@ public void DeleteByObject_WhenMessageDeleted_ShouldReturnNothing() Assert.Null(deletedMessage); } + /// + /// Delete By Object message. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteByObject_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var message = SetupMessageFixture().Create(); + _messagesRepositoryMock.Setup(x => x.Delete(It.IsAny())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _messagesService.Delete(message)); + } + #endregion #region Delete By Enumerable function @@ -1818,12 +1850,32 @@ public void DeleteByEnumerable_WhenMessageDeleted_ShouldReturnNothing() Assert.Null(newMessages); } + /// + /// Delete By Enumerable messages. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteByEnumerable_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var random = new Random(); + var itemsCount = random.Next(10); + var messages = SetupMessageFixture() + .CreateMany(itemsCount) + .ToList(); + _messagesRepositoryMock.Setup(x => x.Delete(It.IsAny>())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _messagesService.Delete(messages)); + } + #endregion #region Delete Async By Id function /// - /// Verify that function Delete Async By Id has been called. + /// Verify that function Delete Async By ID has been called. /// /// Task. [Fact] @@ -1884,6 +1936,24 @@ public async Task DeleteAsyncById_WhenMessageIsDeleted_ShouldReturnNothing() Assert.Null(deletedMessage); } + /// + /// Async delete By ID message. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncById_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var message = SetupMessageFixture().Create(); + _messagesRepositoryMock.Setup(x => x.GetByIdAsync(It.IsAny())) + .ReturnsAsync(message); + _messagesRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _messagesService.DeleteAsync(message.Id)); + } + #endregion #region Delete Async By Object function @@ -1952,6 +2022,22 @@ public async Task DeleteAsyncByObject_WhenMessageIsDeleted_ShouldReturnNothing() Assert.Null(deletedMessage); } + /// + /// Async delete By Object message. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncByObject_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var message = SetupMessageFixture().Create(); + _messagesRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _messagesService.DeleteAsync(message)); + } + #endregion #region Delete Async By Enumerable function @@ -2028,6 +2114,26 @@ public async Task DeleteAsyncByEnumerable_WhenMessageDeleted_ShouldReturnNothing Assert.Null(newMessages); } + /// + /// Async delete By Enumerable messages. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncByEnumerable_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var random = new Random(); + var itemsCount = random.Next(10); + var messages = SetupMessageFixture() + .CreateMany(itemsCount) + .ToList(); + _messagesRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny>())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _messagesService.DeleteAsync(messages)); + } + #endregion #endregion @@ -2119,7 +2225,7 @@ public void Any_WithEqualsSpecification_WhenMessagesExists_ShouldReturnTrue(stri /// /// Check if there are any messages with specification. - /// Should return false with when messages does not exists. + /// Should return false with when messages does not exist. /// /// The subject search. [Theory] @@ -2145,7 +2251,7 @@ public void Any_WithEqualSpecification_WhenMessagesExists_ShouldReturnFalse(stri /// /// Check if there are any messages with specification. - /// Should return false with when messages does not exists. + /// Should return false with when messages does not exist. /// /// The subject search. [Theory] @@ -2254,7 +2360,7 @@ public async Task AnyAsync_WithEqualsSpecification_WhenMessagesExists_ShouldRetu /// /// Async check if there are any messages with specification. - /// Should return false with when messages does not exists. + /// Should return false with when messages does not exist. /// /// The subject search. /// Task. @@ -2281,7 +2387,7 @@ public async Task AnyAsync_WithEqualSpecification_WhenMessagesExists_ShouldRetur /// /// Async check if there are any messages with specification. - /// Should return false with when messages does not exists. + /// Should return false with when messages does not exist. /// /// The subject search. /// Task. @@ -2392,7 +2498,7 @@ public void FirstOrDefault_WithEqualsSpecification_WhenMessagesExists_ShouldRetu /// /// Get first or default message with specification. - /// Should return nothing with when messages does not exists. + /// Should return nothing with when messages does not exist. /// /// The subject search. [Theory] @@ -2418,7 +2524,7 @@ public void FirstOrDefault_WithEqualSpecification_WhenMessagesExists_ShouldRetur /// /// Get first or default message with specification. - /// Should return nothing with when messages does not exists. + /// Should return nothing with when messages does not exist. /// /// The subject search. [Theory] @@ -2526,7 +2632,7 @@ public void LastOrDefault_WithEqualsSpecification_WhenMessagesExists_ShouldRetur /// /// Get last or default message with specification. - /// Should return nothing with when messages does not exists. + /// Should return nothing with when messages does not exist. /// /// The subject search. [Theory] @@ -2552,7 +2658,7 @@ public void LastOrDefault_WithEqualSpecification_WhenMessagesExists_ShouldReturn /// /// Get last or default message with specification. - /// Should return nothing with when messages does not exists. + /// Should return nothing with when messages does not exist. /// /// The subject search. [Theory] @@ -2591,7 +2697,6 @@ protected static PagedListResult Search(SearchQuery query, Lis foreach (var filterClause in query.Filters) { sequence = sequence.Where(filterClause); - var a = sequence.Select(x => x).ToList(); } } @@ -2604,7 +2709,7 @@ protected static PagedListResult Search(SearchQuery query, Lis } // Resolving Sort Criteria - // This code applies the sorting criterias sent as the parameter + // This code applies the sorting criteria sent as the parameter if (query.SortCriterias is { Count: > 0 }) { var sortCriteria = query.SortCriterias[0]; @@ -2789,7 +2894,7 @@ public async Task SearchAsync_WithEqualsSpecification_WhenCMessagesExists_Should /// /// Search async messages with specification. - /// Should return nothing with when messages does not exists. + /// Should return nothing with when messages does not exist. /// /// The search. /// The start. @@ -2836,7 +2941,7 @@ public async Task SearchAsync_WithEqualSpecification_WhenMessagesExists_ShouldRe /// /// Search async messages. - /// Should return nothing when messages does not exists. + /// Should return nothing when messages does not exist. /// /// The search. /// The start. @@ -2886,7 +2991,7 @@ public async Task SearchBySequenceAsync_WhenNoEntitiesExist_ShouldReturnEmpty() var query = new SearchQuery { Skip = 0, Take = 5 }; var expected = new PagedListResult { Entities = new List(), Count = 0 }; - _messagesRepositoryMock.Setup(r => r.SearchBySquenceAsync(query, data)).ReturnsAsync(expected); + _messagesRepositoryMock.Setup(r => r.SearchBySequenceAsync(query, data)).ReturnsAsync(expected); var result = await _messagesService.SearchBySequenceAsync(query, data); @@ -2904,7 +3009,7 @@ public async Task SearchBySequenceAsync_WhenEntitiesExistAndQueryIsNull_ShouldRe var data = SetupMessageFixture().CreateMany(5).AsQueryable(); var expected = new PagedListResult { Entities = data.ToList(), Count = 5 }; - _messagesRepositoryMock.Setup(r => r.SearchBySquenceAsync(null, data)).ReturnsAsync(expected); + _messagesRepositoryMock.Setup(r => r.SearchBySequenceAsync(null, data)).ReturnsAsync(expected); var result = await _messagesService.SearchBySequenceAsync(null, data); @@ -2922,7 +3027,7 @@ public async Task SearchBySequenceAsync_WhenEntitiesExistAndSequenceIsNullIsNull var query = new SearchQuery { Skip = 0, Take = 5 }; var expected = new PagedListResult { Entities = null, Count = 5 }; - _messagesRepositoryMock.Setup(r => r.SearchBySquenceAsync(query, null)).ReturnsAsync(expected); + _messagesRepositoryMock.Setup(r => r.SearchBySequenceAsync(query, null)).ReturnsAsync(expected); var result = await _messagesService.SearchBySequenceAsync(query, null); diff --git a/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/PostTagRelationsServiceTests.cs b/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/PostTagRelationsServiceTests.cs index 7e265c89..c0ce90a1 100644 --- a/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/PostTagRelationsServiceTests.cs +++ b/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/PostTagRelationsServiceTests.cs @@ -254,7 +254,7 @@ public void GetAll_WhenPostTagRelationExists_ShouldReturnPostTagRelationsWithExi /// /// Get all post tag relations. - /// Should return nothing when post tag relations does not exists. + /// Should return nothing when post tag relations does not exist. /// [Fact] public void GetAll_WhenPostTagRelationsDoesNotExists_ShouldReturnNothing() @@ -414,7 +414,7 @@ public async Task GetAllAsync_WhenPostTagRelationExists_ShouldReturnPostTagRelat /// /// Get all post tag relations. - /// Should return nothing when post tag relations does not exists. + /// Should return nothing when post tag relations does not exist. /// [Fact] public async Task GetAllAsync_WhenPostTagRelationsDoesNotExists_ShouldReturnNothing() @@ -517,7 +517,6 @@ public void GetAll_WithContainsSpecification_WhenPostTagRelationsExists_ShouldRe public void GetAll_WithEqualsSpecification_WhenPostsExists_ShouldReturnPost(int equalCount, string titleSearch) { //Arrange - var random = new Random(); var postsTagsRelationsList = SetupPostsTagsRelationsFixture(_fixture.Create(), titleSearch) .CreateMany(1) @@ -612,7 +611,7 @@ public void GetAll_WithContainsSpecification_WhenPostTagRelationsExists_ShouldRe /// /// Get all post tag relations. - /// Should return nothing with when post tag relations does not exists. + /// Should return nothing with when post tag relations does not exist. /// /// The equal count. /// The title search. @@ -642,7 +641,7 @@ public void GetAll_WithEqualSpecification_WhenPostTagRelationsExists_ShouldRetur /// /// Get all post tag relations. - /// Should return nothing with when post tag relations does not exists. + /// Should return nothing with when post tag relations does not exist. /// /// The title search. [Theory] @@ -704,12 +703,11 @@ public void GetAll_WithContainsSpecification_WhenSpecificationIsNull_ShouldRetur .With(x => x.PostId, postIdSearch) .CreateMany(random.Next(100)); - BaseSpecification specification = null; _postsTagsRelationsRepositoryMock.Setup(x => x.GetAll(It.IsAny>())) .Returns(() => postTagRelationsList.Where(x => x.PostId == postIdSearch).AsQueryable()); //Act - var postTagRelations = _postsTagsRelationsService.GetAll(specification); + var postTagRelations = _postsTagsRelationsService.GetAll(null); //Assert Assert.NotNull(postTagRelations); @@ -806,7 +804,6 @@ public async Task GetAllAsync_WithContainsSpecification_WhenPostTagRelationsExis public async Task GetAllAsync_WithEqualsSpecification_WhenPostsExists_ShouldReturnPost(int equalCount, string titleSearch) { //Arrange - var random = new Random(); var postsTagsRelationsList = SetupPostsTagsRelationsFixture(_fixture.Create(), titleSearch) .CreateMany(1) @@ -879,7 +876,6 @@ void Action(PostsTagsRelations postsTagsRelation) public async Task GetAllAsync_WithContainsSpecification_WhenPostTagRelationsExists_ShouldReturnPostTagRelationsWithExistingPostAndTagsAndShouldContainsTheSameTagsCount(int notEqualCount, string postTitle, string tagTitle) { //Arrange - var random = new Random(); var postsTagsRelationsList = SetupPostsTagsRelationsFixture(postTitle, tagTitle) .CreateMany(1) @@ -901,7 +897,7 @@ public async Task GetAllAsync_WithContainsSpecification_WhenPostTagRelationsExis /// /// Get all async post tag relations. - /// Should return nothing with when post tag relations does not exists. + /// Should return nothing with when post tag relations does not exist. /// /// The equal count. /// The title search. @@ -931,7 +927,7 @@ public async Task GetAllAsync_WithEqualSpecification_WhenPostTagRelationsExists_ /// /// Get all async post tag relations. - /// Should return nothing with when post tag relations does not exists. + /// Should return nothing with when post tag relations does not exist. /// /// The title search. [Theory] @@ -993,12 +989,11 @@ public async Task GetAllAsync_WithContainsSpecification_WhenSpecificationIsNull_ .With(x => x.PostId, postIdSearch) .CreateMany(random.Next(100)); - BaseSpecification specification = null; _postsTagsRelationsRepositoryMock.Setup(x => x.GetAllAsync(It.IsAny>())) .ReturnsAsync(() => messagesList.Where(x => x.PostId == postIdSearch).ToList()); //Act - var messages = await _postsTagsRelationsService.GetAllAsync(specification); + var messages = await _postsTagsRelationsService.GetAllAsync(null); //Assert Assert.NotNull(messages); @@ -1080,7 +1075,7 @@ public void Find_WhenPostTagRelationExists_ShouldReturnPostTagRelation() /// /// Find post tag relation. - /// Should return nothing when post does not exists. + /// Should return nothing when post does not exist. /// [Fact] public void Find_WhenPostTagRelationDoesNotExists_ShouldReturnNothing() @@ -1168,7 +1163,7 @@ public async Task FindAsync_WhenPostTagRelationExists_ShouldReturnPostTagRelatio /// /// Async find post tag relation. - /// Should return nothing when post does not exists. + /// Should return nothing when post does not exist. /// /// Task. [Fact] @@ -2131,6 +2126,24 @@ public void DeleteById_WhenPostTagRelationIsDeleted_ShouldReturnNothing() Assert.Null(postsTagsRelation); } + /// + /// Delete By Id post tag relation. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteById_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var postTagRelation = SetupPostsTagsRelationsFixture().Create(); + _postsTagsRelationsRepositoryMock.Setup(x => x.GetById(It.IsAny())) + .Returns(postTagRelation); + _postsTagsRelationsRepositoryMock.Setup(x => x.Delete(It.IsAny())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _postsTagsRelationsService.Delete(postTagRelation.Id)); + } + #endregion #region Delete By Object function @@ -2202,6 +2215,22 @@ public void DeleteByObject_WhenPostTagRelationIsDeleted_ShouldReturnNothing() Assert.Null(postsTagsRelation); } + /// + /// Delete By Object post tag relation. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteByObject_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var postTagRelation = SetupPostsTagsRelationsFixture().Create(); + _postsTagsRelationsRepositoryMock.Setup(x => x.Delete(It.IsAny())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _postsTagsRelationsService.Delete(postTagRelation)); + } + #endregion #region Delete By Enumerable function @@ -2288,12 +2317,32 @@ public void DeleteByEnumerable_WhenPostTagRelationIsDeleted_ShouldReturnNothing( Assert.Null(newPostsTagsRelations); } + /// + /// Delete By Enumerable post tag relations. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteByEnumerable_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var random = new Random(); + var itemsCount = random.Next(10); + var postTagRelations = SetupPostsTagsRelationsFixture() + .CreateMany(itemsCount) + .ToList(); + _postsTagsRelationsRepositoryMock.Setup(x => x.Delete(It.IsAny>())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _postsTagsRelationsService.Delete(postTagRelations)); + } + #endregion #region Delete Async By Id function /// - /// Verify that function Delete Async By Id has been called. + /// Verify that function Delete Async By ID has been called. /// /// Task. [Fact] @@ -2316,7 +2365,7 @@ public async Task Verify_FunctionDeleteAsyncById_HasBeenCalled() //Act await _postsTagsRelationsService.InsertAsync(newPostsTagsRelation); - var postsTagsRelation = await _postsTagsRelationsService.FindAsync(id); + await _postsTagsRelationsService.FindAsync(id); await _postsTagsRelationsService.DeleteAsync(id); _postsTagsRelationsRepositoryMock.Setup(x => x.GetByIdAsync(id)) .ReturnsAsync(() => null); @@ -2351,7 +2400,7 @@ public async Task DeleteAsyncById_WhenPostTagRelationIsDeleted_ShouldReturnNothi //Act await _postsTagsRelationsService.InsertAsync(newPostsTagsRelation); - var postsTagsRelations = await _postsTagsRelationsService.FindAsync(id); + await _postsTagsRelationsService.FindAsync(id); await _postsTagsRelationsService.DeleteAsync(id); _postsTagsRelationsRepositoryMock.Setup(x => x.GetByIdAsync(id)) .ReturnsAsync(() => null); @@ -2361,6 +2410,24 @@ public async Task DeleteAsyncById_WhenPostTagRelationIsDeleted_ShouldReturnNothi Assert.Null(postsTagsRelation); } + /// + /// Async delete By ID post tag relation. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncById_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var postTagRelation = SetupPostsTagsRelationsFixture().Create(); + _postsTagsRelationsRepositoryMock.Setup(x => x.GetByIdAsync(It.IsAny())) + .ReturnsAsync(postTagRelation); + _postsTagsRelationsRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _postsTagsRelationsService.DeleteAsync(postTagRelation.Id)); + } + #endregion #region Delete Async By Object function @@ -2434,6 +2501,22 @@ public async Task DeleteAsyncByObject_WhenPostTagRelationIsDeleted_ShouldReturnN Assert.Null(postsTagsRelation); } + /// + /// Async delete By Object post tag relation. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncByObject_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var postTagRelation = SetupPostsTagsRelationsFixture().Create(); + _postsTagsRelationsRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _postsTagsRelationsService.DeleteAsync(postTagRelation)); + } + #endregion #region Delete Async By Enumerable function @@ -2508,6 +2591,26 @@ public async Task DeleteAsyncByEnumerable_WhenPostTagRelationIsDeleted_ShouldRet Assert.Null(newPostsTagsRelations); } + /// + /// Async delete By Enumerable post tag relations. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncByEnumerable_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var random = new Random(); + var itemsCount = random.Next(10); + var postTagRelations = SetupPostsTagsRelationsFixture() + .CreateMany(itemsCount) + .ToList(); + _postsTagsRelationsRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny>())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _postsTagsRelationsService.DeleteAsync(postTagRelations)); + } + #endregion #endregion @@ -2599,7 +2702,7 @@ public void Any_WithEqualsSpecification_WhenPostTagRelationsExists_ShouldReturnT /// /// Check if there are any post tag relations with specification. - /// Should return false with when post tag relations does not exists. + /// Should return false with when post tag relations does not exist. /// /// The title search. [Theory] @@ -2626,7 +2729,7 @@ public void Any_WithEqualSpecification_WhenPostTagRelationsExists_ShouldReturnFa /// /// Check if there are any post tag relations with specification. - /// Should return false with when post tag relations does not exists. + /// Should return false with when post tag relations does not exist. /// /// The title search. [Theory] @@ -2735,7 +2838,7 @@ public async Task AnyAsync_WithEqualsSpecification_WhenPostTagRelationsExists_Sh /// /// Async check if there are any post tag relations with specification. - /// Should return false with when post tag relations does not exists. + /// Should return false with when post tag relations does not exist. /// /// The title search. /// Task. @@ -2763,7 +2866,7 @@ public async Task AnyAsync_WithEqualSpecification_WhenPostTagRelationsExists_Sho /// /// Async check if there are any post tag relations with specification. - /// Should return false with when post tag relations does not exists. + /// Should return false with when post tag relations does not exist. /// /// The title search. /// Task. @@ -2874,7 +2977,7 @@ public void FirstOrDefault_WithEqualsSpecification_WhenPostTagRelationsExists_Sh /// /// Get first or default post with specification. - /// Should return nothing with when post does not exists. + /// Should return nothing with when post does not exist. /// /// The title search. [Theory] @@ -2901,7 +3004,7 @@ public void FirstOrDefault_WithEqualSpecification_WhenPostTagRelationsExists_Sho /// /// Get first or default post with specification. - /// Should return nothing with when post tag relations does not exists. + /// Should return nothing with when post tag relations does not exist. /// /// The title search. [Theory] @@ -3009,7 +3112,7 @@ public void LastOrDefault_WithEqualsSpecification_WhenPostTagRelationsExists_Sho /// /// Get last or default post with specification. - /// Should return nothing with when post does not exists. + /// Should return nothing with when post does not exist. /// /// The title search. [Theory] @@ -3036,7 +3139,7 @@ public void LastOrDefault_WithEqualSpecification_WhenPostTagRelationsExists_Shou /// /// Get last or default post with specification. - /// Should return nothing with when post tag relations does not exists. + /// Should return nothing with when post tag relations does not exist. /// /// The title search. [Theory] @@ -3087,7 +3190,7 @@ protected static PagedListResult Search(SearchQuery 0 }) { var sortCriteria = query.SortCriterias[0]; @@ -3190,7 +3293,6 @@ public async Task Verify_FunctionSearchAsync_HasBeenCalled(int search, int start public async Task SearchAsync_WhenPostsTagsRelationsExists_ShouldReturnPostsTagsRelations(int search, int start, int take, string fieldName, OrderType orderType) { //Arrange - var random = new Random(); var postsTagsRelationsList = SetupPostsTagsRelationsFixture() .With(x => x.TagId, search) @@ -3309,7 +3411,7 @@ public async Task SearchAsync_WithEqualSpecification_WhenPostsTagsRelationsExist /// /// Search async posts tags relations. - /// Should return nothing when posts tags relations does not exists. + /// Should return nothing when posts tags relations does not exist. /// /// The search. /// The start. @@ -3359,7 +3461,7 @@ public async Task SearchBySequenceAsync_WhenNoEntitiesExist_ShouldReturnEmpty() var query = new SearchQuery { Skip = 0, Take = 5 }; var expected = new PagedListResult { Entities = new List(), Count = 0 }; - _postsTagsRelationsRepositoryMock.Setup(r => r.SearchBySquenceAsync(query, data)).ReturnsAsync(expected); + _postsTagsRelationsRepositoryMock.Setup(r => r.SearchBySequenceAsync(query, data)).ReturnsAsync(expected); var result = await _postsTagsRelationsService.SearchBySequenceAsync(query, data); @@ -3377,7 +3479,7 @@ public async Task SearchBySequenceAsync_WhenEntitiesExistAndQueryIsNull_ShouldRe var data = SetupPostsTagsRelationsFixture().CreateMany(5).AsQueryable(); var expected = new PagedListResult { Entities = data.ToList(), Count = 5 }; - _postsTagsRelationsRepositoryMock.Setup(r => r.SearchBySquenceAsync(null, data)).ReturnsAsync(expected); + _postsTagsRelationsRepositoryMock.Setup(r => r.SearchBySequenceAsync(null, data)).ReturnsAsync(expected); var result = await _postsTagsRelationsService.SearchBySequenceAsync(null, data); @@ -3395,7 +3497,7 @@ public async Task SearchBySequenceAsync_WhenEntitiesExistAndSequenceIsNullIsNull var query = new SearchQuery { Skip = 0, Take = 5 }; var expected = new PagedListResult { Entities = null, Count = 5 }; - _postsTagsRelationsRepositoryMock.Setup(r => r.SearchBySquenceAsync(query, null)).ReturnsAsync(expected); + _postsTagsRelationsRepositoryMock.Setup(r => r.SearchBySequenceAsync(query, null)).ReturnsAsync(expected); var result = await _postsTagsRelationsService.SearchBySequenceAsync(query, null); diff --git a/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/PostsServiceTests.cs b/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/PostsServiceTests.cs index ddd35862..010a76a5 100644 --- a/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/PostsServiceTests.cs +++ b/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/PostsServiceTests.cs @@ -1,7 +1,6 @@ using AutoFixture; using AutoFixture.Dsl; using AutoMapper; -using Blog.CommonServices.Interfaces; using Blog.Core.Enums; using Blog.Core.Infrastructure; using Blog.Core.Infrastructure.Pagination; @@ -176,7 +175,7 @@ public void GetAll_WhenPostsExists_ShouldReturnPosts(int notEqualCount) /// /// Get all posts. - /// Should return nothing when posts does not exists. + /// Should return nothing when posts does not exist. /// [Fact] public void GetAll_WhenPostDoesNotExists_ShouldReturnNothing() @@ -264,7 +263,7 @@ public async Task GetAllAsync_WhenPostsExists_ShouldReturnPosts(int notEqualCoun /// /// Get all async posts. - /// Should return nothing when posts does not exists. + /// Should return nothing when posts does not exist. /// [Fact] public async Task GetAllAsync_WhenPostDoesNotExists_ShouldReturnNothing() @@ -367,7 +366,6 @@ public void GetAll_WithContainsSpecification_WhenPostsExists_ShouldReturnPosts(i public void GetAll_WithEqualsSpecification_WhenPostsExists_ShouldReturnPost(int equalCount, string titleSearch) { //Arrange - var random = new Random(); var postsList = SetupPostFixture() .With(x => x.Title, titleSearch) @@ -388,7 +386,7 @@ public void GetAll_WithEqualsSpecification_WhenPostsExists_ShouldReturnPost(int /// /// Get all posts. - /// Should return nothing with when posts does not exists. + /// Should return nothing with when posts does not exist. /// /// The equal count. /// The title search. @@ -417,7 +415,7 @@ public void GetAll_WithEqualSpecification_WhenPostsExists_ShouldReturnNothing(in /// /// Get all posts. - /// Should return nothing with when posts does not exists. + /// Should return nothing with when posts does not exist. /// /// The title search. [Theory] @@ -479,12 +477,11 @@ public void GetAll_WithContainsSpecification_WhenSpecificationIsNull_ShouldRetur .With(x => x.Title, postTitleSearch) .CreateMany(random.Next(100)); - PostSpecification specification = null; _postsRepositoryMock.Setup(x => x.GetAll(It.IsAny())) .Returns(() => postsList.Where(x => x.Title.Contains(postTitleSearch)).AsQueryable()); //Act - var posts = _postsService.GetAll(specification); + var posts = _postsService.GetAll(null); //Assert Assert.NotNull(posts); @@ -583,7 +580,6 @@ public async Task GetAllAsync_WithContainsSpecification_WhenPostsExists_ShouldRe public async Task GetAllAsync_WithEqualsSpecification_WhenPostsExists_ShouldReturnPost(int equalCount, string titleSearch) { //Arrange - var random = new Random(); var postsList = SetupPostFixture() .With(x => x.Title, titleSearch) @@ -605,7 +601,7 @@ public async Task GetAllAsync_WithEqualsSpecification_WhenPostsExists_ShouldRetu /// /// Get all async posts. - /// Should return nothing with when posts does not exists. + /// Should return nothing with when posts does not exist. /// /// The equal count. /// The title search. @@ -635,7 +631,7 @@ public async Task GetAllAsync_WithEqualSpecification_WhenPostsExists_ShouldRetur /// /// Get all async posts. - /// Should return nothing with when posts does not exists. + /// Should return nothing with when posts does not exist. /// /// The title search. [Theory] @@ -671,7 +667,7 @@ public async Task GetAllAsync_WithContainsSpecification_WhenSpecificationIsEmpty var specification = new PostSpecification(); _postsRepositoryMock.Setup(x => x.GetAllAsync(It.IsAny())) - .Returns(() => postsList.Where(x => x.Title.Contains(postTitleSearch)).AsQueryable()); + .ReturnsAsync(() => postsList.Where(x => x.Title.Contains(postTitleSearch)).ToList()); //Act var posts = await _postsService.GetAllAsync(specification); @@ -697,12 +693,11 @@ public async Task GetAllAsync_WithContainsSpecification_WhenSpecificationIsNull_ .With(x => x.Title, postTitleSearch) .CreateMany(random.Next(100)); - PostSpecification specification = null; _postsRepositoryMock.Setup(x => x.GetAllAsync(It.IsAny())) .ReturnsAsync(() => postsList.Where(x => x.Title.Contains(postTitleSearch)).ToList()); //Act - var posts = await _postsService.GetAllAsync(specification); + var posts = await _postsService.GetAllAsync(null); //Assert Assert.NotNull(posts); @@ -778,7 +773,7 @@ public void Find_WhenPostExists_ShouldReturnPost() /// /// Find post. - /// Should return nothing when post does not exists. + /// Should return nothing when post does not exist. /// [Fact] public void Find_WhenPostDoesNotExists_ShouldReturnNothing() @@ -861,7 +856,7 @@ public async Task FindAsync_WhenPostExists_ShouldReturnPost() /// /// Async find post. - /// Should return nothing when post does not exists. + /// Should return nothing when post does not exist. /// /// Task. [Fact] @@ -869,7 +864,7 @@ public async Task FindAsync_WhenPostDoesNotExists_ShouldReturnNothing() { //Arrange var postId = _fixture.Create(); - + _postsRepositoryMock.Setup(x => x.GetByIdAsync(It.IsAny())) .ReturnsAsync(() => null); @@ -1625,7 +1620,7 @@ public async Task UpdateAsyncEnumerable_WhenRepositoryThrowsException_ShouldThro #region Delete By Id function /// - /// Verify that function Delete By Id has been called. + /// Verify that function Delete By ID has been called. /// [Fact] public void Verify_FunctionDeleteById_HasBeenCalled() @@ -1641,7 +1636,7 @@ public void Verify_FunctionDeleteById_HasBeenCalled() //Act _postsService.Insert(newPost); - var post = _postsService.Find(postId); + _postsService.Find(postId); _postsService.Delete(postId); _postsRepositoryMock.Setup(x => x.GetById(postId)) .Returns(() => null); @@ -1652,7 +1647,7 @@ public void Verify_FunctionDeleteById_HasBeenCalled() } /// - /// Delete By Id post. + /// Delete By ID post. /// Should return nothing when post is deleted. /// [Fact] @@ -1674,7 +1669,7 @@ public void DeleteById_WhenPostIsDeleted_ShouldReturnNothing() //Act _postsService.Insert(newPost); - var post = _postsService.Find(postId); + _postsService.Find(postId); _postsService.Delete(postId); _postsRepositoryMock.Setup(x => x.GetById(postId)) .Returns(() => null); @@ -1684,6 +1679,24 @@ public void DeleteById_WhenPostIsDeleted_ShouldReturnNothing() Assert.Null(deletedPost); } + /// + /// Delete By ID post. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteById_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var post = SetupPostFixture().Create(); + _postsRepositoryMock.Setup(x => x.GetById(It.IsAny())) + .Returns(post); + _postsRepositoryMock.Setup(x => x.Delete(It.IsAny())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _postsService.Delete(post.Id)); + } + #endregion #region Delete By Object function @@ -1744,6 +1757,22 @@ public void DeleteByObject_WhenPostIsDeleted_ShouldReturnNothing() Assert.Null(deletedPost); } + /// + /// Delete By Object post. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteByObject_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var post = SetupPostFixture().Create(); + _postsRepositoryMock.Setup(x => x.Delete(It.IsAny())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _postsService.Delete(post)); + } + #endregion #region Delete By Enumerable function @@ -1821,12 +1850,32 @@ public void DeleteByEnumerable_WhenPostIsDeleted_ShouldReturnNothing() Assert.Null(newPosts); } + /// + /// Delete By Enumerable posts. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteByEnumerable_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var random = new Random(); + var itemsCount = random.Next(10); + var posts = SetupPostFixture() + .CreateMany(itemsCount) + .ToList(); + _postsRepositoryMock.Setup(x => x.Delete(It.IsAny>())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _postsService.Delete(posts)); + } + #endregion #region Delete Async By Id function /// - /// Verify that function Delete Async By Id has been called. + /// Verify that function Delete Async By ID has been called. /// /// Task. [Fact] @@ -1878,6 +1927,24 @@ public async Task DeleteAsyncById_WhenPostIsDeleted_ShouldReturnNothing() Assert.Null(deletedPost); } + /// + /// Async delete By ID post. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncById_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var post = SetupPostFixture().Create(); + _postsRepositoryMock.Setup(x => x.GetByIdAsync(It.IsAny())) + .ReturnsAsync(post); + _postsRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _postsService.DeleteAsync(post.Id)); + } + #endregion #region Delete Async By Object function @@ -1937,6 +2004,22 @@ public async Task DeleteAsyncByObject_WhenPostIsDeleted_ShouldReturnNothing() Assert.Null(deletedPost); } + /// + /// Async delete By Object post. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncByObject_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var post = SetupPostFixture().Create(); + _postsRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _postsService.DeleteAsync(post)); + } + #endregion #region Delete Async By Enumerable function @@ -2013,6 +2096,26 @@ public async Task DeleteAsyncByEnumerable_WhenPostIsDeleted_ShouldReturnNothing( Assert.Null(newPosts); } + /// + /// Async delete By Enumerable posts. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncByEnumerable_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var random = new Random(); + var itemsCount = random.Next(10); + var posts = SetupPostFixture() + .CreateMany(itemsCount) + .ToList(); + _postsRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny>())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _postsService.DeleteAsync(posts)); + } + #endregion #endregion @@ -2104,7 +2207,7 @@ public void Any_WithEqualsSpecification_WhenPostsExists_ShouldReturnTrue(string /// /// Check if there are any posts with specification. - /// Should return false with when posts does not exists. + /// Should return false with when posts does not exist. /// /// The title search. [Theory] @@ -2130,7 +2233,7 @@ public void Any_WithEqualSpecification_WhenPostsExists_ShouldReturnFalse(string /// /// Check if there are any posts with specification. - /// Should return false with when posts does not exists. + /// Should return false with when posts does not exist. /// /// The title search. [Theory] @@ -2239,7 +2342,7 @@ public async Task AnyAsync_WithEqualsSpecification_WhenPostsExists_ShouldReturnT /// /// Async check if there are any posts with specification. - /// Should return false with when posts does not exists. + /// Should return false with when posts does not exist. /// /// The title search. /// Task. @@ -2266,7 +2369,7 @@ public async Task AnyAsync_WithEqualSpecification_WhenPostsExists_ShouldReturnFa /// /// Async check if there are any posts with specification. - /// Should return false with when posts does not exists. + /// Should return false with when posts does not exist. /// /// The title search. /// Task. @@ -2377,7 +2480,7 @@ public void FirstOrDefault_WithEqualsSpecification_WhenPostsExists_ShouldReturnT /// /// Get first or default post with specification. - /// Should return nothing with when post does not exists. + /// Should return nothing with when post does not exist. /// /// The title search. [Theory] @@ -2403,7 +2506,7 @@ public void FirstOrDefault_WithEqualSpecification_WhenPostsExists_ShouldReturnNo /// /// Get first or default post with specification. - /// Should return nothing with when posts does not exists. + /// Should return nothing with when posts does not exist. /// /// The title search. [Theory] @@ -2511,7 +2614,7 @@ public void LastOrDefault_WithEqualsSpecification_WhenPostsExists_ShouldReturnTr /// /// Get last or default post with specification. - /// Should return nothing with when post does not exists. + /// Should return nothing with when post does not exist. /// /// The title search. [Theory] @@ -2537,7 +2640,7 @@ public void LastOrDefault_WithEqualSpecification_WhenPostsExists_ShouldReturnNot /// /// Get last or default post with specification. - /// Should return nothing with when posts does not exists. + /// Should return nothing with when posts does not exist. /// /// The title search. [Theory] @@ -2576,7 +2679,6 @@ protected static PagedListResult Search(SearchQuery query, List x).ToList(); } } @@ -2587,10 +2689,9 @@ protected static PagedListResult Search(SearchQuery query, List current.Include(includeProperty)); } - var b = sequence.ToList(); // Resolving Sort Criteria - // This code applies the sorting criterias sent as the parameter + // This code applies the sorting criteria sent as the parameter if (query.SortCriterias is { Count: > 0 }) { var sortCriteria = query.SortCriterias[0]; @@ -2812,7 +2913,7 @@ public async Task SearchAsync_WithEqualSpecification_WhenPostsExists_ShouldRetur /// /// Search async posts. - /// Should return nothing when posts does not exists. + /// Should return nothing when posts does not exist. /// /// The search. /// The start. @@ -2862,7 +2963,7 @@ public async Task SearchBySequenceAsync_WhenNoEntitiesExist_ShouldReturnEmpty() var query = new SearchQuery { Skip = 0, Take = 5 }; var expected = new PagedListResult { Entities = new List(), Count = 0 }; - _postsRepositoryMock.Setup(r => r.SearchBySquenceAsync(query, data)).ReturnsAsync(expected); + _postsRepositoryMock.Setup(r => r.SearchBySequenceAsync(query, data)).ReturnsAsync(expected); var result = await _postsService.SearchBySequenceAsync(query, data); @@ -2880,7 +2981,7 @@ public async Task SearchBySequenceAsync_WhenEntitiesExistAndQueryIsNull_ShouldRe var data = SetupPostFixture().CreateMany(5).AsQueryable(); var expected = new PagedListResult { Entities = data.ToList(), Count = 5 }; - _postsRepositoryMock.Setup(r => r.SearchBySquenceAsync(null, data)).ReturnsAsync(expected); + _postsRepositoryMock.Setup(r => r.SearchBySequenceAsync(null, data)).ReturnsAsync(expected); var result = await _postsService.SearchBySequenceAsync(null, data); @@ -2898,7 +2999,7 @@ public async Task SearchBySequenceAsync_WhenEntitiesExistAndSequenceIsNullIsNull var query = new SearchQuery { Skip = 0, Take = 5 }; var expected = new PagedListResult { Entities = null, Count = 5 }; - _postsRepositoryMock.Setup(r => r.SearchBySquenceAsync(query, null)).ReturnsAsync(expected); + _postsRepositoryMock.Setup(r => r.SearchBySequenceAsync(query, null)).ReturnsAsync(expected); var result = await _postsService.SearchBySequenceAsync(query, null); diff --git a/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/ProfileServiceTests.cs b/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/ProfileServiceTests.cs index 911e57ff..92c06117 100644 --- a/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/ProfileServiceTests.cs +++ b/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/ProfileServiceTests.cs @@ -140,7 +140,7 @@ public void GetAll_WhenProfilesExists_ShouldReturnProfiles(int notEqualCount) /// /// Get all profiles. - /// Should return nothing when profiles does not exists. + /// Should return nothing when profiles does not exist. /// [Fact] public void GetAll_WhenProfilesDoesNotExists_ShouldReturnNothing() @@ -228,7 +228,7 @@ public async Task GetAllAsync_WhenProfilesExists_ShouldReturnProfiles(int notEqu /// /// Get all async profiles. - /// Should return nothing when profiles does not exists. + /// Should return nothing when profiles does not exist. /// [Fact] public async Task GetAllAsync_WhenProfilesDoesNotExists_ShouldReturnNothing() @@ -271,7 +271,7 @@ public void Verify_FunctionGetAll_WithSpecification_HasBeenCalled() { //Arrange var random = new Random(); - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var profilesList = SetupProfileFixture() @@ -302,7 +302,7 @@ public void GetAll_WithEqualsSpecification_WhenProfilesExists_ShouldReturnProfil //Test failed //Arrange var random = new Random(); - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var profilesList = SetupProfileFixture() @@ -325,7 +325,7 @@ public void GetAll_WithEqualsSpecification_WhenProfilesExists_ShouldReturnProfil /// /// Get all messages with specification. - /// Should return nothing with when messages does not exists. + /// Should return nothing with when messages does not exist. /// /// The equal count. [Theory] @@ -334,7 +334,7 @@ public void GetAll_WithEqualSpecification_WhenProfilesExists_ShouldReturnNothing { //Arrange var random = new Random(); - var searchUserId = $"{new Guid()}1"; + var searchUserId = $"{Guid.Empty}1"; var profilesList = SetupProfileFixture() @@ -356,13 +356,13 @@ public void GetAll_WithEqualSpecification_WhenProfilesExists_ShouldReturnNothing /// /// Get all messages. - /// Should return nothing with when messages does not exists. + /// Should return nothing with when messages does not exist. /// [Fact] public void GetAll_WithEqualSpecification_WhenMessagesDoesNotExists_ShouldReturnNothing() { //Arrange - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var specification = new ProfileSpecification(x => x.UserId.Equals(searchUserId)); _profileRepositoryMock.Setup(x => x.GetAll(specification)) .Returns(() => new List().AsQueryable()); @@ -390,7 +390,7 @@ public void GetAll_WithContainsSpecification_WhenSpecificationIsEmpty_ShouldRetu .With(x => x.UserId, searchUserId) .CreateMany(random.Next(100)); - var specification = new ProfileSpecification(); + var specification = new ProfileSpecification(null); _profileRepositoryMock.Setup(x => x.GetAll(It.IsAny())) .Returns(() => profilesList.Where(x => x.UserId.Contains(searchUserId)).AsQueryable()); @@ -413,22 +413,20 @@ public void GetAll_WithContainsSpecification_WhenSpecificationIsNull_ShouldRetur { //Arrange var random = new Random(); - string searchUserId = null; var profilesList = SetupProfileFixture() .CreateMany(random.Next(100)); - ProfileSpecification specification = null; _profileRepositoryMock.Setup(x => x.GetAll(It.IsAny())) - .Returns(() => profilesList.Where(x => x.UserId.Contains(searchUserId)).AsQueryable()); + .Returns(() => profilesList.Where(x => x.UserId == null).AsQueryable()); //Act - var profiles = _profileService.GetAll(specification); + var profiles = _profileService.GetAll(null); //Assert Assert.NotNull(profiles); - Assert.NotEmpty(profiles); - Assert.NotEqual(notEqualCount, profiles.ToList().Count); + Assert.Empty(profiles); + Assert.Equal(notEqualCount, profiles.ToList().Count); } /// @@ -460,7 +458,7 @@ public async Task Verify_FunctionGetAllAsync_WithSpecification_HasBeenCalled() { //Arrange var random = new Random(); - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var profilesList = SetupProfileFixture() @@ -491,7 +489,7 @@ public async Task GetAllAsync_WithEqualsSpecification_WhenProfilesExists_ShouldR //Test failed //Arrange var random = new Random(); - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var profilesList = SetupProfileFixture() @@ -514,7 +512,7 @@ public async Task GetAllAsync_WithEqualsSpecification_WhenProfilesExists_ShouldR /// /// Get all async messages with specification. - /// Should return nothing with when messages does not exists. + /// Should return nothing with when messages does not exist. /// /// The equal count. [Theory] @@ -523,7 +521,7 @@ public async Task GetAllAsync_WithEqualSpecification_WhenProfilesExists_ShouldRe { //Arrange var random = new Random(); - var searchUserId = $"{new Guid()}1"; + var searchUserId = $"{Guid.Empty}1"; var profilesList = SetupProfileFixture() @@ -545,13 +543,13 @@ public async Task GetAllAsync_WithEqualSpecification_WhenProfilesExists_ShouldRe /// /// Get all async messages. - /// Should return nothing with when messages does not exists. + /// Should return nothing with when messages does not exist. /// [Fact] public async Task GetAllAsync_WithEqualSpecification_WhenMessagesDoesNotExists_ShouldReturnNothing() { //Arrange - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var specification = new ProfileSpecification(x => x.UserId.Equals(searchUserId)); _profileRepositoryMock.Setup(x => x.GetAllAsync(specification)) .ReturnsAsync(() => []); @@ -579,7 +577,7 @@ public async Task GetAllAsync_WithContainsSpecification_WhenSpecificationIsEmpty .With(x => x.UserId, searchUserId) .CreateMany(random.Next(100)); - var specification = new ProfileSpecification(); + var specification = new ProfileSpecification(null); _profileRepositoryMock.Setup(x => x.GetAllAsync(It.IsAny())) .ReturnsAsync(() => profilesList.Where(x => x.UserId.Contains(searchUserId)).ToList()); @@ -602,22 +600,20 @@ public async Task GetAllAsync_WithContainsSpecification_WhenSpecificationIsNull_ { //Arrange var random = new Random(); - string searchUserId = null; var profilesList = SetupProfileFixture() .CreateMany(random.Next(100)); - ProfileSpecification specification = null; _profileRepositoryMock.Setup(x => x.GetAllAsync(It.IsAny())) - .Returns(() => profilesList.Where(x => x.UserId.Contains(searchUserId)).ToList()); + .ReturnsAsync(() => profilesList.Where(x => x.UserId == null).ToList()); //Act - var profiles = await _profileService.GetAllAsync(specification); + var profiles = await _profileService.GetAllAsync(null); //Assert Assert.NotNull(profiles); - Assert.NotEmpty(profiles); - Assert.NotEqual(notEqualCount, profiles.ToList().Count); + Assert.Empty(profiles); + Assert.Equal(notEqualCount, profiles.ToList().Count); } /// @@ -688,7 +684,7 @@ public void Find_WhenProfilesExists_ShouldReturnProfile() /// /// Find profile. - /// Should return nothing when profiles does not exists. + /// Should return nothing when profiles does not exist. /// [Fact] public void Find_WhenProfilesDoesNotExists_ShouldReturnNothing() @@ -737,7 +733,7 @@ public async Task Verify_FunctionFindAsync_HasBeenCalled() var random = new Random(); var profileId = random.Next(52); - var userId = new Guid().ToString(); + var userId = Guid.Empty.ToString(); var user = new ApplicationUser { Id = userId, @@ -776,7 +772,7 @@ public async Task FindAsync_WhenProfilesExists_ShouldReturnProfiles() var random = new Random(); var profileId = random.Next(52); - var userId = new Guid().ToString(); + var userId = Guid.Empty.ToString(); var user = new ApplicationUser { Id = userId, @@ -805,7 +801,7 @@ public async Task FindAsync_WhenProfilesExists_ShouldReturnProfiles() /// /// Async find profile. - /// Should return nothing when profiles does not exists. + /// Should return nothing when profiles does not exist. /// /// Task. [Fact] @@ -1198,7 +1194,7 @@ public void Verify_FunctionUpdate_HasBeenCalled() //Act _profileService.Insert(newProfile); var profile = _profileService.Find(profileId); - profile.UserId = new Guid().ToString(); + profile.UserId = Guid.Empty.ToString(); _profileService.Update(profile); //Assert @@ -1227,7 +1223,7 @@ public void Update_WhenProfileExists_ShouldReturnProfile() //Act _profileService.Insert(newProfile); var profile = _profileService.Find(profileId); - var newUserId = new Guid().ToString(); + var newUserId = Guid.Empty.ToString(); profile.UserId = newUserId; _profileService.Update(profile); @@ -1386,7 +1382,7 @@ public async Task Verify_FunctionUpdateAsync_HasBeenCalled() //Act await _profileService.InsertAsync(newProfile); var profile = await _profileService.FindAsync(profileId); - profile.UserId = new Guid().ToString(); + profile.UserId = Guid.Empty.ToString(); await _profileService.UpdateAsync(profile); //Assert @@ -1416,7 +1412,7 @@ public async Task UpdateAsync_WhenMessageExists_ShouldReturnMessage() //Act await _profileService.InsertAsync(newProfile); var profile = await _profileService.FindAsync(profileId); - var newUserId = new Guid().ToString(); + var newUserId = Guid.Empty.ToString(); profile.UserId = newUserId; await _profileService.UpdateAsync(profile); @@ -1559,7 +1555,7 @@ public async Task UpdateAsyncEnumerable_WhenRepositoryThrowsException_ShouldThro #region Delete By Id function /// - /// Verify that function Delete By Id has been called. + /// Verify that function Delete By ID has been called. /// [Fact] public void Verify_FunctionDeleteById_HasBeenCalled() @@ -1578,7 +1574,7 @@ public void Verify_FunctionDeleteById_HasBeenCalled() //Act _profileService.Insert(newProfile); - var profile = _profileService.Find(profileId); + _profileService.Find(profileId); _profileService.Delete(profileId); _profileRepositoryMock.Setup(x => x.GetById(profileId)) .Returns(() => null); @@ -1589,7 +1585,7 @@ public void Verify_FunctionDeleteById_HasBeenCalled() } /// - /// Delete By Id profile. + /// Delete By ID profile. /// Should return nothing when profile is deleted. /// [Fact] @@ -1609,7 +1605,7 @@ public void DeleteById_WhenProfileDeleted_ShouldReturnNothing() //Act _profileService.Insert(newProfile); - var profile = _profileService.Find(profileId); + _profileService.Find(profileId); _profileService.Delete(profileId); _profileRepositoryMock.Setup(x => x.GetById(profileId)) .Returns(() => null); @@ -1619,6 +1615,24 @@ public void DeleteById_WhenProfileDeleted_ShouldReturnNothing() Assert.Null(deletedProfile); } + /// + /// Delete By ID profile. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteById_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var profile = SetupProfileFixture().Create(); + _profileRepositoryMock.Setup(x => x.GetById(It.IsAny())) + .Returns(profile); + _profileRepositoryMock.Setup(x => x.Delete(It.IsAny())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _profileService.Delete(profile.Id)); + } + #endregion #region Delete By Object function @@ -1684,6 +1698,22 @@ public void DeleteByObject_WhenProfileDeleted_ShouldReturnNothing() Assert.Null(deletedProfile); } + /// + /// Delete By Object profile. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteByObject_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var profile = SetupProfileFixture().Create(); + _profileRepositoryMock.Setup(x => x.Delete(It.IsAny())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _profileService.Delete(profile)); + } + #endregion #region Delete By Enumerable function @@ -1762,12 +1792,32 @@ public void DeleteByEnumerable_WhenProfileDeleted_ShouldReturnNothing() Assert.Null(newProfiles); } + /// + /// Delete By Enumerable profiles. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteByEnumerable_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var random = new Random(); + var itemsCount = random.Next(10); + var profiles = SetupProfileFixture() + .CreateMany(itemsCount) + .ToList(); + _profileRepositoryMock.Setup(x => x.Delete(It.IsAny>())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _profileService.Delete(profiles)); + } + #endregion #region Delete Async By Id function /// - /// Verify that function Delete Async By Id has been called. + /// Verify that function Delete Async By ID has been called. /// /// Task. [Fact] @@ -1787,7 +1837,7 @@ public async Task Verify_FunctionDeleteAsyncById_HasBeenCalled() //Act await _profileService.InsertAsync(newProfile); - var profile = await _profileService.FindAsync(profileId); + await _profileService.FindAsync(profileId); await _profileService.DeleteAsync(profileId); //Assert @@ -1816,7 +1866,7 @@ public async Task DeleteAsyncById_WhenProfileIsDeleted_ShouldReturnNothing() //Act await _profileService.InsertAsync(newProfile); - var profile = await _profileService.FindAsync(profileId); + await _profileService.FindAsync(profileId); await _profileService.DeleteAsync(profileId); _profileRepositoryMock.Setup(x => x.GetByIdAsync(profileId)) .ReturnsAsync(() => null); @@ -1826,6 +1876,24 @@ public async Task DeleteAsyncById_WhenProfileIsDeleted_ShouldReturnNothing() Assert.Null(deletedProfile); } + /// + /// Async delete By ID comment. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncById_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var profile = SetupProfileFixture().Create(); + _profileRepositoryMock.Setup(x => x.GetByIdAsync(It.IsAny())) + .ReturnsAsync(profile); + _profileRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _profileService.DeleteAsync(profile.Id)); + } + #endregion #region Delete Async By Object function @@ -1890,6 +1958,22 @@ public async Task DeleteAsyncByObject_WhenProfileIsDeleted_ShouldReturnNothing() Assert.Null(deletedProfile); } + /// + /// Async delete By Object comment. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncByObject_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var profile = SetupProfileFixture().Create(); + _profileRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _profileService.DeleteAsync(profile)); + } + #endregion #region Delete Async By Enumerable function @@ -1964,6 +2048,26 @@ public async Task DeleteAsyncByEnumerable_WhenProfileDeleted_ShouldReturnNothing Assert.Null(newProfiles); } + /// + /// Async delete By Enumerable profiles. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncByEnumerable_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var random = new Random(); + var itemsCount = random.Next(10); + var profiles = SetupProfileFixture() + .CreateMany(itemsCount) + .ToList(); + _profileRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny>())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _profileService.DeleteAsync(profiles)); + } + #endregion #endregion @@ -1980,7 +2084,7 @@ public void Verify_FunctionAny_WithSpecification_HasBeenCalled() { //Arrange var random = new Random(); - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var profilesList = SetupProfileFixture() @@ -2009,7 +2113,7 @@ public void Any_WithEqualsSpecification_WhenProfilesExists_ShouldReturnTrue() //Test failed //Arrange var random = new Random(); - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var profilesList = SetupProfileFixture() @@ -2030,14 +2134,14 @@ public void Any_WithEqualsSpecification_WhenProfilesExists_ShouldReturnTrue() /// /// Check if there are any messages with specification. - /// Should return false with when messages does not exists. + /// Should return false with when messages does not exist. /// [Fact] public void Any_WithEqualSpecification_WhenProfilesExists_ShouldReturnFalse() { //Arrange var random = new Random(); - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var profilesList = SetupProfileFixture() @@ -2057,13 +2161,13 @@ public void Any_WithEqualSpecification_WhenProfilesExists_ShouldReturnFalse() /// /// Check if there are any profiles with specification. - /// Should return false with when profiles does not exists. + /// Should return false with when profiles does not exist. /// [Fact] public void Any_WithEqualSpecification_WhenProfilesDoesNotExists_ShouldReturnNothing() { //Arrange - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var specification = new ProfileSpecification(x => x.UserId.Equals(searchUserId)); _profileRepositoryMock.Setup(x => x.Any(specification)) .Returns(() => false); @@ -2088,7 +2192,7 @@ public async Task Verify_FunctionAnyAsync_WithSpecification_HasBeenCalled() { //Arrange var random = new Random(); - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var profilesList = SetupProfileFixture() @@ -2118,7 +2222,7 @@ public async Task AnyAsync_WithEqualsSpecification_WhenProfilesExists_ShouldRetu //Test failed //Arrange var random = new Random(); - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var profilesList = SetupProfileFixture() @@ -2139,7 +2243,7 @@ public async Task AnyAsync_WithEqualsSpecification_WhenProfilesExists_ShouldRetu /// /// Async check if there are any profiles with specification. - /// Should return false with when profiles does not exists. + /// Should return false with when profiles does not exist. /// /// Task. [Fact] @@ -2147,7 +2251,7 @@ public async Task AnyAsync_WithEqualSpecification_WhenProfilesExists_ShouldRetur { //Arrange var random = new Random(); - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var profilesList = SetupProfileFixture() @@ -2167,14 +2271,14 @@ public async Task AnyAsync_WithEqualSpecification_WhenProfilesExists_ShouldRetur /// /// Async check if there are any profiles with specification. - /// Should return false with when profiles does not exists. + /// Should return false with when profiles does not exist. /// /// Task. [Fact] public async Task AnyAsync_WithEqualSpecification_WhenProfilesDoesNotExists_ShouldReturnNothing() { //Arrange - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var specification = new ProfileSpecification(x => x.UserId.Equals(searchUserId)); _profileRepositoryMock.Setup(x => x.AnyAsync(specification)) .ReturnsAsync(() => false); @@ -2200,7 +2304,7 @@ public void Verify_FunctionFirstOrDefault_WithSpecification_HasBeenCalled() { //Arrange var random = new Random(); - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var profilesList = SetupProfileFixture() @@ -2229,7 +2333,7 @@ public void FirstOrDefault_WithContainsSpecification_WhenProfilesExists_ShouldRe //Test failed //Arrange var random = new Random(); - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var profilesList = SetupProfileFixture() @@ -2258,7 +2362,7 @@ public void FirstOrDefault_WithEqualSpecification_WhenProfilesExists_ShouldRetur { //Arrange var random = new Random(); - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var profilesList = SetupProfileFixture() @@ -2278,13 +2382,13 @@ public void FirstOrDefault_WithEqualSpecification_WhenProfilesExists_ShouldRetur /// /// Get first or default profile with specification. - /// Should return nothing with equal specification when profiles does not exists. + /// Should return nothing with equal specification when profiles does not exist. /// [Fact] public void FirstOrDefault_WithEqualSpecification_WhenProfilesDoesNotExists_ShouldReturnNothing() { //Arrange - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var specification = new ProfileSpecification(x => x.UserId.Equals(searchUserId)); _profileRepositoryMock.Setup(x => x.FirstOrDefault(specification)) .Returns(() => null); @@ -2308,7 +2412,7 @@ public void Verify_FunctionLastOrDefault_WithSpecification_HasBeenCalled() { //Arrange var random = new Random(); - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var profilesList = SetupProfileFixture() @@ -2337,7 +2441,7 @@ public void LastOrDefault_WithEqualsSpecification_WhenProfilesExists_ShouldRetur //Test failed //Arrange var random = new Random(); - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var profilesList = SetupProfileFixture() @@ -2359,14 +2463,14 @@ public void LastOrDefault_WithEqualsSpecification_WhenProfilesExists_ShouldRetur /// /// Get last or default profile with specification. - /// Should return nothing with equals specification when profiles does not exists. + /// Should return nothing with equals specification when profiles does not exist. /// [Fact] public void LastOrDefault_WithEqualSpecification_WhenProfilesExists_ShouldReturnNothing() { //Arrange var random = new Random(); - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var profilesList = SetupProfileFixture() @@ -2386,13 +2490,13 @@ public void LastOrDefault_WithEqualSpecification_WhenProfilesExists_ShouldReturn /// /// Get last or default profile with specification. - /// Should return nothing with specification when profiles does not exists. + /// Should return nothing with specification when profiles does not exist. /// [Fact] public void LastOrDefault_WithEqualSpecification_WhenProfilesDoesNotExists_ShouldReturnNothing() { //Arrange - var searchUserId = new Guid().ToString(); + var searchUserId = Guid.Empty.ToString(); var specification = new ProfileSpecification(x => x.UserId.Equals(searchUserId)); _profileRepositoryMock.Setup(x => x.LastOrDefault(specification)) .Returns(() => null); @@ -2424,7 +2528,6 @@ protected static PagedListResult Search(SearchQuery foreach (var filterClause in query.Filters) { sequence = sequence.Where(filterClause); - var a = sequence.Select(x => x).ToList(); } } @@ -2437,7 +2540,7 @@ protected static PagedListResult Search(SearchQuery } // Resolving Sort Criteria - // This code applies the sorting criterias sent as the parameter + // This code applies the sorting criteria sent as the parameter if (query.SortCriterias is { Count: > 0 }) { var sortCriteria = query.SortCriterias[0]; @@ -2585,7 +2688,6 @@ public async Task SearchAsync_WhenProfilesExists_ShouldReturnProfiles(string sea public async Task SearchAsync_WithEqualsSpecification_WhenProfilesExists_ShouldReturnProfile(string search, int start, int take, string fieldName, OrderType orderType) { //Arrange - var random = new Random(); var profilesList = SetupProfileFixture() .With(x => x.UserId, search) @@ -2660,7 +2762,7 @@ public async Task SearchAsync_WithEqualSpecification_WhenProfilesExists_ShouldRe /// /// Search async profiles. - /// Should return nothing when profiles does not exists. + /// Should return nothing when profiles does not exist. /// /// The search. /// The start. @@ -2710,7 +2812,7 @@ public async Task SearchBySequenceAsync_WhenNoEntitiesExist_ShouldReturnEmpty() var query = new SearchQuery { Skip = 0, Take = 5 }; var expected = new PagedListResult { Entities = new List(), Count = 0 }; - _profileRepositoryMock.Setup(r => r.SearchBySquenceAsync(query, data)).ReturnsAsync(expected); + _profileRepositoryMock.Setup(r => r.SearchBySequenceAsync(query, data)).ReturnsAsync(expected); var result = await _profileService.SearchBySequenceAsync(query, data); @@ -2728,7 +2830,7 @@ public async Task SearchBySequenceAsync_WhenEntitiesExistAndQueryIsNull_ShouldRe var data = SetupProfileFixture().CreateMany(5).AsQueryable(); var expected = new PagedListResult { Entities = data.ToList(), Count = 5 }; - _profileRepositoryMock.Setup(r => r.SearchBySquenceAsync(null, data)).ReturnsAsync(expected); + _profileRepositoryMock.Setup(r => r.SearchBySequenceAsync(null, data)).ReturnsAsync(expected); var result = await _profileService.SearchBySequenceAsync(null, data); @@ -2746,7 +2848,7 @@ public async Task SearchBySequenceAsync_WhenEntitiesExistAndSequenceIsNullIsNull var query = new SearchQuery { Skip = 0, Take = 5 }; var expected = new PagedListResult { Entities = null, Count = 5 }; - _profileRepositoryMock.Setup(r => r.SearchBySquenceAsync(query, null)).ReturnsAsync(expected); + _profileRepositoryMock.Setup(r => r.SearchBySequenceAsync(query, null)).ReturnsAsync(expected); var result = await _profileService.SearchBySequenceAsync(query, null); diff --git a/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/TagsServiceTests.cs b/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/TagsServiceTests.cs index f8a6f8c4..25fc811d 100644 --- a/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/TagsServiceTests.cs +++ b/BlogWebApp/Tests/Blog.ServicesTests/EntityServices/TagsServiceTests.cs @@ -130,7 +130,7 @@ public void GetAll_WhenTagsExists_ShouldReturnTags(int notEqualCount) /// /// Get all tags. - /// Should return nothing when tags does not exists. + /// Should return nothing when tags does not exist. /// [Fact] public void GetAll_WhenTagsDoesNotExists_ShouldReturnNothing() @@ -218,7 +218,7 @@ public async Task GetAllAsync_WhenTagsExists_ShouldReturnTags(int notEqualCount) /// /// Get all async tags. - /// Should return nothing when tags does not exists. + /// Should return nothing when tags does not exist. /// [Fact] public async Task GetAllAsync_WhenTagsDoesNotExists_ShouldReturnNothing() @@ -344,7 +344,7 @@ public void GetAll_WithEqualsSpecification_WhenTagsExists_ShouldReturnTag(int eq /// /// Get all tags with specification. - /// Should return nothing with when tags does not exists. + /// Should return nothing with when tags does not exist. /// /// The equal count. /// The tag search. @@ -374,7 +374,7 @@ public void GetAll_WithEqualsSpecification_WhenTagsExists_ShouldReturnNothing(in /// /// Get all tags. - /// Should return nothing with when tags does not exists. + /// Should return nothing with when tags does not exist. /// /// The tag search. [Theory] @@ -408,7 +408,7 @@ public void GetAll_WithContainsSpecification_WhenSpecificationIsEmpty_ShouldRetu .With(x => x.Title, tagTitleSearch) .CreateMany(random.Next(100)); - var specification = new TagSpecification(); + var specification = new TagSpecification(null); _tagsRepositoryMock.Setup(x => x.GetAll(It.IsAny())) .Returns(() => tagsList.Where(x => x.Title.Contains(tagTitleSearch)).AsQueryable()); @@ -436,12 +436,11 @@ public void GetAll_WithContainsSpecification_WhenSpecificationIsNull_ShouldRetur .With(x => x.Title, tagTitleSearch) .CreateMany(random.Next(100)); - TagSpecification specification = null; _tagsRepositoryMock.Setup(x => x.GetAll(It.IsAny())) .Returns(() => tagsList.Where(x => x.Title.Contains(tagTitleSearch)).AsQueryable()); //Act - var tags = _tagsService.GetAll(specification); + var tags = _tagsService.GetAll(null); //Assert Assert.NotNull(tags); @@ -560,7 +559,7 @@ public async Task GetAllAsync_WithEqualsSpecification_WhenTagsExists_ShouldRetur /// /// Get all async tags with specification. - /// Should return nothing with when tags does not exists. + /// Should return nothing with when tags does not exist. /// /// The equal count. /// The tag search. @@ -589,7 +588,7 @@ public async Task GetAllAsync_WithEqualSpecification_WhenTagsExists_ShouldReturn /// /// Get all async tags. - /// Should return nothing with when tags does not exists. + /// Should return nothing with when tags does not exist. /// /// The tag search. [Theory] @@ -623,7 +622,7 @@ public async Task GetAllAsync_WithContainsSpecification_WhenSpecificationIsEmpty .With(x => x.Title, tagTitleSearch) .CreateMany(random.Next(100)); - var specification = new TagSpecification(); + var specification = new TagSpecification(null); _tagsRepositoryMock.Setup(x => x.GetAllAsync(It.IsAny())) .ReturnsAsync(() => tagsList.Where(x => x.Title.Contains(tagTitleSearch)).ToList()); @@ -651,12 +650,11 @@ public async Task GetAllAsync_WithContainsSpecification_WhenSpecificationIsNull_ .With(x => x.Title, tagTitleSearch) .CreateMany(random.Next(100)); - TagSpecification specification = null; _tagsRepositoryMock.Setup(x => x.GetAllAsync(It.IsAny())) .ReturnsAsync(() => tagsList.Where(x => x.Title.Contains(tagTitleSearch)).ToList()); //Act - var tags = await _tagsService.GetAllAsync(specification); + var tags = await _tagsService.GetAllAsync(null); //Assert Assert.NotNull(tags); @@ -738,7 +736,7 @@ public void Find_WhenTagExists_ShouldReturnTag() /// /// Find tag. - /// Should return nothing when tag does not exists. + /// Should return nothing when tag does not exist. /// [Fact] public void Find_WhenTagDoesNotExists_ShouldReturnNothing() @@ -827,7 +825,7 @@ public async Task FindAsync_WhenTagExists_ShouldReturnTag() /// /// Async find tag. - /// Should return nothing when tag does not exists. + /// Should return nothing when tag does not exist. /// /// Task. [Fact] @@ -1612,7 +1610,7 @@ public async Task UpdateAsyncEnumerable_WhenRepositoryThrowsException_ShouldThro #region Delete By Id function /// - /// Verify that function Delete By Id has been called. + /// Verify that function Delete By ID has been called. /// [Fact] public void Verify_FunctionDeleteById_HasBeenCalled() @@ -1628,7 +1626,7 @@ public void Verify_FunctionDeleteById_HasBeenCalled() //Act _tagsService.Insert(newTag); - var tag = _tagsService.Find(tagId); + _tagsService.Find(tagId); _tagsService.Delete(tagId); _tagsRepositoryMock.Setup(x => x.GetById(tagId)) .Returns(() => null); @@ -1639,7 +1637,7 @@ public void Verify_FunctionDeleteById_HasBeenCalled() } /// - /// Delete By Id tag. + /// Delete By ID tag. /// Should return nothing when tag is deleted. /// [Fact] @@ -1661,7 +1659,7 @@ public void DeleteById_WhenTagsDeleted_ShouldReturnNothing() //Act _tagsService.Insert(newTag); - var tag = _tagsService.Find(tagId); + _tagsService.Find(tagId); _tagsService.Delete(tagId); _tagsRepositoryMock.Setup(x => x.GetById(tagId)) .Returns(() => null); @@ -1671,6 +1669,24 @@ public void DeleteById_WhenTagsDeleted_ShouldReturnNothing() Assert.Null(deletedTag); } + /// + /// Delete By ID tag. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteById_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var tag = SetupTagFixture().Create(); + _tagsRepositoryMock.Setup(x => x.GetById(It.IsAny())) + .Returns(tag); + _tagsRepositoryMock.Setup(x => x.Delete(It.IsAny())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _tagsService.Delete(tag.Id)); + } + #endregion #region Delete By Object function @@ -1735,6 +1751,22 @@ public void DeleteByObject_WhenTagsDeleted_ShouldReturnNothing() Assert.Null(deletedTag); } + /// + /// Delete By Object tag. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteByObject_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var tag = SetupTagFixture().Create(); + _tagsRepositoryMock.Setup(x => x.Delete(It.IsAny())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _tagsService.Delete(tag)); + } + #endregion #region Delete By Enumerable function @@ -1809,12 +1841,32 @@ public void DeleteByEnumerable_WhenTagsDeleted_ShouldReturnNothing() Assert.Null(newTags); } + /// + /// Delete By Enumerable tags. + /// When repository throws exception should throw exception. + /// + [Fact] + public void DeleteByEnumerable_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var random = new Random(); + var itemsCount = random.Next(10); + var tags = SetupTagFixture() + .CreateMany(itemsCount) + .ToList(); + _tagsRepositoryMock.Setup(x => x.Delete(It.IsAny>())) + .Throws(new Exception("Repo fail")); + + //Assert + Assert.Throws(() => _tagsService.Delete(tags)); + } + #endregion #region Delete By Id Async function /// - /// Verify that function Delete Async By Id has been called. + /// Verify that function Delete Async By ID has been called. /// /// Task. [Fact] @@ -1870,6 +1922,24 @@ public async Task DeleteAsyncById_WhenTagIsDeleted_ShouldReturnNothing() Assert.Null(deletedTag); } + /// + /// Async delete By ID tag. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncById_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var tag = SetupTagFixture().Create(); + _tagsRepositoryMock.Setup(x => x.GetByIdAsync(It.IsAny())) + .ReturnsAsync(tag); + _tagsRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _tagsService.DeleteAsync(tag.Id)); + } + #endregion #region Delete By Object Async function @@ -1933,6 +2003,22 @@ public async Task DeleteAsyncByObject_WhenTagIsDeleted_ShouldReturnNothing() Assert.Null(deletedTag); } + /// + /// Async delete By Object tag. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncByObject_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var tag = SetupTagFixture().Create(); + _tagsRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _tagsService.DeleteAsync(tag)); + } + #endregion #region Delete Async By Enumerable function @@ -2007,6 +2093,26 @@ public async Task DeleteAsyncByEnumerable_WhenTagsDeleted_ShouldReturnNothing() Assert.Null(newTags); } + /// + /// Async delete By Enumerable tags. + /// When repository throws exception should throw exception. + /// + [Fact] + public async Task DeleteAsyncByEnumerable_WhenRepositoryThrowsException_ShouldThrowException() + { + //Arrange + var random = new Random(); + var itemsCount = random.Next(10); + var tags = SetupTagFixture() + .CreateMany(itemsCount) + .ToList(); + _tagsRepositoryMock.Setup(x => x.DeleteAsync(It.IsAny>())) + .ThrowsAsync(new Exception("Repo fail")); + + //Assert + await Assert.ThrowsAsync(() => _tagsService.DeleteAsync(tags)); + } + #endregion #endregion @@ -2101,7 +2207,7 @@ public void Any_WithEqualsSpecification_WhenCommentsExists_ShouldReturnTrue(stri /// /// Check if there are any tags with specification. - /// Should return false with when tags does not exists. + /// Should return false with when tags does not exist. /// /// The tag search. [Theory] @@ -2128,7 +2234,7 @@ public void Any_WithEqualSpecification_WhenCommentsExists_ShouldReturnFalse(stri /// /// Check if there are any tags with specification. - /// Should return false with when tags does not exists. + /// Should return false with when tags does not exist. /// /// The tag search. [Theory] @@ -2240,7 +2346,7 @@ public async Task AnyAsync_WithEqualsSpecification_WhenTagsExists_ShouldReturnTr /// /// Async check if there are any tags with specification. - /// Should return false with when tags does not exists. + /// Should return false with when tags does not exist. /// /// The tag search. /// Task. @@ -2268,7 +2374,7 @@ public async Task AnyAsync_WithEqualSpecification_WhenTagsExists_ShouldReturnFal /// /// Async check if there are any tags with specification. - /// Should return false with when tags does not exists. + /// Should return false with when tags does not exist. /// /// The tag search. /// Task. @@ -2379,7 +2485,7 @@ public void FirstOrDefault_WithEqualsSpecification_WhenTagsExists_ShouldReturnTa /// /// Get first or default tag with specification. - /// Should return nothing with when tags does not exists. + /// Should return nothing with when tags does not exist. /// /// The tag search. [Theory] @@ -2405,7 +2511,7 @@ public void FirstOrDefault_WithEqualSpecification_WhenTagsExists_ShouldReturnNot /// /// Get first or default tag with specification. - /// Should return nothing with when tags does not exists. + /// Should return nothing with when tags does not exist. /// /// The tag search. [Theory] @@ -2513,7 +2619,7 @@ public void LastOrDefault_WithEqualsSpecification_WhenTagsExists_ShouldReturnTag /// /// Get last or default tag with specification. - /// Should return nothing with when tags does not exists. + /// Should return nothing with when tags does not exist. /// /// The tag search. [Theory] @@ -2539,7 +2645,7 @@ public void LastOrDefault_WithEqualSpecification_WhenTagsExists_ShouldReturnNoth /// /// Get last or default tag with specification. - /// Should return nothing with when tags does not exists. + /// Should return nothing with when tags does not exist. /// /// The tag search. [Theory] @@ -2578,7 +2684,6 @@ protected static PagedListResult Search(SearchQuery query, List t foreach (var filterClause in query.Filters) { sequence = sequence.Where(filterClause); - var a = sequence.Select(x => x).ToList(); } } @@ -2591,7 +2696,7 @@ protected static PagedListResult Search(SearchQuery query, List t } // Resolving Sort Criteria - // This code applies the sorting criterias sent as the parameter + // This code applies the sorting criteria sent as the parameter if (query.SortCriterias is { Count: > 0 }) { var sortCriteria = query.SortCriterias[0]; @@ -2726,7 +2831,6 @@ public async Task SearchAsync_WhenTagsExists_ShouldReturnTags(string search, int public async Task SearchAsync_WithEqualsSpecification_WhenTagsExists_ShouldReturnTag(string search, int start, int take, string fieldName, OrderType orderType) { //Arrange - var random = new Random(); var tagsList = SetupTagFixture() .With(x => x.Title, search) @@ -2758,7 +2862,7 @@ public async Task SearchAsync_WithEqualsSpecification_WhenTagsExists_ShouldRetur /// /// Search async tags with specification. - /// Should return nothing with when tags does not exists. + /// Should return nothing with when tags does not exist. /// [Theory] [InlineData("Tag -0", 0, 10, "Title", OrderType.Ascending)] @@ -2797,7 +2901,7 @@ public async Task SearchAsync_WithEqualSpecification_WhenTagsExists_ShouldReturn /// /// Search async tags. - /// Should return nothing when tags does not exists. + /// Should return nothing when tags does not exist. /// [Theory] [InlineData("Comment 0", 0, 10, "CommentBody", OrderType.Ascending)] @@ -2842,7 +2946,7 @@ public async Task SearchBySequenceAsync_WhenNoEntitiesExist_ShouldReturnEmpty() var query = new SearchQuery { Skip = 0, Take = 5 }; var expected = new PagedListResult { Entities = new List(), Count = 0 }; - _tagsRepositoryMock.Setup(r => r.SearchBySquenceAsync(query, data)).ReturnsAsync(expected); + _tagsRepositoryMock.Setup(r => r.SearchBySequenceAsync(query, data)).ReturnsAsync(expected); var result = await _tagsService.SearchBySequenceAsync(query, data); @@ -2860,7 +2964,7 @@ public async Task SearchBySequenceAsync_WhenEntitiesExistAndQueryIsNull_ShouldRe var data = SetupTagFixture().CreateMany(5).AsQueryable(); var expected = new PagedListResult { Entities = data.ToList(), Count = 5 }; - _tagsRepositoryMock.Setup(r => r.SearchBySquenceAsync(null, data)).ReturnsAsync(expected); + _tagsRepositoryMock.Setup(r => r.SearchBySequenceAsync(null, data)).ReturnsAsync(expected); var result = await _tagsService.SearchBySequenceAsync(null, data); @@ -2878,7 +2982,7 @@ public async Task SearchBySequenceAsync_WhenEntitiesExistAndSequenceIsNullIsNull var query = new SearchQuery { Skip = 0, Take = 5 }; var expected = new PagedListResult { Entities = null, Count = 5 }; - _tagsRepositoryMock.Setup(r => r.SearchBySquenceAsync(query, null)).ReturnsAsync(expected); + _tagsRepositoryMock.Setup(r => r.SearchBySequenceAsync(query, null)).ReturnsAsync(expected); var result = await _tagsService.SearchBySequenceAsync(query, null); diff --git a/Sdk/Blog.Sdk/V1/IAccountsControllerRequestsApi.cs b/Sdk/Blog.Sdk/V1/IAccountsControllerRequestsApi.cs index cc05431e..6b84e99a 100644 --- a/Sdk/Blog.Sdk/V1/IAccountsControllerRequestsApi.cs +++ b/Sdk/Blog.Sdk/V1/IAccountsControllerRequestsApi.cs @@ -2,10 +2,10 @@ using System.Collections.Generic; using System.Threading.Tasks; -using Microsoft.AspNetCore.Identity; -using Refit; using Blog.Contracts.V1.Requests.UsersRequests; using Blog.Contracts.V1.Responses.UsersResponses; +using Microsoft.AspNetCore.Identity; +using Refit; /// /// Account controller requests api interface. diff --git a/Shared/Blog.Contracts/V1/ApiRoutes.cs b/Shared/Blog.Contracts/V1/ApiRoutes.cs index 709c1daf..333a5d13 100644 --- a/Shared/Blog.Contracts/V1/ApiRoutes.cs +++ b/Shared/Blog.Contracts/V1/ApiRoutes.cs @@ -31,7 +31,7 @@ public static class AccountsController public const string Accounts = Base + "/accounts"; /// - /// The initialize. + /// Initialize. /// public const string Initialize = "initialize/{userId}"; @@ -53,7 +53,7 @@ public static class AccountsController /// /// The register. /// - public const string Register ="register"; + public const string Register = "register"; /// /// The change password. @@ -92,7 +92,7 @@ public static class CommentsController public const string GetComment = "get-comment"; /// - /// The create comment. + /// The creation comment. /// public const string CreateComment = "create"; diff --git a/Shared/Blog.Contracts/V1/Responses/Chart/ChartDataModel.cs b/Shared/Blog.Contracts/V1/Responses/Chart/ChartDataModel.cs index 02faf51d..e349eb3d 100644 --- a/Shared/Blog.Contracts/V1/Responses/Chart/ChartDataModel.cs +++ b/Shared/Blog.Contracts/V1/Responses/Chart/ChartDataModel.cs @@ -2,8 +2,18 @@ namespace Blog.Contracts.V1.Responses.Chart; +/// +/// The Chart Data model. +/// public class ChartDataModel { + /// + /// Gets or sets name. + /// public string Name { get; set; } - public List Series { get; set; } = new(); + + /// + /// Gets or sets series. + /// + public List Series { get; set; } = []; } \ No newline at end of file diff --git a/Shared/Blog.Contracts/V1/Responses/Chart/ChartItem.cs b/Shared/Blog.Contracts/V1/Responses/Chart/ChartItem.cs index 170c3ac2..4cfc675d 100644 --- a/Shared/Blog.Contracts/V1/Responses/Chart/ChartItem.cs +++ b/Shared/Blog.Contracts/V1/Responses/Chart/ChartItem.cs @@ -1,7 +1,17 @@ namespace Blog.Contracts.V1.Responses.Chart; +/// +/// Chart Item. +/// public class ChartItem { + /// + /// Gets or sets name. + /// public string Name { get; set; } + + /// + /// Gets or sets value. + /// public int Value { get; set; } } \ No newline at end of file diff --git a/Shared/Blog.Contracts/V1/Validators/PostsValidators/CreatePostRequestValidator.cs b/Shared/Blog.Contracts/V1/Validators/PostsValidators/CreatePostRequestValidator.cs index e04a21f1..8aa3b5f9 100644 --- a/Shared/Blog.Contracts/V1/Validators/PostsValidators/CreatePostRequestValidator.cs +++ b/Shared/Blog.Contracts/V1/Validators/PostsValidators/CreatePostRequestValidator.cs @@ -7,7 +7,7 @@ namespace Blog.Contracts.V1.Validators.PostsValidators; /// Create post request validator. /// /// -class CreatePostRequestValidator : AbstractValidator +public class CreatePostRequestValidator : AbstractValidator { /// /// Initializes a new instance of the class. diff --git a/Shared/Blog.Contracts/V1/Validators/PostsValidators/UpdatePostRequestValidator.cs b/Shared/Blog.Contracts/V1/Validators/PostsValidators/UpdatePostRequestValidator.cs index b349e4e7..b824234c 100644 --- a/Shared/Blog.Contracts/V1/Validators/PostsValidators/UpdatePostRequestValidator.cs +++ b/Shared/Blog.Contracts/V1/Validators/PostsValidators/UpdatePostRequestValidator.cs @@ -7,7 +7,7 @@ namespace Blog.Contracts.V1.Validators.PostsValidators; /// Update post request validator. /// /// -class UpdatePostRequestValidator : AbstractValidator +public class UpdatePostRequestValidator : AbstractValidator { /// /// Initializes a new instance of the class. diff --git a/Shared/Blog.Core/Attributes/SwaggerAttributes/SwaggerGroupAttribute.cs b/Shared/Blog.Core/Attributes/SwaggerAttributes/SwaggerGroupAttribute.cs index 03e477fc..6e4afe86 100644 --- a/Shared/Blog.Core/Attributes/SwaggerAttributes/SwaggerGroupAttribute.cs +++ b/Shared/Blog.Core/Attributes/SwaggerAttributes/SwaggerGroupAttribute.cs @@ -1,4 +1,8 @@ -namespace Blog.Core.Attributes.SwaggerAttributes; +// +// Copyright (c) PlaceholderCompany. All rights reserved. +// + +namespace Blog.Core.Attributes.SwaggerAttributes; using System; diff --git a/Shared/Blog.Core/Emails/Email.cs b/Shared/Blog.Core/Emails/Email.cs index 9012168b..ff996aff 100644 --- a/Shared/Blog.Core/Emails/Email.cs +++ b/Shared/Blog.Core/Emails/Email.cs @@ -11,14 +11,6 @@ namespace Blog.Core.Emails; /// public class Email { - /// - /// Initializes a new instance of the class. - /// - public Email() - { - this.Attachments = []; - } - /// /// Gets or sets body. /// @@ -42,5 +34,5 @@ public Email() /// /// Gets or sets attachments. /// - public List Attachments { get; set; } + public List Attachments { get; set; } = []; } \ No newline at end of file diff --git a/Shared/Blog.Core/Helpers/CommonHelper.cs b/Shared/Blog.Core/Helpers/CommonHelper.cs index 915daca4..9a7c12a3 100644 --- a/Shared/Blog.Core/Helpers/CommonHelper.cs +++ b/Shared/Blog.Core/Helpers/CommonHelper.cs @@ -4,6 +4,7 @@ namespace Blog.Core.Helpers; +using Infrastructure; using System; using System.Collections.Generic; using System.ComponentModel; @@ -13,7 +14,6 @@ namespace Blog.Core.Helpers; using System.Reflection; using System.Security.Cryptography; using System.Text.RegularExpressions; -using Infrastructure; /// /// Common Helper. @@ -50,7 +50,7 @@ public static int BusinessDays(DateTime firstDay, DateTime lastDay, params DateT var businessDays = span.Days + 1; var fullWeekCount = businessDays / 7; - // find out if there are weekends during the time exceedng the full weeks + // find out if there are weekends during the time exceeding the full weeks if (businessDays > fullWeekCount * 7) { // we are here to find out if there is a 1-day or 2-days weekend @@ -140,9 +140,7 @@ public static bool IsValidEmail(string email) /// ipAddress. /// bool. public static bool IsValidIpAddress(string ipAddress) - { - return IPAddress.TryParse(ipAddress, out IPAddress _); - } + => IPAddress.TryParse(ipAddress, out _); /// /// Generate random digit code. @@ -183,19 +181,14 @@ public static int GenerateRandomInteger(int min = 0, int max = int.MaxValue) /// string. public static string EnsureMaximumLength(string str, int maxLength, string postfix = null) { - if (string.IsNullOrEmpty(str)) - { - return str; - } - - if (str.Length <= maxLength) + if (string.IsNullOrEmpty(str) || str.Length <= maxLength) { return str; } var pLen = postfix?.Length ?? 0; - var result = str.Substring(0, maxLength - pLen); + var result = str[..(maxLength - pLen)]; if (!string.IsNullOrEmpty(postfix)) { result += postfix; @@ -298,7 +291,7 @@ public static void SetProperty(object instance, string propertyName, object valu value = To(value, pi.PropertyType); } - pi.SetValue(instance, value, new object[0]); + pi.SetValue(instance, value, []); } /// @@ -382,7 +375,7 @@ public static string ConvertEnum(string str) { if (c.ToString() != c.ToString().ToLower()) { - result += " " + c.ToString(); + result += " " + c; } else { @@ -436,12 +429,12 @@ public static object GetPrivateFieldValue(object target, string fieldName) { if (target == null) { - throw new ArgumentNullException("target", "The assignment target cannot be null."); + throw new ArgumentNullException(nameof(target), "The assignment target cannot be null."); } if (string.IsNullOrEmpty(fieldName)) { - throw new ArgumentException("The field name cannot be null or empty.", "fieldName"); + throw new ArgumentException("The field name cannot be null or empty.", nameof(fieldName)); } var t = target.GetType(); diff --git a/Shared/Blog.Core/Helpers/EmailHelper.cs b/Shared/Blog.Core/Helpers/EmailHelper.cs index 0e038eac..a712a9cd 100644 --- a/Shared/Blog.Core/Helpers/EmailHelper.cs +++ b/Shared/Blog.Core/Helpers/EmailHelper.cs @@ -1,9 +1,9 @@ namespace Blog.Core.Helpers; +using Calabonga.Microservices.Core.Extensions; using System; using System.Collections.Generic; using System.Linq; -using Calabonga.Microservices.Core.Extensions; /// /// Email validation helper. @@ -21,7 +21,8 @@ public static IEnumerable GetValidEmails(string emails) { return null; } - var split = emails.Split(new[] { ';', '|', ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); + + var split = emails.Split([';', '|', ' ', ','], StringSplitOptions.RemoveEmptyEntries); return split.Where(x => x.IsEmail()); } } \ No newline at end of file diff --git a/Shared/Blog.Core/Helpers/Utilities.cs b/Shared/Blog.Core/Helpers/Utilities.cs index 315f48a6..f2d714c1 100644 --- a/Shared/Blog.Core/Helpers/Utilities.cs +++ b/Shared/Blog.Core/Helpers/Utilities.cs @@ -110,20 +110,19 @@ public static async Task SetFileContent(string filePath, string content) try { var folder = Path.GetDirectoryName(filePath); - if (!Directory.Exists(folder)) + if (!string.IsNullOrEmpty(folder) && !Directory.Exists(folder)) { Directory.CreateDirectory(folder); } - if (File.Exists(filePath)) + if (string.IsNullOrEmpty(filePath) || File.Exists(filePath)) { } - using (var fs = File.Create(filePath)) - { - var info = new UTF8Encoding(true).GetBytes(content); - await fs.WriteAsync(info, 0, info.Length); - } + await using var fs = File.Create(filePath); + + var info = new UTF8Encoding(true).GetBytes(content); + await fs.WriteAsync(info, 0, info.Length); } catch { @@ -163,13 +162,12 @@ public static string GetWorkingFolder() /// string. private static string GenerateETag(byte[] data) { - using (var md5 = MD5.Create()) - { - var hash = md5.ComputeHash(data); - var hex = BitConverter.ToString(hash); + using var md5 = MD5.Create(); - return hex.Replace("-", string.Empty); - } + var hash = md5.ComputeHash(data); + var hex = BitConverter.ToString(hash); + + return hex.Replace("-", string.Empty); } /// diff --git a/Shared/Blog.Core/Helpers/ValidationContextHelper.cs b/Shared/Blog.Core/Helpers/ValidationContextHelper.cs index a2ce135b..daa2b5cd 100644 --- a/Shared/Blog.Core/Helpers/ValidationContextHelper.cs +++ b/Shared/Blog.Core/Helpers/ValidationContextHelper.cs @@ -1,4 +1,8 @@ -namespace Blog.Core.Helpers; +// +// Copyright (c) PlaceholderCompany. All rights reserved. +// + +namespace Blog.Core.Helpers; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; @@ -9,7 +13,7 @@ public static class ValidationContextHelper { /// - /// Tries the validate. + /// Tries to validate. /// /// The object. /// The results. @@ -18,7 +22,7 @@ public static class ValidationContextHelper public static bool TryValidate(object obj, out Collection results, ValidationContext validationContext = null) { var context = validationContext ?? new ValidationContext(obj, serviceProvider: null, items: null); - results = new Collection(); + results = []; return Validator.TryValidateObject(obj, context, results, validateAllProperties: true); } diff --git a/Shared/Blog.Core/IEntity.cs b/Shared/Blog.Core/IEntity.cs index 8e279bf2..bcd7c1d9 100644 --- a/Shared/Blog.Core/IEntity.cs +++ b/Shared/Blog.Core/IEntity.cs @@ -7,16 +7,12 @@ namespace Blog.Core; /// /// Entity interface. /// -public interface IEntity -{ -} +public interface IEntity; /// /// Entity base interface. /// -public interface IEntityBase : IEntity -{ -} +public interface IEntityBase : IEntity; /// /// Entity interface. diff --git a/Shared/Blog.Core/Infrastructure/FieldSortOrder.cs b/Shared/Blog.Core/Infrastructure/FieldSortOrder.cs index c6dcfa3f..5a571570 100644 --- a/Shared/Blog.Core/Infrastructure/FieldSortOrder.cs +++ b/Shared/Blog.Core/Infrastructure/FieldSortOrder.cs @@ -4,9 +4,9 @@ namespace Blog.Core.Infrastructure; -using System.Linq; -using Enums; using Blog.Core.Infrastructure.Pagination.Interfaces; +using Enums; +using System.Linq; /// /// Field sort order. diff --git a/Shared/Blog.Core/Infrastructure/FileProvider.cs b/Shared/Blog.Core/Infrastructure/FileProvider.cs index b39e5bbd..9d100e85 100644 --- a/Shared/Blog.Core/Infrastructure/FileProvider.cs +++ b/Shared/Blog.Core/Infrastructure/FileProvider.cs @@ -4,14 +4,14 @@ namespace Blog.Core.Infrastructure; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.FileProviders; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; -using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.FileProviders; /// /// File provider. diff --git a/Shared/Blog.Core/Infrastructure/Mediator/Behaviors/ValidatorBehavior.cs b/Shared/Blog.Core/Infrastructure/Mediator/Behaviors/ValidatorBehavior.cs index d0eca569..562afc8e 100644 --- a/Shared/Blog.Core/Infrastructure/Mediator/Behaviors/ValidatorBehavior.cs +++ b/Shared/Blog.Core/Infrastructure/Mediator/Behaviors/ValidatorBehavior.cs @@ -1,14 +1,18 @@ -namespace Blog.Core.Infrastructure.Mediator.Behaviors; +// +// Copyright (c) PlaceholderCompany. All rights reserved. +// +namespace Blog.Core.Infrastructure.Mediator.Behaviors; + +using Calabonga.Microservices.Core.Exceptions; +using FluentValidation; +using MediatR; +using OperationResults; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; -using OperationResults; -using Calabonga.Microservices.Core.Exceptions; -using FluentValidation; -using MediatR; /// /// Base validator for requests. diff --git a/Shared/Blog.Core/Infrastructure/Middlewares/ETagMiddleware.cs b/Shared/Blog.Core/Infrastructure/Middlewares/ETagMiddleware.cs index ac53d0b8..b94363f3 100644 --- a/Shared/Blog.Core/Infrastructure/Middlewares/ETagMiddleware.cs +++ b/Shared/Blog.Core/Infrastructure/Middlewares/ETagMiddleware.cs @@ -4,12 +4,12 @@ namespace Blog.Core.Infrastructure.Middlewares; -using System.IO; -using System.Security.Cryptography; -using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Net.Http.Headers; +using System.IO; +using System.Security.Cryptography; +using System.Threading.Tasks; /// /// ETag middleware from Mads Kristensen. diff --git a/Shared/Blog.Core/Infrastructure/Middlewares/ErrorHandlingMiddleware.cs b/Shared/Blog.Core/Infrastructure/Middlewares/ErrorHandlingMiddleware.cs index 9bf644a7..9fd0d1cf 100644 --- a/Shared/Blog.Core/Infrastructure/Middlewares/ErrorHandlingMiddleware.cs +++ b/Shared/Blog.Core/Infrastructure/Middlewares/ErrorHandlingMiddleware.cs @@ -4,11 +4,11 @@ namespace Blog.Core.Infrastructure.Middlewares; -using System; -using System.Threading.Tasks; +using Helpers; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; -using Helpers; +using System; +using System.Threading.Tasks; /// /// Custom error handler. It allows to view error messages on UI. diff --git a/Shared/Blog.Core/Infrastructure/OperationResults/Metadata.cs b/Shared/Blog.Core/Infrastructure/OperationResults/Metadata.cs index 49f64b08..8f29b985 100644 --- a/Shared/Blog.Core/Infrastructure/OperationResults/Metadata.cs +++ b/Shared/Blog.Core/Infrastructure/OperationResults/Metadata.cs @@ -4,8 +4,8 @@ namespace Blog.Core.Infrastructure.OperationResults; -using System; using Interfaces; +using System; /// /// Metadata. diff --git a/Shared/Blog.Core/Infrastructure/OperationResults/OperationResult.cs b/Shared/Blog.Core/Infrastructure/OperationResults/OperationResult.cs index ed9724cf..2e454a60 100644 --- a/Shared/Blog.Core/Infrastructure/OperationResults/OperationResult.cs +++ b/Shared/Blog.Core/Infrastructure/OperationResults/OperationResult.cs @@ -1,4 +1,8 @@ -namespace Blog.Core.Infrastructure.OperationResults; +// +// Copyright (c) PlaceholderCompany. All rights reserved. +// + +namespace Blog.Core.Infrastructure.OperationResults; using System; using System.Collections.Generic; @@ -19,7 +23,7 @@ public abstract class OperationResult /// /// Initializes a new instance of the class. /// - protected OperationResult() => this.ActivityId = OperationResult.Generate(11); + protected OperationResult() => this.ActivityId = Generate(11); /// /// Gets or sets the activity identifier. @@ -63,12 +67,10 @@ public abstract class OperationResult public static OperationResult CreateResult( TResult result, Exception error) - { - return new OperationResult() + => new() { Result = result, }; - } /// /// Creates the result. @@ -76,14 +78,14 @@ public static OperationResult CreateResult( /// The type of the result. /// The result. /// OperationResult. - public static OperationResult CreateResult(TResult result) => OperationResult.CreateResult(result, null); + public static OperationResult CreateResult(TResult result) => CreateResult(result, null); /// /// Creates the result. /// /// The type of the result. /// OperationResult. - public static OperationResult CreateResult() => OperationResult.CreateResult(default, null); + public static OperationResult CreateResult() => CreateResult(default, null); /// /// Appends the log. @@ -98,7 +100,7 @@ public void AppendLog(string messageLog) if (messageLog.Length > 500) { - this._logs.Add(messageLog.Substring(0, 500)); + this._logs.Add(messageLog[..500]); } this._logs.Add(messageLog); diff --git a/Shared/Blog.Core/Infrastructure/OperationResults/OperationResultExtensions.cs b/Shared/Blog.Core/Infrastructure/OperationResults/OperationResultExtensions.cs index 96d3ed0c..717eb982 100644 --- a/Shared/Blog.Core/Infrastructure/OperationResults/OperationResultExtensions.cs +++ b/Shared/Blog.Core/Infrastructure/OperationResults/OperationResultExtensions.cs @@ -1,9 +1,13 @@ -namespace Blog.Core.Infrastructure.OperationResults; +// +// Copyright (c) PlaceholderCompany. All rights reserved. +// +namespace Blog.Core.Infrastructure.OperationResults; + +using Interfaces; using System; using System.Linq; using System.Text; -using Interfaces; /// /// Operation result extensions. diff --git a/Shared/Blog.Core/Infrastructure/Pagination/PagedListResult.cs b/Shared/Blog.Core/Infrastructure/Pagination/PagedListResult.cs index ffff3cb5..70ce6b26 100644 --- a/Shared/Blog.Core/Infrastructure/Pagination/PagedListResult.cs +++ b/Shared/Blog.Core/Infrastructure/Pagination/PagedListResult.cs @@ -13,12 +13,12 @@ namespace Blog.Core.Infrastructure.Pagination; public class PagedListResult { /// - /// Gets or sets a value indicating whether has next value. + /// Gets or sets a value indicating whether it has next value. /// public bool HasNext { get; set; } /// - /// Gets or sets a value indicating whether has previous value. + /// Gets or sets a value indicating whether it has previous value. /// public bool HasPrevious { get; set; } diff --git a/Shared/Blog.Core/Infrastructure/Pagination/SearchQuery.cs b/Shared/Blog.Core/Infrastructure/Pagination/SearchQuery.cs index 19fd8e47..fdf2ec01 100644 --- a/Shared/Blog.Core/Infrastructure/Pagination/SearchQuery.cs +++ b/Shared/Blog.Core/Infrastructure/Pagination/SearchQuery.cs @@ -4,10 +4,10 @@ namespace Blog.Core.Infrastructure.Pagination; +using Interfaces; using System; using System.Collections.Generic; using System.Linq.Expressions; -using Interfaces; /// /// Search query. @@ -16,7 +16,7 @@ namespace Blog.Core.Infrastructure.Pagination; public class SearchQuery { /// - /// Gets or sets sort criterias. + /// Gets or sets sort criteria. /// public List> SortCriterias { @@ -44,8 +44,8 @@ public List> SortCriterias /// public SearchQuery() { - this.Filters = new List>>(); - this.SortCriterias = new List>(); + this.Filters = []; + this.SortCriterias = []; } /// diff --git a/Shared/Blog.Core/Mapping/Interfaces/IMapFrom.cs b/Shared/Blog.Core/Mapping/Interfaces/IMapFrom.cs index 075e6d03..9f7aa211 100644 --- a/Shared/Blog.Core/Mapping/Interfaces/IMapFrom.cs +++ b/Shared/Blog.Core/Mapping/Interfaces/IMapFrom.cs @@ -8,6 +8,4 @@ namespace Blog.Core.Mapping.Interfaces; /// Map From interface. /// /// Type. -public interface IMapFrom -{ -} \ No newline at end of file +public interface IMapFrom; \ No newline at end of file diff --git a/Shared/Blog.Core/Mapping/Interfaces/IMapTo.cs b/Shared/Blog.Core/Mapping/Interfaces/IMapTo.cs index 870a610c..54dc5383 100644 --- a/Shared/Blog.Core/Mapping/Interfaces/IMapTo.cs +++ b/Shared/Blog.Core/Mapping/Interfaces/IMapTo.cs @@ -8,6 +8,4 @@ namespace Blog.Core.Mapping.Interfaces; /// Map To interface. /// /// Type. -public interface IMapTo -{ -} \ No newline at end of file +public interface IMapTo; \ No newline at end of file diff --git a/Shared/Blog.Core/Mapping/QueryableMappingExtensions.cs b/Shared/Blog.Core/Mapping/QueryableMappingExtensions.cs index 8dedee0f..3b4fba05 100644 --- a/Shared/Blog.Core/Mapping/QueryableMappingExtensions.cs +++ b/Shared/Blog.Core/Mapping/QueryableMappingExtensions.cs @@ -4,10 +4,10 @@ namespace Blog.Core.Mapping; +using AutoMapper.QueryableExtensions; using System; using System.Linq; using System.Linq.Expressions; -using AutoMapper.QueryableExtensions; /// /// Queryable mapping extensions. @@ -24,14 +24,9 @@ public static class QueryableMappingExtensions public static IQueryable To( this IQueryable source, params Expression>[] membersToExpand) - { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - return source.ProjectTo(null, membersToExpand); - } + => source == null + ? throw new ArgumentNullException(nameof(source)) + : source.ProjectTo(null, membersToExpand); /// /// To map. @@ -43,12 +38,7 @@ public static IQueryable To( public static IQueryable To( this IQueryable source, object parameters) - { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } - - return source.ProjectTo((AutoMapper.IConfigurationProvider)parameters); - } + => source == null + ? throw new ArgumentNullException(nameof(source)) + : source.ProjectTo((AutoMapper.IConfigurationProvider)parameters); } \ No newline at end of file diff --git a/Shared/Blog.Core/WebHelper.cs b/Shared/Blog.Core/WebHelper.cs index b4e43b36..dd59ee37 100644 --- a/Shared/Blog.Core/WebHelper.cs +++ b/Shared/Blog.Core/WebHelper.cs @@ -4,10 +4,10 @@ namespace Blog.Core; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; +using Configuration; +using Helpers; +using Infrastructure; +using Interfaces; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Http.Features; @@ -15,10 +15,10 @@ namespace Blog.Core; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; -using Configuration; -using Helpers; -using Infrastructure; -using Interfaces; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; /// /// Web helper. @@ -114,7 +114,7 @@ public virtual string GetCurrentIpAddress() if (!string.IsNullOrEmpty(this.hostingConfig.ForwardedHttpHeader)) { // but in some cases server use other HTTP header - // in these cases an administrator can specify a custom Forwarded HTTP header (e.g. CF-Connecting-IP, X-FORWARDED-PROTO, etc) + // in these cases an administrator can specify a custom Forwarded HTTP header (e.g. CF-Connecting-IP, X-FORWARDED-PROTO, etc.) forwardedHttpHeaderKey = this.hostingConfig.ForwardedHttpHeader; } @@ -258,11 +258,11 @@ public virtual bool IsStaticResource() string path = this.httpContextAccessor.HttpContext.Request.Path; - // a little workaround. FileExtensionContentTypeProvider contains most of static file extensions. So we can use it + // a little workaround. FileExtensionContentTypeProvider contains most static file extensions. So we can use it // source: https://github.com/aspnet/StaticFiles/blob/dev/src/Microsoft.AspNetCore.StaticFiles/FileExtensionContentTypeProvider.cs // if it can return content type, then it's a static file var contentTypeProvider = new FileExtensionContentTypeProvider(); - return contentTypeProvider.TryGetContentType(path, out string _); + return contentTypeProvider.TryGetContentType(path, out var _); } /// @@ -333,14 +333,9 @@ public virtual string RemoveQueryString(string url, string key, string value = n /// public virtual T QueryString(string name) { - if (!this.IsRequestAvailable()) - { - return default(T); - } - - if (StringValues.IsNullOrEmpty(this.httpContextAccessor.HttpContext.Request.Query[name])) + if (!this.IsRequestAvailable() || StringValues.IsNullOrEmpty(this.httpContextAccessor.HttpContext.Request.Query[name])) { - return default(T); + return default; } return CommonHelper.To(this.httpContextAccessor.HttpContext.Request.Query[name].ToString()); @@ -429,7 +424,7 @@ protected virtual bool IsIpAddressSet(IPAddress address) } /// - /// Try write web config. + /// Try to write web config. /// /// bool. protected virtual bool TryWriteWebConfig()