From 06874e4a2b1a4e58e7c718827665410bb3ebdf3f Mon Sep 17 00:00:00 2001 From: mikaal-anwar Date: Sat, 15 Aug 2020 20:15:28 +0500 Subject: [PATCH] Code cleanup and refactoring --- .../Configuration/CorrelationMiddleware.cs | 10 +-- .../Configuration/ExecutionContextAccessor.cs | 6 +- .../Configuration/SwaggerExtensions.cs | 12 +-- .../Customers/CustomersController.cs | 16 ++-- .../Orders/CustomerOrderRequest.cs | 4 +- .../Orders/CustomerOrdersController.cs | 36 ++++----- src/SampleProject.API/Program.cs | 8 +- ...ssRuleValidationExceptionProblemDetails.cs | 8 +- .../SeedWork/InvalidCommandProblemDetails.cs | 8 +- src/SampleProject.API/Startup.cs | 30 ++++---- .../Configuration/Commands/CommandBase.cs | 8 +- .../Configuration/Commands/ICommand.cs | 4 +- .../Commands/InternalCommandBase.cs | 6 +- .../DomainEvents/DomainNotificationBase.cs | 9 +-- .../DomainEvents/IDomainEventNotification.cs | 4 +- .../Configuration/Emails/EmailMessage.cs | 8 +- .../Processing/ICommandsScheduler.cs | 5 +- .../Validation/CommandValidationBehavior.cs | 48 ++++++------ .../Validation/InvalidCommandException.cs | 2 +- .../CustomerUniquenessChecker.cs | 4 +- .../GetCustomerDetailsQuery.cs | 4 +- .../GetCustomerDetailsQueryHandler.cs | 8 +- .../CustomerRegisteredNotification.cs | 4 +- .../CustomerRegisteredNotificationHandler.cs | 8 +- .../MarkCustomerAsWelcomedCommandHandler.cs | 8 +- .../MarkCustomerAsWelcomedCommand.cs | 4 +- .../RegisterCustomerCommand.cs | 9 +-- .../RegisterCustomerCommandHandler.cs | 19 +++-- .../ChangeCustomerOrderCommand.cs | 19 +++-- .../ChangeCustomerOrderCommandHandler.cs | 30 ++++---- .../GetCustomerOrderDetailsQuery.cs | 7 +- .../GetCustomerOrderDetailsQueryHandler.cs | 15 ++-- .../GetCustomerOrdersQuery.cs | 7 +- .../GetCustomerOrdersQueryHandler.cs | 31 ++++---- .../OrderPlacedDomainEventHandler.cs | 10 +-- .../OrderPlacedNotification.cs | 8 +- .../OrderPlacedNotificationHandler.cs | 22 +++--- .../PlaceCustomerOrderCommand.cs | 15 ++-- .../PlaceCustomerOrderCommandHandler.cs | 34 ++++----- .../PlaceCustomerOrderCommandValidator.cs | 2 +- .../PlaceCustomerOrder/ProductDtoValidator.cs | 2 +- .../ProductPriceProvider.cs | 10 +-- .../Orders/ProductDto.cs | 9 +-- .../RemoveCustomerOrderCommand.cs | 9 +-- .../RemoveCustomerOrderCommandHandler.cs | 10 +-- .../Payments/PaymentCreatedNotification.cs | 4 +- .../PaymentCreatedNotificationHandler.cs | 8 +- .../SendEmailAfterPaymentCommand.cs | 6 +- .../SendEmailAfterPaymentCommandHandler.cs | 12 +-- .../Customers/Customer.cs | 42 +++++------ .../Customers/CustomerId.cs | 4 +- .../Customers/CustomerRegisteredEvent.cs | 2 +- .../Orders/Events/OrderChangedEvent.cs | 2 +- .../Orders/Events/OrderPlacedEvent.cs | 11 ++- .../Orders/Events/OrderRemovedEvent.cs | 2 +- .../Customers/Orders/ICustomerRepository.cs | 3 +- .../Customers/Orders/Order.cs | 74 +++++++++---------- .../Customers/Orders/OrderId.cs | 4 +- .../Customers/Orders/OrderProduct.cs | 25 +++---- ...notOrderMoreThan2OrdersOnTheSameDayRule.cs | 8 +- .../Rules/CustomerEmailMustBeUniqueRule.cs | 7 +- .../OrderMustHaveAtLeastOneProductRule.cs | 10 ++- .../ForeignExchange/ConversionRate.cs | 11 ++- .../Payments/IPaymentRepository.cs | 3 +- src/SampleProject.Domain/Payments/Payment.cs | 24 +++--- .../Payments/PaymentCreatedEvent.cs | 7 +- .../Payments/PaymentId.cs | 4 +- .../Products/IProductRepository.cs | 3 +- src/SampleProject.Domain/Products/Product.cs | 7 +- .../Products/ProductId.cs | 4 +- .../Products/ProductPrice.cs | 2 +- .../BusinessRuleValidationException.cs | 2 +- .../SeedWork/DomainEventBase.cs | 2 +- src/SampleProject.Domain/SeedWork/Entity.cs | 2 +- .../SeedWork/IAggregateRoot.cs | 2 +- .../SeedWork/IDomainEvent.cs | 4 +- .../SeedWork/TypedIdValueBase.cs | 10 ++- .../SeedWork/ValueObject.cs | 27 ++++--- .../SharedKernel/MoneyValue.cs | 8 +- .../MoneyValueMustHaveCurrencyRule.cs | 5 +- ...ionMustBePerformedOnTheSameCurrencyRule.cs | 5 +- .../SharedKernel/SystemClock.cs | 10 ++- .../ApplicationStartup.cs | 40 +++++----- .../Caching/CachingModule.cs | 6 +- .../Caching/MemoryCacheStore.cs | 16 ++-- .../Database/DataAccessModule.cs | 5 +- .../Database/SqlConnectionFactory.cs | 19 +++-- .../CustomerEntityTypeConfiguration.cs | 12 +-- .../Domain/Customers/CustomerRepository.cs | 14 ++-- .../ForeignExchanges/ConversionRatesCache.cs | 6 +- .../ForeignExchanges/ForeignExchange.cs | 19 ++--- .../PaymentEntityTypeConfiguration.cs | 6 +- .../Domain/Payments/PaymentRepository.cs | 12 +-- .../ProductEntityTypeConfiguration.cs | 2 +- .../Domain/Products/ProductRepository.cs | 16 ++-- .../Domain/UnitOfWork.cs | 16 ++-- .../Emails/EmailModule.cs | 2 +- .../Emails/EmailSender.cs | 4 +- .../Logging/LoggingCommandHandlerDecorator.cs | 17 ++--- ...oggingCommandHandlerWithResultDecorator.cs | 17 ++--- .../Processing/AllConstructorFinder.cs | 6 +- .../Processing/Assemblies.cs | 4 +- .../Processing/CommandsExecutor.cs | 13 ++-- .../Processing/CommandsScheduler.cs | 10 +-- .../Processing/DomainEventsDispatcher.cs | 36 ++++----- ...sDispatcherNotificationHandlerDecorator.cs | 11 ++- .../InternalCommands/CommandsDispatcher.cs | 19 +++-- .../InternalCommandEntityTypeConfiguration.cs | 2 +- .../ProcessInternalCommandsCommand.cs | 1 - .../ProcessInternalCommandsCommandHandler.cs | 17 ++--- .../ProcessInternalCommandsJob.cs | 4 +- .../Processing/MediatorModule.cs | 31 +++++--- .../Processing/Outbox/OutboxMessage.cs | 10 +-- .../OutboxMessageEntityTypeConfiguration.cs | 2 +- .../Processing/Outbox/ProcessOutboxCommand.cs | 1 - .../Outbox/ProcessOutboxCommandHandler.cs | 21 +++--- .../Processing/Outbox/ProcessOutboxJob.cs | 4 +- .../Processing/ProcessingModule.cs | 7 +- .../Processing/QueriesExecutor.cs | 9 +-- .../UnitOfWorkCommandHandlerDecorator.cs | 21 +++--- ...OfWorkCommandHandlerWithResultDecorator.cs | 19 +++-- .../Quartz/JobFactory.cs | 8 +- .../Quartz/QuartzModule.cs | 4 +- .../SeedWork/DbSetExtensions.cs | 4 +- .../StronglyTypedIdValueConverterSelector.cs | 20 ++--- .../SeedWork/TypedIdValueConverter.cs | 11 ++- .../Customers/CustomersTests.cs | 18 ++--- .../Orders/OrdersTests.cs | 34 ++++----- .../SeedWork/CacheStore.cs | 7 +- .../SeedWork/ExecutionContextMock.cs | 4 +- .../SeedWork/OutboxMessagesHelper.cs | 14 ++-- .../SeedWork/TestBase.cs | 16 ++-- .../Customers/CustomerFactory.cs | 4 +- .../Customers/CustomerRegistrationTests.cs | 6 +- .../Customers/PlaceOrderTests.cs | 61 ++++++++------- .../SeedWork/DomainEventsTestHelper.cs | 24 +++--- .../SeedWork/TestBase.cs | 16 ++-- .../SharedKernel/MoneyValueTests.cs | 20 ++--- 138 files changed, 828 insertions(+), 826 deletions(-) diff --git a/src/SampleProject.API/Configuration/CorrelationMiddleware.cs b/src/SampleProject.API/Configuration/CorrelationMiddleware.cs index 96e457b..ac5e6aa 100644 --- a/src/SampleProject.API/Configuration/CorrelationMiddleware.cs +++ b/src/SampleProject.API/Configuration/CorrelationMiddleware.cs @@ -1,6 +1,6 @@ -using System; +using Microsoft.AspNetCore.Http; +using System; using System.Threading.Tasks; -using Microsoft.AspNetCore.Http; namespace SampleProject.API.Configuration { @@ -13,19 +13,19 @@ internal class CorrelationMiddleware public CorrelationMiddleware( RequestDelegate next) { - this._next = next; + _next = next; } public async Task Invoke(HttpContext context) { - var correlationId = Guid.NewGuid(); + Guid correlationId = Guid.NewGuid(); if (context.Request != null) { context.Request.Headers.Add(CorrelationHeaderKey, correlationId.ToString()); } - await this._next.Invoke(context); + await _next.Invoke(context); } } } \ No newline at end of file diff --git a/src/SampleProject.API/Configuration/ExecutionContextAccessor.cs b/src/SampleProject.API/Configuration/ExecutionContextAccessor.cs index d338de9..11b211c 100644 --- a/src/SampleProject.API/Configuration/ExecutionContextAccessor.cs +++ b/src/SampleProject.API/Configuration/ExecutionContextAccessor.cs @@ -1,7 +1,7 @@ -using System; -using System.Linq; -using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http; using SampleProject.Application.Configuration; +using System; +using System.Linq; namespace SampleProject.API.Configuration { diff --git a/src/SampleProject.API/Configuration/SwaggerExtensions.cs b/src/SampleProject.API/Configuration/SwaggerExtensions.cs index 93c9bdd..96dccd2 100644 --- a/src/SampleProject.API/Configuration/SwaggerExtensions.cs +++ b/src/SampleProject.API/Configuration/SwaggerExtensions.cs @@ -1,8 +1,8 @@ -using System; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; +using System; using System.IO; using System.Reflection; -using Microsoft.AspNetCore.Builder; -using Microsoft.Extensions.DependencyInjection; namespace SampleProject.API.Configuration { @@ -19,9 +19,9 @@ internal static IServiceCollection AddSwaggerDocumentation(this IServiceCollecti Description = "Sample .NET Core REST API CQRS implementation with raw SQL and DDD using Clean Architecture.", }); - var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; - var commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + ".XML"; - var commentsFile = Path.Combine(baseDirectory, commentsFileName); + string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; + string commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + ".XML"; + string commentsFile = Path.Combine(baseDirectory, commentsFileName); options.IncludeXmlComments(commentsFile); }); diff --git a/src/SampleProject.API/Customers/CustomersController.cs b/src/SampleProject.API/Customers/CustomersController.cs index 6cce5b4..632a44c 100644 --- a/src/SampleProject.API/Customers/CustomersController.cs +++ b/src/SampleProject.API/Customers/CustomersController.cs @@ -1,9 +1,9 @@ -using System.Net; -using System.Threading.Tasks; -using MediatR; +using MediatR; using Microsoft.AspNetCore.Mvc; using SampleProject.Application.Customers; using SampleProject.Application.Customers.RegisterCustomer; +using System.Net; +using System.Threading.Tasks; namespace SampleProject.API.Customers { @@ -15,7 +15,7 @@ public class CustomersController : Controller public CustomersController(IMediator mediator) { - this._mediator = mediator; + _mediator = mediator; } /// @@ -24,11 +24,11 @@ public CustomersController(IMediator mediator) [Route("")] [HttpPost] [ProducesResponseType(typeof(CustomerDto), (int)HttpStatusCode.Created)] - public async Task RegisterCustomer([FromBody]RegisterCustomerRequest request) + public async Task RegisterCustomer([FromBody] RegisterCustomerRequest request) { - var customer = await _mediator.Send(new RegisterCustomerCommand(request.Email, request.Name)); + CustomerDto customer = await _mediator.Send(new RegisterCustomerCommand(request.Email, request.Name)); - return Created(string.Empty, customer); - } + return Created(string.Empty, customer); + } } } diff --git a/src/SampleProject.API/Orders/CustomerOrderRequest.cs b/src/SampleProject.API/Orders/CustomerOrderRequest.cs index 3eb618b..15e8a4d 100644 --- a/src/SampleProject.API/Orders/CustomerOrderRequest.cs +++ b/src/SampleProject.API/Orders/CustomerOrderRequest.cs @@ -1,5 +1,5 @@ -using System.Collections.Generic; -using SampleProject.Application.Orders; +using SampleProject.Application.Orders; +using System.Collections.Generic; namespace SampleProject.API.Orders { diff --git a/src/SampleProject.API/Orders/CustomerOrdersController.cs b/src/SampleProject.API/Orders/CustomerOrdersController.cs index b6750c4..898d566 100644 --- a/src/SampleProject.API/Orders/CustomerOrdersController.cs +++ b/src/SampleProject.API/Orders/CustomerOrdersController.cs @@ -1,14 +1,14 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Threading.Tasks; -using MediatR; +using MediatR; using Microsoft.AspNetCore.Mvc; using SampleProject.Application.Orders.ChangeCustomerOrder; using SampleProject.Application.Orders.GetCustomerOrderDetails; using SampleProject.Application.Orders.GetCustomerOrders; using SampleProject.Application.Orders.PlaceCustomerOrder; using SampleProject.Application.Orders.RemoveCustomerOrder; +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; namespace SampleProject.API.Orders { @@ -20,7 +20,7 @@ public class CustomerOrdersController : Controller public CustomerOrdersController(IMediator mediator) { - this._mediator = mediator; + _mediator = mediator; } /// @@ -33,7 +33,7 @@ public CustomerOrdersController(IMediator mediator) [ProducesResponseType(typeof(List), (int)HttpStatusCode.OK)] public async Task GetCustomerOrders(Guid customerId) { - var orders = await _mediator.Send(new GetCustomerOrdersQuery(customerId)); + List orders = await _mediator.Send(new GetCustomerOrdersQuery(customerId)); return Ok(orders); } @@ -46,9 +46,9 @@ public async Task GetCustomerOrders(Guid customerId) [HttpGet] [ProducesResponseType(typeof(OrderDetailsDto), (int)HttpStatusCode.OK)] public async Task GetCustomerOrderDetails( - [FromRoute]Guid orderId) + [FromRoute] Guid orderId) { - var orderDetails = await _mediator.Send(new GetCustomerOrderDetailsQuery(orderId)); + OrderDetailsDto orderDetails = await _mediator.Send(new GetCustomerOrderDetailsQuery(orderId)); return Ok(orderDetails); } @@ -63,12 +63,12 @@ public async Task GetCustomerOrderDetails( [HttpPost] [ProducesResponseType((int)HttpStatusCode.Created)] public async Task AddCustomerOrder( - [FromRoute]Guid customerId, - [FromBody]CustomerOrderRequest request) + [FromRoute] Guid customerId, + [FromBody] CustomerOrderRequest request) { - await _mediator.Send(new PlaceCustomerOrderCommand(customerId, request.Products, request.Currency)); + await _mediator.Send(new PlaceCustomerOrderCommand(customerId, request.Products, request.Currency)); - return Created(string.Empty, null); + return Created(string.Empty, null); } /// @@ -81,9 +81,9 @@ public async Task AddCustomerOrder( [HttpPut] [ProducesResponseType((int)HttpStatusCode.OK)] public async Task ChangeCustomerOrder( - [FromRoute]Guid customerId, - [FromRoute]Guid orderId, - [FromBody]CustomerOrderRequest request) + [FromRoute] Guid customerId, + [FromRoute] Guid orderId, + [FromBody] CustomerOrderRequest request) { await _mediator.Send(new ChangeCustomerOrderCommand(customerId, orderId, request.Products, request.Currency)); @@ -99,8 +99,8 @@ public async Task ChangeCustomerOrder( [HttpDelete] [ProducesResponseType(typeof(List), (int)HttpStatusCode.OK)] public async Task RemoveCustomerOrder( - [FromRoute]Guid customerId, - [FromRoute]Guid orderId) + [FromRoute] Guid customerId, + [FromRoute] Guid orderId) { await _mediator.Send(new RemoveCustomerOrderCommand(customerId, orderId)); diff --git a/src/SampleProject.API/Program.cs b/src/SampleProject.API/Program.cs index 8c7aff0..6d6ddb0 100644 --- a/src/SampleProject.API/Program.cs +++ b/src/SampleProject.API/Program.cs @@ -10,8 +10,10 @@ public static void Main(string[] args) CreateWebHostBuilder(args).Build().Run(); } - public static IWebHostBuilder CreateWebHostBuilder(string[] args) => - WebHost.CreateDefaultBuilder(args) - .UseStartup(); + public static IWebHostBuilder CreateWebHostBuilder(string[] args) + { + return WebHost.CreateDefaultBuilder(args) +.UseStartup(); + } } } diff --git a/src/SampleProject.API/SeedWork/BusinessRuleValidationExceptionProblemDetails.cs b/src/SampleProject.API/SeedWork/BusinessRuleValidationExceptionProblemDetails.cs index f11d431..52bf23e 100644 --- a/src/SampleProject.API/SeedWork/BusinessRuleValidationExceptionProblemDetails.cs +++ b/src/SampleProject.API/SeedWork/BusinessRuleValidationExceptionProblemDetails.cs @@ -7,10 +7,10 @@ public class BusinessRuleValidationExceptionProblemDetails : Microsoft.AspNetCor { public BusinessRuleValidationExceptionProblemDetails(BusinessRuleValidationException exception) { - this.Title = "Business rule validation error"; - this.Status = StatusCodes.Status409Conflict; - this.Detail = exception.Details; - this.Type = "https://somedomain/business-rule-validation-error"; + Title = "Business rule validation error"; + Status = StatusCodes.Status409Conflict; + Detail = exception.Details; + Type = "https://somedomain/business-rule-validation-error"; } } } \ No newline at end of file diff --git a/src/SampleProject.API/SeedWork/InvalidCommandProblemDetails.cs b/src/SampleProject.API/SeedWork/InvalidCommandProblemDetails.cs index 51fc0c3..ed36ee8 100644 --- a/src/SampleProject.API/SeedWork/InvalidCommandProblemDetails.cs +++ b/src/SampleProject.API/SeedWork/InvalidCommandProblemDetails.cs @@ -7,10 +7,10 @@ public class InvalidCommandProblemDetails : Microsoft.AspNetCore.Mvc.ProblemDeta { public InvalidCommandProblemDetails(InvalidCommandException exception) { - this.Title = exception.Message; - this.Status = StatusCodes.Status400BadRequest; - this.Detail = exception.Details; - this.Type = "https://somedomain/validation-error"; + Title = exception.Message; + Status = StatusCodes.Status400BadRequest; + Detail = exception.Details; + Type = "https://somedomain/validation-error"; } } } \ No newline at end of file diff --git a/src/SampleProject.API/Startup.cs b/src/SampleProject.API/Startup.cs index 4a091de..6267a58 100644 --- a/src/SampleProject.API/Startup.cs +++ b/src/SampleProject.API/Startup.cs @@ -1,6 +1,4 @@ -using System; -using System.Linq; -using Hellang.Middleware.ProblemDetails; +using Hellang.Middleware.ProblemDetails; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; @@ -10,19 +8,21 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SampleProject.API.Configuration; -using SampleProject.Application.Configuration.Validation; using SampleProject.API.SeedWork; using SampleProject.Application.Configuration; using SampleProject.Application.Configuration.Emails; +using SampleProject.Application.Configuration.Validation; using SampleProject.Domain.SeedWork; using SampleProject.Infrastructure; using SampleProject.Infrastructure.Caching; using Serilog; using Serilog.Formatting.Compact; +using System; +using System.Linq; [assembly: UserSecretsId("54e8eb06-aaa1-4fff-9f05-3ced1cb623c2")] namespace SampleProject.API -{ +{ public class Startup { private readonly IConfiguration _configuration; @@ -36,7 +36,7 @@ public Startup(IWebHostEnvironment env) _logger = ConfigureLogger(); _logger.Information("Logger configured"); - this._configuration = new ConfigurationBuilder() + _configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{env.EnvironmentName}.json") .AddJsonFile($"hosting.{env.EnvironmentName}.json") @@ -47,7 +47,7 @@ public Startup(IWebHostEnvironment env) public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddControllers(); - + services.AddMemoryCache(); services.AddSwaggerDocumentation(); @@ -57,20 +57,20 @@ public IServiceProvider ConfigureServices(IServiceCollection services) x.Map(ex => new InvalidCommandProblemDetails(ex)); x.Map(ex => new BusinessRuleValidationExceptionProblemDetails(ex)); }); - + services.AddHttpContextAccessor(); - var serviceProvider = services.BuildServiceProvider(); + ServiceProvider serviceProvider = services.BuildServiceProvider(); IExecutionContextAccessor executionContextAccessor = new ExecutionContextAccessor(serviceProvider.GetService()); - var children = this._configuration.GetSection("Caching").GetChildren(); - var cachingConfiguration = children.ToDictionary(child => child.Key, child => TimeSpan.Parse(child.Value)); - var emailsSettings = _configuration.GetSection("EmailsSettings").Get(); - var memoryCache = serviceProvider.GetService(); + System.Collections.Generic.IEnumerable children = _configuration.GetSection("Caching").GetChildren(); + System.Collections.Generic.Dictionary cachingConfiguration = children.ToDictionary(child => child.Key, child => TimeSpan.Parse(child.Value)); + EmailsSettings emailsSettings = _configuration.GetSection("EmailsSettings").Get(); + IMemoryCache memoryCache = serviceProvider.GetService(); return ApplicationStartup.Initialize( - services, - this._configuration[OrdersConnectionString], + services, + _configuration[OrdersConnectionString], new MemoryCacheStore(memoryCache, cachingConfiguration), null, emailsSettings, diff --git a/src/SampleProject.Application/Configuration/Commands/CommandBase.cs b/src/SampleProject.Application/Configuration/Commands/CommandBase.cs index 0fef68f..0ffcc79 100644 --- a/src/SampleProject.Application/Configuration/Commands/CommandBase.cs +++ b/src/SampleProject.Application/Configuration/Commands/CommandBase.cs @@ -8,12 +8,12 @@ public class CommandBase : ICommand public CommandBase() { - this.Id = Guid.NewGuid(); + Id = Guid.NewGuid(); } protected CommandBase(Guid id) { - this.Id = id; + Id = id; } } @@ -23,12 +23,12 @@ public abstract class CommandBase : ICommand protected CommandBase() { - this.Id = Guid.NewGuid(); + Id = Guid.NewGuid(); } protected CommandBase(Guid id) { - this.Id = id; + Id = id; } } } \ No newline at end of file diff --git a/src/SampleProject.Application/Configuration/Commands/ICommand.cs b/src/SampleProject.Application/Configuration/Commands/ICommand.cs index 5bade4c..1fe5d66 100644 --- a/src/SampleProject.Application/Configuration/Commands/ICommand.cs +++ b/src/SampleProject.Application/Configuration/Commands/ICommand.cs @@ -1,5 +1,5 @@ -using System; -using MediatR; +using MediatR; +using System; namespace SampleProject.Application.Configuration.Commands { diff --git a/src/SampleProject.Application/Configuration/Commands/InternalCommandBase.cs b/src/SampleProject.Application/Configuration/Commands/InternalCommandBase.cs index 6d0473e..0416d57 100644 --- a/src/SampleProject.Application/Configuration/Commands/InternalCommandBase.cs +++ b/src/SampleProject.Application/Configuration/Commands/InternalCommandBase.cs @@ -8,7 +8,7 @@ public abstract class InternalCommandBase : ICommand protected InternalCommandBase(Guid id) { - this.Id = id; + Id = id; } } @@ -18,12 +18,12 @@ public abstract class InternalCommandBase : ICommand protected InternalCommandBase() { - this.Id = Guid.NewGuid(); + Id = Guid.NewGuid(); } protected InternalCommandBase(Guid id) { - this.Id = id; + Id = id; } } } \ No newline at end of file diff --git a/src/SampleProject.Application/Configuration/DomainEvents/DomainNotificationBase.cs b/src/SampleProject.Application/Configuration/DomainEvents/DomainNotificationBase.cs index 95027cd..173dc62 100644 --- a/src/SampleProject.Application/Configuration/DomainEvents/DomainNotificationBase.cs +++ b/src/SampleProject.Application/Configuration/DomainEvents/DomainNotificationBase.cs @@ -1,7 +1,6 @@ -using System; -using MediatR; -using Newtonsoft.Json; +using Newtonsoft.Json; using SampleProject.Domain.SeedWork; +using System; namespace SampleProject.Application.Configuration.DomainEvents { @@ -14,8 +13,8 @@ public class DomainNotificationBase : IDomainEventNotification where T : I public DomainNotificationBase(T domainEvent) { - this.Id = Guid.NewGuid(); - this.DomainEvent = domainEvent; + Id = Guid.NewGuid(); + DomainEvent = domainEvent; } } } \ No newline at end of file diff --git a/src/SampleProject.Application/Configuration/DomainEvents/IDomainEventNotification.cs b/src/SampleProject.Application/Configuration/DomainEvents/IDomainEventNotification.cs index 43d3b2b..a9e8a68 100644 --- a/src/SampleProject.Application/Configuration/DomainEvents/IDomainEventNotification.cs +++ b/src/SampleProject.Application/Configuration/DomainEvents/IDomainEventNotification.cs @@ -1,5 +1,5 @@ -using System; -using MediatR; +using MediatR; +using System; namespace SampleProject.Application.Configuration.DomainEvents { diff --git a/src/SampleProject.Application/Configuration/Emails/EmailMessage.cs b/src/SampleProject.Application/Configuration/Emails/EmailMessage.cs index 558c6ac..b0ccc9b 100644 --- a/src/SampleProject.Application/Configuration/Emails/EmailMessage.cs +++ b/src/SampleProject.Application/Configuration/Emails/EmailMessage.cs @@ -9,13 +9,13 @@ public struct EmailMessage public string Content { get; } public EmailMessage( - string from, + string from, string to, string content) { - this.From = from; - this.To = to; - this.Content = content; + From = from; + To = to; + Content = content; } } } \ No newline at end of file diff --git a/src/SampleProject.Application/Configuration/Processing/ICommandsScheduler.cs b/src/SampleProject.Application/Configuration/Processing/ICommandsScheduler.cs index f1765de..d261b5b 100644 --- a/src/SampleProject.Application/Configuration/Processing/ICommandsScheduler.cs +++ b/src/SampleProject.Application/Configuration/Processing/ICommandsScheduler.cs @@ -1,6 +1,5 @@ -using System.Threading.Tasks; -using MediatR; -using SampleProject.Application.Configuration.Commands; +using SampleProject.Application.Configuration.Commands; +using System.Threading.Tasks; namespace SampleProject.Application.Configuration.Processing { diff --git a/src/SampleProject.Application/Configuration/Validation/CommandValidationBehavior.cs b/src/SampleProject.Application/Configuration/Validation/CommandValidationBehavior.cs index 4542d60..fa8fb47 100644 --- a/src/SampleProject.Application/Configuration/Validation/CommandValidationBehavior.cs +++ b/src/SampleProject.Application/Configuration/Validation/CommandValidationBehavior.cs @@ -1,45 +1,45 @@ -using System.Collections.Generic; +using FluentValidation; +using MediatR; +using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; -using FluentValidation; -using MediatR; namespace SampleProject.Application.Configuration.Validation { -public class CommandValidationBehavior : IPipelineBehavior -{ - private readonly IList> _validators; - - public CommandValidationBehavior(IList> validators) + public class CommandValidationBehavior : IPipelineBehavior { - this._validators = validators; - } + private readonly IList> _validators; - public Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) - { - var errors = _validators + public CommandValidationBehavior(IList> validators) + { + _validators = validators; + } + + public Task Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate next) + { + List errors = _validators .Select(v => v.Validate(request)) .SelectMany(result => result.Errors) .Where(error => error != null) .ToList(); - if (errors.Any()) - { - var errorBuilder = new StringBuilder(); + if (errors.Any()) + { + StringBuilder errorBuilder = new StringBuilder(); - errorBuilder.AppendLine("Invalid command, reason: "); + errorBuilder.AppendLine("Invalid command, reason: "); - foreach (var error in errors) - { - errorBuilder.AppendLine(error.ErrorMessage); + foreach (FluentValidation.Results.ValidationFailure error in errors) + { + errorBuilder.AppendLine(error.ErrorMessage); + } + + throw new InvalidCommandException(errorBuilder.ToString(), null); } - throw new InvalidCommandException(errorBuilder.ToString(), null); + return next(); } - - return next(); } -} } \ No newline at end of file diff --git a/src/SampleProject.Application/Configuration/Validation/InvalidCommandException.cs b/src/SampleProject.Application/Configuration/Validation/InvalidCommandException.cs index 11db725..2baa378 100644 --- a/src/SampleProject.Application/Configuration/Validation/InvalidCommandException.cs +++ b/src/SampleProject.Application/Configuration/Validation/InvalidCommandException.cs @@ -7,7 +7,7 @@ public class InvalidCommandException : Exception public string Details { get; } public InvalidCommandException(string message, string details) : base(message) { - this.Details = details; + Details = details; } } } \ No newline at end of file diff --git a/src/SampleProject.Application/Customers/DomainServices/CustomerUniquenessChecker.cs b/src/SampleProject.Application/Customers/DomainServices/CustomerUniquenessChecker.cs index 415d118..f408d60 100644 --- a/src/SampleProject.Application/Customers/DomainServices/CustomerUniquenessChecker.cs +++ b/src/SampleProject.Application/Customers/DomainServices/CustomerUniquenessChecker.cs @@ -15,12 +15,12 @@ public CustomerUniquenessChecker(ISqlConnectionFactory sqlConnectionFactory) public bool IsUnique(string customerEmail) { - var connection = this._sqlConnectionFactory.GetOpenConnection(); + System.Data.IDbConnection connection = _sqlConnectionFactory.GetOpenConnection(); const string sql = "SELECT TOP 1 1" + "FROM [orders].[Customers] AS [Customer] " + "WHERE [Customer].[Email] = @Email"; - var customersNumber = connection.QuerySingleOrDefault(sql, + int? customersNumber = connection.QuerySingleOrDefault(sql, new { Email = customerEmail diff --git a/src/SampleProject.Application/Customers/GetCustomerDetails/GetCustomerDetailsQuery.cs b/src/SampleProject.Application/Customers/GetCustomerDetails/GetCustomerDetailsQuery.cs index 53a4bd4..c03d544 100644 --- a/src/SampleProject.Application/Customers/GetCustomerDetails/GetCustomerDetailsQuery.cs +++ b/src/SampleProject.Application/Customers/GetCustomerDetails/GetCustomerDetailsQuery.cs @@ -1,5 +1,5 @@ -using System; -using SampleProject.Application.Configuration.Queries; +using SampleProject.Application.Configuration.Queries; +using System; namespace SampleProject.Application.Customers.GetCustomerDetails { diff --git a/src/SampleProject.Application/Customers/GetCustomerDetails/GetCustomerDetailsQueryHandler.cs b/src/SampleProject.Application/Customers/GetCustomerDetails/GetCustomerDetailsQueryHandler.cs index 030cab1..d2780f6 100644 --- a/src/SampleProject.Application/Customers/GetCustomerDetails/GetCustomerDetailsQueryHandler.cs +++ b/src/SampleProject.Application/Customers/GetCustomerDetails/GetCustomerDetailsQueryHandler.cs @@ -1,8 +1,8 @@ -using System.Threading; -using System.Threading.Tasks; -using Dapper; +using Dapper; using SampleProject.Application.Configuration.Data; using SampleProject.Application.Configuration.Queries; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Application.Customers.GetCustomerDetails { @@ -25,7 +25,7 @@ public Task Handle(GetCustomerDetailsQuery request, Cancella "FROM orders.v_Customers AS [Customer] " + "WHERE [Customer].[Id] = @CustomerId "; - var connection = _sqlConnectionFactory.GetOpenConnection(); + System.Data.IDbConnection connection = _sqlConnectionFactory.GetOpenConnection(); return connection.QuerySingleAsync(sql, new { diff --git a/src/SampleProject.Application/Customers/IntegrationHandlers/CustomerRegisteredNotification.cs b/src/SampleProject.Application/Customers/IntegrationHandlers/CustomerRegisteredNotification.cs index e42ed53..d469e96 100644 --- a/src/SampleProject.Application/Customers/IntegrationHandlers/CustomerRegisteredNotification.cs +++ b/src/SampleProject.Application/Customers/IntegrationHandlers/CustomerRegisteredNotification.cs @@ -10,13 +10,13 @@ public class CustomerRegisteredNotification : DomainNotificationBase Handle(MarkCustomerAsWelcomedCommand command, CancellationToken cancellationToken) { - var customer = await this._customerRepository.GetByIdAsync(command.CustomerId); + Domain.Customers.Customer customer = await _customerRepository.GetByIdAsync(command.CustomerId); customer.MarkAsWelcomedByEmail(); diff --git a/src/SampleProject.Application/Customers/MarkCustomerAsWelcomedCommand.cs b/src/SampleProject.Application/Customers/MarkCustomerAsWelcomedCommand.cs index 6d99b77..d3fdd14 100644 --- a/src/SampleProject.Application/Customers/MarkCustomerAsWelcomedCommand.cs +++ b/src/SampleProject.Application/Customers/MarkCustomerAsWelcomedCommand.cs @@ -1,8 +1,8 @@ -using System; -using MediatR; +using MediatR; using Newtonsoft.Json; using SampleProject.Application.Configuration.Commands; using SampleProject.Domain.Customers; +using System; namespace SampleProject.Application.Customers { diff --git a/src/SampleProject.Application/Customers/RegisterCustomer/RegisterCustomerCommand.cs b/src/SampleProject.Application/Customers/RegisterCustomer/RegisterCustomerCommand.cs index 4a57d00..2fa94b6 100644 --- a/src/SampleProject.Application/Customers/RegisterCustomer/RegisterCustomerCommand.cs +++ b/src/SampleProject.Application/Customers/RegisterCustomer/RegisterCustomerCommand.cs @@ -1,5 +1,4 @@ -using MediatR; -using SampleProject.Application.Configuration.Commands; +using SampleProject.Application.Configuration.Commands; namespace SampleProject.Application.Customers.RegisterCustomer { @@ -11,8 +10,8 @@ public class RegisterCustomerCommand : CommandBase public RegisterCustomerCommand(string email, string name) { - this.Email = email; - this.Name = name; - } + Email = email; + Name = name; + } } } \ No newline at end of file diff --git a/src/SampleProject.Application/Customers/RegisterCustomer/RegisterCustomerCommandHandler.cs b/src/SampleProject.Application/Customers/RegisterCustomer/RegisterCustomerCommandHandler.cs index 4dee03c..2c995bf 100644 --- a/src/SampleProject.Application/Customers/RegisterCustomer/RegisterCustomerCommandHandler.cs +++ b/src/SampleProject.Application/Customers/RegisterCustomer/RegisterCustomerCommandHandler.cs @@ -1,10 +1,9 @@ -using System.Threading; -using System.Threading.Tasks; -using MediatR; -using SampleProject.Application.Configuration.Commands; +using SampleProject.Application.Configuration.Commands; using SampleProject.Domain.Customers; using SampleProject.Domain.Customers.Orders; using SampleProject.Domain.SeedWork; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Application.Customers.RegisterCustomer { @@ -15,22 +14,22 @@ public class RegisterCustomerCommandHandler : ICommandHandler Handle(RegisterCustomerCommand request, CancellationToken cancellationToken) { - var customer = Customer.CreateRegistered(request.Email, request.Name, this._customerUniquenessChecker); + Customer customer = Customer.CreateRegistered(request.Email, request.Name, _customerUniquenessChecker); - await this._customerRepository.AddAsync(customer); + await _customerRepository.AddAsync(customer); - await this._unitOfWork.CommitAsync(cancellationToken); + await _unitOfWork.CommitAsync(cancellationToken); return new CustomerDto { Id = customer.Id.Value }; } diff --git a/src/SampleProject.Application/Orders/ChangeCustomerOrder/ChangeCustomerOrderCommand.cs b/src/SampleProject.Application/Orders/ChangeCustomerOrder/ChangeCustomerOrderCommand.cs index a34b103..5fe4b36 100644 --- a/src/SampleProject.Application/Orders/ChangeCustomerOrder/ChangeCustomerOrderCommand.cs +++ b/src/SampleProject.Application/Orders/ChangeCustomerOrder/ChangeCustomerOrderCommand.cs @@ -1,8 +1,7 @@ -using System; -using System.Collections.Generic; -using MediatR; +using MediatR; using SampleProject.Application.Configuration.Commands; -using SampleProject.Domain.Products; +using System; +using System.Collections.Generic; namespace SampleProject.Application.Orders.ChangeCustomerOrder { @@ -17,15 +16,15 @@ public class ChangeCustomerOrderCommand : CommandBase public List Products { get; } public ChangeCustomerOrderCommand( - Guid customerId, + Guid customerId, Guid orderId, - List products, + List products, string currency) { - this.CustomerId = customerId; - this.OrderId = orderId; - this.Currency = currency; - this.Products = products; + CustomerId = customerId; + OrderId = orderId; + Currency = currency; + Products = products; } } } diff --git a/src/SampleProject.Application/Orders/ChangeCustomerOrder/ChangeCustomerOrderCommandHandler.cs b/src/SampleProject.Application/Orders/ChangeCustomerOrder/ChangeCustomerOrderCommandHandler.cs index f35f527..b30f06f 100644 --- a/src/SampleProject.Application/Orders/ChangeCustomerOrder/ChangeCustomerOrderCommandHandler.cs +++ b/src/SampleProject.Application/Orders/ChangeCustomerOrder/ChangeCustomerOrderCommandHandler.cs @@ -1,7 +1,4 @@ -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using MediatR; +using MediatR; using SampleProject.Application.Configuration.Commands; using SampleProject.Application.Configuration.Data; using SampleProject.Application.Orders.PlaceCustomerOrder; @@ -9,10 +6,13 @@ using SampleProject.Domain.Customers.Orders; using SampleProject.Domain.ForeignExchange; using SampleProject.Domain.Products; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Application.Orders.ChangeCustomerOrder { - internal sealed class ChangeCustomerOrderCommandHandler : ICommandHandler + internal sealed class ChangeCustomerOrderCommandHandler : ICommandHandler { private readonly ICustomerRepository _customerRepository; @@ -22,34 +22,34 @@ internal sealed class ChangeCustomerOrderCommandHandler : ICommandHandler Handle(ChangeCustomerOrderCommand request, CancellationToken cancellationToken) { - var customer = await this._customerRepository.GetByIdAsync(new CustomerId(request.CustomerId)); + Customer customer = await _customerRepository.GetByIdAsync(new CustomerId(request.CustomerId)); - var orderId = new OrderId(request.OrderId); + OrderId orderId = new OrderId(request.OrderId); - var conversionRates = this._foreignExchange.GetConversionRates(); - var orderProducts = request + System.Collections.Generic.List conversionRates = _foreignExchange.GetConversionRates(); + System.Collections.Generic.List orderProducts = request .Products .Select(x => new OrderProductData(new ProductId(x.Id), x.Quantity)) .ToList(); - var allProductPrices = + System.Collections.Generic.List allProductPrices = await ProductPriceProvider.GetAllProductPrices(_sqlConnectionFactory.GetOpenConnection()); customer.ChangeOrder( orderId, - allProductPrices, - orderProducts, - conversionRates, + allProductPrices, + orderProducts, + conversionRates, request.Currency); return Unit.Value; diff --git a/src/SampleProject.Application/Orders/GetCustomerOrderDetails/GetCustomerOrderDetailsQuery.cs b/src/SampleProject.Application/Orders/GetCustomerOrderDetails/GetCustomerOrderDetailsQuery.cs index 18c251b..ab109b0 100644 --- a/src/SampleProject.Application/Orders/GetCustomerOrderDetails/GetCustomerOrderDetailsQuery.cs +++ b/src/SampleProject.Application/Orders/GetCustomerOrderDetails/GetCustomerOrderDetailsQuery.cs @@ -1,6 +1,5 @@ -using System; -using MediatR; -using SampleProject.Application.Configuration.Queries; +using SampleProject.Application.Configuration.Queries; +using System; namespace SampleProject.Application.Orders.GetCustomerOrderDetails { @@ -10,7 +9,7 @@ public class GetCustomerOrderDetailsQuery : IQuery public GetCustomerOrderDetailsQuery(Guid orderId) { - this.OrderId = orderId; + OrderId = orderId; } } } \ No newline at end of file diff --git a/src/SampleProject.Application/Orders/GetCustomerOrderDetails/GetCustomerOrderDetailsQueryHandler.cs b/src/SampleProject.Application/Orders/GetCustomerOrderDetails/GetCustomerOrderDetailsQueryHandler.cs index 9e1b656..1d7f11a 100644 --- a/src/SampleProject.Application/Orders/GetCustomerOrderDetails/GetCustomerOrderDetailsQueryHandler.cs +++ b/src/SampleProject.Application/Orders/GetCustomerOrderDetails/GetCustomerOrderDetailsQueryHandler.cs @@ -1,9 +1,8 @@ -using System.Threading; -using System.Threading.Tasks; -using Dapper; -using MediatR; +using Dapper; using SampleProject.Application.Configuration.Data; using SampleProject.Application.Configuration.Queries; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Application.Orders.GetCustomerOrderDetails { @@ -13,12 +12,12 @@ internal sealed class GetCustomerOrderDetailsQueryHandler : IQueryHandler Handle(GetCustomerOrderDetailsQuery request, CancellationToken cancellationToken) { - var connection = this._sqlConnectionFactory.GetOpenConnection(); + System.Data.IDbConnection connection = _sqlConnectionFactory.GetOpenConnection(); const string sql = "SELECT " + "[Order].[Id], " + @@ -27,7 +26,7 @@ public async Task Handle(GetCustomerOrderDetailsQuery request, "[Order].[Currency] " + "FROM orders.v_Orders AS [Order] " + "WHERE [Order].Id = @OrderId"; - var order = await connection.QuerySingleOrDefaultAsync(sql, new { request.OrderId }); + OrderDetailsDto order = await connection.QuerySingleOrDefaultAsync(sql, new { request.OrderId }); const string sqlProducts = "SELECT " + "[Order].[ProductId] AS [Id], " + @@ -37,7 +36,7 @@ public async Task Handle(GetCustomerOrderDetailsQuery request, "[Order].[Currency] " + "FROM orders.v_OrderProducts AS [Order] " + "WHERE [Order].OrderId = @OrderId"; - var products = await connection.QueryAsync(sqlProducts, new { request.OrderId }); + System.Collections.Generic.IEnumerable products = await connection.QueryAsync(sqlProducts, new { request.OrderId }); order.Products = products.AsList(); diff --git a/src/SampleProject.Application/Orders/GetCustomerOrders/GetCustomerOrdersQuery.cs b/src/SampleProject.Application/Orders/GetCustomerOrders/GetCustomerOrdersQuery.cs index 7be1694..d98c746 100644 --- a/src/SampleProject.Application/Orders/GetCustomerOrders/GetCustomerOrdersQuery.cs +++ b/src/SampleProject.Application/Orders/GetCustomerOrders/GetCustomerOrdersQuery.cs @@ -1,7 +1,6 @@ -using System; +using SampleProject.Application.Configuration.Queries; +using System; using System.Collections.Generic; -using MediatR; -using SampleProject.Application.Configuration.Queries; namespace SampleProject.Application.Orders.GetCustomerOrders { @@ -11,7 +10,7 @@ public class GetCustomerOrdersQuery : IQuery> public GetCustomerOrdersQuery(Guid customerId) { - this.CustomerId = customerId; + CustomerId = customerId; } } } \ No newline at end of file diff --git a/src/SampleProject.Application/Orders/GetCustomerOrders/GetCustomerOrdersQueryHandler.cs b/src/SampleProject.Application/Orders/GetCustomerOrders/GetCustomerOrdersQueryHandler.cs index cacb6d6..54085ff 100644 --- a/src/SampleProject.Application/Orders/GetCustomerOrders/GetCustomerOrdersQueryHandler.cs +++ b/src/SampleProject.Application/Orders/GetCustomerOrders/GetCustomerOrdersQueryHandler.cs @@ -1,10 +1,9 @@ -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Dapper; -using MediatR; +using Dapper; using SampleProject.Application.Configuration.Data; using SampleProject.Application.Configuration.Queries; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Application.Orders.GetCustomerOrders { @@ -14,22 +13,22 @@ internal sealed class GetCustomerOrdersQueryHandler : IQueryHandler> Handle(GetCustomerOrdersQuery request, CancellationToken cancellationToken) { - var connection = this._sqlConnectionFactory.GetOpenConnection(); - const string sql = "SELECT " + - "[Order].[Id], " + - "[Order].[IsRemoved], " + - "[Order].[Value], " + - "[Order].[Currency] " + - "FROM orders.v_Orders AS [Order] " + - "WHERE [Order].CustomerId = @CustomerId"; - var orders = await connection.QueryAsync(sql, new {request.CustomerId}); + System.Data.IDbConnection connection = _sqlConnectionFactory.GetOpenConnection(); + const string sql = "SELECT " + + "[Order].[Id], " + + "[Order].[IsRemoved], " + + "[Order].[Value], " + + "[Order].[Currency] " + + "FROM orders.v_Orders AS [Order] " + + "WHERE [Order].CustomerId = @CustomerId"; + IEnumerable orders = await connection.QueryAsync(sql, new { request.CustomerId }); - return orders.AsList(); + return orders.AsList(); } } } \ No newline at end of file diff --git a/src/SampleProject.Application/Orders/PlaceCustomerOrder/OrderPlacedDomainEventHandler.cs b/src/SampleProject.Application/Orders/PlaceCustomerOrder/OrderPlacedDomainEventHandler.cs index 7e95a34..8f969f8 100644 --- a/src/SampleProject.Application/Orders/PlaceCustomerOrder/OrderPlacedDomainEventHandler.cs +++ b/src/SampleProject.Application/Orders/PlaceCustomerOrder/OrderPlacedDomainEventHandler.cs @@ -1,8 +1,8 @@ -using System.Threading; -using System.Threading.Tasks; -using MediatR; +using MediatR; using SampleProject.Domain.Customers.Orders.Events; using SampleProject.Domain.Payments; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Application.Orders.PlaceCustomerOrder { @@ -17,9 +17,9 @@ public OrderPlacedDomainEventHandler(IPaymentRepository paymentRepository) public async Task Handle(OrderPlacedEvent notification, CancellationToken cancellationToken) { - var newPayment = new Payment(notification.OrderId); + Payment newPayment = new Payment(notification.OrderId); - await this._paymentRepository.AddAsync(newPayment); + await _paymentRepository.AddAsync(newPayment); } } } \ No newline at end of file diff --git a/src/SampleProject.Application/Orders/PlaceCustomerOrder/OrderPlacedNotification.cs b/src/SampleProject.Application/Orders/PlaceCustomerOrder/OrderPlacedNotification.cs index f9bc0cf..39571d2 100644 --- a/src/SampleProject.Application/Orders/PlaceCustomerOrder/OrderPlacedNotification.cs +++ b/src/SampleProject.Application/Orders/PlaceCustomerOrder/OrderPlacedNotification.cs @@ -13,15 +13,15 @@ public class OrderPlacedNotification : DomainNotificationBase public OrderPlacedNotification(OrderPlacedEvent domainEvent) : base(domainEvent) { - this.OrderId = domainEvent.OrderId; - this.CustomerId = domainEvent.CustomerId; + OrderId = domainEvent.OrderId; + CustomerId = domainEvent.CustomerId; } [JsonConstructor] public OrderPlacedNotification(OrderId orderId, CustomerId customerId) : base(null) { - this.OrderId = orderId; - this.CustomerId = customerId; + OrderId = orderId; + CustomerId = customerId; } } } \ No newline at end of file diff --git a/src/SampleProject.Application/Orders/PlaceCustomerOrder/OrderPlacedNotificationHandler.cs b/src/SampleProject.Application/Orders/PlaceCustomerOrder/OrderPlacedNotificationHandler.cs index 8101e8b..ea9cae1 100644 --- a/src/SampleProject.Application/Orders/PlaceCustomerOrder/OrderPlacedNotificationHandler.cs +++ b/src/SampleProject.Application/Orders/PlaceCustomerOrder/OrderPlacedNotificationHandler.cs @@ -1,10 +1,10 @@ -using System.Threading; -using System.Threading.Tasks; -using Dapper; +using Dapper; using MediatR; using SampleProject.Application.Configuration.Data; using SampleProject.Application.Configuration.Emails; using SampleProject.Domain.Customers.Orders; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Application.Orders.PlaceCustomerOrder { @@ -15,8 +15,8 @@ public class OrderPlacedNotificationHandler : INotificationHandler(sql, + string customerEmail = await connection.QueryFirstAsync(sql, new { Id = request.CustomerId.Value }); - var emailMessage = new EmailMessage( - _emailsSettings.FromAddressEmail, - customerEmail, + EmailMessage emailMessage = new EmailMessage( + _emailsSettings.FromAddressEmail, + customerEmail, OrderNotificationsService.GetOrderEmailConfirmationDescription(request.OrderId)); - + await _emailSender.SendEmailAsync(emailMessage); } } diff --git a/src/SampleProject.Application/Orders/PlaceCustomerOrder/PlaceCustomerOrderCommand.cs b/src/SampleProject.Application/Orders/PlaceCustomerOrder/PlaceCustomerOrderCommand.cs index 4f77364..d5896e1 100644 --- a/src/SampleProject.Application/Orders/PlaceCustomerOrder/PlaceCustomerOrderCommand.cs +++ b/src/SampleProject.Application/Orders/PlaceCustomerOrder/PlaceCustomerOrderCommand.cs @@ -1,7 +1,6 @@ -using System; +using SampleProject.Application.Configuration.Commands; +using System; using System.Collections.Generic; -using MediatR; -using SampleProject.Application.Configuration.Commands; namespace SampleProject.Application.Orders.PlaceCustomerOrder { @@ -14,13 +13,13 @@ public class PlaceCustomerOrderCommand : CommandBase public string Currency { get; } public PlaceCustomerOrderCommand( - Guid customerId, - List products, + Guid customerId, + List products, string currency) { - this.CustomerId = customerId; - this.Products = products; - this.Currency = currency; + CustomerId = customerId; + Products = products; + Currency = currency; } } } \ No newline at end of file diff --git a/src/SampleProject.Application/Orders/PlaceCustomerOrder/PlaceCustomerOrderCommandHandler.cs b/src/SampleProject.Application/Orders/PlaceCustomerOrder/PlaceCustomerOrderCommandHandler.cs index f6ea7a1..ccde1c8 100644 --- a/src/SampleProject.Application/Orders/PlaceCustomerOrder/PlaceCustomerOrderCommandHandler.cs +++ b/src/SampleProject.Application/Orders/PlaceCustomerOrder/PlaceCustomerOrderCommandHandler.cs @@ -1,49 +1,49 @@ -using System; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using SampleProject.Application.Configuration.Commands; +using SampleProject.Application.Configuration.Commands; using SampleProject.Application.Configuration.Data; using SampleProject.Domain.Customers; using SampleProject.Domain.Customers.Orders; using SampleProject.Domain.ForeignExchange; using SampleProject.Domain.Products; +using System; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Application.Orders.PlaceCustomerOrder { public class PlaceCustomerOrderCommandHandler : ICommandHandler { private readonly ICustomerRepository _customerRepository; - + private readonly ISqlConnectionFactory _sqlConnectionFactory; - + private readonly IForeignExchange _foreignExchange; public PlaceCustomerOrderCommandHandler( ICustomerRepository customerRepository, - IForeignExchange foreignExchange, + IForeignExchange foreignExchange, ISqlConnectionFactory sqlConnectionFactory) { - this._customerRepository = customerRepository; - this._foreignExchange = foreignExchange; + _customerRepository = customerRepository; + _foreignExchange = foreignExchange; _sqlConnectionFactory = sqlConnectionFactory; } public async Task Handle(PlaceCustomerOrderCommand command, CancellationToken cancellationToken) { - var customer = await this._customerRepository.GetByIdAsync(new CustomerId(command.CustomerId)); + Customer customer = await _customerRepository.GetByIdAsync(new CustomerId(command.CustomerId)); - var allProductPrices = + System.Collections.Generic.List allProductPrices = await ProductPriceProvider.GetAllProductPrices(_sqlConnectionFactory.GetOpenConnection()); - var conversionRates = this._foreignExchange.GetConversionRates(); + System.Collections.Generic.List conversionRates = _foreignExchange.GetConversionRates(); - var orderProductsData = command + System.Collections.Generic.List orderProductsData = command .Products .Select(x => new OrderProductData(new ProductId(x.Id), x.Quantity)) - .ToList(); - - var orderId = customer.PlaceOrder( + .ToList(); + + OrderId orderId = customer.PlaceOrder( orderProductsData, allProductPrices, command.Currency, diff --git a/src/SampleProject.Application/Orders/PlaceCustomerOrder/PlaceCustomerOrderCommandValidator.cs b/src/SampleProject.Application/Orders/PlaceCustomerOrder/PlaceCustomerOrderCommandValidator.cs index c48f686..f11a7f7 100644 --- a/src/SampleProject.Application/Orders/PlaceCustomerOrder/PlaceCustomerOrderCommandValidator.cs +++ b/src/SampleProject.Application/Orders/PlaceCustomerOrder/PlaceCustomerOrderCommandValidator.cs @@ -10,7 +10,7 @@ public PlaceCustomerOrderCommandValidator() RuleFor(x => x.Products).NotEmpty().WithMessage("Products list is empty"); RuleForEach(x => x.Products).SetValidator(new ProductDtoValidator()); - this.RuleFor(x => x.Currency).Must(x => x == "USD" || x == "EUR") + RuleFor(x => x.Currency).Must(x => x == "USD" || x == "EUR") .WithMessage("At least one product has invalid currency"); } } diff --git a/src/SampleProject.Application/Orders/PlaceCustomerOrder/ProductDtoValidator.cs b/src/SampleProject.Application/Orders/PlaceCustomerOrder/ProductDtoValidator.cs index 7a3060c..702a2ff 100644 --- a/src/SampleProject.Application/Orders/PlaceCustomerOrder/ProductDtoValidator.cs +++ b/src/SampleProject.Application/Orders/PlaceCustomerOrder/ProductDtoValidator.cs @@ -6,7 +6,7 @@ public class ProductDtoValidator : AbstractValidator { public ProductDtoValidator() { - this.RuleFor(x => x.Quantity).GreaterThan(0) + RuleFor(x => x.Quantity).GreaterThan(0) .WithMessage("At least one product has invalid quantity"); } } diff --git a/src/SampleProject.Application/Orders/PlaceCustomerOrder/ProductPriceProvider.cs b/src/SampleProject.Application/Orders/PlaceCustomerOrder/ProductPriceProvider.cs index e9b87ef..c53eafe 100644 --- a/src/SampleProject.Application/Orders/PlaceCustomerOrder/ProductPriceProvider.cs +++ b/src/SampleProject.Application/Orders/PlaceCustomerOrder/ProductPriceProvider.cs @@ -1,11 +1,11 @@ -using System; +using Dapper; +using SampleProject.Domain.Products; +using SampleProject.Domain.SharedKernel; +using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Threading.Tasks; -using Dapper; -using SampleProject.Domain.Products; -using SampleProject.Domain.SharedKernel; namespace SampleProject.Application.Orders.PlaceCustomerOrder { @@ -13,7 +13,7 @@ public static class ProductPriceProvider { public static async Task> GetAllProductPrices(IDbConnection connection) { - var productPrices = await connection.QueryAsync("SELECT " + + IEnumerable productPrices = await connection.QueryAsync("SELECT " + $"[ProductPrice].ProductId AS [{nameof(ProductPriceResponse.ProductId)}], " + $"[ProductPrice].Value AS [{nameof(ProductPriceResponse.Value)}], " + $"[ProductPrice].Currency AS [{nameof(ProductPriceResponse.Currency)}] " + diff --git a/src/SampleProject.Application/Orders/ProductDto.cs b/src/SampleProject.Application/Orders/ProductDto.cs index 93f2a08..cc8a4ef 100644 --- a/src/SampleProject.Application/Orders/ProductDto.cs +++ b/src/SampleProject.Application/Orders/ProductDto.cs @@ -1,5 +1,4 @@ using System; -using System.Runtime.InteropServices.ComTypes; namespace SampleProject.Application.Orders { @@ -9,19 +8,19 @@ public class ProductDto public int Quantity { get; set; } - + public string Name { get; set; } public ProductDto() { - + } public ProductDto(Guid id, int quantity) { - this.Id = id; - this.Quantity = quantity; + Id = id; + Quantity = quantity; } } } \ No newline at end of file diff --git a/src/SampleProject.Application/Orders/RemoveCustomerOrder/RemoveCustomerOrderCommand.cs b/src/SampleProject.Application/Orders/RemoveCustomerOrder/RemoveCustomerOrderCommand.cs index 4c6e169..f7aa583 100644 --- a/src/SampleProject.Application/Orders/RemoveCustomerOrder/RemoveCustomerOrderCommand.cs +++ b/src/SampleProject.Application/Orders/RemoveCustomerOrder/RemoveCustomerOrderCommand.cs @@ -1,6 +1,5 @@ -using System; -using MediatR; -using SampleProject.Application.Configuration.Commands; +using SampleProject.Application.Configuration.Commands; +using System; namespace SampleProject.Application.Orders.RemoveCustomerOrder { @@ -14,8 +13,8 @@ public RemoveCustomerOrderCommand( Guid customerId, Guid orderId) { - this.CustomerId = customerId; - this.OrderId = orderId; + CustomerId = customerId; + OrderId = orderId; } } } \ No newline at end of file diff --git a/src/SampleProject.Application/Orders/RemoveCustomerOrder/RemoveCustomerOrderCommandHandler.cs b/src/SampleProject.Application/Orders/RemoveCustomerOrder/RemoveCustomerOrderCommandHandler.cs index e804f15..59a0e4c 100644 --- a/src/SampleProject.Application/Orders/RemoveCustomerOrder/RemoveCustomerOrderCommandHandler.cs +++ b/src/SampleProject.Application/Orders/RemoveCustomerOrder/RemoveCustomerOrderCommandHandler.cs @@ -1,9 +1,9 @@ -using System.Threading; -using System.Threading.Tasks; -using MediatR; +using MediatR; using SampleProject.Application.Configuration.Commands; using SampleProject.Domain.Customers; using SampleProject.Domain.Customers.Orders; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Application.Orders.RemoveCustomerOrder { @@ -13,12 +13,12 @@ public class RemoveCustomerOrderCommandHandler : ICommandHandler Handle(RemoveCustomerOrderCommand request, CancellationToken cancellationToken) { - var customer = await this._customerRepository.GetByIdAsync(new CustomerId(request.CustomerId)); + Customer customer = await _customerRepository.GetByIdAsync(new CustomerId(request.CustomerId)); customer.RemoveOrder(new OrderId(request.OrderId)); diff --git a/src/SampleProject.Application/Payments/PaymentCreatedNotification.cs b/src/SampleProject.Application/Payments/PaymentCreatedNotification.cs index 68cb9ab..7c82e4f 100644 --- a/src/SampleProject.Application/Payments/PaymentCreatedNotification.cs +++ b/src/SampleProject.Application/Payments/PaymentCreatedNotification.cs @@ -10,13 +10,13 @@ public class PaymentCreatedNotification : DomainNotificationBase [JsonConstructor] public SendEmailAfterPaymentCommand(Guid id, PaymentId paymentId) : base(id) { - this.PaymentId = paymentId; + PaymentId = paymentId; } } } \ No newline at end of file diff --git a/src/SampleProject.Application/Payments/SendEmailAfterPayment/SendEmailAfterPaymentCommandHandler.cs b/src/SampleProject.Application/Payments/SendEmailAfterPayment/SendEmailAfterPaymentCommandHandler.cs index 6da3b6e..66b75fd 100644 --- a/src/SampleProject.Application/Payments/SendEmailAfterPayment/SendEmailAfterPaymentCommandHandler.cs +++ b/src/SampleProject.Application/Payments/SendEmailAfterPayment/SendEmailAfterPaymentCommandHandler.cs @@ -1,9 +1,9 @@ -using System.Threading; -using System.Threading.Tasks; -using MediatR; +using MediatR; using SampleProject.Application.Configuration.Commands; using SampleProject.Application.Configuration.Emails; using SampleProject.Domain.Payments; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Application.Payments.SendEmailAfterPayment { @@ -13,7 +13,7 @@ public class SendEmailAfterPaymentCommandHandler : ICommandHandler Handle(SendEmailAfterPaymentCommand request, CancellationToken cancellationToken) { // Logic of preparing an email. This is only mock. - var emailMessage = new EmailMessage("from@email.com", "to@email.com", "content"); + EmailMessage emailMessage = new EmailMessage("from@email.com", "to@email.com", "content"); await _emailSender.SendEmailAsync(emailMessage); - var payment = await this._paymentRepository.GetByIdAsync(request.PaymentId); + Payment payment = await _paymentRepository.GetByIdAsync(request.PaymentId); payment.MarkEmailNotificationIsSent(); diff --git a/src/SampleProject.Domain/Customers/Customer.cs b/src/SampleProject.Domain/Customers/Customer.cs index 14bbe6e..721c197 100644 --- a/src/SampleProject.Domain/Customers/Customer.cs +++ b/src/SampleProject.Domain/Customers/Customer.cs @@ -1,12 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using SampleProject.Domain.Customers.Orders; +using SampleProject.Domain.Customers.Orders; using SampleProject.Domain.Customers.Orders.Events; using SampleProject.Domain.Customers.Rules; using SampleProject.Domain.ForeignExchange; using SampleProject.Domain.Products; using SampleProject.Domain.SeedWork; +using System; +using System.Collections.Generic; +using System.Linq; namespace SampleProject.Domain.Customers { @@ -14,9 +14,9 @@ public class Customer : Entity, IAggregateRoot { public CustomerId Id { get; private set; } - private string _email; + private readonly string _email; - private string _name; + private readonly string _name; private readonly List _orders; @@ -24,22 +24,22 @@ public class Customer : Entity, IAggregateRoot private Customer() { - this._orders = new List(); + _orders = new List(); } - + private Customer(string email, string name) { - this.Id = new CustomerId(Guid.NewGuid()); + Id = new CustomerId(Guid.NewGuid()); _email = email; _name = name; _welcomeEmailWasSent = false; _orders = new List(); - this.AddDomainEvent(new CustomerRegisteredEvent(this.Id)); + AddDomainEvent(new CustomerRegisteredEvent(Id)); } public static Customer CreateRegistered( - string email, + string email, string name, ICustomerUniquenessChecker customerUniquenessChecker) { @@ -51,23 +51,23 @@ public static Customer CreateRegistered( public OrderId PlaceOrder( List orderProductsData, List allProductPrices, - string currency, + string currency, List conversionRates) { CheckRule(new CustomerCannotOrderMoreThan2OrdersOnTheSameDayRule(_orders)); CheckRule(new OrderMustHaveAtLeastOneProductRule(orderProductsData)); - var order = Order.CreateNew(orderProductsData, allProductPrices, currency, conversionRates); + Order order = Order.CreateNew(orderProductsData, allProductPrices, currency, conversionRates); - this._orders.Add(order); + _orders.Add(order); - this.AddDomainEvent(new OrderPlacedEvent(order.Id, this.Id, order.GetValue())); + AddDomainEvent(new OrderPlacedEvent(order.Id, Id, order.GetValue())); return order.Id; } public void ChangeOrder( - OrderId orderId, + OrderId orderId, List existingProducts, List newOrderProductsData, List conversionRates, @@ -75,23 +75,23 @@ public void ChangeOrder( { CheckRule(new OrderMustHaveAtLeastOneProductRule(newOrderProductsData)); - var order = this._orders.Single(x => x.Id == orderId); + Order order = _orders.Single(x => x.Id == orderId); order.Change(existingProducts, newOrderProductsData, conversionRates, currency); - this.AddDomainEvent(new OrderChangedEvent(orderId)); + AddDomainEvent(new OrderChangedEvent(orderId)); } public void RemoveOrder(OrderId orderId) { - var order = this._orders.Single(x => x.Id == orderId); + Order order = _orders.Single(x => x.Id == orderId); order.Remove(); - this.AddDomainEvent(new OrderRemovedEvent(orderId)); + AddDomainEvent(new OrderRemovedEvent(orderId)); } public void MarkAsWelcomedByEmail() { - this._welcomeEmailWasSent = true; + _welcomeEmailWasSent = true; } } } \ No newline at end of file diff --git a/src/SampleProject.Domain/Customers/CustomerId.cs b/src/SampleProject.Domain/Customers/CustomerId.cs index 071b50c..8ed95d7 100644 --- a/src/SampleProject.Domain/Customers/CustomerId.cs +++ b/src/SampleProject.Domain/Customers/CustomerId.cs @@ -1,5 +1,5 @@ -using System; -using SampleProject.Domain.SeedWork; +using SampleProject.Domain.SeedWork; +using System; namespace SampleProject.Domain.Customers { diff --git a/src/SampleProject.Domain/Customers/CustomerRegisteredEvent.cs b/src/SampleProject.Domain/Customers/CustomerRegisteredEvent.cs index f2baeb2..e22b790 100644 --- a/src/SampleProject.Domain/Customers/CustomerRegisteredEvent.cs +++ b/src/SampleProject.Domain/Customers/CustomerRegisteredEvent.cs @@ -8,7 +8,7 @@ public class CustomerRegisteredEvent : DomainEventBase public CustomerRegisteredEvent(CustomerId customerId) { - this.CustomerId = customerId; + CustomerId = customerId; } } } \ No newline at end of file diff --git a/src/SampleProject.Domain/Customers/Orders/Events/OrderChangedEvent.cs b/src/SampleProject.Domain/Customers/Orders/Events/OrderChangedEvent.cs index 5d8154c..746c8ba 100644 --- a/src/SampleProject.Domain/Customers/Orders/Events/OrderChangedEvent.cs +++ b/src/SampleProject.Domain/Customers/Orders/Events/OrderChangedEvent.cs @@ -8,7 +8,7 @@ public class OrderChangedEvent : DomainEventBase public OrderChangedEvent(OrderId orderId) { - this.OrderId = orderId; + OrderId = orderId; } } } \ No newline at end of file diff --git a/src/SampleProject.Domain/Customers/Orders/Events/OrderPlacedEvent.cs b/src/SampleProject.Domain/Customers/Orders/Events/OrderPlacedEvent.cs index f402357..85c9a5b 100644 --- a/src/SampleProject.Domain/Customers/Orders/Events/OrderPlacedEvent.cs +++ b/src/SampleProject.Domain/Customers/Orders/Events/OrderPlacedEvent.cs @@ -1,5 +1,4 @@ -using System; -using SampleProject.Domain.SeedWork; +using SampleProject.Domain.SeedWork; using SampleProject.Domain.SharedKernel; namespace SampleProject.Domain.Customers.Orders.Events @@ -13,12 +12,12 @@ public class OrderPlacedEvent : DomainEventBase public MoneyValue Value { get; } public OrderPlacedEvent( - OrderId orderId, - CustomerId customerId, + OrderId orderId, + CustomerId customerId, MoneyValue value) { - this.OrderId = orderId; - this.CustomerId = customerId; + OrderId = orderId; + CustomerId = customerId; Value = value; } } diff --git a/src/SampleProject.Domain/Customers/Orders/Events/OrderRemovedEvent.cs b/src/SampleProject.Domain/Customers/Orders/Events/OrderRemovedEvent.cs index d253852..b3b33e9 100644 --- a/src/SampleProject.Domain/Customers/Orders/Events/OrderRemovedEvent.cs +++ b/src/SampleProject.Domain/Customers/Orders/Events/OrderRemovedEvent.cs @@ -8,7 +8,7 @@ public class OrderRemovedEvent : DomainEventBase public OrderRemovedEvent(OrderId orderId) { - this.OrderId = orderId; + OrderId = orderId; } } } \ No newline at end of file diff --git a/src/SampleProject.Domain/Customers/Orders/ICustomerRepository.cs b/src/SampleProject.Domain/Customers/Orders/ICustomerRepository.cs index 792da0a..40fef64 100644 --- a/src/SampleProject.Domain/Customers/Orders/ICustomerRepository.cs +++ b/src/SampleProject.Domain/Customers/Orders/ICustomerRepository.cs @@ -1,5 +1,4 @@ -using System; -using System.Threading.Tasks; +using System.Threading.Tasks; namespace SampleProject.Domain.Customers.Orders { diff --git a/src/SampleProject.Domain/Customers/Orders/Order.cs b/src/SampleProject.Domain/Customers/Orders/Order.cs index de584e1..2f2cebe 100644 --- a/src/SampleProject.Domain/Customers/Orders/Order.cs +++ b/src/SampleProject.Domain/Customers/Orders/Order.cs @@ -1,10 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using SampleProject.Domain.ForeignExchange; +using SampleProject.Domain.ForeignExchange; using SampleProject.Domain.Products; using SampleProject.Domain.SeedWork; using SampleProject.Domain.SharedKernel; +using System; +using System.Collections.Generic; +using System.Linq; namespace SampleProject.Domain.Customers.Orders { @@ -18,46 +18,46 @@ public class Order : Entity private MoneyValue _valueInEUR; - private List _orderProducts; + private readonly List _orderProducts; - private OrderStatus _status; + private readonly OrderStatus _status; - private DateTime _orderDate; + private readonly DateTime _orderDate; private DateTime? _orderChangeDate; private Order() { - this._orderProducts = new List(); - this._isRemoved = false; + _orderProducts = new List(); + _isRemoved = false; } private Order( List orderProductsData, List productPrices, - string currency, + string currency, List conversionRates ) { - this._orderDate = SystemClock.Now; - this.Id = new OrderId(Guid.NewGuid()); - this._orderProducts = new List(); + _orderDate = SystemClock.Now; + Id = new OrderId(Guid.NewGuid()); + _orderProducts = new List(); - foreach (var orderProductData in orderProductsData) + foreach (OrderProductData orderProductData in orderProductsData) { - var productPrice = productPrices.Single(x => x.ProductId == orderProductData.ProductId && + ProductPriceData productPrice = productPrices.Single(x => x.ProductId == orderProductData.ProductId && x.Price.Currency == currency); - var orderProduct = OrderProduct.CreateForProduct( - productPrice, + OrderProduct orderProduct = OrderProduct.CreateForProduct( + productPrice, orderProductData.Quantity, - currency, + currency, conversionRates); _orderProducts.Add(orderProduct); } - this.CalculateOrderValue(); - this._status = OrderStatus.Placed; + CalculateOrderValue(); + _status = OrderStatus.Placed; } internal static Order CreateNew(List orderProductsData, @@ -70,52 +70,52 @@ internal static Order CreateNew(List orderProductsData, internal void Change( List allProductPrices, - List orderProductsData, + List orderProductsData, List conversionRates, string currency) { - foreach (var orderProductData in orderProductsData) + foreach (OrderProductData orderProductData in orderProductsData) { - var product = allProductPrices.Single(x => x.ProductId == orderProductData.ProductId && + ProductPriceData product = allProductPrices.Single(x => x.ProductId == orderProductData.ProductId && x.Price.Currency == currency); - - var existingProductOrder = _orderProducts.SingleOrDefault(x => x.ProductId == orderProductData.ProductId); + + OrderProduct existingProductOrder = _orderProducts.SingleOrDefault(x => x.ProductId == orderProductData.ProductId); if (existingProductOrder != null) { - var existingOrderProduct = this._orderProducts.Single(x => x.ProductId == existingProductOrder.ProductId); - + OrderProduct existingOrderProduct = _orderProducts.Single(x => x.ProductId == existingProductOrder.ProductId); + existingOrderProduct.ChangeQuantity(product, orderProductData.Quantity, conversionRates); } else { - var orderProduct = OrderProduct.CreateForProduct(product, orderProductData.Quantity, currency, conversionRates); - this._orderProducts.Add(orderProduct); + OrderProduct orderProduct = OrderProduct.CreateForProduct(product, orderProductData.Quantity, currency, conversionRates); + _orderProducts.Add(orderProduct); } } - var orderProductsToCheck = _orderProducts.ToList(); - foreach (var existingProduct in orderProductsToCheck) + List orderProductsToCheck = _orderProducts.ToList(); + foreach (OrderProduct existingProduct in orderProductsToCheck) { - var product = orderProductsData.SingleOrDefault(x => x.ProductId == existingProduct.ProductId); + OrderProductData product = orderProductsData.SingleOrDefault(x => x.ProductId == existingProduct.ProductId); if (product == null) { - this._orderProducts.Remove(existingProduct); + _orderProducts.Remove(existingProduct); } } - this.CalculateOrderValue(); + CalculateOrderValue(); - this._orderChangeDate = DateTime.UtcNow; + _orderChangeDate = DateTime.UtcNow; } internal void Remove() { - this._isRemoved = true; + _isRemoved = true; } internal bool IsOrderedToday() { - return this._orderDate.Date == SystemClock.Now.Date; + return _orderDate.Date == SystemClock.Now.Date; } internal MoneyValue GetValue() diff --git a/src/SampleProject.Domain/Customers/Orders/OrderId.cs b/src/SampleProject.Domain/Customers/Orders/OrderId.cs index 428210a..e67f41e 100644 --- a/src/SampleProject.Domain/Customers/Orders/OrderId.cs +++ b/src/SampleProject.Domain/Customers/Orders/OrderId.cs @@ -1,5 +1,5 @@ -using System; -using SampleProject.Domain.SeedWork; +using SampleProject.Domain.SeedWork; +using System; namespace SampleProject.Domain.Customers.Orders { diff --git a/src/SampleProject.Domain/Customers/Orders/OrderProduct.cs b/src/SampleProject.Domain/Customers/Orders/OrderProduct.cs index 94b2658..fde0ca1 100644 --- a/src/SampleProject.Domain/Customers/Orders/OrderProduct.cs +++ b/src/SampleProject.Domain/Customers/Orders/OrderProduct.cs @@ -1,10 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using SampleProject.Domain.ForeignExchange; +using SampleProject.Domain.ForeignExchange; using SampleProject.Domain.Products; using SampleProject.Domain.SeedWork; using SampleProject.Domain.SharedKernel; +using System.Collections.Generic; +using System.Linq; namespace SampleProject.Domain.Customers.Orders { @@ -29,10 +28,10 @@ private OrderProduct( string currency, List conversionRates) { - this.ProductId = productPrice.ProductId; - this.Quantity = quantity; + ProductId = productPrice.ProductId; + Quantity = quantity; - this.CalculateValue(productPrice, currency, conversionRates); + CalculateValue(productPrice, currency, conversionRates); } internal static OrderProduct CreateForProduct( @@ -44,22 +43,22 @@ internal static OrderProduct CreateForProduct( internal void ChangeQuantity(ProductPriceData productPrice, int quantity, List conversionRates) { - this.Quantity = quantity; + Quantity = quantity; - this.CalculateValue(productPrice, this.Value.Currency, conversionRates); + CalculateValue(productPrice, Value.Currency, conversionRates); } private void CalculateValue(ProductPriceData productPrice, string currency, List conversionRates) { - this.Value = this.Quantity * productPrice.Price; + Value = Quantity * productPrice.Price; if (currency == "EUR") { - this.ValueInEUR = this.Quantity * productPrice.Price; + ValueInEUR = Quantity * productPrice.Price; } else { - var conversionRate = conversionRates.Single(x => x.SourceCurrency == currency && x.TargetCurrency == "EUR"); - this.ValueInEUR = conversionRate.Convert(this.Value); + ConversionRate conversionRate = conversionRates.Single(x => x.SourceCurrency == currency && x.TargetCurrency == "EUR"); + ValueInEUR = conversionRate.Convert(Value); } } } diff --git a/src/SampleProject.Domain/Customers/Rules/CustomerCannotOrderMoreThan2OrdersOnTheSameDayRule.cs b/src/SampleProject.Domain/Customers/Rules/CustomerCannotOrderMoreThan2OrdersOnTheSameDayRule.cs index 9267e78..bd7f436 100644 --- a/src/SampleProject.Domain/Customers/Rules/CustomerCannotOrderMoreThan2OrdersOnTheSameDayRule.cs +++ b/src/SampleProject.Domain/Customers/Rules/CustomerCannotOrderMoreThan2OrdersOnTheSameDayRule.cs @@ -1,7 +1,7 @@ -using System.Collections.Generic; -using System.Linq; -using SampleProject.Domain.Customers.Orders; +using SampleProject.Domain.Customers.Orders; using SampleProject.Domain.SeedWork; +using System.Collections.Generic; +using System.Linq; namespace SampleProject.Domain.Customers.Rules { @@ -16,7 +16,7 @@ public CustomerCannotOrderMoreThan2OrdersOnTheSameDayRule(IList orders) public bool IsBroken() { - return _orders.Count(x => x.IsOrderedToday()) >= 2; + return _orders.Count(x => x.IsOrderedToday()) >= 2; } public string Message => "You cannot order more than 2 orders on the same day."; diff --git a/src/SampleProject.Domain/Customers/Rules/CustomerEmailMustBeUniqueRule.cs b/src/SampleProject.Domain/Customers/Rules/CustomerEmailMustBeUniqueRule.cs index d7bef94..dc3acc8 100644 --- a/src/SampleProject.Domain/Customers/Rules/CustomerEmailMustBeUniqueRule.cs +++ b/src/SampleProject.Domain/Customers/Rules/CustomerEmailMustBeUniqueRule.cs @@ -9,14 +9,17 @@ public class CustomerEmailMustBeUniqueRule : IBusinessRule private readonly string _email; public CustomerEmailMustBeUniqueRule( - ICustomerUniquenessChecker customerUniquenessChecker, + ICustomerUniquenessChecker customerUniquenessChecker, string email) { _customerUniquenessChecker = customerUniquenessChecker; _email = email; } - public bool IsBroken() => !_customerUniquenessChecker.IsUnique(_email); + public bool IsBroken() + { + return !_customerUniquenessChecker.IsUnique(_email); + } public string Message => "Customer with this email already exists."; } diff --git a/src/SampleProject.Domain/Customers/Rules/OrderMustHaveAtLeastOneProductRule.cs b/src/SampleProject.Domain/Customers/Rules/OrderMustHaveAtLeastOneProductRule.cs index d412732..fa6d1f7 100644 --- a/src/SampleProject.Domain/Customers/Rules/OrderMustHaveAtLeastOneProductRule.cs +++ b/src/SampleProject.Domain/Customers/Rules/OrderMustHaveAtLeastOneProductRule.cs @@ -1,8 +1,7 @@ -using System.Buffers; +using SampleProject.Domain.Customers.Orders; +using SampleProject.Domain.SeedWork; using System.Collections.Generic; using System.Linq; -using SampleProject.Domain.Customers.Orders; -using SampleProject.Domain.SeedWork; namespace SampleProject.Domain.Customers.Rules { @@ -15,7 +14,10 @@ public OrderMustHaveAtLeastOneProductRule(List orderProductDat _orderProductData = orderProductData; } - public bool IsBroken() => !_orderProductData.Any(); + public bool IsBroken() + { + return !_orderProductData.Any(); + } public string Message => "Order must have at least one product"; } diff --git a/src/SampleProject.Domain/ForeignExchange/ConversionRate.cs b/src/SampleProject.Domain/ForeignExchange/ConversionRate.cs index c075688..c980eeb 100644 --- a/src/SampleProject.Domain/ForeignExchange/ConversionRate.cs +++ b/src/SampleProject.Domain/ForeignExchange/ConversionRate.cs @@ -1,5 +1,4 @@ -using System; -using SampleProject.Domain.SharedKernel; +using SampleProject.Domain.SharedKernel; namespace SampleProject.Domain.ForeignExchange { @@ -13,14 +12,14 @@ public class ConversionRate public ConversionRate(string sourceCurrency, string targetCurrency, decimal factor) { - this.SourceCurrency = sourceCurrency; - this.TargetCurrency = targetCurrency; - this.Factor = factor; + SourceCurrency = sourceCurrency; + TargetCurrency = targetCurrency; + Factor = factor; } internal MoneyValue Convert(MoneyValue value) { - return this.Factor * value; + return Factor * value; } } } \ No newline at end of file diff --git a/src/SampleProject.Domain/Payments/IPaymentRepository.cs b/src/SampleProject.Domain/Payments/IPaymentRepository.cs index 47c0adb..ad76da9 100644 --- a/src/SampleProject.Domain/Payments/IPaymentRepository.cs +++ b/src/SampleProject.Domain/Payments/IPaymentRepository.cs @@ -1,5 +1,4 @@ -using System; -using System.Threading.Tasks; +using System.Threading.Tasks; namespace SampleProject.Domain.Payments { diff --git a/src/SampleProject.Domain/Payments/Payment.cs b/src/SampleProject.Domain/Payments/Payment.cs index a9ebb56..c1f0dbb 100644 --- a/src/SampleProject.Domain/Payments/Payment.cs +++ b/src/SampleProject.Domain/Payments/Payment.cs @@ -1,6 +1,6 @@ -using System; -using SampleProject.Domain.Customers.Orders; +using SampleProject.Domain.Customers.Orders; using SampleProject.Domain.SeedWork; +using System; namespace SampleProject.Domain.Payments { @@ -8,11 +8,11 @@ public class Payment : Entity, IAggregateRoot { public PaymentId Id { get; private set; } - private OrderId _orderId; + private readonly OrderId _orderId; - private DateTime _createDate; + private readonly DateTime _createDate; - private PaymentStatus _status; + private readonly PaymentStatus _status; private bool _emailNotificationIsSent; @@ -23,18 +23,18 @@ private Payment() public Payment(OrderId orderId) { - this.Id = new PaymentId(Guid.NewGuid()); - this._createDate = DateTime.UtcNow; - this._orderId = orderId; - this._status = PaymentStatus.ToPay; - this._emailNotificationIsSent = false; + Id = new PaymentId(Guid.NewGuid()); + _createDate = DateTime.UtcNow; + _orderId = orderId; + _status = PaymentStatus.ToPay; + _emailNotificationIsSent = false; - this.AddDomainEvent(new PaymentCreatedEvent(this.Id, this._orderId)); + AddDomainEvent(new PaymentCreatedEvent(Id, _orderId)); } public void MarkEmailNotificationIsSent() { - this._emailNotificationIsSent = true; + _emailNotificationIsSent = true; } } } \ No newline at end of file diff --git a/src/SampleProject.Domain/Payments/PaymentCreatedEvent.cs b/src/SampleProject.Domain/Payments/PaymentCreatedEvent.cs index 5eb95db..f6456c5 100644 --- a/src/SampleProject.Domain/Payments/PaymentCreatedEvent.cs +++ b/src/SampleProject.Domain/Payments/PaymentCreatedEvent.cs @@ -1,5 +1,4 @@ -using System; -using SampleProject.Domain.Customers.Orders; +using SampleProject.Domain.Customers.Orders; using SampleProject.Domain.SeedWork; namespace SampleProject.Domain.Payments @@ -8,8 +7,8 @@ public class PaymentCreatedEvent : DomainEventBase { public PaymentCreatedEvent(PaymentId paymentId, OrderId orderId) { - this.PaymentId = paymentId; - this.OrderId = orderId; + PaymentId = paymentId; + OrderId = orderId; } public PaymentId PaymentId { get; } diff --git a/src/SampleProject.Domain/Payments/PaymentId.cs b/src/SampleProject.Domain/Payments/PaymentId.cs index d1ac3af..8e6e360 100644 --- a/src/SampleProject.Domain/Payments/PaymentId.cs +++ b/src/SampleProject.Domain/Payments/PaymentId.cs @@ -1,5 +1,5 @@ -using System; -using SampleProject.Domain.SeedWork; +using SampleProject.Domain.SeedWork; +using System; namespace SampleProject.Domain.Payments { diff --git a/src/SampleProject.Domain/Products/IProductRepository.cs b/src/SampleProject.Domain/Products/IProductRepository.cs index d355d56..a241b65 100644 --- a/src/SampleProject.Domain/Products/IProductRepository.cs +++ b/src/SampleProject.Domain/Products/IProductRepository.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading.Tasks; namespace SampleProject.Domain.Products diff --git a/src/SampleProject.Domain/Products/Product.cs b/src/SampleProject.Domain/Products/Product.cs index e9dfbc0..5a60d27 100644 --- a/src/SampleProject.Domain/Products/Product.cs +++ b/src/SampleProject.Domain/Products/Product.cs @@ -1,8 +1,5 @@ -using System; +using SampleProject.Domain.SeedWork; using System.Collections.Generic; -using System.Linq; -using SampleProject.Domain.SeedWork; -using SampleProject.Domain.SharedKernel; namespace SampleProject.Domain.Products { @@ -12,7 +9,7 @@ public class Product : Entity, IAggregateRoot public string Name { get; private set; } - private List _prices; + private readonly List _prices; private Product() { diff --git a/src/SampleProject.Domain/Products/ProductId.cs b/src/SampleProject.Domain/Products/ProductId.cs index b930f8f..f06561d 100644 --- a/src/SampleProject.Domain/Products/ProductId.cs +++ b/src/SampleProject.Domain/Products/ProductId.cs @@ -1,5 +1,5 @@ -using System; -using SampleProject.Domain.SeedWork; +using SampleProject.Domain.SeedWork; +using System; namespace SampleProject.Domain.Products { diff --git a/src/SampleProject.Domain/Products/ProductPrice.cs b/src/SampleProject.Domain/Products/ProductPrice.cs index 24666ee..58e9023 100644 --- a/src/SampleProject.Domain/Products/ProductPrice.cs +++ b/src/SampleProject.Domain/Products/ProductPrice.cs @@ -8,7 +8,7 @@ public class ProductPrice private ProductPrice() { - + } } } \ No newline at end of file diff --git a/src/SampleProject.Domain/SeedWork/BusinessRuleValidationException.cs b/src/SampleProject.Domain/SeedWork/BusinessRuleValidationException.cs index a310086..f853136 100644 --- a/src/SampleProject.Domain/SeedWork/BusinessRuleValidationException.cs +++ b/src/SampleProject.Domain/SeedWork/BusinessRuleValidationException.cs @@ -11,7 +11,7 @@ public class BusinessRuleValidationException : Exception public BusinessRuleValidationException(IBusinessRule brokenRule) : base(brokenRule.Message) { BrokenRule = brokenRule; - this.Details = brokenRule.Message; + Details = brokenRule.Message; } public override string ToString() diff --git a/src/SampleProject.Domain/SeedWork/DomainEventBase.cs b/src/SampleProject.Domain/SeedWork/DomainEventBase.cs index f8731f5..7213a6f 100644 --- a/src/SampleProject.Domain/SeedWork/DomainEventBase.cs +++ b/src/SampleProject.Domain/SeedWork/DomainEventBase.cs @@ -6,7 +6,7 @@ public class DomainEventBase : IDomainEvent { public DomainEventBase() { - this.OccurredOn = DateTime.Now; + OccurredOn = DateTime.Now; } public DateTime OccurredOn { get; } diff --git a/src/SampleProject.Domain/SeedWork/Entity.cs b/src/SampleProject.Domain/SeedWork/Entity.cs index 6b8b5f0..a09a7f6 100644 --- a/src/SampleProject.Domain/SeedWork/Entity.cs +++ b/src/SampleProject.Domain/SeedWork/Entity.cs @@ -21,7 +21,7 @@ public abstract class Entity protected void AddDomainEvent(IDomainEvent domainEvent) { _domainEvents = _domainEvents ?? new List(); - this._domainEvents.Add(domainEvent); + _domainEvents.Add(domainEvent); } /// diff --git a/src/SampleProject.Domain/SeedWork/IAggregateRoot.cs b/src/SampleProject.Domain/SeedWork/IAggregateRoot.cs index 89c3692..fec2ce9 100644 --- a/src/SampleProject.Domain/SeedWork/IAggregateRoot.cs +++ b/src/SampleProject.Domain/SeedWork/IAggregateRoot.cs @@ -2,6 +2,6 @@ { public interface IAggregateRoot { - + } } \ No newline at end of file diff --git a/src/SampleProject.Domain/SeedWork/IDomainEvent.cs b/src/SampleProject.Domain/SeedWork/IDomainEvent.cs index 721f579..c71ef18 100644 --- a/src/SampleProject.Domain/SeedWork/IDomainEvent.cs +++ b/src/SampleProject.Domain/SeedWork/IDomainEvent.cs @@ -1,5 +1,5 @@ -using System; -using MediatR; +using MediatR; +using System; namespace SampleProject.Domain.SeedWork { diff --git a/src/SampleProject.Domain/SeedWork/TypedIdValueBase.cs b/src/SampleProject.Domain/SeedWork/TypedIdValueBase.cs index 8abd0a7..2855740 100644 --- a/src/SampleProject.Domain/SeedWork/TypedIdValueBase.cs +++ b/src/SampleProject.Domain/SeedWork/TypedIdValueBase.cs @@ -13,7 +13,11 @@ protected TypedIdValueBase(Guid value) public override bool Equals(object obj) { - if (ReferenceEquals(null, obj)) return false; + if (ReferenceEquals(null, obj)) + { + return false; + } + return obj is TypedIdValueBase other && Equals(other); } @@ -24,7 +28,7 @@ public override int GetHashCode() public bool Equals(TypedIdValueBase other) { - return this.Value == other.Value; + return Value == other.Value; } public static bool operator ==(TypedIdValueBase obj1, TypedIdValueBase obj2) @@ -39,7 +43,7 @@ public bool Equals(TypedIdValueBase other) } return obj1.Equals(obj2); } - public static bool operator !=(TypedIdValueBase x, TypedIdValueBase y) + public static bool operator !=(TypedIdValueBase x, TypedIdValueBase y) { return !(x == y); } diff --git a/src/SampleProject.Domain/SeedWork/ValueObject.cs b/src/SampleProject.Domain/SeedWork/ValueObject.cs index 16bf180..2ea92b9 100644 --- a/src/SampleProject.Domain/SeedWork/ValueObject.cs +++ b/src/SampleProject.Domain/SeedWork/ValueObject.cs @@ -35,7 +35,10 @@ public bool Equals(ValueObject obj) public override bool Equals(object obj) { - if (obj == null || GetType() != obj.GetType()) return false; + if (obj == null || GetType() != obj.GetType()) + { + return false; + } return GetProperties().All(p => PropertiesAreEqual(obj, p)) && GetFields().All(f => FieldsAreEqual(obj, f)); @@ -53,9 +56,9 @@ private bool FieldsAreEqual(object obj, FieldInfo f) private IEnumerable GetProperties() { - if (this._properties == null) + if (_properties == null) { - this._properties = GetType() + _properties = GetType() .GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(p => p.GetCustomAttribute(typeof(IgnoreMemberAttribute)) == null) .ToList(); @@ -64,19 +67,19 @@ private IEnumerable GetProperties() // !Attribute.IsDefined(p, typeof(IgnoreMemberAttribute))).ToList(); } - return this._properties; + return _properties; } private IEnumerable GetFields() { - if (this._fields == null) + if (_fields == null) { - this._fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + _fields = GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) .Where(p => p.GetCustomAttribute(typeof(IgnoreMemberAttribute)) == null) .ToList(); } - return this._fields; + return _fields; } public override int GetHashCode() @@ -84,15 +87,15 @@ public override int GetHashCode() unchecked //allow overflow { int hash = 17; - foreach (var prop in GetProperties()) + foreach (PropertyInfo prop in GetProperties()) { - var value = prop.GetValue(this, null); + object value = prop.GetValue(this, null); hash = HashValue(hash, value); } - foreach (var field in GetFields()) + foreach (FieldInfo field in GetFields()) { - var value = field.GetValue(this); + object value = field.GetValue(this); hash = HashValue(hash, value); } @@ -102,7 +105,7 @@ public override int GetHashCode() private static int HashValue(int seed, object value) { - var currentHash = value?.GetHashCode() ?? 0; + int currentHash = value?.GetHashCode() ?? 0; return seed * 23 + currentHash; } diff --git a/src/SampleProject.Domain/SharedKernel/MoneyValue.cs b/src/SampleProject.Domain/SharedKernel/MoneyValue.cs index 464d864..9deacd1 100644 --- a/src/SampleProject.Domain/SharedKernel/MoneyValue.cs +++ b/src/SampleProject.Domain/SharedKernel/MoneyValue.cs @@ -1,7 +1,7 @@ -using System; +using SampleProject.Domain.SeedWork; +using System; using System.Collections.Generic; using System.Linq; -using SampleProject.Domain.SeedWork; namespace SampleProject.Domain.SharedKernel { @@ -13,8 +13,8 @@ public class MoneyValue : ValueObject private MoneyValue(decimal value, string currency) { - this.Value = value; - this.Currency = currency; + Value = value; + Currency = currency; } public static MoneyValue Of(decimal value, string currency) diff --git a/src/SampleProject.Domain/SharedKernel/MoneyValueMustHaveCurrencyRule.cs b/src/SampleProject.Domain/SharedKernel/MoneyValueMustHaveCurrencyRule.cs index f702638..f8601fa 100644 --- a/src/SampleProject.Domain/SharedKernel/MoneyValueMustHaveCurrencyRule.cs +++ b/src/SampleProject.Domain/SharedKernel/MoneyValueMustHaveCurrencyRule.cs @@ -11,7 +11,10 @@ public MoneyValueMustHaveCurrencyRule(string currency) _currency = currency; } - public bool IsBroken() => string.IsNullOrEmpty(_currency); + public bool IsBroken() + { + return string.IsNullOrEmpty(_currency); + } public string Message => "Money value must have currency"; } diff --git a/src/SampleProject.Domain/SharedKernel/MoneyValueOperationMustBePerformedOnTheSameCurrencyRule.cs b/src/SampleProject.Domain/SharedKernel/MoneyValueOperationMustBePerformedOnTheSameCurrencyRule.cs index 26cebec..4b0f5bc 100644 --- a/src/SampleProject.Domain/SharedKernel/MoneyValueOperationMustBePerformedOnTheSameCurrencyRule.cs +++ b/src/SampleProject.Domain/SharedKernel/MoneyValueOperationMustBePerformedOnTheSameCurrencyRule.cs @@ -14,7 +14,10 @@ public MoneyValueOperationMustBePerformedOnTheSameCurrencyRule(MoneyValue left, _right = right; } - public bool IsBroken() => _left.Currency != _right.Currency; + public bool IsBroken() + { + return _left.Currency != _right.Currency; + } public string Message => "Money value currencies must be the same"; } diff --git a/src/SampleProject.Domain/SharedKernel/SystemClock.cs b/src/SampleProject.Domain/SharedKernel/SystemClock.cs index 6028a16..636f4aa 100644 --- a/src/SampleProject.Domain/SharedKernel/SystemClock.cs +++ b/src/SampleProject.Domain/SharedKernel/SystemClock.cs @@ -19,8 +19,14 @@ public static DateTime Now } } - public static void Set(DateTime customDate) => _customDate = customDate; + public static void Set(DateTime customDate) + { + _customDate = customDate; + } - public static void Reset() => _customDate = null; + public static void Reset() + { + _customDate = null; + } } } \ No newline at end of file diff --git a/src/SampleProject.Infrastructure/ApplicationStartup.cs b/src/SampleProject.Infrastructure/ApplicationStartup.cs index 2d0487f..675378f 100644 --- a/src/SampleProject.Infrastructure/ApplicationStartup.cs +++ b/src/SampleProject.Infrastructure/ApplicationStartup.cs @@ -1,5 +1,4 @@ -using System; -using Autofac; +using Autofac; using Autofac.Extensions.DependencyInjection; using Autofac.Extras.CommonServiceLocator; using CommonServiceLocator; @@ -21,6 +20,7 @@ using SampleProject.Infrastructure.Quartz; using SampleProject.Infrastructure.SeedWork; using Serilog; +using System; namespace SampleProject.Infrastructure { @@ -43,10 +43,10 @@ public static IServiceProvider Initialize( services.AddSingleton(cacheStore); - var serviceProvider = CreateAutofacServiceProvider( - services, - connectionString, - emailSender, + IServiceProvider serviceProvider = CreateAutofacServiceProvider( + services, + connectionString, + emailSender, emailsSettings, logger, executionContextAccessor); @@ -62,7 +62,7 @@ private static IServiceProvider CreateAutofacServiceProvider( ILogger logger, IExecutionContextAccessor executionContextAccessor) { - var container = new ContainerBuilder(); + ContainerBuilder container = new ContainerBuilder(); container.Populate(services); @@ -70,7 +70,7 @@ private static IServiceProvider CreateAutofacServiceProvider( container.RegisterModule(new DataAccessModule(connectionString)); container.RegisterModule(new MediatorModule()); container.RegisterModule(new DomainModule()); - + if (emailSender != null) { container.RegisterModule(new EmailModule(emailSender, emailsSettings)); @@ -79,16 +79,16 @@ private static IServiceProvider CreateAutofacServiceProvider( { container.RegisterModule(new EmailModule(emailsSettings)); } - + container.RegisterModule(new ProcessingModule()); container.RegisterInstance(executionContextAccessor); - var buildContainer = container.Build(); + IContainer buildContainer = container.Build(); ServiceLocator.SetLocatorProvider(() => new AutofacServiceLocator(buildContainer)); - var serviceProvider = new AutofacServiceProvider(buildContainer); + AutofacServiceProvider serviceProvider = new AutofacServiceProvider(buildContainer); CompositionRoot.SetContainer(buildContainer); @@ -96,15 +96,15 @@ private static IServiceProvider CreateAutofacServiceProvider( } private static void StartQuartz( - string connectionString, + string connectionString, EmailsSettings emailsSettings, ILogger logger, IExecutionContextAccessor executionContextAccessor) { - var schedulerFactory = new StdSchedulerFactory(); - var scheduler = schedulerFactory.GetScheduler().GetAwaiter().GetResult(); + StdSchedulerFactory schedulerFactory = new StdSchedulerFactory(); + IScheduler scheduler = schedulerFactory.GetScheduler().GetAwaiter().GetResult(); - var container = new ContainerBuilder(); + ContainerBuilder container = new ContainerBuilder(); container.RegisterModule(new LoggingModule(logger)); container.RegisterModule(new QuartzModule()); @@ -116,7 +116,7 @@ private static void StartQuartz( container.RegisterInstance(executionContextAccessor); container.Register(c => { - var dbContextOptionsBuilder = new DbContextOptionsBuilder(); + DbContextOptionsBuilder dbContextOptionsBuilder = new DbContextOptionsBuilder(); dbContextOptionsBuilder.UseSqlServer(connectionString); dbContextOptionsBuilder @@ -129,8 +129,8 @@ private static void StartQuartz( scheduler.Start().GetAwaiter().GetResult(); - var processOutboxJob = JobBuilder.Create().Build(); - var trigger = + IJobDetail processOutboxJob = JobBuilder.Create().Build(); + ITrigger trigger = TriggerBuilder .Create() .StartNow() @@ -139,8 +139,8 @@ private static void StartQuartz( scheduler.ScheduleJob(processOutboxJob, trigger).GetAwaiter().GetResult(); - var processInternalCommandsJob = JobBuilder.Create().Build(); - var triggerCommandsProcessing = + IJobDetail processInternalCommandsJob = JobBuilder.Create().Build(); + ITrigger triggerCommandsProcessing = TriggerBuilder .Create() .StartNow() diff --git a/src/SampleProject.Infrastructure/Caching/CachingModule.cs b/src/SampleProject.Infrastructure/Caching/CachingModule.cs index 7f7f228..00b16c9 100644 --- a/src/SampleProject.Infrastructure/Caching/CachingModule.cs +++ b/src/SampleProject.Infrastructure/Caching/CachingModule.cs @@ -1,6 +1,6 @@ -using System; +using Autofac; +using System; using System.Collections.Generic; -using Autofac; namespace SampleProject.Infrastructure.Caching { @@ -17,7 +17,7 @@ protected override void Load(ContainerBuilder builder) { builder.RegisterType() .As() - .WithParameter("expirationConfiguration", this._expirationConfiguration) + .WithParameter("expirationConfiguration", _expirationConfiguration) .SingleInstance(); } } diff --git a/src/SampleProject.Infrastructure/Caching/MemoryCacheStore.cs b/src/SampleProject.Infrastructure/Caching/MemoryCacheStore.cs index 2922aac..4a5f60b 100644 --- a/src/SampleProject.Infrastructure/Caching/MemoryCacheStore.cs +++ b/src/SampleProject.Infrastructure/Caching/MemoryCacheStore.cs @@ -1,6 +1,6 @@ -using System; +using Microsoft.Extensions.Caching.Memory; +using System; using System.Collections.Generic; -using Microsoft.Extensions.Caching.Memory; namespace SampleProject.Infrastructure.Caching { @@ -14,12 +14,12 @@ public MemoryCacheStore( Dictionary expirationConfiguration) { _memoryCache = memoryCache; - this._expirationConfiguration = expirationConfiguration; + _expirationConfiguration = expirationConfiguration; } public void Add(TItem item, ICacheKey key, TimeSpan? expirationTime = null) { - var cachedObjectName = item.GetType().Name; + string cachedObjectName = item.GetType().Name; TimeSpan timespan; if (expirationTime.HasValue) { @@ -30,7 +30,7 @@ public void Add(TItem item, ICacheKey key, TimeSpan? expirationTim timespan = _expirationConfiguration[cachedObjectName]; } - this._memoryCache.Set(key.CacheKey, item, timespan); + _memoryCache.Set(key.CacheKey, item, timespan); } public void Add(TItem item, ICacheKey key, DateTime? absoluteExpiration = null) @@ -45,12 +45,12 @@ public void Add(TItem item, ICacheKey key, DateTime? absoluteExpir offset = DateTimeOffset.MaxValue; } - this._memoryCache.Set(key.CacheKey, item, offset); + _memoryCache.Set(key.CacheKey, item, offset); } public TItem Get(ICacheKey key) where TItem : class { - if (this._memoryCache.TryGetValue(key.CacheKey, out TItem value)) + if (_memoryCache.TryGetValue(key.CacheKey, out TItem value)) { return value; } @@ -60,7 +60,7 @@ public TItem Get(ICacheKey key) where TItem : class public void Remove(ICacheKey key) { - this._memoryCache.Remove(key.CacheKey); + _memoryCache.Remove(key.CacheKey); } } } \ No newline at end of file diff --git a/src/SampleProject.Infrastructure/Database/DataAccessModule.cs b/src/SampleProject.Infrastructure/Database/DataAccessModule.cs index 0992a7c..2bcd4da 100644 --- a/src/SampleProject.Infrastructure/Database/DataAccessModule.cs +++ b/src/SampleProject.Infrastructure/Database/DataAccessModule.cs @@ -1,7 +1,6 @@ using Autofac; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using SampleProject.Application; using SampleProject.Application.Configuration.Data; using SampleProject.Domain.Customers.Orders; using SampleProject.Domain.Payments; @@ -21,7 +20,7 @@ public class DataAccessModule : Autofac.Module public DataAccessModule(string databaseConnectionString) { - this._databaseConnectionString = databaseConnectionString; + _databaseConnectionString = databaseConnectionString; } protected override void Load(ContainerBuilder builder) @@ -55,7 +54,7 @@ protected override void Load(ContainerBuilder builder) builder .Register(c => { - var dbContextOptionsBuilder = new DbContextOptionsBuilder(); + DbContextOptionsBuilder dbContextOptionsBuilder = new DbContextOptionsBuilder(); dbContextOptionsBuilder.UseSqlServer(_databaseConnectionString); dbContextOptionsBuilder .ReplaceService(); diff --git a/src/SampleProject.Infrastructure/Database/SqlConnectionFactory.cs b/src/SampleProject.Infrastructure/Database/SqlConnectionFactory.cs index 45e28f8..ed5a528 100644 --- a/src/SampleProject.Infrastructure/Database/SqlConnectionFactory.cs +++ b/src/SampleProject.Infrastructure/Database/SqlConnectionFactory.cs @@ -1,8 +1,7 @@ -using System; +using SampleProject.Application.Configuration.Data; +using System; using System.Data; using System.Data.SqlClient; -using SampleProject.Application; -using SampleProject.Application.Configuration.Data; namespace SampleProject.Infrastructure.Database { @@ -13,25 +12,25 @@ public class SqlConnectionFactory : ISqlConnectionFactory, IDisposable public SqlConnectionFactory(string connectionString) { - this._connectionString = connectionString; + _connectionString = connectionString; } public IDbConnection GetOpenConnection() { - if (this._connection == null || this._connection.State != ConnectionState.Open) + if (_connection == null || _connection.State != ConnectionState.Open) { - this._connection = new SqlConnection(_connectionString); - this._connection.Open(); + _connection = new SqlConnection(_connectionString); + _connection.Open(); } - return this._connection; + return _connection; } public void Dispose() { - if (this._connection != null && this._connection.State == ConnectionState.Open) + if (_connection != null && _connection.State == ConnectionState.Open) { - this._connection.Dispose(); + _connection.Dispose(); } } } diff --git a/src/SampleProject.Infrastructure/Domain/Customers/CustomerEntityTypeConfiguration.cs b/src/SampleProject.Infrastructure/Domain/Customers/CustomerEntityTypeConfiguration.cs index 4aa1962..b975887 100644 --- a/src/SampleProject.Infrastructure/Domain/Customers/CustomerEntityTypeConfiguration.cs +++ b/src/SampleProject.Infrastructure/Domain/Customers/CustomerEntityTypeConfiguration.cs @@ -1,5 +1,4 @@ -using System; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using SampleProject.Domain.Customers; @@ -7,6 +6,7 @@ using SampleProject.Domain.Products; using SampleProject.Domain.SharedKernel; using SampleProject.Infrastructure.Database; +using System; namespace SampleProject.Infrastructure.Domain.Customers { @@ -18,19 +18,19 @@ internal sealed class CustomerEntityTypeConfiguration : IEntityTypeConfiguration public void Configure(EntityTypeBuilder builder) { builder.ToTable("Customers", SchemaNames.Orders); - + builder.HasKey(b => b.Id); builder.Property("_welcomeEmailWasSent").HasColumnName("WelcomeEmailWasSent"); builder.Property("_email").HasColumnName("Email"); builder.Property("_name").HasColumnName("Name"); - + builder.OwnsMany(OrdersList, x => { x.WithOwner().HasForeignKey("CustomerId"); x.ToTable("Orders", SchemaNames.Orders); - + x.Property("_isRemoved").HasColumnName("IsRemoved"); x.Property("_orderDate").HasColumnName("OrderDate"); x.Property("_orderChangeDate").HasColumnName("OrderChangeDate"); @@ -46,7 +46,7 @@ public void Configure(EntityTypeBuilder builder) y.ToTable("OrderProducts", SchemaNames.Orders); y.Property("OrderId"); y.Property("ProductId"); - + y.HasKey("OrderId", "ProductId"); y.OwnsOne("Value", mv => diff --git a/src/SampleProject.Infrastructure/Domain/Customers/CustomerRepository.cs b/src/SampleProject.Infrastructure/Domain/Customers/CustomerRepository.cs index 9d3e203..4014c4a 100644 --- a/src/SampleProject.Infrastructure/Domain/Customers/CustomerRepository.cs +++ b/src/SampleProject.Infrastructure/Domain/Customers/CustomerRepository.cs @@ -1,10 +1,10 @@ -using System; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using SampleProject.Domain.Customers; using SampleProject.Domain.Customers.Orders; using SampleProject.Infrastructure.Database; using SampleProject.Infrastructure.SeedWork; +using System; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Domain.Customers { @@ -14,19 +14,19 @@ public class CustomerRepository : ICustomerRepository public CustomerRepository(OrdersContext context) { - this._context = context ?? throw new ArgumentNullException(nameof(context)); + _context = context ?? throw new ArgumentNullException(nameof(context)); } public async Task AddAsync(Customer customer) { - await this._context.Customers.AddAsync(customer); + await _context.Customers.AddAsync(customer); } public async Task GetByIdAsync(CustomerId id) { - return await this._context.Customers + return await _context.Customers .IncludePaths( - CustomerEntityTypeConfiguration.OrdersList, + CustomerEntityTypeConfiguration.OrdersList, CustomerEntityTypeConfiguration.OrderProducts) .SingleAsync(x => x.Id == id); } diff --git a/src/SampleProject.Infrastructure/Domain/ForeignExchanges/ConversionRatesCache.cs b/src/SampleProject.Infrastructure/Domain/ForeignExchanges/ConversionRatesCache.cs index c1967c8..81a9ae0 100644 --- a/src/SampleProject.Infrastructure/Domain/ForeignExchanges/ConversionRatesCache.cs +++ b/src/SampleProject.Infrastructure/Domain/ForeignExchanges/ConversionRatesCache.cs @@ -1,5 +1,5 @@ -using System.Collections.Generic; -using SampleProject.Domain.ForeignExchange; +using SampleProject.Domain.ForeignExchange; +using System.Collections.Generic; namespace SampleProject.Infrastructure.Domain.ForeignExchanges { @@ -9,7 +9,7 @@ public class ConversionRatesCache public ConversionRatesCache(List rates) { - this.Rates = rates; + Rates = rates; } } } \ No newline at end of file diff --git a/src/SampleProject.Infrastructure/Domain/ForeignExchanges/ForeignExchange.cs b/src/SampleProject.Infrastructure/Domain/ForeignExchanges/ForeignExchange.cs index 2e72372..b58b15c 100644 --- a/src/SampleProject.Infrastructure/Domain/ForeignExchanges/ForeignExchange.cs +++ b/src/SampleProject.Infrastructure/Domain/ForeignExchanges/ForeignExchange.cs @@ -1,7 +1,7 @@ -using System; -using System.Collections.Generic; -using SampleProject.Domain.ForeignExchange; +using SampleProject.Domain.ForeignExchange; using SampleProject.Infrastructure.Caching; +using System; +using System.Collections.Generic; namespace SampleProject.Infrastructure.Domain.ForeignExchanges { @@ -16,7 +16,7 @@ public ForeignExchange(ICacheStore cacheStore) public List GetConversionRates() { - var ratesCache = this._cacheStore.Get(new ConversionRatesCacheKey()); + ConversionRatesCache ratesCache = _cacheStore.Get(new ConversionRatesCacheKey()); if (ratesCache != null) { @@ -25,7 +25,7 @@ public List GetConversionRates() List rates = GetConversionRatesFromExternalApi(); - this._cacheStore.Add(new ConversionRatesCache(rates), new ConversionRatesCacheKey(), DateTime.Now.Date.AddDays(1)); + _cacheStore.Add(new ConversionRatesCache(rates), new ConversionRatesCacheKey(), DateTime.Now.Date.AddDays(1)); return rates; } @@ -34,10 +34,11 @@ private static List GetConversionRatesFromExternalApi() { // Communication with external API. Here is only mock. - var conversionRates = new List(); - - conversionRates.Add(new ConversionRate("USD", "EUR", (decimal)0.88)); - conversionRates.Add(new ConversionRate("EUR", "USD", (decimal)1.13)); + List conversionRates = new List + { + new ConversionRate("USD", "EUR", (decimal)0.88), + new ConversionRate("EUR", "USD", (decimal)1.13) + }; return conversionRates; } diff --git a/src/SampleProject.Infrastructure/Domain/Payments/PaymentEntityTypeConfiguration.cs b/src/SampleProject.Infrastructure/Domain/Payments/PaymentEntityTypeConfiguration.cs index c765fe1..8eaa4d4 100644 --- a/src/SampleProject.Infrastructure/Domain/Payments/PaymentEntityTypeConfiguration.cs +++ b/src/SampleProject.Infrastructure/Domain/Payments/PaymentEntityTypeConfiguration.cs @@ -1,10 +1,10 @@ -using System; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using SampleProject.Domain.Customers.Orders; using SampleProject.Domain.Payments; using SampleProject.Infrastructure.Database; +using System; namespace SampleProject.Infrastructure.Domain.Payments { @@ -13,7 +13,7 @@ internal sealed class PaymentEntityTypeConfiguration : IEntityTypeConfiguration< public void Configure(EntityTypeBuilder builder) { builder.ToTable("Payments", SchemaNames.Payments); - + builder.HasKey(b => b.Id); builder.Property("_createDate").HasColumnName("CreateDate"); diff --git a/src/SampleProject.Infrastructure/Domain/Payments/PaymentRepository.cs b/src/SampleProject.Infrastructure/Domain/Payments/PaymentRepository.cs index 09e33c9..d313d23 100644 --- a/src/SampleProject.Infrastructure/Domain/Payments/PaymentRepository.cs +++ b/src/SampleProject.Infrastructure/Domain/Payments/PaymentRepository.cs @@ -1,8 +1,8 @@ -using System; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using SampleProject.Domain.Payments; using SampleProject.Infrastructure.Database; +using System; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Domain.Payments { @@ -12,18 +12,18 @@ public class PaymentRepository : IPaymentRepository public PaymentRepository(OrdersContext context) { - this._context = context ?? throw new ArgumentNullException(nameof(context)); + _context = context ?? throw new ArgumentNullException(nameof(context)); } public async Task GetByIdAsync(PaymentId id) { - return await this._context.Payments + return await _context.Payments .SingleAsync(x => x.Id == id); } public async Task AddAsync(Payment payment) { - await this._context.Payments.AddAsync(payment); + await _context.Payments.AddAsync(payment); } } } \ No newline at end of file diff --git a/src/SampleProject.Infrastructure/Domain/Products/ProductEntityTypeConfiguration.cs b/src/SampleProject.Infrastructure/Domain/Products/ProductEntityTypeConfiguration.cs index 669fee4..46c7cc9 100644 --- a/src/SampleProject.Infrastructure/Domain/Products/ProductEntityTypeConfiguration.cs +++ b/src/SampleProject.Infrastructure/Domain/Products/ProductEntityTypeConfiguration.cs @@ -10,7 +10,7 @@ internal sealed class ProductEntityTypeConfiguration : IEntityTypeConfiguration< public void Configure(EntityTypeBuilder builder) { builder.ToTable("Products", SchemaNames.Orders); - + builder.HasKey(b => b.Id); builder.OwnsMany("_prices", y => diff --git a/src/SampleProject.Infrastructure/Domain/Products/ProductRepository.cs b/src/SampleProject.Infrastructure/Domain/Products/ProductRepository.cs index 6d4d54f..a3ef85f 100644 --- a/src/SampleProject.Infrastructure/Domain/Products/ProductRepository.cs +++ b/src/SampleProject.Infrastructure/Domain/Products/ProductRepository.cs @@ -1,11 +1,11 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using SampleProject.Domain.Products; using SampleProject.Infrastructure.Database; using SampleProject.Infrastructure.SeedWork; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Domain.Products { @@ -14,12 +14,12 @@ public class ProductRepository : IProductRepository private readonly OrdersContext _context; public ProductRepository(OrdersContext context) { - this._context = context ?? throw new ArgumentNullException(nameof(context)); + _context = context ?? throw new ArgumentNullException(nameof(context)); } public async Task> GetByIdsAsync(List ids) { - return await this._context + return await _context .Products .IncludePaths("_prices") .Where(x => ids.Contains(x.Id)).ToListAsync(); @@ -27,7 +27,7 @@ public async Task> GetByIdsAsync(List ids) public async Task> GetAllAsync() { - return await this._context + return await _context .Products .IncludePaths("_prices") .ToListAsync(); diff --git a/src/SampleProject.Infrastructure/Domain/UnitOfWork.cs b/src/SampleProject.Infrastructure/Domain/UnitOfWork.cs index 40ade98..aec0ba0 100644 --- a/src/SampleProject.Infrastructure/Domain/UnitOfWork.cs +++ b/src/SampleProject.Infrastructure/Domain/UnitOfWork.cs @@ -1,8 +1,8 @@ -using System.Threading; -using System.Threading.Tasks; -using SampleProject.Domain.SeedWork; +using SampleProject.Domain.SeedWork; using SampleProject.Infrastructure.Database; using SampleProject.Infrastructure.Processing; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Domain { @@ -12,17 +12,17 @@ public class UnitOfWork : IUnitOfWork private readonly IDomainEventsDispatcher _domainEventsDispatcher; public UnitOfWork( - OrdersContext ordersContext, + OrdersContext ordersContext, IDomainEventsDispatcher domainEventsDispatcher) { - this._ordersContext = ordersContext; - this._domainEventsDispatcher = domainEventsDispatcher; + _ordersContext = ordersContext; + _domainEventsDispatcher = domainEventsDispatcher; } public async Task CommitAsync(CancellationToken cancellationToken = default(CancellationToken)) { - await this._domainEventsDispatcher.DispatchEventsAsync(); - return await this._ordersContext.SaveChangesAsync(cancellationToken); + await _domainEventsDispatcher.DispatchEventsAsync(); + return await _ordersContext.SaveChangesAsync(cancellationToken); } } } \ No newline at end of file diff --git a/src/SampleProject.Infrastructure/Emails/EmailModule.cs b/src/SampleProject.Infrastructure/Emails/EmailModule.cs index 437644b..e822da4 100644 --- a/src/SampleProject.Infrastructure/Emails/EmailModule.cs +++ b/src/SampleProject.Infrastructure/Emails/EmailModule.cs @@ -8,7 +8,7 @@ internal class EmailModule : Module { private readonly IEmailSender _emailSender; private readonly EmailsSettings _emailsSettings; - + internal EmailModule(IEmailSender emailSender, EmailsSettings emailsSettings) { _emailSender = emailSender; diff --git a/src/SampleProject.Infrastructure/Emails/EmailSender.cs b/src/SampleProject.Infrastructure/Emails/EmailSender.cs index fdae978..6cc19c2 100644 --- a/src/SampleProject.Infrastructure/Emails/EmailSender.cs +++ b/src/SampleProject.Infrastructure/Emails/EmailSender.cs @@ -1,5 +1,5 @@ -using System.Threading.Tasks; -using SampleProject.Application.Configuration.Emails; +using SampleProject.Application.Configuration.Emails; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Emails { diff --git a/src/SampleProject.Infrastructure/Logging/LoggingCommandHandlerDecorator.cs b/src/SampleProject.Infrastructure/Logging/LoggingCommandHandlerDecorator.cs index 33ede03..4f3b948 100644 --- a/src/SampleProject.Infrastructure/Logging/LoggingCommandHandlerDecorator.cs +++ b/src/SampleProject.Infrastructure/Logging/LoggingCommandHandlerDecorator.cs @@ -1,8 +1,4 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using MediatR; -using SampleProject.Application; +using MediatR; using SampleProject.Application.Configuration; using SampleProject.Application.Configuration.Commands; using SampleProject.Infrastructure.Processing.Outbox; @@ -10,6 +6,9 @@ using Serilog.Context; using Serilog.Core; using Serilog.Events; +using System; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Logging { @@ -44,19 +43,19 @@ public async Task Handle(T command, CancellationToken cancellationToken) { try { - this._logger.Information( + _logger.Information( "Executing command {Command}", command.GetType().Name); - var result = await _decorated.Handle(command, cancellationToken); + Unit result = await _decorated.Handle(command, cancellationToken); - this._logger.Information("Command {Command} processed successful", command.GetType().Name); + _logger.Information("Command {Command} processed successful", command.GetType().Name); return result; } catch (Exception exception) { - this._logger.Error(exception, "Command {Command} processing failed", command.GetType().Name); + _logger.Error(exception, "Command {Command} processing failed", command.GetType().Name); throw; } } diff --git a/src/SampleProject.Infrastructure/Logging/LoggingCommandHandlerWithResultDecorator.cs b/src/SampleProject.Infrastructure/Logging/LoggingCommandHandlerWithResultDecorator.cs index 9722402..81e7441 100644 --- a/src/SampleProject.Infrastructure/Logging/LoggingCommandHandlerWithResultDecorator.cs +++ b/src/SampleProject.Infrastructure/Logging/LoggingCommandHandlerWithResultDecorator.cs @@ -1,14 +1,13 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using SampleProject.Application; -using SampleProject.Application.Configuration; +using SampleProject.Application.Configuration; using SampleProject.Application.Configuration.Commands; using SampleProject.Infrastructure.Processing.Outbox; using Serilog; using Serilog.Context; using Serilog.Core; using Serilog.Events; +using System; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Logging { @@ -41,19 +40,19 @@ public async Task Handle(T command, CancellationToken cancellationToken { try { - this._logger.Information( + _logger.Information( "Executing command {@Command}", command); - var result = await _decorated.Handle(command, cancellationToken); + TResult result = await _decorated.Handle(command, cancellationToken); - this._logger.Information("Command processed successful, result {Result}", result); + _logger.Information("Command processed successful, result {Result}", result); return result; } catch (Exception exception) { - this._logger.Error(exception, "Command processing failed"); + _logger.Error(exception, "Command processing failed"); throw; } } diff --git a/src/SampleProject.Infrastructure/Processing/AllConstructorFinder.cs b/src/SampleProject.Infrastructure/Processing/AllConstructorFinder.cs index 110ff04..9109cd1 100644 --- a/src/SampleProject.Infrastructure/Processing/AllConstructorFinder.cs +++ b/src/SampleProject.Infrastructure/Processing/AllConstructorFinder.cs @@ -1,8 +1,8 @@ -using System; +using Autofac.Core.Activators.Reflection; +using System; using System.Collections.Concurrent; using System.Linq; using System.Reflection; -using Autofac.Core.Activators.Reflection; namespace SampleProject.Infrastructure.Processing { @@ -14,7 +14,7 @@ internal class AllConstructorFinder : IConstructorFinder public ConstructorInfo[] FindConstructors(Type targetType) { - var result = Cache.GetOrAdd(targetType, + ConstructorInfo[] result = Cache.GetOrAdd(targetType, t => t.GetTypeInfo().DeclaredConstructors.ToArray()); return result.Length > 0 ? result : throw new NoConstructorsFoundException(targetType); diff --git a/src/SampleProject.Infrastructure/Processing/Assemblies.cs b/src/SampleProject.Infrastructure/Processing/Assemblies.cs index 8abe9db..c706717 100644 --- a/src/SampleProject.Infrastructure/Processing/Assemblies.cs +++ b/src/SampleProject.Infrastructure/Processing/Assemblies.cs @@ -1,5 +1,5 @@ -using System.Reflection; -using SampleProject.Application.Orders.PlaceCustomerOrder; +using SampleProject.Application.Orders.PlaceCustomerOrder; +using System.Reflection; namespace SampleProject.Infrastructure.Processing { diff --git a/src/SampleProject.Infrastructure/Processing/CommandsExecutor.cs b/src/SampleProject.Infrastructure/Processing/CommandsExecutor.cs index 86601ae..0a9b4eb 100644 --- a/src/SampleProject.Infrastructure/Processing/CommandsExecutor.cs +++ b/src/SampleProject.Infrastructure/Processing/CommandsExecutor.cs @@ -1,8 +1,7 @@ -using System.Threading.Tasks; -using Autofac; +using Autofac; using MediatR; -using SampleProject.Application; using SampleProject.Application.Configuration.Commands; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Processing { @@ -10,18 +9,18 @@ public static class CommandsExecutor { public static async Task Execute(ICommand command) { - using (var scope = CompositionRoot.BeginLifetimeScope()) + using (ILifetimeScope scope = CompositionRoot.BeginLifetimeScope()) { - var mediator = scope.Resolve(); + IMediator mediator = scope.Resolve(); await mediator.Send(command); } } public static async Task Execute(ICommand command) { - using (var scope = CompositionRoot.BeginLifetimeScope()) + using (ILifetimeScope scope = CompositionRoot.BeginLifetimeScope()) { - var mediator = scope.Resolve(); + IMediator mediator = scope.Resolve(); return await mediator.Send(command); } } diff --git a/src/SampleProject.Infrastructure/Processing/CommandsScheduler.cs b/src/SampleProject.Infrastructure/Processing/CommandsScheduler.cs index 65e97ca..c834b67 100644 --- a/src/SampleProject.Infrastructure/Processing/CommandsScheduler.cs +++ b/src/SampleProject.Infrastructure/Processing/CommandsScheduler.cs @@ -1,12 +1,10 @@ -using System; -using System.Threading.Tasks; -using Dapper; -using MediatR; +using Dapper; using Newtonsoft.Json; -using SampleProject.Application; using SampleProject.Application.Configuration.Commands; using SampleProject.Application.Configuration.Data; using SampleProject.Application.Configuration.Processing; +using System; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Processing { @@ -21,7 +19,7 @@ public CommandsScheduler(ISqlConnectionFactory sqlConnectionFactory) public async Task EnqueueAsync(ICommand command) { - var connection = this._sqlConnectionFactory.GetOpenConnection(); + System.Data.IDbConnection connection = _sqlConnectionFactory.GetOpenConnection(); const string sqlInsert = "INSERT INTO [app].[InternalCommands] ([Id], [EnqueueDate] , [Type], [Data]) VALUES " + "(@Id, @EnqueueDate, @Type, @Data)"; diff --git a/src/SampleProject.Infrastructure/Processing/DomainEventsDispatcher.cs b/src/SampleProject.Infrastructure/Processing/DomainEventsDispatcher.cs index fe6789f..a321478 100644 --- a/src/SampleProject.Infrastructure/Processing/DomainEventsDispatcher.cs +++ b/src/SampleProject.Infrastructure/Processing/DomainEventsDispatcher.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Autofac; +using Autofac; using Autofac.Core; using MediatR; using Newtonsoft.Json; @@ -10,6 +6,10 @@ using SampleProject.Domain.SeedWork; using SampleProject.Infrastructure.Database; using SampleProject.Infrastructure.Processing.Outbox; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Processing { @@ -21,27 +21,27 @@ public class DomainEventsDispatcher : IDomainEventsDispatcher public DomainEventsDispatcher(IMediator mediator, ILifetimeScope scope, OrdersContext ordersContext) { - this._mediator = mediator; - this._scope = scope; - this._ordersContext = ordersContext; + _mediator = mediator; + _scope = scope; + _ordersContext = ordersContext; } public async Task DispatchEventsAsync() { - var domainEntities = this._ordersContext.ChangeTracker + List> domainEntities = _ordersContext.ChangeTracker .Entries() .Where(x => x.Entity.DomainEvents != null && x.Entity.DomainEvents.Any()).ToList(); - var domainEvents = domainEntities + List domainEvents = domainEntities .SelectMany(x => x.Entity.DomainEvents) .ToList(); - var domainEventNotifications = new List>(); - foreach (var domainEvent in domainEvents) + List> domainEventNotifications = new List>(); + foreach (IDomainEvent domainEvent in domainEvents) { Type domainEvenNotificationType = typeof(IDomainEventNotification<>); - var domainNotificationWithGenericType = domainEvenNotificationType.MakeGenericType(domainEvent.GetType()); - var domainNotification = _scope.ResolveOptional(domainNotificationWithGenericType, new List + Type domainNotificationWithGenericType = domainEvenNotificationType.MakeGenericType(domainEvent.GetType()); + object domainNotification = _scope.ResolveOptional(domainNotificationWithGenericType, new List { new NamedParameter("domainEvent", domainEvent) }); @@ -55,7 +55,7 @@ public async Task DispatchEventsAsync() domainEntities .ForEach(entity => entity.Entity.ClearDomainEvents()); - var tasks = domainEvents + IEnumerable tasks = domainEvents .Select(async (domainEvent) => { await _mediator.Publish(domainEvent); @@ -63,15 +63,15 @@ public async Task DispatchEventsAsync() await Task.WhenAll(tasks); - foreach (var domainEventNotification in domainEventNotifications) + foreach (IDomainEventNotification domainEventNotification in domainEventNotifications) { string type = domainEventNotification.GetType().FullName; - var data = JsonConvert.SerializeObject(domainEventNotification); + string data = JsonConvert.SerializeObject(domainEventNotification); OutboxMessage outboxMessage = new OutboxMessage( domainEventNotification.DomainEvent.OccurredOn, type, data); - this._ordersContext.OutboxMessages.Add(outboxMessage); + _ordersContext.OutboxMessages.Add(outboxMessage); } } } diff --git a/src/SampleProject.Infrastructure/Processing/DomainEventsDispatcherNotificationHandlerDecorator.cs b/src/SampleProject.Infrastructure/Processing/DomainEventsDispatcherNotificationHandlerDecorator.cs index ed914c1..d322393 100644 --- a/src/SampleProject.Infrastructure/Processing/DomainEventsDispatcherNotificationHandlerDecorator.cs +++ b/src/SampleProject.Infrastructure/Processing/DomainEventsDispatcherNotificationHandlerDecorator.cs @@ -1,7 +1,6 @@ -using System.Threading; +using MediatR; +using System.Threading; using System.Threading.Tasks; -using MediatR; -using SampleProject.Application.Configuration.DomainEvents; namespace SampleProject.Infrastructure.Processing { @@ -11,7 +10,7 @@ public class DomainEventsDispatcherNotificationHandlerDecorator : INotificati private readonly IDomainEventsDispatcher _domainEventsDispatcher; public DomainEventsDispatcherNotificationHandlerDecorator( - IDomainEventsDispatcher domainEventsDispatcher, + IDomainEventsDispatcher domainEventsDispatcher, INotificationHandler decorated) { _domainEventsDispatcher = domainEventsDispatcher; @@ -20,9 +19,9 @@ public DomainEventsDispatcherNotificationHandlerDecorator( public async Task Handle(T notification, CancellationToken cancellationToken) { - await this._decorated.Handle(notification, cancellationToken); + await _decorated.Handle(notification, cancellationToken); - await this._domainEventsDispatcher.DispatchEventsAsync(); + await _domainEventsDispatcher.DispatchEventsAsync(); } } } diff --git a/src/SampleProject.Infrastructure/Processing/InternalCommands/CommandsDispatcher.cs b/src/SampleProject.Infrastructure/Processing/InternalCommands/CommandsDispatcher.cs index 1541960..ace2559 100644 --- a/src/SampleProject.Infrastructure/Processing/InternalCommands/CommandsDispatcher.cs +++ b/src/SampleProject.Infrastructure/Processing/InternalCommands/CommandsDispatcher.cs @@ -1,12 +1,11 @@ -using System; -using System.Reflection; -using System.Threading.Tasks; -using MediatR; +using MediatR; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; -using SampleProject.Application.Configuration.Processing; using SampleProject.Application.Customers; using SampleProject.Infrastructure.Database; +using System; +using System.Reflection; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Processing.InternalCommands { @@ -16,23 +15,23 @@ public class CommandsDispatcher : ICommandsDispatcher private readonly OrdersContext _ordersContext; public CommandsDispatcher( - IMediator mediator, + IMediator mediator, OrdersContext ordersContext) { - this._mediator = mediator; - this._ordersContext = ordersContext; + _mediator = mediator; + _ordersContext = ordersContext; } public async Task DispatchCommandAsync(Guid id) { - var internalCommand = await this._ordersContext.InternalCommands.SingleOrDefaultAsync(x => x.Id == id); + InternalCommand internalCommand = await _ordersContext.InternalCommands.SingleOrDefaultAsync(x => x.Id == id); Type type = Assembly.GetAssembly(typeof(MarkCustomerAsWelcomedCommand)).GetType(internalCommand.Type); dynamic command = JsonConvert.DeserializeObject(internalCommand.Data, type); internalCommand.ProcessedDate = DateTime.UtcNow; - await this._mediator.Send(command); + await _mediator.Send(command); } } } \ No newline at end of file diff --git a/src/SampleProject.Infrastructure/Processing/InternalCommands/InternalCommandEntityTypeConfiguration.cs b/src/SampleProject.Infrastructure/Processing/InternalCommands/InternalCommandEntityTypeConfiguration.cs index 1c6a44a..c3122f1 100644 --- a/src/SampleProject.Infrastructure/Processing/InternalCommands/InternalCommandEntityTypeConfiguration.cs +++ b/src/SampleProject.Infrastructure/Processing/InternalCommands/InternalCommandEntityTypeConfiguration.cs @@ -9,7 +9,7 @@ internal sealed class InternalCommandEntityTypeConfiguration : IEntityTypeConfig public void Configure(EntityTypeBuilder builder) { builder.ToTable("InternalCommands", SchemaNames.Application); - + builder.HasKey(b => b.Id); builder.Property(b => b.Id).ValueGeneratedNever(); } diff --git a/src/SampleProject.Infrastructure/Processing/InternalCommands/ProcessInternalCommandsCommand.cs b/src/SampleProject.Infrastructure/Processing/InternalCommands/ProcessInternalCommandsCommand.cs index bfa0b62..45f48be 100644 --- a/src/SampleProject.Infrastructure/Processing/InternalCommands/ProcessInternalCommandsCommand.cs +++ b/src/SampleProject.Infrastructure/Processing/InternalCommands/ProcessInternalCommandsCommand.cs @@ -1,5 +1,4 @@ using MediatR; -using SampleProject.Application; using SampleProject.Application.Configuration.Commands; using SampleProject.Infrastructure.Processing.Outbox; diff --git a/src/SampleProject.Infrastructure/Processing/InternalCommands/ProcessInternalCommandsCommandHandler.cs b/src/SampleProject.Infrastructure/Processing/InternalCommands/ProcessInternalCommandsCommandHandler.cs index 4e21c01..c5ddd22 100644 --- a/src/SampleProject.Infrastructure/Processing/InternalCommands/ProcessInternalCommandsCommandHandler.cs +++ b/src/SampleProject.Infrastructure/Processing/InternalCommands/ProcessInternalCommandsCommandHandler.cs @@ -1,12 +1,11 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Dapper; +using Dapper; using MediatR; using Newtonsoft.Json; -using SampleProject.Application; using SampleProject.Application.Configuration.Commands; using SampleProject.Application.Configuration.Data; +using System; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Processing.InternalCommands { @@ -22,18 +21,18 @@ public ProcessInternalCommandsCommandHandler( public async Task Handle(ProcessInternalCommandsCommand command, CancellationToken cancellationToken) { - var connection = this._sqlConnectionFactory.GetOpenConnection(); + System.Data.IDbConnection connection = _sqlConnectionFactory.GetOpenConnection(); const string sql = "SELECT " + "[Command].[Type], " + "[Command].[Data] " + "FROM [app].[InternalCommands] AS [Command] " + "WHERE [Command].[ProcessedDate] IS NULL"; - var commands = await connection.QueryAsync(sql); + System.Collections.Generic.IEnumerable commands = await connection.QueryAsync(sql); - var internalCommandsList = commands.AsList(); + System.Collections.Generic.List internalCommandsList = commands.AsList(); - foreach (var internalCommand in internalCommandsList) + foreach (InternalCommandDto internalCommand in internalCommandsList) { Type type = Assemblies.Application.GetType(internalCommand.Type); dynamic commandToProcess = JsonConvert.DeserializeObject(internalCommand.Data, type); diff --git a/src/SampleProject.Infrastructure/Processing/InternalCommands/ProcessInternalCommandsJob.cs b/src/SampleProject.Infrastructure/Processing/InternalCommands/ProcessInternalCommandsJob.cs index 117571e..8cf34ed 100644 --- a/src/SampleProject.Infrastructure/Processing/InternalCommands/ProcessInternalCommandsJob.cs +++ b/src/SampleProject.Infrastructure/Processing/InternalCommands/ProcessInternalCommandsJob.cs @@ -1,5 +1,5 @@ -using System.Threading.Tasks; -using Quartz; +using Quartz; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Processing.InternalCommands { diff --git a/src/SampleProject.Infrastructure/Processing/MediatorModule.cs b/src/SampleProject.Infrastructure/Processing/MediatorModule.cs index 33efeb2..19be2e6 100644 --- a/src/SampleProject.Infrastructure/Processing/MediatorModule.cs +++ b/src/SampleProject.Infrastructure/Processing/MediatorModule.cs @@ -1,15 +1,14 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using Autofac; +using Autofac; using Autofac.Core; using Autofac.Features.Variance; using FluentValidation; using MediatR; using MediatR.Pipeline; using SampleProject.Application.Configuration.Validation; -using SampleProject.Application.Orders.GetCustomerOrders; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; namespace SampleProject.Infrastructure.Processing { @@ -25,14 +24,14 @@ protected override void Load(ContainerBuilder builder) builder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly).AsImplementedInterfaces(); - var mediatrOpenTypes = new[] + Type[] mediatrOpenTypes = new[] { typeof(IRequestHandler<,>), typeof(INotificationHandler<>), typeof(IValidator<>), }; - foreach (var mediatrOpenType in mediatrOpenTypes) + foreach (Type mediatrOpenType in mediatrOpenTypes) { builder .RegisterAssemblyTypes(Assemblies.Application, ThisAssembly) @@ -46,7 +45,7 @@ protected override void Load(ContainerBuilder builder) builder.Register(ctx => { - var c = ctx.Resolve(); + IComponentContext c = ctx.Resolve(); return t => c.Resolve(t); }); @@ -61,9 +60,15 @@ private class ScopedContravariantRegistrationSource : IRegistrationSource public ScopedContravariantRegistrationSource(params Type[] types) { if (types == null) + { throw new ArgumentNullException(nameof(types)); + } + if (!types.All(x => x.IsGenericTypeDefinition)) + { throw new ArgumentException("Supplied types should be generic type definitions"); + } + _types.AddRange(types); } @@ -71,15 +76,17 @@ public IEnumerable RegistrationsFor( Service service, Func> registrationAccessor) { - var components = _source.RegistrationsFor(service, registrationAccessor); - foreach (var c in components) + IEnumerable components = _source.RegistrationsFor(service, registrationAccessor); + foreach (IComponentRegistration c in components) { - var defs = c.Target.Services + IEnumerable defs = c.Target.Services .OfType() .Select(x => x.ServiceType.GetGenericTypeDefinition()); if (defs.Any(_types.Contains)) + { yield return c; + } } } diff --git a/src/SampleProject.Infrastructure/Processing/Outbox/OutboxMessage.cs b/src/SampleProject.Infrastructure/Processing/Outbox/OutboxMessage.cs index d0883e7..ec333b6 100644 --- a/src/SampleProject.Infrastructure/Processing/Outbox/OutboxMessage.cs +++ b/src/SampleProject.Infrastructure/Processing/Outbox/OutboxMessage.cs @@ -16,15 +16,15 @@ public class OutboxMessage private OutboxMessage() { - + } public OutboxMessage(DateTime occurredOn, string type, string data) { - this.Id = Guid.NewGuid(); - this.OccurredOn = occurredOn; - this.Type = type; - this.Data = data; + Id = Guid.NewGuid(); + OccurredOn = occurredOn; + Type = type; + Data = data; } } } \ No newline at end of file diff --git a/src/SampleProject.Infrastructure/Processing/Outbox/OutboxMessageEntityTypeConfiguration.cs b/src/SampleProject.Infrastructure/Processing/Outbox/OutboxMessageEntityTypeConfiguration.cs index 0521696..d3fa017 100644 --- a/src/SampleProject.Infrastructure/Processing/Outbox/OutboxMessageEntityTypeConfiguration.cs +++ b/src/SampleProject.Infrastructure/Processing/Outbox/OutboxMessageEntityTypeConfiguration.cs @@ -9,7 +9,7 @@ internal sealed class OutboxMessageEntityTypeConfiguration : IEntityTypeConfigur public void Configure(EntityTypeBuilder builder) { builder.ToTable("OutboxMessages", SchemaNames.Application); - + builder.HasKey(b => b.Id); builder.Property(b => b.Id).ValueGeneratedNever(); } diff --git a/src/SampleProject.Infrastructure/Processing/Outbox/ProcessOutboxCommand.cs b/src/SampleProject.Infrastructure/Processing/Outbox/ProcessOutboxCommand.cs index 9bef7fb..7febfcf 100644 --- a/src/SampleProject.Infrastructure/Processing/Outbox/ProcessOutboxCommand.cs +++ b/src/SampleProject.Infrastructure/Processing/Outbox/ProcessOutboxCommand.cs @@ -1,5 +1,4 @@ using MediatR; -using SampleProject.Application; using SampleProject.Application.Configuration.Commands; namespace SampleProject.Infrastructure.Processing.Outbox diff --git a/src/SampleProject.Infrastructure/Processing/Outbox/ProcessOutboxCommandHandler.cs b/src/SampleProject.Infrastructure/Processing/Outbox/ProcessOutboxCommandHandler.cs index 80357e6..c66a5f7 100644 --- a/src/SampleProject.Infrastructure/Processing/Outbox/ProcessOutboxCommandHandler.cs +++ b/src/SampleProject.Infrastructure/Processing/Outbox/ProcessOutboxCommandHandler.cs @@ -1,16 +1,15 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Dapper; +using Dapper; using MediatR; using Newtonsoft.Json; -using SampleProject.Application; using SampleProject.Application.Configuration.Commands; using SampleProject.Application.Configuration.Data; using SampleProject.Application.Configuration.DomainEvents; using Serilog.Context; using Serilog.Core; using Serilog.Events; +using System; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Processing.Outbox { @@ -28,7 +27,7 @@ public ProcessOutboxCommandHandler(IMediator mediator, ISqlConnectionFactory sql public async Task Handle(ProcessOutboxCommand command, CancellationToken cancellationToken) { - var connection = this._sqlConnectionFactory.GetOpenConnection(); + System.Data.IDbConnection connection = _sqlConnectionFactory.GetOpenConnection(); const string sql = "SELECT " + "[OutboxMessage].[Id], " + "[OutboxMessage].[Type], " + @@ -36,23 +35,23 @@ public async Task Handle(ProcessOutboxCommand command, CancellationToken c "FROM [app].[OutboxMessages] AS [OutboxMessage] " + "WHERE [OutboxMessage].[ProcessedDate] IS NULL"; - var messages = await connection.QueryAsync(sql); - var messagesList = messages.AsList(); + System.Collections.Generic.IEnumerable messages = await connection.QueryAsync(sql); + System.Collections.Generic.List messagesList = messages.AsList(); const string sqlUpdateProcessedDate = "UPDATE [app].[OutboxMessages] " + "SET [ProcessedDate] = @Date " + "WHERE [Id] = @Id"; if (messagesList.Count > 0) { - foreach (var message in messagesList) + foreach (OutboxMessageDto message in messagesList) { Type type = Assemblies.Application .GetType(message.Type); - var request = JsonConvert.DeserializeObject(message.Data, type) as IDomainEventNotification; + IDomainEventNotification request = JsonConvert.DeserializeObject(message.Data, type) as IDomainEventNotification; using (LogContext.Push(new OutboxMessageContextEnricher(request))) { - await this._mediator.Publish(request, cancellationToken); + await _mediator.Publish(request, cancellationToken); await connection.ExecuteAsync(sqlUpdateProcessedDate, new { diff --git a/src/SampleProject.Infrastructure/Processing/Outbox/ProcessOutboxJob.cs b/src/SampleProject.Infrastructure/Processing/Outbox/ProcessOutboxJob.cs index a0d3c75..b862fae 100644 --- a/src/SampleProject.Infrastructure/Processing/Outbox/ProcessOutboxJob.cs +++ b/src/SampleProject.Infrastructure/Processing/Outbox/ProcessOutboxJob.cs @@ -1,5 +1,5 @@ -using System.Threading.Tasks; -using Quartz; +using Quartz; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Processing.Outbox { diff --git a/src/SampleProject.Infrastructure/Processing/ProcessingModule.cs b/src/SampleProject.Infrastructure/Processing/ProcessingModule.cs index a6f3138..3f27603 100644 --- a/src/SampleProject.Infrastructure/Processing/ProcessingModule.cs +++ b/src/SampleProject.Infrastructure/Processing/ProcessingModule.cs @@ -1,13 +1,12 @@ -using System.Reflection; -using Autofac; +using Autofac; using MediatR; -using SampleProject.Application; using SampleProject.Application.Configuration.Commands; using SampleProject.Application.Configuration.DomainEvents; using SampleProject.Application.Configuration.Processing; using SampleProject.Application.Payments; using SampleProject.Infrastructure.Logging; using SampleProject.Infrastructure.Processing.InternalCommands; +using System.Reflection; namespace SampleProject.Infrastructure.Processing { @@ -23,7 +22,7 @@ protected override void Load(ContainerBuilder builder) .AsClosedTypesOf(typeof(IDomainEventNotification<>)).InstancePerDependency(); builder.RegisterGenericDecorator( - typeof(DomainEventsDispatcherNotificationHandlerDecorator<>), + typeof(DomainEventsDispatcherNotificationHandlerDecorator<>), typeof(INotificationHandler<>)); builder.RegisterGenericDecorator( diff --git a/src/SampleProject.Infrastructure/Processing/QueriesExecutor.cs b/src/SampleProject.Infrastructure/Processing/QueriesExecutor.cs index 9fd1ef3..97a5501 100644 --- a/src/SampleProject.Infrastructure/Processing/QueriesExecutor.cs +++ b/src/SampleProject.Infrastructure/Processing/QueriesExecutor.cs @@ -1,8 +1,7 @@ -using System.Threading.Tasks; -using Autofac; +using Autofac; using MediatR; -using SampleProject.Application; using SampleProject.Application.Configuration.Queries; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Processing { @@ -10,9 +9,9 @@ public static class QueriesExecutor { public static async Task Execute(IQuery query) { - using (var scope = CompositionRoot.BeginLifetimeScope()) + using (ILifetimeScope scope = CompositionRoot.BeginLifetimeScope()) { - var mediator = scope.Resolve(); + IMediator mediator = scope.Resolve(); return await mediator.Send(query); } diff --git a/src/SampleProject.Infrastructure/Processing/UnitOfWorkCommandHandlerDecorator.cs b/src/SampleProject.Infrastructure/Processing/UnitOfWorkCommandHandlerDecorator.cs index e956ea6..73ff581 100644 --- a/src/SampleProject.Infrastructure/Processing/UnitOfWorkCommandHandlerDecorator.cs +++ b/src/SampleProject.Infrastructure/Processing/UnitOfWorkCommandHandlerDecorator.cs @@ -1,16 +1,15 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using MediatR; +using MediatR; using Microsoft.EntityFrameworkCore; -using SampleProject.Application; using SampleProject.Application.Configuration.Commands; using SampleProject.Domain.SeedWork; using SampleProject.Infrastructure.Database; +using System; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Processing { - public class UnitOfWorkCommandHandlerDecorator : ICommandHandler where T:ICommand + public class UnitOfWorkCommandHandlerDecorator : ICommandHandler where T : ICommand { private readonly ICommandHandler _decorated; @@ -19,8 +18,8 @@ public class UnitOfWorkCommandHandlerDecorator : ICommandHandler where T:I private readonly OrdersContext _ordersContext; public UnitOfWorkCommandHandlerDecorator( - ICommandHandler decorated, - IUnitOfWork unitOfWork, + ICommandHandler decorated, + IUnitOfWork unitOfWork, OrdersContext ordersContext) { _decorated = decorated; @@ -30,11 +29,11 @@ public UnitOfWorkCommandHandlerDecorator( public async Task Handle(T command, CancellationToken cancellationToken) { - await this._decorated.Handle(command, cancellationToken); + await _decorated.Handle(command, cancellationToken); if (command is InternalCommandBase) { - var internalCommand = + InternalCommands.InternalCommand internalCommand = await _ordersContext.InternalCommands.FirstOrDefaultAsync(x => x.Id == command.Id, cancellationToken: cancellationToken); @@ -44,7 +43,7 @@ await _ordersContext.InternalCommands.FirstOrDefaultAsync(x => x.Id == command.I } } - await this._unitOfWork.CommitAsync(cancellationToken); + await _unitOfWork.CommitAsync(cancellationToken); return Unit.Value; } diff --git a/src/SampleProject.Infrastructure/Processing/UnitOfWorkCommandHandlerWithResultDecorator.cs b/src/SampleProject.Infrastructure/Processing/UnitOfWorkCommandHandlerWithResultDecorator.cs index 2fd86f0..7a959a1 100644 --- a/src/SampleProject.Infrastructure/Processing/UnitOfWorkCommandHandlerWithResultDecorator.cs +++ b/src/SampleProject.Infrastructure/Processing/UnitOfWorkCommandHandlerWithResultDecorator.cs @@ -1,11 +1,10 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using SampleProject.Application; +using Microsoft.EntityFrameworkCore; using SampleProject.Application.Configuration.Commands; using SampleProject.Domain.SeedWork; using SampleProject.Infrastructure.Database; +using System; +using System.Threading; +using System.Threading.Tasks; namespace SampleProject.Infrastructure.Processing { @@ -18,8 +17,8 @@ public class UnitOfWorkCommandHandlerWithResultDecorator : ICommandH private readonly OrdersContext _ordersContext; public UnitOfWorkCommandHandlerWithResultDecorator( - ICommandHandler decorated, - IUnitOfWork unitOfWork, + ICommandHandler decorated, + IUnitOfWork unitOfWork, OrdersContext ordersContext) { _decorated = decorated; @@ -29,11 +28,11 @@ public UnitOfWorkCommandHandlerWithResultDecorator( public async Task Handle(T command, CancellationToken cancellationToken) { - var result = await this._decorated.Handle(command, cancellationToken); + TResult result = await _decorated.Handle(command, cancellationToken); if (command is InternalCommandBase) { - var internalCommand = await _ordersContext.InternalCommands.FirstOrDefaultAsync(x => x.Id == command.Id, cancellationToken: cancellationToken); + InternalCommands.InternalCommand internalCommand = await _ordersContext.InternalCommands.FirstOrDefaultAsync(x => x.Id == command.Id, cancellationToken: cancellationToken); if (internalCommand != null) { @@ -41,7 +40,7 @@ public async Task Handle(T command, CancellationToken cancellationToken } } - await this._unitOfWork.CommitAsync(cancellationToken); + await _unitOfWork.CommitAsync(cancellationToken); return result; } diff --git a/src/SampleProject.Infrastructure/Quartz/JobFactory.cs b/src/SampleProject.Infrastructure/Quartz/JobFactory.cs index 65af0a6..e2af878 100644 --- a/src/SampleProject.Infrastructure/Quartz/JobFactory.cs +++ b/src/SampleProject.Infrastructure/Quartz/JobFactory.cs @@ -10,14 +10,14 @@ public class JobFactory : IJobFactory public JobFactory(IContainer container) { - this._container = container; + _container = container; } public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler) { - var job = _container.Resolve(bundle.JobDetail.JobType); - - return job as IJob; + object job = _container.Resolve(bundle.JobDetail.JobType); + + return job as IJob; } public void ReturnJob(IJob job) diff --git a/src/SampleProject.Infrastructure/Quartz/QuartzModule.cs b/src/SampleProject.Infrastructure/Quartz/QuartzModule.cs index 19c1733..486508b 100644 --- a/src/SampleProject.Infrastructure/Quartz/QuartzModule.cs +++ b/src/SampleProject.Infrastructure/Quartz/QuartzModule.cs @@ -1,6 +1,6 @@ -using System.Reflection; -using Autofac; +using Autofac; using Quartz; +using System.Reflection; using Module = Autofac.Module; namespace SampleProject.Infrastructure.Quartz diff --git a/src/SampleProject.Infrastructure/SeedWork/DbSetExtensions.cs b/src/SampleProject.Infrastructure/SeedWork/DbSetExtensions.cs index 7431316..747c160 100644 --- a/src/SampleProject.Infrastructure/SeedWork/DbSetExtensions.cs +++ b/src/SampleProject.Infrastructure/SeedWork/DbSetExtensions.cs @@ -1,6 +1,6 @@ -using System.Linq; -using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Query.Internal; +using System.Linq; namespace SampleProject.Infrastructure.SeedWork { diff --git a/src/SampleProject.Infrastructure/SeedWork/StronglyTypedIdValueConverterSelector.cs b/src/SampleProject.Infrastructure/SeedWork/StronglyTypedIdValueConverterSelector.cs index c63d1f1..c724384 100644 --- a/src/SampleProject.Infrastructure/SeedWork/StronglyTypedIdValueConverterSelector.cs +++ b/src/SampleProject.Infrastructure/SeedWork/StronglyTypedIdValueConverterSelector.cs @@ -1,8 +1,8 @@ -using System; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SampleProject.Domain.SeedWork; +using System; using System.Collections.Concurrent; using System.Collections.Generic; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using SampleProject.Domain.SeedWork; namespace SampleProject.Infrastructure.SeedWork { @@ -14,28 +14,28 @@ public class StronglyTypedIdValueConverterSelector : ValueConverterSelector private readonly ConcurrentDictionary<(Type ModelClrType, Type ProviderClrType), ValueConverterInfo> _converters = new ConcurrentDictionary<(Type ModelClrType, Type ProviderClrType), ValueConverterInfo>(); - public StronglyTypedIdValueConverterSelector(ValueConverterSelectorDependencies dependencies) + public StronglyTypedIdValueConverterSelector(ValueConverterSelectorDependencies dependencies) : base(dependencies) { } public override IEnumerable Select(Type modelClrType, Type providerClrType = null) { - var baseConverters = base.Select(modelClrType, providerClrType); - foreach (var converter in baseConverters) + IEnumerable baseConverters = base.Select(modelClrType, providerClrType); + foreach (ValueConverterInfo converter in baseConverters) { yield return converter; } - var underlyingModelType = UnwrapNullableType(modelClrType); - var underlyingProviderType = UnwrapNullableType(providerClrType); + Type underlyingModelType = UnwrapNullableType(modelClrType); + Type underlyingProviderType = UnwrapNullableType(providerClrType); if (underlyingProviderType is null || underlyingProviderType == typeof(Guid)) { - var isTypedIdValue = typeof(TypedIdValueBase).IsAssignableFrom(underlyingModelType); + bool isTypedIdValue = typeof(TypedIdValueBase).IsAssignableFrom(underlyingModelType); if (isTypedIdValue) { - var converterType = typeof(TypedIdValueConverter<>).MakeGenericType(underlyingModelType); + Type converterType = typeof(TypedIdValueConverter<>).MakeGenericType(underlyingModelType); yield return _converters.GetOrAdd((underlyingModelType, typeof(Guid)), _ => { diff --git a/src/SampleProject.Infrastructure/SeedWork/TypedIdValueConverter.cs b/src/SampleProject.Infrastructure/SeedWork/TypedIdValueConverter.cs index 2332193..f38cdfc 100644 --- a/src/SampleProject.Infrastructure/SeedWork/TypedIdValueConverter.cs +++ b/src/SampleProject.Infrastructure/SeedWork/TypedIdValueConverter.cs @@ -1,17 +1,20 @@ -using System; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using SampleProject.Domain.SeedWork; +using System; namespace SampleProject.Infrastructure.SeedWork { public class TypedIdValueConverter : ValueConverter where TTypedIdValue : TypedIdValueBase { - public TypedIdValueConverter(ConverterMappingHints mappingHints = null) + public TypedIdValueConverter(ConverterMappingHints mappingHints = null) : base(id => id.Value, value => Create(value), mappingHints) { } - private static TTypedIdValue Create(Guid id) => Activator.CreateInstance(typeof(TTypedIdValue), id) as TTypedIdValue; + private static TTypedIdValue Create(Guid id) + { + return Activator.CreateInstance(typeof(TTypedIdValue), id) as TTypedIdValue; + } } } \ No newline at end of file diff --git a/src/Tests/SampleProject.IntegrationTests/Customers/CustomersTests.cs b/src/Tests/SampleProject.IntegrationTests/Customers/CustomersTests.cs index 72e6e5e..946018d 100644 --- a/src/Tests/SampleProject.IntegrationTests/Customers/CustomersTests.cs +++ b/src/Tests/SampleProject.IntegrationTests/Customers/CustomersTests.cs @@ -1,12 +1,12 @@ -using System.Data.SqlClient; -using System.Threading.Tasks; -using NUnit.Framework; +using NUnit.Framework; using SampleProject.Application.Customers.GetCustomerDetails; using SampleProject.Application.Customers.IntegrationHandlers; using SampleProject.Application.Customers.RegisterCustomer; using SampleProject.Domain.Customers; using SampleProject.Infrastructure.Processing; using SampleProject.IntegrationTests.SeedWork; +using System.Data.SqlClient; +using System.Threading.Tasks; namespace SampleProject.IntegrationTests.Customers { @@ -18,20 +18,20 @@ public async Task RegisterCustomerTest() { const string email = "newCustomer@mail.com"; const string name = "Sample Company"; - - var customer = await CommandsExecutor.Execute(new RegisterCustomerCommand(email, name)); - var customerDetails = await QueriesExecutor.Execute(new GetCustomerDetailsQuery(customer.Id)); + + Application.Customers.CustomerDto customer = await CommandsExecutor.Execute(new RegisterCustomerCommand(email, name)); + CustomerDetailsDto customerDetails = await QueriesExecutor.Execute(new GetCustomerDetailsQuery(customer.Id)); Assert.That(customerDetails, Is.Not.Null); Assert.That(customerDetails.Name, Is.EqualTo(name)); Assert.That(customerDetails.Email, Is.EqualTo(email)); - var connection = new SqlConnection(ConnectionString); - var messagesList = await OutboxMessagesHelper.GetOutboxMessages(connection); + SqlConnection connection = new SqlConnection(ConnectionString); + System.Collections.Generic.List messagesList = await OutboxMessagesHelper.GetOutboxMessages(connection); Assert.That(messagesList.Count, Is.EqualTo(1)); - var customerRegisteredNotification = + CustomerRegisteredNotification customerRegisteredNotification = OutboxMessagesHelper.Deserialize(messagesList[0]); Assert.That(customerRegisteredNotification.CustomerId, Is.EqualTo(new CustomerId(customer.Id))); diff --git a/src/Tests/SampleProject.IntegrationTests/Orders/OrdersTests.cs b/src/Tests/SampleProject.IntegrationTests/Orders/OrdersTests.cs index e7acdd8..f8915db 100644 --- a/src/Tests/SampleProject.IntegrationTests/Orders/OrdersTests.cs +++ b/src/Tests/SampleProject.IntegrationTests/Orders/OrdersTests.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Data.SqlClient; -using System.Threading.Tasks; -using NUnit.Framework; +using NUnit.Framework; using SampleProject.Application.Customers.IntegrationHandlers; using SampleProject.Application.Customers.RegisterCustomer; using SampleProject.Application.Orders; @@ -13,6 +9,10 @@ using SampleProject.Domain.Customers.Orders; using SampleProject.Infrastructure.Processing; using SampleProject.IntegrationTests.SeedWork; +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.Threading.Tasks; namespace SampleProject.IntegrationTests.Orders { @@ -22,15 +22,15 @@ public class OrdersTests : TestBase [Test] public async Task PlaceOrder_Test() { - var customerEmail = "email@email.com"; - var customer = await CommandsExecutor.Execute(new RegisterCustomerCommand(customerEmail, "Sample Customer")); + string customerEmail = "email@email.com"; + Application.Customers.CustomerDto customer = await CommandsExecutor.Execute(new RegisterCustomerCommand(customerEmail, "Sample Customer")); List products = new List(); - var productId = Guid.Parse("9DB6E474-AE74-4CF5-A0DC-BA23A42E2566"); + Guid productId = Guid.Parse("9DB6E474-AE74-4CF5-A0DC-BA23A42E2566"); products.Add(new ProductDto(productId, 2)); - var orderId = await CommandsExecutor.Execute(new PlaceCustomerOrderCommand(customer.Id, products, "EUR")); + Guid orderId = await CommandsExecutor.Execute(new PlaceCustomerOrderCommand(customer.Id, products, "EUR")); - var orderDetails = await QueriesExecutor.Execute(new GetCustomerOrderDetailsQuery(orderId)); + OrderDetailsDto orderDetails = await QueriesExecutor.Execute(new GetCustomerOrderDetailsQuery(orderId)); Assert.That(orderDetails, Is.Not.Null); Assert.That(orderDetails.Value, Is.EqualTo(70)); @@ -38,22 +38,22 @@ public async Task PlaceOrder_Test() Assert.That(orderDetails.Products[0].Quantity, Is.EqualTo(2)); Assert.That(orderDetails.Products[0].Id, Is.EqualTo(productId)); - var connection = new SqlConnection(ConnectionString); - var messagesList = await OutboxMessagesHelper.GetOutboxMessages(connection); - + SqlConnection connection = new SqlConnection(ConnectionString); + List messagesList = await OutboxMessagesHelper.GetOutboxMessages(connection); + Assert.That(messagesList.Count, Is.EqualTo(3)); - - var customerRegisteredNotification = + + CustomerRegisteredNotification customerRegisteredNotification = OutboxMessagesHelper.Deserialize(messagesList[0]); Assert.That(customerRegisteredNotification.CustomerId, Is.EqualTo(new CustomerId(customer.Id))); - var orderPlaced = + OrderPlacedNotification orderPlaced = OutboxMessagesHelper.Deserialize(messagesList[1]); Assert.That(orderPlaced.OrderId, Is.EqualTo(new OrderId(orderId))); - var paymentCreated = + PaymentCreatedNotification paymentCreated = OutboxMessagesHelper.Deserialize(messagesList[2]); Assert.That(paymentCreated, Is.Not.Null); diff --git a/src/Tests/SampleProject.IntegrationTests/SeedWork/CacheStore.cs b/src/Tests/SampleProject.IntegrationTests/SeedWork/CacheStore.cs index 85447d0..f91ef06 100644 --- a/src/Tests/SampleProject.IntegrationTests/SeedWork/CacheStore.cs +++ b/src/Tests/SampleProject.IntegrationTests/SeedWork/CacheStore.cs @@ -1,14 +1,13 @@ -using System; +using SampleProject.Infrastructure.Caching; +using System; using System.Collections; -using System.Collections.Generic; using System.Collections.Specialized; -using SampleProject.Infrastructure.Caching; namespace SampleProject.IntegrationTests.SeedWork { public class CacheStore : ICacheStore { - private IDictionary dictionary = new ListDictionary(); + private readonly IDictionary dictionary = new ListDictionary(); public void Add(TItem item, ICacheKey key, TimeSpan? expirationTime = null) { dictionary.Add(key, item); diff --git a/src/Tests/SampleProject.IntegrationTests/SeedWork/ExecutionContextMock.cs b/src/Tests/SampleProject.IntegrationTests/SeedWork/ExecutionContextMock.cs index e1310c4..246a66f 100644 --- a/src/Tests/SampleProject.IntegrationTests/SeedWork/ExecutionContextMock.cs +++ b/src/Tests/SampleProject.IntegrationTests/SeedWork/ExecutionContextMock.cs @@ -1,5 +1,5 @@ -using System; -using SampleProject.Application.Configuration; +using SampleProject.Application.Configuration; +using System; namespace SampleProject.IntegrationTests.SeedWork { diff --git a/src/Tests/SampleProject.IntegrationTests/SeedWork/OutboxMessagesHelper.cs b/src/Tests/SampleProject.IntegrationTests/SeedWork/OutboxMessagesHelper.cs index 3fe304b..8e80de6 100644 --- a/src/Tests/SampleProject.IntegrationTests/SeedWork/OutboxMessagesHelper.cs +++ b/src/Tests/SampleProject.IntegrationTests/SeedWork/OutboxMessagesHelper.cs @@ -1,13 +1,13 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Reflection; -using System.Threading.Tasks; -using Dapper; +using Dapper; using MediatR; using Newtonsoft.Json; using SampleProject.Application.Payments; using SampleProject.Infrastructure.Processing.Outbox; +using System; +using System.Collections.Generic; +using System.Data; +using System.Reflection; +using System.Threading.Tasks; namespace SampleProject.IntegrationTests.SeedWork { @@ -22,7 +22,7 @@ public static async Task> GetOutboxMessages(IDbConnection "FROM [app].[OutboxMessages] AS [OutboxMessage] " + "ORDER BY [OutboxMessage].[OccurredOn]"; - var messages = await connection.QueryAsync(sql); + IEnumerable messages = await connection.QueryAsync(sql); return messages.AsList(); } diff --git a/src/Tests/SampleProject.IntegrationTests/SeedWork/TestBase.cs b/src/Tests/SampleProject.IntegrationTests/SeedWork/TestBase.cs index 42c797f..bc4f304 100644 --- a/src/Tests/SampleProject.IntegrationTests/SeedWork/TestBase.cs +++ b/src/Tests/SampleProject.IntegrationTests/SeedWork/TestBase.cs @@ -1,7 +1,3 @@ -using System; -using System.Data; -using System.Data.SqlClient; -using System.Threading.Tasks; using Dapper; using Microsoft.Extensions.DependencyInjection; using NSubstitute; @@ -9,6 +5,10 @@ using SampleProject.Application.Configuration.Emails; using SampleProject.Infrastructure; using Serilog.Core; +using System; +using System.Data; +using System.Data.SqlClient; +using System.Threading.Tasks; namespace SampleProject.IntegrationTests.SeedWork { @@ -34,11 +34,11 @@ public async Task BeforeEachTest() $"Define connection string to integration tests database using environment variable: {connectionStringEnvironmentVariable}"); } - await using var sqlConnection = new SqlConnection(ConnectionString); + await using SqlConnection sqlConnection = new SqlConnection(ConnectionString); await ClearDatabase(sqlConnection); - EmailsSettings = new EmailsSettings {FromAddressEmail = "from@mail.com"}; + EmailsSettings = new EmailsSettings { FromAddressEmail = "from@mail.com" }; EmailSender = Substitute.For(); @@ -46,13 +46,13 @@ public async Task BeforeEachTest() ApplicationStartup.Initialize( new ServiceCollection(), - ConnectionString, + ConnectionString, new CacheStore(), EmailSender, EmailsSettings, Logger.None, ExecutionContext, - runQuartz:false); + runQuartz: false); } private static async Task ClearDatabase(IDbConnection connection) diff --git a/src/Tests/SampleProject.UnitTests/Customers/CustomerFactory.cs b/src/Tests/SampleProject.UnitTests/Customers/CustomerFactory.cs index e6158b9..e322a73 100644 --- a/src/Tests/SampleProject.UnitTests/Customers/CustomerFactory.cs +++ b/src/Tests/SampleProject.UnitTests/Customers/CustomerFactory.cs @@ -7,8 +7,8 @@ public class CustomerFactory { public static Customer Create() { - var customerUniquenessChecker = Substitute.For(); - var email = "customer@mail.com"; + ICustomerUniquenessChecker customerUniquenessChecker = Substitute.For(); + string email = "customer@mail.com"; customerUniquenessChecker.IsUnique(email).Returns(true); return Customer.CreateRegistered(email, "Name", customerUniquenessChecker); diff --git a/src/Tests/SampleProject.UnitTests/Customers/CustomerRegistrationTests.cs b/src/Tests/SampleProject.UnitTests/Customers/CustomerRegistrationTests.cs index 0a58152..28c30ab 100644 --- a/src/Tests/SampleProject.UnitTests/Customers/CustomerRegistrationTests.cs +++ b/src/Tests/SampleProject.UnitTests/Customers/CustomerRegistrationTests.cs @@ -13,12 +13,12 @@ public class CustomerRegistrationTests : TestBase public void GivenCustomerEmailIsUnique_WhenCustomerIsRegistering_IsSuccessful() { // Arrange - var customerUniquenessChecker = Substitute.For(); + ICustomerUniquenessChecker customerUniquenessChecker = Substitute.For(); const string email = "testEmail@email.com"; customerUniquenessChecker.IsUnique(email).Returns(true); // Act - var customer = Customer.CreateRegistered(email, "Sample name", customerUniquenessChecker); + Customer customer = Customer.CreateRegistered(email, "Sample name", customerUniquenessChecker); // Assert AssertPublishedDomainEvent(customer); @@ -28,7 +28,7 @@ public void GivenCustomerEmailIsUnique_WhenCustomerIsRegistering_IsSuccessful() public void GivenCustomerEmailIsNotUnique_WhenCustomerIsRegistering_BreaksCustomerEmailMustBeUniqueRule() { // Arrange - var customerUniquenessChecker = Substitute.For(); + ICustomerUniquenessChecker customerUniquenessChecker = Substitute.For(); const string email = "testEmail@email.com"; customerUniquenessChecker.IsUnique(email).Returns(false); diff --git a/src/Tests/SampleProject.UnitTests/Customers/PlaceOrderTests.cs b/src/Tests/SampleProject.UnitTests/Customers/PlaceOrderTests.cs index e93bedb..9d387a2 100644 --- a/src/Tests/SampleProject.UnitTests/Customers/PlaceOrderTests.cs +++ b/src/Tests/SampleProject.UnitTests/Customers/PlaceOrderTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using NUnit.Framework; +using NUnit.Framework; using SampleProject.Domain.Customers.Orders; using SampleProject.Domain.Customers.Orders.Events; using SampleProject.Domain.Customers.Rules; @@ -8,6 +6,8 @@ using SampleProject.Domain.Products; using SampleProject.Domain.SharedKernel; using SampleProject.UnitTests.SeedWork; +using System; +using System.Collections.Generic; namespace SampleProject.UnitTests.Customers { @@ -18,28 +18,30 @@ public class PlaceOrderTests : TestBase public void PlaceOrder_WhenAtLeastOneProductIsAdded_IsSuccessful() { // Arrange - var customer = CustomerFactory.Create(); + Domain.Customers.Customer customer = CustomerFactory.Create(); + + List orderProductsData = new List + { + new OrderProductData(SampleProducts.Product1Id, 2) + }; - var orderProductsData = new List(); - orderProductsData.Add(new OrderProductData(SampleProducts.Product1Id, 2)); - - var allProductPrices = new List + List allProductPrices = new List { SampleProductPrices.Product1EUR, SampleProductPrices.Product1USD }; - + const string currency = "EUR"; - var conversionRates = GetConversionRates(); - + List conversionRates = GetConversionRates(); + // Act customer.PlaceOrder( - orderProductsData, - allProductPrices, - currency, + orderProductsData, + allProductPrices, + currency, conversionRates); // Assert - var orderPlaced = AssertPublishedDomainEvent(customer); + OrderPlacedEvent orderPlaced = AssertPublishedDomainEvent(customer); Assert.That(orderPlaced.Value, Is.EqualTo(MoneyValue.Of(200, "EUR"))); } @@ -47,17 +49,17 @@ public void PlaceOrder_WhenAtLeastOneProductIsAdded_IsSuccessful() public void PlaceOrder_WhenNoProductIsAdded_BreaksOrderMustHaveAtLeastOneProductRule() { // Arrange - var customer = CustomerFactory.Create(); + Domain.Customers.Customer customer = CustomerFactory.Create(); - var orderProductsData = new List(); + List orderProductsData = new List(); - var allProductPrices = new List + List allProductPrices = new List { SampleProductPrices.Product1EUR, SampleProductPrices.Product1USD }; const string currency = "EUR"; - var conversionRates = GetConversionRates(); + List conversionRates = GetConversionRates(); // Assert AssertBrokenRule(() => @@ -75,18 +77,20 @@ public void PlaceOrder_WhenNoProductIsAdded_BreaksOrderMustHaveAtLeastOneProduct public void PlaceOrder_GivenTwoOrdersInThatDayAlreadyMade_BreaksCustomerCannotOrderMoreThan2OrdersOnTheSameDayRule() { // Arrange - var customer = CustomerFactory.Create(); + Domain.Customers.Customer customer = CustomerFactory.Create(); - var orderProductsData = new List(); - orderProductsData.Add(new OrderProductData(SampleProducts.Product1Id, 2)); + List orderProductsData = new List + { + new OrderProductData(SampleProducts.Product1Id, 2) + }; - var allProductPrices = new List + List allProductPrices = new List { SampleProductPrices.Product1EUR, SampleProductPrices.Product1USD }; const string currency = "EUR"; - var conversionRates = GetConversionRates(); + List conversionRates = GetConversionRates(); SystemClock.Set(new DateTime(2020, 1, 10, 11, 0, 0)); customer.PlaceOrder( @@ -119,10 +123,11 @@ public void PlaceOrder_GivenTwoOrdersInThatDayAlreadyMade_BreaksCustomerCannotOr private static List GetConversionRates() { - var conversionRates = new List(); - - conversionRates.Add(new ConversionRate("USD", "EUR", (decimal)0.88)); - conversionRates.Add(new ConversionRate("EUR", "USD", (decimal)1.13)); + List conversionRates = new List + { + new ConversionRate("USD", "EUR", (decimal)0.88), + new ConversionRate("EUR", "USD", (decimal)1.13) + }; return conversionRates; } diff --git a/src/Tests/SampleProject.UnitTests/SeedWork/DomainEventsTestHelper.cs b/src/Tests/SampleProject.UnitTests/SeedWork/DomainEventsTestHelper.cs index 541a204..8418094 100644 --- a/src/Tests/SampleProject.UnitTests/SeedWork/DomainEventsTestHelper.cs +++ b/src/Tests/SampleProject.UnitTests/SeedWork/DomainEventsTestHelper.cs @@ -1,8 +1,8 @@ -using System.Collections; +using SampleProject.Domain.SeedWork; +using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; -using SampleProject.Domain.SeedWork; namespace SampleProject.UnitTests.SeedWork { @@ -17,15 +17,15 @@ public static List GetAllDomainEvents(Entity aggregate) domainEvents.AddRange(aggregate.DomainEvents); } - var fields = aggregate.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).Concat(aggregate.GetType().BaseType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)).ToArray(); + FieldInfo[] fields = aggregate.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).Concat(aggregate.GetType().BaseType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)).ToArray(); - foreach (var field in fields) + foreach (FieldInfo field in fields) { - var isEntity = field.FieldType.IsAssignableFrom(typeof(Entity)); + bool isEntity = field.FieldType.IsAssignableFrom(typeof(Entity)); if (isEntity) { - var entity = field.GetValue(aggregate) as Entity; + Entity entity = field.GetValue(aggregate) as Entity; domainEvents.AddRange(GetAllDomainEvents(entity).ToList()); } @@ -33,7 +33,7 @@ public static List GetAllDomainEvents(Entity aggregate) { if (field.GetValue(aggregate) is IEnumerable enumerable) { - foreach (var en in enumerable) + foreach (object en in enumerable) { if (en is Entity entityItem) { @@ -51,15 +51,15 @@ public static void ClearAllDomainEvents(Entity aggregate) { aggregate.ClearDomainEvents(); - var fields = aggregate.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).Concat(aggregate.GetType().BaseType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)).ToArray(); + FieldInfo[] fields = aggregate.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public).Concat(aggregate.GetType().BaseType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)).ToArray(); - foreach (var field in fields) + foreach (FieldInfo field in fields) { - var isEntity = field.FieldType.IsAssignableFrom(typeof(Entity)); + bool isEntity = field.FieldType.IsAssignableFrom(typeof(Entity)); if (isEntity) { - var entity = field.GetValue(aggregate) as Entity; + Entity entity = field.GetValue(aggregate) as Entity; ClearAllDomainEvents(entity); } @@ -67,7 +67,7 @@ public static void ClearAllDomainEvents(Entity aggregate) { if (field.GetValue(aggregate) is IEnumerable enumerable) { - foreach (var en in enumerable) + foreach (object en in enumerable) { if (en is Entity entityItem) { diff --git a/src/Tests/SampleProject.UnitTests/SeedWork/TestBase.cs b/src/Tests/SampleProject.UnitTests/SeedWork/TestBase.cs index 2136f6e..c7d4b12 100644 --- a/src/Tests/SampleProject.UnitTests/SeedWork/TestBase.cs +++ b/src/Tests/SampleProject.UnitTests/SeedWork/TestBase.cs @@ -1,9 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using NUnit.Framework; +using NUnit.Framework; using SampleProject.Domain.SeedWork; using SampleProject.Domain.SharedKernel; +using System; +using System.Collections.Generic; +using System.Linq; namespace SampleProject.UnitTests.SeedWork { @@ -11,7 +11,7 @@ public abstract class TestBase { public static T AssertPublishedDomainEvent(Entity aggregate) where T : IDomainEvent { - var domainEvent = DomainEventsTestHelper.GetAllDomainEvents(aggregate).OfType().SingleOrDefault(); + T domainEvent = DomainEventsTestHelper.GetAllDomainEvents(aggregate).OfType().SingleOrDefault(); if (domainEvent == null) { @@ -23,7 +23,7 @@ public static T AssertPublishedDomainEvent(Entity aggregate) where T : IDomai public static List AssertPublishedDomainEvents(Entity aggregate) where T : IDomainEvent { - var domainEvents = DomainEventsTestHelper.GetAllDomainEvents(aggregate).OfType().ToList(); + List domainEvents = DomainEventsTestHelper.GetAllDomainEvents(aggregate).OfType().ToList(); if (!domainEvents.Any()) { @@ -35,8 +35,8 @@ public static List AssertPublishedDomainEvents(Entity aggregate) where T : public static void AssertBrokenRule(TestDelegate testDelegate) where TRule : class, IBusinessRule { - var message = $"Expected {typeof(TRule).Name} broken rule"; - var businessRuleValidationException = Assert.Catch(testDelegate, message); + string message = $"Expected {typeof(TRule).Name} broken rule"; + BusinessRuleValidationException businessRuleValidationException = Assert.Catch(testDelegate, message); if (businessRuleValidationException != null) { Assert.That(businessRuleValidationException.BrokenRule, Is.TypeOf(), message); diff --git a/src/Tests/SampleProject.UnitTests/SharedKernel/MoneyValueTests.cs b/src/Tests/SampleProject.UnitTests/SharedKernel/MoneyValueTests.cs index 45d41b4..c215d87 100644 --- a/src/Tests/SampleProject.UnitTests/SharedKernel/MoneyValueTests.cs +++ b/src/Tests/SampleProject.UnitTests/SharedKernel/MoneyValueTests.cs @@ -1,7 +1,7 @@ -using System.Collections.Generic; -using NUnit.Framework; +using NUnit.Framework; using SampleProject.Domain.SharedKernel; using SampleProject.UnitTests.SeedWork; +using System.Collections.Generic; namespace SampleProject.UnitTests.SharedKernel { @@ -11,7 +11,7 @@ public class MoneyValueTests : TestBase [Test] public void MoneyValueOf_WhenCurrencyIsProvided_IsSuccessful() { - var value = MoneyValue.Of(120, "EUR"); + MoneyValue value = MoneyValue.Of(120, "EUR"); Assert.That(value.Value, Is.EqualTo(120)); Assert.That(value.Currency, Is.EqualTo("EUR")); @@ -29,8 +29,8 @@ public void MoneyValueOf_WhenCurrencyIsNotProvided_ThrowsMoneyValueMustHaveCurre [Test] public void GivenTwoMoneyValuesWithTheSameCurrencies_WhenAddThem_IsSuccessful() { - var valueInEuros = MoneyValue.Of(100, "EUR"); - var valueInEuros2 = MoneyValue.Of(50, "EUR"); + MoneyValue valueInEuros = MoneyValue.Of(100, "EUR"); + MoneyValue valueInEuros2 = MoneyValue.Of(50, "EUR"); MoneyValue add = valueInEuros + valueInEuros2; @@ -41,8 +41,8 @@ public void GivenTwoMoneyValuesWithTheSameCurrencies_WhenAddThem_IsSuccessful() [Test] public void GivenTwoMoneyValuesWithTheSameCurrencies_SumThem_IsSuccessful() { - var valueInEuros = MoneyValue.Of(100, "EUR"); - var valueInEuros2 = MoneyValue.Of(50, "EUR"); + MoneyValue valueInEuros = MoneyValue.Of(100, "EUR"); + MoneyValue valueInEuros2 = MoneyValue.Of(50, "EUR"); IList values = new List { @@ -58,11 +58,11 @@ public void GivenTwoMoneyValuesWithTheSameCurrencies_SumThem_IsSuccessful() [Test] public void GivenTwoMoneyValuesWithDifferentCurrencies_WhenAddThem_ThrowsMoneyValueOperationMustBePerformedOnTheSameCurrencyRule() { - var valueInEuros = MoneyValue.Of(100, "EUR"); - var valueInDollars = MoneyValue.Of(50, "USD"); + MoneyValue valueInEuros = MoneyValue.Of(100, "EUR"); + MoneyValue valueInDollars = MoneyValue.Of(50, "USD"); AssertBrokenRule(() => { - var add = valueInEuros + valueInDollars; + MoneyValue add = valueInEuros + valueInDollars; }); } }