Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Improvements/code (#580)
Krzysztof Pajaka17e634b6fca
diff --git a/.github/workflows/build.yml b/.github/workflows/sonarcube.ymlsimilarity index 82%rename from .github/workflows/build.ymlrename to .github/workflows/sonarcube.ymlindex 4f3cb90a9..767415791 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/sonarcube.yml@@ -42,6 +42,8 @@ jobs:SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}shell: powershellrun: |- .\.sonar\scanner\dotnet-sonarscanner begin /k:"grandnode_grandnode2" /o:"grandnode" /d:sonar.token="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="https://sonarcloud.io"- dotnet build- .\.sonar\scanner\dotnet-sonarscanner end /d:sonar.token="${{ secrets.SONAR_TOKEN }}"+ .\.sonar\scanner\dotnet-sonarscanner begin /k:"grandnode_grandnode2" /o:"grandnode" `+ /d:sonar.token="${{ secrets.SONAR_TOKEN }}" `+ /d:sonar.host.url="https://sonarcloud.io" `+ /d:sonar.coverage.exclusions="**" `+ /d:sonar.cpd.exclusions="**"\ No newline at end of filediff --git a/src/Aspire/Aspire.AppHost/Program.cs b/src/Aspire/Aspire.AppHost/Program.csindex be68c9585..a575b90d6 100644--- a/src/Aspire/Aspire.AppHost/Program.cs+++ b/src/Aspire/Aspire.AppHost/Program.cs@@ -6,4 +6,4 @@ var mongo = builder.AddMongoDB("mongo").WithLifetime(ContainerLifetime.Persistenvar mongodb = mongo.AddDatabase("Mongodb");builder.ConfigureGrandWebProject(mongodb);-builder.Build().Run();+await builder.Build().RunAsync();diff --git a/src/Business/Grand.Business.Catalog/Commands/UpdateProductReviewTotalsCommandHandler.cs b/src/Business/Grand.Business.Catalog/Commands/UpdateProductReviewTotalsCommandHandler.csindex f33173529..ee2fa7673 100644--- a/src/Business/Grand.Business.Catalog/Commands/UpdateProductReviewTotalsCommandHandler.cs+++ b/src/Business/Grand.Business.Catalog/Commands/UpdateProductReviewTotalsCommandHandler.cs@@ -20,8 +20,7 @@ public class UpdateProductReviewTotalsCommandHandler : IRequestHandler<UpdatePropublic async Task<bool> Handle(UpdateProductReviewTotalsCommand request, CancellationToken cancellationToken){- if (request.Product == null)- throw new ArgumentNullException(nameof(request.Product));+ ArgumentNullException.ThrowIfNull(request.Product);var approvedRatingSum = 0;var notApprovedRatingSum = 0;diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.csindex 7378fcce6..49979cde4 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs@@ -2,6 +2,7 @@ using Grand.Business.Core.Interfaces.Catalog.Products;using Grand.Data;using Grand.Domain;using Grand.Domain.Catalog;+using Grand.Domain.Directory;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;using Grand.Infrastructure.Extensions;@@ -257,12 +258,10 @@ public class ProductAttributeService : IProductAttributeServiceArgumentNullException.ThrowIfNull(productAttributeValue);var p = await _productRepository.GetByIdAsync(productId);- if (p == null)- throw new ArgumentNullException(nameof(p));+ ArgumentNullException.ThrowIfNull(p, nameof(p));var pam = p.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMappingId);- if (pam == null)- throw new ArgumentNullException(nameof(pam));+ ArgumentNullException.ThrowIfNull(pam, nameof(pam));pam.ProductAttributeValues.Add(productAttributeValue);await _productRepository.UpdateToSet(productId, x => x.ProductAttributeMappings, z => z.Id,diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.csindex 59f87272a..44d4846e5 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs@@ -28,8 +28,7 @@ public class ProductCourseService : IProductCourseServicepublic virtual async Task UpdateCourseOnProduct(string productId, string courseId){- if (string.IsNullOrEmpty(productId))- throw new ArgumentNullException(nameof(productId));+ ArgumentNullException.ThrowIfNullOrEmpty(productId);await _productRepository.UpdateField(productId, x => x.CourseId, courseId);await _productRepository.UpdateField(productId, x => x.UpdatedOnUtc, DateTime.UtcNow);diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductService.csindex 3414bd9c0..5963caa5f 100644--- a/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs+++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs@@ -1181,8 +1181,8 @@ public class ProductService : IProductServicepublic virtual async Task DeleteDiscount(string discountId, string productId){- if (string.IsNullOrEmpty(discountId))- throw new ArgumentNullException(nameof(discountId));+ ArgumentNullException.ThrowIfNullOrEmpty(discountId);+ ArgumentNullException.ThrowIfNullOrEmpty(productId);await _productRepository.Pull(productId, x => x.AppliedDiscounts, discountId);diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ActivatedValueForPurchasedVouchersCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ActivatedValueForPurchasedVouchersCommandHandler.csindex 7997b1dc5..f2889a90f 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ActivatedValueForPurchasedVouchersCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ActivatedValueForPurchasedVouchersCommandHandler.cs@@ -28,8 +28,7 @@ public classpublic async Task<bool> Handle(ActivatedValueForPurchasedGiftVouchersCommand request,CancellationToken cancellationToken){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));+ ArgumentNullException.ThrowIfNull(request.Order);foreach (var orderItem in request.Order.OrderItems){diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandler.csindex 3cf52bed5..f970b6c12 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandler.cs@@ -34,8 +34,7 @@ public class AwardLoyaltyPointsCommandHandler : IRequestHandler<AwardLoyaltyPoinpublic async Task<bool> Handle(AwardLoyaltyPointsCommand request, CancellationToken cancellationToken){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));+ ArgumentNullException.ThrowIfNull(request.Order);var customer = await _customerService.GetCustomerById(request.Order.CustomerId);var currency = await _currencyService.GetCurrencyByCode(request.Order.CustomerCurrencyCode);diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderCommandHandler.csindex 4b1507b5f..1cbec94e7 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderCommandHandler.cs@@ -49,8 +49,7 @@ public class CancelOrderCommandHandler : IRequestHandler<CancelOrderCommand, boopublic async Task<bool> Handle(CancelOrderCommand request, CancellationToken cancellationToken){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));+ ArgumentNullException.ThrowIfNull(request.Order);if (request.Order.OrderStatusId == (int)OrderStatusSystem.Cancelled)throw new Exception("Cannot do cancel for order.");diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderItemCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderItemCommandHandler.csindex 02aea6f73..ea37fa62a 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderItemCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderItemCommandHandler.cs@@ -33,11 +33,8 @@ public class CancelOrderItemCommandHandler : IRequestHandler<CancelOrderItemCommpublic async Task<(bool error, string message)> Handle(CancelOrderItemCommand request,CancellationToken cancellationToken){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));-- if (request.OrderItem == null)- throw new ArgumentNullException(nameof(request.OrderItem));+ ArgumentNullException.ThrowIfNull(request.Order);+ ArgumentNullException.ThrowIfNull(request.OrderItem);var product = await _productService.GetProductById(request.OrderItem.ProductId);if (product == null)diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.csindex 0e6faeed6..1766c2be0 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs@@ -1,4 +1,5 @@-using Grand.Business.Core.Commands.Checkout.Orders;+using Azure.Core;+using Grand.Business.Core.Commands.Checkout.Orders;using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Payments;@@ -36,8 +37,7 @@ public class CaptureCommandHandler : IRequestHandler<CaptureCommand, IList<strinpublic async Task<IList<string>> Handle(CaptureCommand command, CancellationToken cancellationToken){var paymentTransaction = command.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(command.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);var canCapture = await _mediator.Send(new CanCaptureQuery { PaymentTransaction = paymentTransaction },cancellationToken);diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CheckOrderStatusCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CheckOrderStatusCommandHandler.csindex 2c91fd7b2..a5b3eb9aa 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CheckOrderStatusCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CheckOrderStatusCommandHandler.cs@@ -25,8 +25,7 @@ public class CheckOrderStatusCommandHandler : IRequestHandler<CheckOrderStatusCopublic async Task<bool> Handle(CheckOrderStatusCommand request, CancellationToken cancellationToken){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));+ ArgumentNullException.ThrowIfNull(request.Order);if (request.Order.PaymentStatusId == PaymentStatus.Paid && !request.Order.PaidDateUtc.HasValue){diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderCommandHandler.csindex ca8a98332..cc5ba3c14 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderCommandHandler.cs@@ -45,8 +45,7 @@ public class DeleteOrderCommandHandler : IRequestHandler<DeleteOrderCommand, boopublic async Task<bool> Handle(DeleteOrderCommand request, CancellationToken cancellationToken){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));+ ArgumentNullException.ThrowIfNull(request.Order);var shipments = await _shipmentService.GetShipmentsByOrder(request.Order.Id);if (shipments.Any())diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderItemCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderItemCommandHandler.csindex a91d57b95..f51da453b 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderItemCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/DeleteOrderItemCommandHandler.cs@@ -37,11 +37,8 @@ public class DeleteOrderItemCommandHandler : IRequestHandler<DeleteOrderItemCommpublic async Task<(bool error, string message)> Handle(DeleteOrderItemCommand request,CancellationToken cancellationToken){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));-- if (request.OrderItem == null)- throw new ArgumentNullException(nameof(request.OrderItem));+ ArgumentNullException.ThrowIfNull(request.Order);+ ArgumentNullException.ThrowIfNull(request.OrderItem);var product = await _productService.GetProductById(request.OrderItem.ProductId);if (product == null)diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/InsertOrderItemCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/InsertOrderItemCommandHandler.csindex f321770f9..ae3962d50 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/InsertOrderItemCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/InsertOrderItemCommandHandler.cs@@ -29,11 +29,8 @@ public class InsertOrderItemCommandHandler : IRequestHandler<InsertOrderItemCommpublic async Task<bool> Handle(InsertOrderItemCommand request, CancellationToken cancellationToken){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));-- if (request.OrderItem == null)- throw new ArgumentNullException(nameof(request.OrderItem));+ ArgumentNullException.ThrowIfNull(request.Order);+ ArgumentNullException.ThrowIfNull(request.OrderItem);request.Order.OrderItems.Add(request.OrderItem);request.Order.OrderSubtotalExclTax += request.OrderItem.PriceExclTax;diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsAuthorizedCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsAuthorizedCommandHandler.csindex 7780ff199..bd8cf57aa 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsAuthorizedCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsAuthorizedCommandHandler.cs@@ -26,15 +26,13 @@ public class MarkAsAuthorizedCommandHandler : IRequestHandler<MarkAsAuthorizedCopublic async Task<bool> Handle(MarkAsAuthorizedCommand request, CancellationToken cancellationToken){var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);paymentTransaction.TransactionStatus = TransactionStatus.Authorized;await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));+ ArgumentNullException.ThrowIfNull(order);order.PaymentStatusId = PaymentStatus.Authorized;await _orderService.UpdateOrder(order);diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsPaidCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsPaidCommandHandler.csindex f4312471e..f897a9b06 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsPaidCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/MarkAsPaidCommandHandler.cs@@ -28,8 +28,7 @@ public class MarkAsPaidCommandHandler : IRequestHandler<MarkAsPaidCommand, bool>public async Task<bool> Handle(MarkAsPaidCommand request, CancellationToken cancellationToken){var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);var canMarkOrderAsPaid =await _mediator.Send(new CanMarkPaymentTransactionAsPaidQuery { PaymentTransaction = paymentTransaction },@@ -42,8 +41,7 @@ public class MarkAsPaidCommandHandler : IRequestHandler<MarkAsPaidCommand, bool>await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));+ ArgumentNullException.ThrowIfNull(order);order.PaidAmount = paymentTransaction.PaidAmount;order.PaymentStatusId = PaymentStatus.Paid;diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderStatusCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderStatusCommandHandler.csindex dba44d69f..71db7cc7d 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderStatusCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderStatusCommandHandler.cs@@ -41,8 +41,7 @@ public class OrderStatusCommandHandler : IRequestHandler<SetOrderStatusCommand,public async Task<bool> Handle(SetOrderStatusCommand request, CancellationToken cancellationToken){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));+ ArgumentNullException.ThrowIfNull(request.Order);var prevOrderStatus = request.Order.OrderStatusId;if (prevOrderStatus == (int)request.Os)diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyPaidOfflineCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyPaidOfflineCommandHandler.csindex 148780b79..96ff52b63 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyPaidOfflineCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyPaidOfflineCommandHandler.cs@@ -28,8 +28,7 @@ public class PartiallyPaidOfflineCommandHandler : IRequestHandler<PartiallyPaidOpublic async Task<bool> Handle(PartiallyPaidOfflineCommand command, CancellationToken cancellationToken){var paymentTransaction = command.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(command.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);var amountToPaid = command.AmountToPaid;@@ -47,8 +46,7 @@ public class PartiallyPaidOfflineCommandHandler : IRequestHandler<PartiallyPaidOawait _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));+ ArgumentNullException.ThrowIfNull(order);//update order infoorder.PaidAmount += amountToPaid;diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.csindex 242db8b52..dfae48ddf 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs@@ -44,8 +44,7 @@ public class PartiallyRefundCommandHandler : IRequestHandler<PartiallyRefundCommpublic async Task<IList<string>> Handle(PartiallyRefundCommand command, CancellationToken cancellationToken){var paymentTransaction = command.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(command.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);var amountToRefund = command.AmountToRefund;@@ -74,8 +73,7 @@ public class PartiallyRefundCommandHandler : IRequestHandler<PartiallyRefundCommawait _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));+ ArgumentNullException.ThrowIfNull(order);//total amount refundedif (paymentTransaction.TransactionStatus == TransactionStatus.Refunded)diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandler.csindex 9e2c844a0..063e34464 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandler.cs@@ -37,8 +37,7 @@ public class PartiallyRefundOfflineCommandHandler : IRequestHandler<PartiallyRefpublic async Task<bool> Handle(PartiallyRefundOfflineCommand command, CancellationToken cancellationToken){var paymentTransaction = command.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(command.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);var amountToRefund = command.AmountToRefund;@@ -56,8 +55,7 @@ public class PartiallyRefundOfflineCommandHandler : IRequestHandler<PartiallyRefawait _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));+ ArgumentNullException.ThrowIfNull(order);//total amount refundedvar totalAmountRefunded = order.RefundedAmount + amountToRefund;diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.csindex 8f276e3b0..6b330e57c 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs@@ -337,8 +337,8 @@ public class PlaceOrderCommandHandler : IRequestHandler<PlaceOrderCommand, Place/// <returns>Shopping cart item weight</returns>private async Task<double> GetShoppingCartItemWeight(ShoppingCartItem shoppingCartItem){- if (shoppingCartItem == null)- throw new ArgumentNullException(nameof(shoppingCartItem));+ ArgumentNullException.ThrowIfNull(shoppingCartItem);+var product = await _productService.GetProductById(shoppingCartItem.ProductId);if (product == null)return 0;diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ProcessOrderPaidCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ProcessOrderPaidCommandHandler.csindex 664e46d58..f01b0afd8 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ProcessOrderPaidCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ProcessOrderPaidCommandHandler.cs@@ -6,7 +6,9 @@ using Grand.Business.Core.Interfaces.Messages;using Grand.Business.Core.Queries.Checkout.Orders;using Grand.Domain.Localization;using Grand.Domain.Orders;+using Grand.Domain.Payments;using MediatR;+using Microsoft.IdentityModel.Protocols.OpenIdConnect;namespace Grand.Business.Checkout.Commands.Handlers.Orders;@@ -47,8 +49,7 @@ public class ProcessOrderPaidCommandHandler : IRequestHandler<ProcessOrderPaidCo/// <param name="order">Order</param>protected virtual async Task ProcessOrderPaid(Order order){- if (order == null)- throw new ArgumentNullException(nameof(order));+ ArgumentNullException.ThrowIfNull(order);//raise eventawait _mediator.Publish(new OrderPaidEvent(order));diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.csindex 80012581a..d9e378406 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.cs@@ -31,8 +31,7 @@ public class ReOrderCommandHandler : IRequestHandler<ReOrderCommand, IList<strinpublic async Task<IList<string>> Handle(ReOrderCommand request, CancellationToken cancellationToken){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));+ ArgumentNullException.ThrowIfNull(request.Order);var warnings = new List<string>();var customer = await _customerService.GetCustomerById(request.Order.CustomerId);diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandler.csindex 2ef9b6d04..493767031 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandler.cs@@ -34,8 +34,7 @@ public class ReduceLoyaltyPointsCommandHandler : IRequestHandler<ReduceLoyaltyPopublic async Task<bool> Handle(ReduceLoyaltyPointsCommand request, CancellationToken cancellationToken){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));+ ArgumentNullException.ThrowIfNull(request.Order);var customer = await _customerService.GetCustomerById(request.Order.CustomerId);diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.csindex cb33a7dd1..0871726ec 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs@@ -43,11 +43,7 @@ public class RefundCommandHandler : IRequestHandler<RefundCommand, IList<string>public async Task<IList<string>> Handle(RefundCommand command, CancellationToken cancellationToken){var paymentTransaction = command.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(command.PaymentTransaction));-- //if (!await CanRefund(order))- // throw new GrandException("Cannot do refund for order.");+ ArgumentNullException.ThrowIfNull(paymentTransaction);var request = new RefundPaymentRequest();RefundPaymentResult result = null;@@ -64,8 +60,7 @@ public class RefundCommandHandler : IRequestHandler<RefundCommand, IList<string>await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));+ ArgumentNullException.ThrowIfNull(order);var totalAmountRefunded = order.RefundedAmount + request.AmountToRefund;diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundOfflineCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundOfflineCommandHandler.csindex 5934aff3f..8c86788db 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundOfflineCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundOfflineCommandHandler.cs@@ -36,8 +36,7 @@ public class RefundOfflineCommandHandler : IRequestHandler<RefundOfflineCommand,public async Task<bool> Handle(RefundOfflineCommand request, CancellationToken cancellationToken){var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);var canRefundOffline =await _mediator.Send(new CanRefundOfflineQuery { PaymentTransaction = paymentTransaction },@@ -53,8 +52,7 @@ public class RefundOfflineCommandHandler : IRequestHandler<RefundOfflineCommand,var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));+ ArgumentNullException.ThrowIfNull(order);//amount to refundvar amountToRefund = order.OrderTotal;diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandler.csindex 398f6fdd9..9f2ba4a0e 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandler.cs@@ -21,8 +21,7 @@ public classpublic async Task<bool> Handle(ReturnBackRedeemedLoyaltyPointsCommand request, CancellationToken cancellationToken){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));+ ArgumentNullException.ThrowIfNull(request.Order);//were some points redeemed when placing an order?if (request.Order.RedeemedLoyaltyPoints == 0)diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/UpdateOrderItemCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/UpdateOrderItemCommandHandler.csindex 435df0fd4..1dd533b2b 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/UpdateOrderItemCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/UpdateOrderItemCommandHandler.cs@@ -32,11 +32,8 @@ public class UpdateOrderItemCommandHandler : IRequestHandler<UpdateOrderItemCommpublic async Task<bool> Handle(UpdateOrderItemCommand request, CancellationToken cancellationToken){- if (request.Order == null)- throw new ArgumentNullException(nameof(request.Order));-- if (request.OrderItem == null)- throw new ArgumentNullException(nameof(request.OrderItem));+ ArgumentNullException.ThrowIfNull(request.Order);+ ArgumentNullException.ThrowIfNull(request.OrderItem);var originalOrder = await _orderService.GetOrderById(request.Order.Id);var originalOrderItem = originalOrder.OrderItems.FirstOrDefault(x => x.Id == request.OrderItem.Id);diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandler.csindex b8b41909d..39d7d0f81 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandler.cs@@ -1,6 +1,7 @@using Grand.Business.Core.Commands.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Domain.Orders;+using Grand.Domain.Payments;using MediatR;namespace Grand.Business.Checkout.Commands.Handlers.Orders;@@ -23,11 +24,8 @@ public classpublic async Task<bool> Handle(ValidateMinShoppingCartSubtotalAmountCommand request,CancellationToken cancellationToken){- if (request.Cart == null)- throw new ArgumentNullException(nameof(request.Cart));-- if (request.Customer == null)- throw new ArgumentNullException(nameof(request.Customer));+ ArgumentNullException.ThrowIfNull(request.Cart);+ ArgumentNullException.ThrowIfNull(request.Customer);return await ValidateMinOrderSubtotalAmount(request.Cart);}diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.csindex 35e513ec2..7e69dfea8 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs@@ -1,4 +1,5 @@-using Grand.Business.Core.Commands.Checkout.Orders;+using Azure.Core;+using Grand.Business.Core.Commands.Checkout.Orders;using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Payments;@@ -36,8 +37,7 @@ public class VoidCommandHandler : IRequestHandler<VoidCommand, IList<string>>public async Task<IList<string>> Handle(VoidCommand command, CancellationToken cancellationToken){var paymentTransaction = command.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(command.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);var canVoid = await _mediator.Send(new CanVoidQuery { PaymentTransaction = paymentTransaction },cancellationToken);@@ -59,8 +59,7 @@ public class VoidCommandHandler : IRequestHandler<VoidCommand, IList<string>>await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));+ ArgumentNullException.ThrowIfNull(order);if (paymentTransaction.TransactionStatus == TransactionStatus.Voided){diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidOfflineCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidOfflineCommandHandler.csindex e9269de0c..35eda61ac 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidOfflineCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidOfflineCommandHandler.cs@@ -28,15 +28,13 @@ public class VoidOfflineCommandHandler : IRequestHandler<VoidOfflineCommand, boopublic async Task<bool> Handle(VoidOfflineCommand request, CancellationToken cancellationToken){var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);paymentTransaction.TransactionStatus = TransactionStatus.Voided;await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction);var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid);- if (order == null)- throw new ArgumentNullException(nameof(order));+ ArgumentNullException.ThrowIfNull(order);if (!await _mediator.Send(new CanVoidOfflineQuery { PaymentTransaction = paymentTransaction },cancellationToken))diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/DeliveryCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/DeliveryCommandHandler.csindex 112756f2c..6984c3fd8 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/DeliveryCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/DeliveryCommandHandler.cs@@ -5,6 +5,7 @@ using Grand.Business.Core.Interfaces.Checkout.Orders;using Grand.Business.Core.Interfaces.Checkout.Shipping;using Grand.Business.Core.Interfaces.Messages;using Grand.Domain.Orders;+using Grand.Domain.Payments;using Grand.Domain.Shipping;using MediatR;@@ -31,8 +32,7 @@ public class DeliveryCommandHandler : IRequestHandler<DeliveryCommand, bool>public async Task<bool> Handle(DeliveryCommand request, CancellationToken cancellationToken){- if (request.Shipment == null)- throw new ArgumentNullException(nameof(request.Shipment));+ ArgumentNullException.ThrowIfNull(request.Shipment);var order = await _orderService.GetOrderById(request.Shipment.OrderId);if (order == null)diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/ShipCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/ShipCommandHandler.csindex 949203511..9f242199c 100644--- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/ShipCommandHandler.cs+++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/ShipCommandHandler.cs@@ -31,8 +31,7 @@ public class ShipCommandHandler : IRequestHandler<ShipCommand, bool>public async Task<bool> Handle(ShipCommand request, CancellationToken cancellationToken){- if (request.Shipment == null)- throw new ArgumentNullException(nameof(request.Shipment));+ ArgumentNullException.ThrowIfNull(request.Shipment);var order = await _orderService.GetOrderById(request.Shipment.OrderId);if (order == null)diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCancelOrderQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCancelOrderQueryHandler.csindex b0e1901c9..eb5578514 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCancelOrderQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCancelOrderQueryHandler.cs@@ -9,8 +9,7 @@ public class CanCancelOrderQueryHandler : IRequestHandler<CanCancelOrderQuery, bpublic Task<bool> Handle(CanCancelOrderQuery request, CancellationToken cancellationToken){var order = request.Order;- if (order == null)- throw new ArgumentNullException(nameof(request.Order));+ ArgumentNullException.ThrowIfNull(request.Order);return Task.FromResult(order.OrderStatusId == (int)OrderStatusSystem.Pending);}diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCaptureQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCaptureQueryHandler.csindex 4e56c77c3..1bc949680 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCaptureQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanCaptureQueryHandler.cs@@ -17,8 +17,7 @@ public class CanCaptureQueryHandler : IRequestHandler<CanCaptureQuery, bool>public async Task<bool> Handle(CanCaptureQuery request, CancellationToken cancellationToken){var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);if (paymentTransaction.TransactionStatus is TransactionStatus.Canceled or TransactionStatus.Pending)return false;diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsAuthorizedQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsAuthorizedQueryHandler.csindex 58e8ed8be..59c366fe1 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsAuthorizedQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsAuthorizedQueryHandler.cs@@ -11,8 +11,7 @@ public classpublic Task<bool> Handle(CanMarkPaymentTransactionAsAuthorizedQuery request, CancellationToken cancellationToken){var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);return paymentTransaction.TransactionStatus == TransactionStatus.Canceled? Task.FromResult(false)diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsPaidQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsPaidQueryHandler.csindex 9784003e0..7f7ed5b45 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsPaidQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanMarkPaymentTransactionAsPaidQueryHandler.cs@@ -9,8 +9,7 @@ public class CanMarkPaymentTransactionAsPaidQueryHandler : IRequestHandler<CanMapublic async Task<bool> Handle(CanMarkPaymentTransactionAsPaidQuery request, CancellationToken cancellationToken){var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);if (paymentTransaction.TransactionStatus is TransactionStatus.Canceled or TransactionStatus.Paidor TransactionStatus.Refunded or TransactionStatus.PartiallyRefunded or TransactionStatus.Voided)diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyPaidOfflineQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyPaidOfflineQueryHandler.csindex 3dd54ab43..ba957fc03 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyPaidOfflineQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyPaidOfflineQueryHandler.cs@@ -9,8 +9,7 @@ public class CanPartiallyPaidOfflineQueryHandler : IRequestHandler<CanPartiallyPpublic Task<bool> Handle(CanPartiallyPaidOfflineQuery request, CancellationToken cancellationToken){var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);var amountToPaid = request.AmountToPaid;diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundOfflineQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundOfflineQueryHandler.csindex 11ff7d13e..f190910d3 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundOfflineQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundOfflineQueryHandler.cs@@ -9,8 +9,7 @@ public class CanPartiallyRefundOfflineQueryHandler : IRequestHandler<CanPartiallpublic Task<bool> Handle(CanPartiallyRefundOfflineQuery request, CancellationToken cancellationToken){var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);var amountToRefund = request.AmountToRefund;diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.csindex 8bf49cfb9..07d8cc683 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanPartiallyRefundQueryHandler.cs@@ -17,8 +17,7 @@ public class CanPartiallyRefundQueryHandler : IRequestHandler<CanPartiallyRefundpublic async Task<bool> Handle(CanPartiallyRefundQuery request, CancellationToken cancellationToken){var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);var amountToRefund = request.AmountToRefund;diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundOfflineQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundOfflineQueryHandler.csindex 7414b7cc9..2410c5987 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundOfflineQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundOfflineQueryHandler.cs@@ -9,8 +9,7 @@ public class CanRefundOfflineQueryHandler : IRequestHandler<CanRefundOfflineQuerpublic Task<bool> Handle(CanRefundOfflineQuery request, CancellationToken cancellationToken){var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);if (paymentTransaction.TransactionAmount == 0)return Task.FromResult(false);diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundQueryHandler.csindex 2acf964a4..957b66d9f 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanRefundQueryHandler.cs@@ -17,8 +17,7 @@ public class CanRefundQueryHandler : IRequestHandler<CanRefundQuery, bool>public async Task<bool> Handle(CanRefundQuery request, CancellationToken cancellationToken){var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);if (paymentTransaction.TransactionAmount == 0)return false;diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidOfflineQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidOfflineQueryHandler.csindex 57156643c..03b7eb756 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidOfflineQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidOfflineQueryHandler.cs@@ -9,8 +9,7 @@ public class CanVoidOfflineQueryHandler : IRequestHandler<CanVoidOfflineQuery, bpublic Task<bool> Handle(CanVoidOfflineQuery request, CancellationToken cancellationToken){var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);return paymentTransaction.TransactionAmount == 0? Task.FromResult(false)diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidQueryHandler.csindex e6c0e8fef..60289c3cb 100644--- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidQueryHandler.cs+++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/CanVoidQueryHandler.cs@@ -17,8 +17,7 @@ public class CanVoidQueryHandler : IRequestHandler<CanVoidQuery, bool>public async Task<bool> Handle(CanVoidQuery request, CancellationToken cancellationToken){var paymentTransaction = request.PaymentTransaction;- if (paymentTransaction == null)- throw new ArgumentNullException(nameof(request.PaymentTransaction));+ ArgumentNullException.ThrowIfNull(paymentTransaction);if (paymentTransaction.TransactionAmount == 0)return false;diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.csindex 7b70b5274..ea2cf5cae 100644--- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs+++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs@@ -8,6 +8,7 @@ using Grand.Domain.Catalog;using Grand.Domain.Common;using Grand.Domain.Customers;using Grand.Domain.Orders;+using Grand.Domain.Payments;using Grand.Infrastructure;using Grand.Infrastructure.Extensions;using MediatR;@@ -198,8 +199,7 @@ public class ShoppingCartService : IShoppingCartServicevalidator ??= new ShoppingCartValidatorOptions();var product = await _productService.GetProductById(productId);- if (product == null)- throw new ArgumentNullException(nameof(product));+ ArgumentNullException.ThrowIfNull(product);var cart = customer.ShoppingCartItems.Where(sci => sci.ShoppingCartTypeId == shoppingCartType)diff --git a/src/Business/Grand.Business.Cms/Services/BlogService.cs b/src/Business/Grand.Business.Cms/Services/BlogService.csindex c08db149c..0419192c3 100644--- a/src/Business/Grand.Business.Cms/Services/BlogService.cs+++ b/src/Business/Grand.Business.Cms/Services/BlogService.cs@@ -2,6 +2,7 @@ using Grand.Business.Core.Interfaces.Cms;using Grand.Data;using Grand.Domain;using Grand.Domain.Blogs;+using Grand.Domain.Payments;using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Extensions;using MediatR;@@ -322,8 +323,7 @@ public class BlogService : IBlogService/// <returns></returns>public virtual async Task<BlogCategory> GetBlogCategoryBySeName(string blogCategorySeName){- if (string.IsNullOrEmpty(blogCategorySeName))- throw new ArgumentNullException(nameof(blogCategorySeName));+ ArgumentNullException.ThrowIfNullOrEmpty(blogCategorySeName);return await _blogCategoryRepository.GetOneAsync(x => x.SeName == blogCategorySeName.ToLowerInvariant());}diff --git a/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs b/src/Business/Grand.Business.Common/Services/Configuration/SettingService.csindex fadc0d2da..21e770569 100644--- a/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs+++ b/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs@@ -1,6 +1,7 @@using Grand.Business.Core.Interfaces.Common.Configuration;using Grand.Data;using Grand.Domain.Configuration;+using Grand.Domain.Payments;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;using System.Text.Json;@@ -37,9 +38,7 @@ public class SettingService : ISettingService/// <returns>Setting</returns>private IList<Setting> GetSettingsByName(string name){- if (string.IsNullOrEmpty(name))- throw new ArgumentNullException(nameof(name));-+ ArgumentNullException.ThrowIfNullOrEmpty(name);return _settingRepository.Table.Where(x => x.Name == name.ToLowerInvariant()).ToList();}diff --git a/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs b/src/Business/Grand.Business.Common/Services/Directory/CountryService.csindex 2ec86a048..474d7181c 100644--- a/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs+++ b/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs@@ -2,6 +2,7 @@ using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Data;using Grand.Domain.Directory;+using Grand.Domain.Payments;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;using Grand.Infrastructure.Configuration;@@ -253,8 +254,7 @@ public class CountryService : ICountryServiceArgumentNullException.ThrowIfNull(stateProvince);var country = await GetCountryById(countryId);- if (country == null)- throw new ArgumentNullException(nameof(country));+ ArgumentNullException.ThrowIfNull(country);country.StateProvinces.Add(stateProvince);@@ -271,8 +271,7 @@ public class CountryService : ICountryServiceArgumentNullException.ThrowIfNull(stateProvince);var country = await GetCountryById(countryId);- if (country == null)- throw new ArgumentNullException(nameof(country));+ ArgumentNullException.ThrowIfNull(country);if (country.StateProvinces.FirstOrDefault(x => x.Id == stateProvince.Id) != null){@@ -300,8 +299,7 @@ public class CountryService : ICountryServiceArgumentNullException.ThrowIfNull(stateProvince);var country = await GetCountryById(countryId);- if (country == null)- throw new ArgumentNullException(nameof(country));+ ArgumentNullException.ThrowIfNull(country);var state = country.StateProvinces.FirstOrDefault(x => x.Id == stateProvince.Id);country.StateProvinces.Remove(state);diff --git a/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs b/src/Business/Grand.Business.Common/Services/Directory/GroupService.csindex dff793280..91b13715f 100644--- a/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs+++ b/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs@@ -2,6 +2,7 @@using Grand.Data;using Grand.Domain;using Grand.Domain.Customers;+using Grand.Domain.Directory;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;using Grand.Infrastructure.Extensions;@@ -145,9 +146,7 @@ public class GroupService : IGroupServicebool? isSystem = null){ArgumentNullException.ThrowIfNull(customer);-- if (string.IsNullOrEmpty(customerGroupSystemName))- throw new ArgumentNullException(nameof(customerGroupSystemName));+ ArgumentNullException.ThrowIfNullOrEmpty(customerGroupSystemName);var customerGroup = await GetCustomerGroupBySystemName(customerGroupSystemName);if (customerGroup == null)diff --git a/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs b/src/Business/Grand.Business.Common/Services/Localization/LanguageService.csindex 533189ddc..aae8703de 100644--- a/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs+++ b/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs@@ -88,8 +88,7 @@ public class LanguageService : ILanguageService/// <returns>Language</returns>public virtual async Task<Language> GetLanguageByCode(string languageCode){- if (string.IsNullOrEmpty(languageCode))- throw new ArgumentNullException(nameof(languageCode));+ ArgumentNullException.ThrowIfNullOrEmpty(languageCode);var key = string.Format(CacheKey.LANGUAGES_BY_CODE, languageCode);return await _cacheBase.GetAsync(key, async () =>diff --git a/src/Business/Grand.Business.Common/Services/Pdf/HtmlToPdfService.cs b/src/Business/Grand.Business.Common/Services/Pdf/HtmlToPdfService.csindex 6eec9a2b3..52c247e10 100644--- a/src/Business/Grand.Business.Common/Services/Pdf/HtmlToPdfService.cs+++ b/src/Business/Grand.Business.Common/Services/Pdf/HtmlToPdfService.cs@@ -56,8 +56,7 @@ public class HtmlToPdfService : IPdfServicevar fileName = $"order_{order.OrderGuid}_{CommonHelper.GenerateRandomDigitCode(4)}.pdf";var dir = Path.Combine(_webHostEnvironment.WebRootPath, "assets/files/exportimport");- if (dir == null)- throw new ArgumentNullException(nameof(dir));+ ArgumentNullException.ThrowIfNull(dir);if (!System.IO.Directory.Exists(dir)) System.IO.Directory.CreateDirectory(dir);diff --git a/src/Business/Grand.Business.Core/Extensions/AffiliateExtensions.cs b/src/Business/Grand.Business.Core/Extensions/AffiliateExtensions.csindex 2958e8e5a..ab30f574a 100644--- a/src/Business/Grand.Business.Core/Extensions/AffiliateExtensions.cs+++ b/src/Business/Grand.Business.Core/Extensions/AffiliateExtensions.cs@@ -47,9 +47,7 @@ public static class AffiliateExtensionspublic static string GenerateUrl(this Affiliate affiliate, string host){ArgumentNullException.ThrowIfNull(affiliate);-- if (string.IsNullOrEmpty(host))- throw new ArgumentNullException(nameof(host));+ ArgumentNullException.ThrowIfNullOrEmpty(host);var uriBuilder = new UriBuilder(host);var query = HttpUtility.ParseQueryString(uriBuilder.Query);diff --git a/src/Business/Grand.Business.Customers/Queries/Handlers/GetGroupBySystemNameQueryHandler.cs b/src/Business/Grand.Business.Customers/Queries/Handlers/GetGroupBySystemNameQueryHandler.csindex acf87a9cd..dba7b7f94 100644--- a/src/Business/Grand.Business.Customers/Queries/Handlers/GetGroupBySystemNameQueryHandler.cs+++ b/src/Business/Grand.Business.Customers/Queries/Handlers/GetGroupBySystemNameQueryHandler.cs@@ -16,8 +16,7 @@ public class GetGroupBySystemNameQueryHandler : IRequestHandler<GetGroupBySystempublic async Task<CustomerGroup> Handle(GetGroupBySystemNameQuery request, CancellationToken cancellationToken){- if (string.IsNullOrEmpty(request.SystemName))- throw new ArgumentNullException(nameof(request.SystemName));+ ArgumentNullException.ThrowIfNullOrEmpty(request.SystemName);return await _groupService.GetCustomerGroupBySystemName(request.SystemName);}diff --git a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.csindex 3ea2f34d2..b0c5bbc2e 100644--- a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs+++ b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs@@ -173,8 +173,7 @@ public class CustomerManagerService : ICustomerManagerServiceArgumentNullException.ThrowIfNull(request);var customer = await _customerService.GetCustomerByEmail(request.Email);- if (customer == null)- throw new ArgumentNullException(nameof(customer));+ ArgumentNullException.ThrowIfNull(customer);switch (request.PasswordFormat){diff --git a/src/Business/Grand.Business.Customers/Services/CustomerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerService.csindex 0e320a855..d3c24ed19 100644--- a/src/Business/Grand.Business.Customers/Services/CustomerService.cs+++ b/src/Business/Grand.Business.Customers/Services/CustomerService.cs@@ -321,8 +321,7 @@ public class CustomerService : ICustomerServicepublic virtual async Task UpdateCustomerField<T>(string customerId,Expression<Func<Customer, T>> expression, T value){- if (string.IsNullOrEmpty(customerId))- throw new ArgumentNullException(nameof(customerId));+ ArgumentNullException.ThrowIfNullOrEmpty(customerId);await _customerRepository.UpdateField(customerId, expression, value);}@@ -609,9 +608,7 @@ public class CustomerService : ICustomerServicepublic virtual async Task DeleteCustomerGroupInCustomer(CustomerGroup customerGroup, string customerId){ArgumentNullException.ThrowIfNull(customerGroup);-- if (string.IsNullOrEmpty(customerId))- throw new ArgumentNullException(nameof(customerId));+ ArgumentNullException.ThrowIfNullOrEmpty(customerId);await _customerRepository.Pull(customerId, x => x.Groups, customerGroup.Id);}@@ -619,9 +616,7 @@ public class CustomerService : ICustomerServicepublic virtual async Task InsertCustomerGroupInCustomer(CustomerGroup customerGroup, string customerId){ArgumentNullException.ThrowIfNull(customerGroup);-- if (string.IsNullOrEmpty(customerId))- throw new ArgumentNullException(nameof(customerId));+ ArgumentNullException.ThrowIfNullOrEmpty(customerId);await _customerRepository.AddToSet(customerId, x => x.Groups, customerGroup.Id);}@@ -633,9 +628,7 @@ public class CustomerService : ICustomerServicepublic virtual async Task DeleteAddress(Address address, string customerId){ArgumentNullException.ThrowIfNull(address);-- if (string.IsNullOrEmpty(customerId))- throw new ArgumentNullException(nameof(customerId));+ ArgumentNullException.ThrowIfNullOrEmpty(customerId);await _customerRepository.PullFilter(customerId, x => x.Addresses, x => x.Id, address.Id);@@ -646,9 +639,7 @@ public class CustomerService : ICustomerServicepublic virtual async Task InsertAddress(Address address, string customerId){ArgumentNullException.ThrowIfNull(address);-- if (string.IsNullOrEmpty(customerId))- throw new ArgumentNullException(nameof(customerId));+ ArgumentNullException.ThrowIfNullOrEmpty(customerId);if (address.StateProvinceId == "0")address.StateProvinceId = "";@@ -662,9 +653,7 @@ public class CustomerService : ICustomerServicepublic virtual async Task UpdateAddress(Address address, string customerId){ArgumentNullException.ThrowIfNull(address);-- if (string.IsNullOrEmpty(customerId))- throw new ArgumentNullException(nameof(customerId));+ ArgumentNullException.ThrowIfNullOrEmpty(customerId);await _customerRepository.UpdateToSet(customerId, x => x.Addresses, z => z.Id, address.Id, address);@@ -676,9 +665,7 @@ public class CustomerService : ICustomerServicepublic virtual async Task UpdateBillingAddress(Address address, string customerId){ArgumentNullException.ThrowIfNull(address);-- if (string.IsNullOrEmpty(customerId))- throw new ArgumentNullException(nameof(customerId));+ ArgumentNullException.ThrowIfNullOrEmpty(customerId);await _customerRepository.UpdateField(customerId, x => x.BillingAddress, address);}@@ -686,9 +673,7 @@ public class CustomerService : ICustomerServicepublic virtual async Task UpdateShippingAddress(Address address, string customerId){ArgumentNullException.ThrowIfNull(address);-- if (string.IsNullOrEmpty(customerId))- throw new ArgumentNullException(nameof(customerId));+ ArgumentNullException.ThrowIfNullOrEmpty(customerId);await _customerRepository.UpdateField(customerId, x => x.ShippingAddress, address);}diff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.csindex 34781e28c..62885d2fd 100644--- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs@@ -1,6 +1,7 @@using Grand.Business.Core.Interfaces.Marketing.Courses;using Grand.Data;using Grand.Domain.Courses;+using Grand.Domain.Customers;using Grand.Infrastructure.Extensions;using MediatR;@@ -29,8 +30,7 @@ public class CourseLessonService : ICourseLessonServicepublic virtual async Task<IList<CourseLesson>> GetByCourseId(string courseId){- if (string.IsNullOrEmpty(courseId))- throw new ArgumentNullException(nameof(courseId));+ ArgumentNullException.ThrowIfNullOrEmpty(courseId);var query = from c in _courseLessonRepository.Tablewhere c.CourseId == courseIddiff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseSubjectService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseSubjectService.csindex 07f351a50..1dac716e4 100644--- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseSubjectService.cs+++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseSubjectService.cs@@ -1,6 +1,7 @@using Grand.Business.Core.Interfaces.Marketing.Courses;using Grand.Data;using Grand.Domain.Courses;+using Grand.Domain.Customers;using Grand.Infrastructure.Extensions;using MediatR;@@ -29,8 +30,7 @@ public class CourseSubjectService : ICourseSubjectServicepublic virtual async Task<IList<CourseSubject>> GetByCourseId(string courseId){- if (string.IsNullOrEmpty(courseId))- throw new ArgumentNullException(nameof(courseId));+ ArgumentNullException.ThrowIfNullOrEmpty(courseId);var query = from c in _courseSubjectRepository.Tablewhere c.CourseId == courseIddiff --git a/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs b/src/Business/Grand.Business.Storage/Services/AmazonPictureService.csindex 7622e535e..64b7ba631 100644--- a/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs+++ b/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs@@ -5,6 +5,7 @@ using Amazon.S3.Model;using Amazon.S3.Util;using Grand.Business.Core.Interfaces.Storage;using Grand.Data;+using Grand.Domain.Customers;using Grand.Domain.Media;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Configuration;@@ -40,12 +41,9 @@ public class AmazonPictureService : PictureService_config = config;//Arguments guard- if (string.IsNullOrEmpty(_config.AmazonAwsAccessKeyId))- throw new ArgumentNullException("AmazonAwsAccessKeyId");- if (string.IsNullOrEmpty(_config.AmazonAwsSecretAccessKey))- throw new ArgumentNullException("AmazonAwsSecretAccessKey");- if (string.IsNullOrEmpty(_config.AmazonBucketName))- throw new ArgumentNullException("AmazonBucketName");+ ArgumentNullException.ThrowIfNullOrEmpty(_config.AmazonAwsAccessKeyId);+ ArgumentNullException.ThrowIfNullOrEmpty(_config.AmazonAwsSecretAccessKey);+ ArgumentNullException.ThrowIfNullOrEmpty(_config.AmazonBucketName);//Region guardvar regionEndpoint = RegionEndpoint.GetBySystemName(_config.AmazonRegion);diff --git a/src/Core/Grand.Data/LiteDb/LiteDBContext.cs b/src/Core/Grand.Data/LiteDb/LiteDBContext.csindex 3da831aa5..7635e91b5 100644--- a/src/Core/Grand.Data/LiteDb/LiteDBContext.cs+++ b/src/Core/Grand.Data/LiteDb/LiteDBContext.cs@@ -1,6 +1,7 @@using Grand.Domain;using Grand.Domain.Common;using LiteDB;+using System.Xml.Linq;namespace Grand.Data.LiteDb;@@ -26,8 +27,7 @@ public class LiteDBContext : IDatabaseContextpublic Task DeleteTable(string name){- if (string.IsNullOrEmpty(name))- throw new ArgumentNullException(nameof(name));+ ArgumentNullException.ThrowIfNullOrEmpty(name);_database.DropCollection(name);@@ -37,8 +37,7 @@ public class LiteDBContext : IDatabaseContextpublic Task CreateIndex<T>(IRepository<T> repository, OrderBuilder<T> orderBuilder, string indexName,bool unique = false) where T : BaseEntity{- if (string.IsNullOrEmpty(indexName))- throw new ArgumentNullException(nameof(indexName));+ ArgumentNullException.ThrowIfNullOrEmpty(indexName);try{foreach (var (selector, value, fieldName) in orderBuilder?.Fields)diff --git a/src/Core/Grand.Data/LiteDb/LiteDBStoreFilesContext.cs b/src/Core/Grand.Data/LiteDb/LiteDBStoreFilesContext.csindex 86f878a30..b5d52ecd5 100644--- a/src/Core/Grand.Data/LiteDb/LiteDBStoreFilesContext.cs+++ b/src/Core/Grand.Data/LiteDb/LiteDBStoreFilesContext.cs@@ -1,5 +1,6 @@using Grand.Domain;using LiteDB;+using System.Xml.Linq;namespace Grand.Data.LiteDb;@@ -16,9 +17,8 @@ public class LiteDBStoreFilesContext : IStoreFilesContext{var fs = _database.FileStorage;var file = fs.FindById(id);-- if (file == null)- throw new ArgumentNullException(nameof(file));++ ArgumentNullException.ThrowIfNull(file);using (var stream = file.OpenRead())using (MemoryStream mstream = new())diff --git a/src/Core/Grand.Data/Mongo/MongoDBContext.cs b/src/Core/Grand.Data/Mongo/MongoDBContext.csindex ce8d3a33d..15f759e71 100644--- a/src/Core/Grand.Data/Mongo/MongoDBContext.cs+++ b/src/Core/Grand.Data/Mongo/MongoDBContext.cs@@ -1,6 +1,7 @@using Grand.Domain;using MongoDB.Bson;using MongoDB.Driver;+using System.Xml.Linq;namespace Grand.Data.Mongo;@@ -22,8 +23,7 @@ public class MongoDBContext : IDatabaseContextpublic async Task CreateTable(string name, string collation){- if (string.IsNullOrEmpty(name))- throw new ArgumentNullException(nameof(name));+ ArgumentNullException.ThrowIfNullOrEmpty(name);if (!string.IsNullOrEmpty(collation)){@@ -40,17 +40,14 @@ public class MongoDBContext : IDatabaseContextpublic async Task DeleteTable(string name){- if (string.IsNullOrEmpty(name))- throw new ArgumentNullException(nameof(name));-+ ArgumentNullException.ThrowIfNullOrEmpty(name);await _database.DropCollectionAsync(name);}public async Task CreateIndex<T>(IRepository<T> repository, OrderBuilder<T> orderBuilder, string indexName,bool unique = false) where T : BaseEntity{- if (string.IsNullOrEmpty(indexName))- throw new ArgumentNullException(nameof(indexName));+ ArgumentNullException.ThrowIfNullOrEmpty(indexName);IList<IndexKeysDefinition<T>> keys = new List<IndexKeysDefinition<T>>();foreach (var item in orderBuilder.Fields)@@ -74,8 +71,7 @@ public class MongoDBContext : IDatabaseContextpublic async Task DeleteIndex<T>(IRepository<T> repository, string indexName) where T : BaseEntity{- if (string.IsNullOrEmpty(indexName))- throw new ArgumentNullException(nameof(indexName));+ ArgumentNullException.ThrowIfNullOrEmpty(indexName);try{await ((MongoRepository<T>)repository).Collection.Indexes.DropOneAsync(indexName);diff --git a/src/Core/Grand.Infrastructure/Extensions/ProviderExtensions.cs b/src/Core/Grand.Infrastructure/Extensions/ProviderExtensions.csindex fb476c738..4e23947c6 100644--- a/src/Core/Grand.Infrastructure/Extensions/ProviderExtensions.cs+++ b/src/Core/Grand.Infrastructure/Extensions/ProviderExtensions.cs@@ -10,16 +10,14 @@ public static class ProviderExtensions{public static bool IsAuthenticateStore(this IProvider method, Store store){- if (method == null)- throw new ArgumentNullException(nameof(method));+ ArgumentNullException.ThrowIfNull(method);return store == null || IsAuthenticateStore(method, store.Id);}public static bool IsAuthenticateStore(this IProvider method, string storeId){- if (method == null)- throw new ArgumentNullException(nameof(method));+ ArgumentNullException.ThrowIfNull(method);if (string.IsNullOrEmpty(storeId))return true;@@ -32,8 +30,7 @@ public static class ProviderExtensionspublic static bool IsAuthenticateGroup(this IProvider method, Customer customer){- if (method == null)- throw new ArgumentNullException(nameof(method));+ ArgumentNullException.ThrowIfNull(method);if (customer == null)return true;diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginExtensions.cs b/src/Core/Grand.Infrastructure/Plugins/PluginExtensions.csindex 05224834d..a05c475f5 100644--- a/src/Core/Grand.Infrastructure/Plugins/PluginExtensions.cs+++ b/src/Core/Grand.Infrastructure/Plugins/PluginExtensions.cs@@ -60,8 +60,7 @@ public static class PluginExtensions/// <param name="systemName">Plugin system name</param>public static async Task MarkPluginAsInstalled(string systemName){- if (string.IsNullOrEmpty(systemName))- throw new ArgumentNullException(nameof(systemName));+ ArgumentNullException.ThrowIfNullOrEmpty(systemName);var filePath = PluginPaths.Instance.InstalledPluginsFile;if (!File.Exists(filePath))@@ -87,13 +86,13 @@ public static class PluginExtensions/// <param name="systemName">Plugin system name</param>public static async Task MarkPluginAsUninstalled(string systemName){- if (string.IsNullOrEmpty(systemName))- throw new ArgumentNullException(nameof(systemName));+ ArgumentNullException.ThrowIfNullOrEmpty(systemName);var filePath = PluginPaths.Instance.InstalledPluginsFile;if (!File.Exists(filePath))await using (File.Create(filePath)){+ //we use 'using' to close the file after it's created}var installedPluginSystemNames = ParseInstalledPluginsFile(filePath);diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs b/src/Core/Grand.Infrastructure/Plugins/PluginManager.csindex a8c5fc585..97d110fe2 100644--- a/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs+++ b/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs@@ -53,8 +53,7 @@ public static class PluginManagerlock (_synLock){- if (mvcCoreBuilder == null)- throw new ArgumentNullException(nameof(mvcCoreBuilder));+ ArgumentNullException.ThrowIfNull(mvcCoreBuilder);_logger = mvcCoreBuilder.Services.BuildServiceProvider().GetService<ILoggerFactory>().CreateLogger("PluginManager");@@ -191,8 +190,7 @@ public static class PluginManager/// <returns>Plugin descriptor if exists; otherwise null</returns>public static PluginInfo FindPlugin(Type typeAssembly){- if (typeAssembly == null)- throw new ArgumentNullException(nameof(typeAssembly));+ ArgumentNullException.ThrowIfNull(typeAssembly);return ReferencedPlugins?.FirstOrDefault(plugin => plugin.ReferencedAssembly != null&& plugin.ReferencedAssembly.FullName!.Equals(@@ -217,8 +215,7 @@ public static class PluginManagerprivate static IList<PluginInfo> GetPluginInfo(){- if (_pluginFolder == null)- throw new ArgumentNullException(nameof(_pluginFolder));+ ArgumentNullException.ThrowIfNull(_pluginFolder);var result = new List<PluginInfo>();foreach (var pluginFile in _pluginFolder.GetFiles("*.dll", SearchOption.AllDirectories))diff --git a/src/Modules/Grand.Module.Api/Filters/AuthorizeApiAdminAttribute.cs b/src/Modules/Grand.Module.Api/Filters/AuthorizeApiAdminAttribute.csindex 7566cc253..86ed8c47f 100644--- a/src/Modules/Grand.Module.Api/Filters/AuthorizeApiAdminAttribute.cs+++ b/src/Modules/Grand.Module.Api/Filters/AuthorizeApiAdminAttribute.cs@@ -30,17 +30,11 @@ public class AuthorizeApiAdminAttribute : TypeFilterAttribute/// <summary>/// Represents a filter that confirms access to the admin panel/// </summary>- private class AuthorizeApiAdminFilter : IAsyncAuthorizationFilter+ private class AuthorizeApiAdminFilter(bool ignoreFilter, IPermissionService permissionService,+ SecuritySettings securitySettings) : IAsyncAuthorizationFilter{- #region Ctor- public AuthorizeApiAdminFilter(bool ignoreFilter, IPermissionService permissionService,- SecuritySettings securitySettings)- {- _ignoreFilter = ignoreFilter;- _permissionService = permissionService;- _securitySettings = securitySettings;- }+ #region Ctor#endregion@@ -60,7 +54,7 @@ public class AuthorizeApiAdminAttribute : TypeFilterAttribute.Select(f => f.Filter).OfType<AuthorizeApiAdminAttribute>().FirstOrDefault();//ignore filter (the action is available even if a customer hasn't access to the admin area)- if (actionFilter?.IgnoreFilter ?? _ignoreFilter)+ if (actionFilter?.IgnoreFilter ?? ignoreFilter)return;if (!DataSettingsManager.DatabaseIsInstalled())@@ -70,11 +64,11 @@ public class AuthorizeApiAdminAttribute : TypeFilterAttributeif (filterContext.Filters.Any(filter => filter is AuthorizeApiAdminFilter)){//authorize permission of access to the admin area- if (!await _permissionService.Authorize(StandardPermission.ManageAccessAdminPanel))+ if (!await permissionService.Authorize(StandardPermission.ManageAccessAdminPanel))filterContext.Result = new ForbidResult(JwtBearerDefaults.AuthenticationScheme);//get allowed IP addresses- var ipAddresses = _securitySettings.AdminAreaAllowedIpAddresses;+ var ipAddresses = securitySettings.AdminAreaAllowedIpAddresses;//there are no restrictionsif (ipAddresses == null || !ipAddresses.Any())@@ -88,14 +82,7 @@ public class AuthorizeApiAdminAttribute : TypeFilterAttribute}#endregion-- #region Fields-- private readonly bool _ignoreFilter;- private readonly IPermissionService _permissionService;- private readonly SecuritySettings _securitySettings;-- #endregion+}#endregiondiff --git a/src/Modules/Grand.Module.Api/Jwt/JwtTokenBuilder.cs b/src/Modules/Grand.Module.Api/Jwt/JwtTokenBuilder.csindex 9e6dcc8de..ca57a5329 100644--- a/src/Modules/Grand.Module.Api/Jwt/JwtTokenBuilder.cs+++ b/src/Modules/Grand.Module.Api/Jwt/JwtTokenBuilder.cs@@ -16,14 +16,9 @@ public sealed class JwtTokenBuilderprivate void EnsureArguments(){- if (securityKey == null)- throw new ArgumentNullException(nameof(securityKey));-- if (useissuer && string.IsNullOrEmpty(issuer))- throw new ArgumentNullException(nameof(issuer));-- if (useaudience && string.IsNullOrEmpty(audience))- throw new ArgumentNullException(nameof(audience));+ ArgumentNullException.ThrowIfNull(securityKey);+ if (useissuer) ArgumentNullException.ThrowIfNullOrEmpty(issuer);+ if (useaudience) ArgumentNullException.ThrowIfNullOrEmpty(audience);}public JwtTokenBuilder AddSecurityKey(SecurityKey securityKey)diff --git a/src/Modules/Grand.Module.ScheduledTasks/Commands/Handlers/Catalog/SendNotificationsToSubscribersCommandHandler.cs b/src/Modules/Grand.Module.ScheduledTasks/Commands/Handlers/Catalog/SendNotificationsToSubscribersCommandHandler.csindex e943e7632..09b9aba3d 100644--- a/src/Modules/Grand.Module.ScheduledTasks/Commands/Handlers/Catalog/SendNotificationsToSubscribersCommandHandler.cs+++ b/src/Modules/Grand.Module.ScheduledTasks/Commands/Handlers/Catalog/SendNotificationsToSubscribersCommandHandler.cs@@ -7,6 +7,7 @@ using Grand.Domain.Common;using Grand.Domain.Customers;using Grand.SharedKernel.Extensions;using MediatR;+using Microsoft.IdentityModel.Tokens;namespace Grand.Module.ScheduledTasks.Commands.Handlers.Catalog;@@ -31,8 +32,7 @@ public classpublic async Task<IList<OutOfStockSubscription>> Handle(SendNotificationsToSubscribersCommand request,CancellationToken cancellationToken){- if (request.Product == null)- throw new ArgumentNullException(nameof(request.Product));+ ArgumentNullException.ThrowIfNull(request.Product);var subscriptions =await GetAllSubscriptionsByProductId(request.Product.Id, request.Attributes, request.Warehouse);diff --git a/src/Plugins/Theme.Modern/Views/Modern/Product/Partials/ProductAttributes.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Product/Partials/ProductAttributes.cshtmlindex f79425eaa..8a616c92d 100644--- a/src/Plugins/Theme.Modern/Views/Modern/Product/Partials/ProductAttributes.cshtml+++ b/src/Plugins/Theme.Modern/Views/Modern/Product/Partials/ProductAttributes.cshtml@@ -3,42 +3,8 @@<div id="product-attributes"></div>@{//dynamic update support- var attributeChangeScriptsBuilder = new StringBuilder();var attributeChangeHandlerFuncName = $"attribute_change_handler_{Model.Id}";var fileLink = Url.RouteUrl("UploadFileProductAttribute");- //generate change event script- foreach (var attribute in Model.ProductAttributes)- {- var controlId = $"product_attribute_{attribute.Id}";- switch (attribute.AttributeControlType)- {- case AttributeControlType.DropdownList:- {- attributeChangeScriptsBuilder.Append($"document.querySelector('#{controlId}').addEventListener('change', function (){{{attributeChangeHandlerFuncName}();}});\n");- }- break;- case AttributeControlType.RadioList:- case AttributeControlType.ColorSquares:- case AttributeControlType.ImageSquares:- {- foreach (var attributeValue in attribute.Values)- {- attributeChangeScriptsBuilder.Append($"document.querySelector('#{controlId}_{attributeValue.Id}').addEventListener('click',function(e){{{attributeChangeHandlerFuncName}();}},false);\n");- }- }- break;- case AttributeControlType.Checkboxes:- case AttributeControlType.ReadonlyCheckboxes:- {- foreach (var attributeValue in attribute.Values)- {- attributeChangeScriptsBuilder.Append($"document.querySelector('#{controlId}_{attributeValue.Id}').addEventListener('click',function(e){{{attributeChangeHandlerFuncName}();}},false);\n");- }- }- break;- }- }-//render scripts<div id="product-attributes"><template v-if="standardProductAttributes_@(Model.Id).ProductAttributes !== 'undefined'">diff --git a/src/Tests/Grand.Business.Common.Tests/Services/Stores/StoreServiceTests.cs b/src/Tests/Grand.Business.Common.Tests/Services/Stores/StoreServiceTests.csindex 48df1e7b0..d3c34c83c 100644--- a/src/Tests/Grand.Business.Common.Tests/Services/Stores/StoreServiceTests.cs+++ b/src/Tests/Grand.Business.Common.Tests/Services/Stores/StoreServiceTests.cs@@ -117,6 +117,6 @@ public class StoreServiceTestsvar result = await _service.GetStoreByHost("nonexisting.com");// Assert - returns first store- Assert.AreEqual(null, result);+ Assert.IsNull(result);}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Admin/Controllers/DiscountController.cs b/src/Web/Grand.Web.Admin/Controllers/DiscountController.csindex d2287c206..f41d4e91d 100644--- a/src/Web/Grand.Web.Admin/Controllers/DiscountController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/DiscountController.cs@@ -304,8 +304,7 @@ public class DiscountController : BaseAdminControllerpublic async Task<IActionResult> GetDiscountRequirementConfigurationUrl(string rulesystemName,string discountId, string discountRequirementId){- if (string.IsNullOrEmpty(rulesystemName))- throw new ArgumentNullException(nameof(rulesystemName));+ ArgumentNullException.ThrowIfNullOrEmpty(rulesystemName);var discountPlugin = _discountProviderLoader.LoadDiscountProviderByRuleSystemName(rulesystemName);diff --git a/src/Web/Grand.Web.Admin/Controllers/OrderController.cs b/src/Web/Grand.Web.Admin/Controllers/OrderController.csindex ec867c382..2e09adaea 100644--- a/src/Web/Grand.Web.Admin/Controllers/OrderController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/OrderController.cs@@ -259,8 +259,7 @@ public class OrderController(try{var status = await orderStatusService.GetByStatusId(model.OrderStatusId);- if (status == null)- throw new ArgumentNullException(nameof(status));+ ArgumentNullException.ThrowIfNull(status);order.OrderStatusId = model.OrderStatusId;await orderService.UpdateOrder(order);diff --git a/src/Web/Grand.Web.Admin/Controllers/OrderTagsController.cs b/src/Web/Grand.Web.Admin/Controllers/OrderTagsController.csindex 1323a272b..fda41aa40 100644--- a/src/Web/Grand.Web.Admin/Controllers/OrderTagsController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/OrderTagsController.cs@@ -69,8 +69,7 @@ public class OrderTagsController : BaseAdminController});var tag = await _orderTagService.GetOrderTagById(tagId);- if (tag == null)- throw new ArgumentNullException(nameof(tag));+ ArgumentNullException.ThrowIfNull(tag);var orders =(await _orderService.SearchOrders(pageIndex: command.Page - 1, pageSize: command.PageSize,diff --git a/src/Web/Grand.Web.Admin/Controllers/PluginController.cs b/src/Web/Grand.Web.Admin/Controllers/PluginController.csindex 5352359ca..70cf1dedf 100644--- a/src/Web/Grand.Web.Admin/Controllers/PluginController.cs+++ b/src/Web/Grand.Web.Admin/Controllers/PluginController.cs@@ -59,8 +59,7 @@ public class PluginController(/// <param name="path">Directory path</param>protected void DeleteDirectory(string path){- if (string.IsNullOrEmpty(path))- throw new ArgumentNullException(path);+ ArgumentNullException.ThrowIfNullOrEmpty(path);// Ensure the path is within the PluginsPathif (!path.StartsWith(PluginsPath, StringComparison.Ordinal))diff --git a/src/Web/Grand.Web.Admin/Services/KnowledgebaseViewModelService.cs b/src/Web/Grand.Web.Admin/Services/KnowledgebaseViewModelService.csindex 55a0fb4e4..714407609 100644--- a/src/Web/Grand.Web.Admin/Services/KnowledgebaseViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/KnowledgebaseViewModelService.cs@@ -186,9 +186,8 @@ public class KnowledgebaseViewModelService : IKnowledgebaseViewModelService{var article = await _knowledgebaseService.GetKnowledgebaseArticle(model.ArticleId);var related = await _knowledgebaseService.GetKnowledgebaseArticle(model.Id);-- if (article == null || related == null)- throw new ArgumentNullException("No article found with specified id");+ ArgumentNullException.ThrowIfNull(article);+ ArgumentNullException.ThrowIfNull(related);var toDelete = "";foreach (var item in article.RelatedArticles)diff --git a/src/Web/Grand.Web.Admin/Services/MenuViewModelService.cs b/src/Web/Grand.Web.Admin/Services/MenuViewModelService.csindex f314148f2..edbab21b4 100644--- a/src/Web/Grand.Web.Admin/Services/MenuViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/MenuViewModelService.cs@@ -27,8 +27,7 @@ public class MenuViewModelService : IMenuViewModelServicepublic virtual async Task<AdminSiteMap> GetMenuById(string id){- if (string.IsNullOrEmpty(id))- throw new ArgumentNullException(nameof(id));+ ArgumentNullException.ThrowIfNullOrEmpty(id);var sitemap = await _adminSiteMapService.GetSiteMap();return sitemap.Select(rootNode => FindAdminSiteMapById(rootNode, id)).FirstOrDefault(result => result != null);@@ -80,8 +79,7 @@ public class MenuViewModelService : IMenuViewModelServicepublic virtual async Task DeleteMenu(string id){- if (string.IsNullOrEmpty(id))- throw new ArgumentNullException(nameof(id));+ ArgumentNullException.ThrowIfNullOrEmpty(id);var sitemap = await _adminSiteMapService.GetSiteMap();var parentEntity = FindTopLevelNodeById(sitemap, id);diff --git a/src/Web/Grand.Web.Admin/Services/OrderViewModelService.cs b/src/Web/Grand.Web.Admin/Services/OrderViewModelService.csindex 9d8d8836c..81f6df1ed 100644--- a/src/Web/Grand.Web.Admin/Services/OrderViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/OrderViewModelService.cs@@ -28,7 +28,6 @@ using Grand.Infrastructure;using Grand.Web.Admin.Extensions.Mapping;using Grand.Web.Admin.Interfaces;using Grand.Web.Admin.Models.Orders;-using Grand.Web.Common.Extensions;using Grand.Web.Common.Localization;using MediatR;using Microsoft.AspNetCore.Mvc.Rendering;@@ -39,7 +38,7 @@ namespace Grand.Web.Admin.Services;public class OrderViewModelService : IOrderViewModelService{-+#region Fieldsprivate readonly IOrderService _orderService;@@ -198,8 +197,7 @@ public class OrderViewModelService : IOrderViewModelService}//order's tags- model.AvailableOrderTags.Add(new SelectListItem- { Text = _translationService.GetResource("Admin.Common.All"), Value = " " });+ model.AvailableOrderTags.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Common.All"), Value = " " });foreach (var s in await _orderTagService.GetAllOrderTags())model.AvailableOrderTags.Add(new SelectListItem { Text = s.Name, Value = s.Id });@@ -218,27 +216,23 @@ public class OrderViewModelService : IOrderViewModelService}//stores- model.AvailableStores.Add(new SelectListItem- { Text = _translationService.GetResource("Admin.Common.All"), Value = " " });+ model.AvailableStores.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Common.All"), Value = " " });foreach (var s in (await _storeService.GetAllStores()).Where(x =>x.Id == storeId || string.IsNullOrWhiteSpace(storeId)))model.AvailableStores.Add(new SelectListItem { Text = s.Shortcut, Value = s.Id });//vendors- model.AvailableVendors.Add(new SelectListItem- { Text = _translationService.GetResource("Admin.Common.All"), Value = " " });+ model.AvailableVendors.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Common.All"), Value = " " });foreach (var v in await _vendorService.GetAllVendors(showHidden: true))model.AvailableVendors.Add(new SelectListItem { Text = v.Name, Value = v.Id });//warehouses- model.AvailableWarehouses.Add(new SelectListItem- { Text = _translationService.GetResource("Admin.Common.All"), Value = " " });+ model.AvailableWarehouses.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Common.All"), Value = " " });foreach (var w in await _warehouseService.GetAllWarehouses())model.AvailableWarehouses.Add(new SelectListItem { Text = w.Name, Value = w.Id });//payment methods- model.AvailablePaymentMethods.Add(new SelectListItem- { Text = _translationService.GetResource("Admin.Common.All"), Value = " " });+ model.AvailablePaymentMethods.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Common.All"), Value = " " });foreach (var pm in await _paymentService.LoadAllPaymentMethods())model.AvailablePaymentMethods.Add(new SelectListItem { Text = pm.FriendlyName, Value = pm.SystemName });@@ -925,19 +919,16 @@ public class OrderViewModelService : IOrderViewModelServicemodel.Address.AddressTypeEnabled = _addressSettings.AddressTypeEnabled;//countries- model.Address.AvailableCountries.Add(new SelectListItem- { Text = _translationService.GetResource("Admin.Address.SelectCountry"), Value = "" });+ model.Address.AvailableCountries.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Address.SelectCountry"), Value = "" });foreach (var c in await _countryService.GetAllCountries(showHidden: true))- model.Address.AvailableCountries.Add(new SelectListItem- { Text = c.Name, Value = c.Id, Selected = c.Id == address.CountryId });+ model.Address.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id, Selected = c.Id == address.CountryId });//statesvar states = !string.IsNullOrEmpty(address.CountryId)? (await _countryService.GetCountryById(address.CountryId))?.StateProvinces: new List<StateProvince>();if (states?.Count > 0)foreach (var s in states)- model.Address.AvailableStates.Add(new SelectListItem- { Text = s.Name, Value = s.Id, Selected = s.Id == address.StateProvinceId });+ model.Address.AvailableStates.Add(new SelectListItem { Text = s.Name, Value = s.Id, Selected = s.Id == address.StateProvinceId });//customer attribute servicesawait model.Address.PrepareCustomAddressAttributes(address, _addressAttributeService,@@ -1039,57 +1030,47 @@ public class OrderViewModelService : IOrderViewModelServicecase AttributeControlType.RadioList:case AttributeControlType.ColorSquares:case AttributeControlType.ImageSquares:- {- var ctrlAttributes = model.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(ctrlAttributes))- customattributes = ProductExtensions.AddProductAttribute(customattributes,- attribute, ctrlAttributes).ToList();- }+ {+ var ctrlAttributes = model.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(ctrlAttributes))+ customattributes = ProductExtensions.AddProductAttribute(customattributes,+ attribute, ctrlAttributes).ToList();+ }break;case AttributeControlType.Checkboxes:- {- var cblAttributes = model.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(cblAttributes))- foreach (var item in cblAttributes- .Split([','], StringSplitOptions.RemoveEmptyEntries))- customattributes = ProductExtensions.AddProductAttribute(- customattributes,- attribute, item).ToList();- }+ {+ var cblAttributes = model.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(cblAttributes))+ foreach (var item in cblAttributes+ .Split([','], StringSplitOptions.RemoveEmptyEntries))+ customattributes = ProductExtensions.AddProductAttribute(+ customattributes,+ attribute, item).ToList();+ }break;case AttributeControlType.ReadonlyCheckboxes:- {- //load read-only (already server-side selected) values- var attributeValues = attribute.ProductAttributeValues;- foreach (var selectedAttributeId in attributeValues- .Where(v => v.IsPreSelected)- .Select(v => v.Id)- .ToList())- customattributes = ProductExtensions.AddProductAttribute(customattributes,- attribute, selectedAttributeId).ToList();- }+ {+ //load read-only (already server-side selected) values+ var attributeValues = attribute.ProductAttributeValues;+ foreach (var selectedAttributeId in attributeValues+ .Where(v => v.IsPreSelected)+ .Select(v => v.Id)+ .ToList())+ customattributes = ProductExtensions.AddProductAttribute(customattributes,+ attribute, selectedAttributeId).ToList();+ }break;case AttributeControlType.TextBox:case AttributeControlType.MultilineTextbox:- {- var ctrlAttributes = model.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(ctrlAttributes))+ case AttributeControlType.FileUpload:{- var enteredText = ctrlAttributes.Trim();- customattributes = ProductExtensions.AddProductAttribute(customattributes,- attribute, enteredText).ToList();+ var ctrlAttributes = model.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(ctrlAttributes))+ {+ var enteredText = ctrlAttributes.Trim();+ customattributes = ProductExtensions.AddProductAttribute(customattributes, attribute, enteredText).ToList();+ }}- }- break;- case AttributeControlType.FileUpload:- {- var guid = model.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- Guid.TryParse(guid, out var downloadGuid);- var download = await _downloadService.GetDownloadByGuid(downloadGuid);- if (download != null)- customattributes = ProductExtensions.AddProductAttribute(customattributes,- attribute, download.DownloadGuid.ToString()).ToList();- }break;}@@ -1162,8 +1143,7 @@ public class OrderViewModelService : IOrderViewModelServiceCreatedOnUtc = DateTime.UtcNow};- await _mediator.Send(new InsertOrderItemCommand- { Order = order, OrderItem = orderItem, Product = product });+ await _mediator.Send(new InsertOrderItemCommand { Order = order, OrderItem = orderItem, Product = product });}return warnings;@@ -1307,8 +1287,8 @@ public class OrderViewModelService : IOrderViewModelService}if (picture == null){- var pp = product.ProductPictures.OrderByDescending(p => p.IsDefault)- .ThenBy(p => p.DisplayOrder)+ var pp = product.ProductPictures.OrderByDescending(p => p.IsDefault)+ .ThenBy(p => p.DisplayOrder).FirstOrDefault();if (pp != null)picture = await _pictureService.GetPictureById(pp.PictureId);diff --git a/src/Web/Grand.Web.Admin/Services/PictureViewModelService.cs b/src/Web/Grand.Web.Admin/Services/PictureViewModelService.csindex bdc8a129f..c5dfe3c8b 100644--- a/src/Web/Grand.Web.Admin/Services/PictureViewModelService.cs+++ b/src/Web/Grand.Web.Admin/Services/PictureViewModelService.cs@@ -20,15 +20,9 @@ public class PictureViewModelService : IPictureViewModelServicepublic virtual async Task<PictureModel> PreparePictureModel(string pictureId, string objectId){- if (string.IsNullOrEmpty(pictureId))- throw new ArgumentNullException(nameof(pictureId));-- if (string.IsNullOrEmpty(objectId))- throw new ArgumentNullException(nameof(objectId));-+ ArgumentNullException.ThrowIfNullOrEmpty(objectId);var picture = await _pictureService.GetPictureById(pictureId);- if (picture == null)- throw new ArgumentNullException(nameof(picture));+ ArgumentNullException.ThrowIfNull(picture);var model = new PictureModel {Id = picture.Id,@@ -55,12 +49,10 @@ public class PictureViewModelService : IPictureViewModelServicepublic virtual async Task UpdatePicture(PictureModel model){- if (model == null)- throw new ArgumentNullException(nameof(model));+ ArgumentNullException.ThrowIfNull(model);var picture = await _pictureService.GetPictureById(model.Id);- if (picture == null)- throw new ArgumentNullException(nameof(picture));+ ArgumentNullException.ThrowIfNull(picture);//Update picture fieldsawait _pictureService.UpdatePictureField(picture, x => x.AltAttribute, model.AltAttribute);diff --git a/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs b/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.csindex a52f9eb5c..888795400 100644--- a/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs+++ b/src/Web/Grand.Web.Admin/Validators/Customers/CustomerValidator.cs@@ -183,7 +183,7 @@ public class CustomerValidator : BaseGrandValidator<CustomerModel>context.AddFailure("Owner email is not exists");}- if (!string.IsNullOrWhiteSpace(x.Username) & customerSettings.UsernamesEnabled)+ if (!string.IsNullOrWhiteSpace(x.Username) && customerSettings.UsernamesEnabled){var customerByUsername = await customerService.GetCustomerByUsername(x.Username);if (customerByUsername != null)@@ -248,7 +248,7 @@ public class CustomerValidator : BaseGrandValidator<CustomerModel>translationService.GetResource("Account.EmailUsernameErrors.EmailAlreadyExists"));}- if (customer != null && !string.IsNullOrWhiteSpace(x.Username) & customerSettings.UsernamesEnabled)+ if (customer != null && !string.IsNullOrWhiteSpace(x.Username) && customerSettings.UsernamesEnabled){if (x.Username.Length > 100)context.AddFailure("Username is too long");diff --git a/src/Web/Grand.Web.Common/Binders/DataSourceRequestFilterBinder.cs b/src/Web/Grand.Web.Common/Binders/DataSourceRequestFilterBinder.csindex 063c484aa..91459b271 100644--- a/src/Web/Grand.Web.Common/Binders/DataSourceRequestFilterBinder.cs+++ b/src/Web/Grand.Web.Common/Binders/DataSourceRequestFilterBinder.cs@@ -8,8 +8,7 @@ public class DataSourceRequestFilterBinder : IModelBinder{public Task BindModelAsync(ModelBindingContext bindingContext){- if (bindingContext == null)- throw new ArgumentNullException(nameof(bindingContext));+ ArgumentNullException.ThrowIfNull(bindingContext);var query = bindingContext.HttpContext.Request.Query;var model = new DataSourceRequestFilter();diff --git a/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs b/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.csindex f5c01d75f..847267932 100644--- a/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs@@ -24,21 +24,10 @@ public class AffiliateAttribute : TypeFilterAttribute/// <summary>/// Represents a filter that checks and updates affiliate of customer/// </summary>- private class AffiliateFilter : IAsyncActionFilter+ private class AffiliateFilter(IAffiliateService affiliateService,+ ICustomerService customerService,+ IContextAccessor contextAccessor) : IAsyncActionFilter{- #region Ctor-- public AffiliateFilter(IAffiliateService affiliateService,- ICustomerService customerService,- IContextAccessor contextAccessor)- {- _affiliateService = affiliateService;- _customerService = customerService;- _contextAccessor = contextAccessor;- }-- #endregion-#region Methods/// <summary>@@ -65,7 +54,7 @@ public class AffiliateAttribute : TypeFilterAttribute{var affiliateId = affiliateIds.FirstOrDefault();if (!string.IsNullOrEmpty(affiliateId))- await SetCustomerAffiliateId(await _affiliateService.GetAffiliateById(affiliateId));+ await SetCustomerAffiliateId(await affiliateService.GetAffiliateById(affiliateId));return;}@@ -75,7 +64,7 @@ public class AffiliateAttribute : TypeFilterAttribute{var affiliateName = affiliateNames.FirstOrDefault();if (!string.IsNullOrEmpty(affiliateName))- await SetCustomerAffiliateId(await _affiliateService.GetAffiliateByFriendlyUrlName(affiliateName));+ await SetCustomerAffiliateId(await affiliateService.GetAffiliateByFriendlyUrlName(affiliateName));}}@@ -92,13 +81,13 @@ public class AffiliateAttribute : TypeFilterAttributeif (affiliate is not { Active: true })return;- if (affiliate.Id == _contextAccessor.WorkContext.CurrentCustomer.AffiliateId)+ if (affiliate.Id == contextAccessor.WorkContext.CurrentCustomer.AffiliateId)return;//update affiliate identifier- _contextAccessor.WorkContext.CurrentCustomer.AffiliateId = affiliate.Id;- await _customerService.UpdateCustomerField(_contextAccessor.WorkContext.CurrentCustomer.Id, x => x.AffiliateId,- _contextAccessor.WorkContext.CurrentCustomer.AffiliateId);+ contextAccessor.WorkContext.CurrentCustomer.AffiliateId = affiliate.Id;+ await customerService.UpdateCustomerField(contextAccessor.WorkContext.CurrentCustomer.Id, x => x.AffiliateId,+ contextAccessor.WorkContext.CurrentCustomer.AffiliateId);}#endregion@@ -109,14 +98,6 @@ public class AffiliateAttribute : TypeFilterAttributeprivate const string FriendlyUrlNameQueryParameterName = "affiliate";#endregion-- #region Fields-- private readonly IAffiliateService _affiliateService;- private readonly ICustomerService _customerService;- private readonly IContextAccessor _contextAccessor;-- #endregion}#endregiondiff --git a/src/Web/Grand.Web.Common/Filters/AuthorizeAdminAttribute.cs b/src/Web/Grand.Web.Common/Filters/AuthorizeAdminAttribute.csindex e908a1635..368807c58 100644--- a/src/Web/Grand.Web.Common/Filters/AuthorizeAdminAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/AuthorizeAdminAttribute.cs@@ -32,21 +32,9 @@ public class AuthorizeAdminAttribute : TypeFilterAttribute/// <summary>/// Represents a filter that confirms access to the admin panel/// </summary>- private class AuthorizeAdminFilter : IAsyncAuthorizationFilter+ private class AuthorizeAdminFilter(bool ignoreFilter, IPermissionService permissionService,+ SecuritySettings securitySettings, IContextAccessor contextAccessor, IGroupService groupService) : IAsyncAuthorizationFilter{- #region Ctor-- public AuthorizeAdminFilter(bool ignoreFilter, IPermissionService permissionService,- SecuritySettings securitySettings, IContextAccessor contextAccessor, IGroupService groupService)- {- _ignoreFilter = ignoreFilter;- _permissionService = permissionService;- _securitySettings = securitySettings;- _contextAccessor = contextAccessor;- _groupService = groupService;- }-- #endregion#region Methods@@ -64,7 +52,7 @@ public class AuthorizeAdminAttribute : TypeFilterAttribute.Select(f => f.Filter).OfType<AuthorizeAdminAttribute>().FirstOrDefault();//ignore filter (the action is available even if a customer hasn't access to the admin area)- if (actionFilter?.IgnoreFilter ?? _ignoreFilter)+ if (actionFilter?.IgnoreFilter ?? ignoreFilter)return;if (!DataSettingsManager.DatabaseIsInstalled())@@ -74,16 +62,16 @@ public class AuthorizeAdminAttribute : TypeFilterAttributeif (filterContext.Filters.Any(filter => filter is AuthorizeAdminFilter)){//authorize permission of access to the admin area- if (!await _permissionService.Authorize(StandardPermission.ManageAccessAdminPanel))+ if (!await permissionService.Authorize(StandardPermission.ManageAccessAdminPanel))filterContext.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());//whether current customer is vendor- if (await _groupService.IsVendor(_contextAccessor.WorkContext.CurrentCustomer) ||- _contextAccessor.WorkContext.CurrentVendor is not null)+ if (await groupService.IsVendor(contextAccessor.WorkContext.CurrentCustomer) ||+ contextAccessor.WorkContext.CurrentVendor is not null)filterContext.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());//get allowed IP addresses- var ipAddresses = _securitySettings.AdminAreaAllowedIpAddresses;+ var ipAddresses = securitySettings.AdminAreaAllowedIpAddresses;//there are no restrictionsif (ipAddresses == null || !ipAddresses.Any())@@ -97,17 +85,6 @@ public class AuthorizeAdminAttribute : TypeFilterAttribute}#endregion-- #region Fields-- private readonly bool _ignoreFilter;- private readonly IPermissionService _permissionService;- private readonly IContextAccessor _contextAccessor;- private readonly IGroupService _groupService;-- private readonly SecuritySettings _securitySettings;-- #endregion}#endregiondiff --git a/src/Web/Grand.Web.Common/Filters/AuthorizeVendorAttribute.cs b/src/Web/Grand.Web.Common/Filters/AuthorizeVendorAttribute.csindex e733e0949..65f87947c 100644--- a/src/Web/Grand.Web.Common/Filters/AuthorizeVendorAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/AuthorizeVendorAttribute.cs@@ -33,21 +33,9 @@ public class AuthorizeVendorAttribute : TypeFilterAttribute/// Represents a filter confirming that user with "Vendor" customer group has appropriate vendor account associated/// (and active)/// </summary>- private class AuthorizeVendorFilter : IAsyncAuthorizationFilter+ private class AuthorizeVendorFilter(bool ignoreFilter, IContextAccessor contextAccessor, IGroupService groupService,+ IPermissionService permissionService) : IAsyncAuthorizationFilter{- #region Ctor-- public AuthorizeVendorFilter(bool ignoreFilter, IContextAccessor contextAccessor, IGroupService groupService,- IPermissionService permissionService)- {- _ignoreFilter = ignoreFilter;- _contextAccessor = contextAccessor;- _groupService = groupService;- _permissionService = permissionService;- }-- #endregion-#region Methods/// <summary>@@ -65,31 +53,22 @@ public class AuthorizeVendorAttribute : TypeFilterAttribute.Select(f => f.Filter).OfType<AuthorizeVendorAttribute>().FirstOrDefault();//ignore filter (the action is available even if the current customer isn't a vendor)- if (actionFilter?.IgnoreFilter ?? _ignoreFilter)+ if (actionFilter?.IgnoreFilter ?? ignoreFilter)return;if (!DataSettingsManager.DatabaseIsInstalled())return;//authorize permission of access to the vendor area- if (!await _permissionService.Authorize(StandardPermission.ManageAccessVendorPanel))+ if (!await permissionService.Authorize(StandardPermission.ManageAccessVendorPanel))context.Result = new RedirectToRouteResult("VendorLogin", new RouteValueDictionary());//ensure that this user has active vendor record associated- if (!await _groupService.IsVendor(_contextAccessor.WorkContext.CurrentCustomer) || _contextAccessor.WorkContext.CurrentVendor == null)+ if (!await groupService.IsVendor(contextAccessor.WorkContext.CurrentCustomer) || contextAccessor.WorkContext.CurrentVendor == null)context.Result = new RedirectToRouteResult("VendorLogin", new RouteValueDictionary());}#endregion-- #region Fields-- private readonly bool _ignoreFilter;- private readonly IPermissionService _permissionService;- private readonly IContextAccessor _contextAccessor;- private readonly IGroupService _groupService;-- #endregion}#endregiondiff --git a/src/Web/Grand.Web.Common/Filters/ClosedStoreAttribute.cs b/src/Web/Grand.Web.Common/Filters/ClosedStoreAttribute.csindex 29cda80b7..e9e687e2b 100644--- a/src/Web/Grand.Web.Common/Filters/ClosedStoreAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/ClosedStoreAttribute.cs@@ -33,25 +33,12 @@ public class ClosedStoreAttribute : TypeFilterAttribute/// <summary>/// Represents a filter that confirms access to closed store/// </summary>- private class CheckAccessClosedStoreFilter : IAsyncActionFilter+ private class CheckAccessClosedStoreFilter(bool ignoreFilter,+ IPermissionService permissionService,+ IContextAccessor contextAccessor,+ IPageService pageService,+ StoreInformationSettings storeInformationSettings) : IAsyncActionFilter{- #region Ctor-- public CheckAccessClosedStoreFilter(bool ignoreFilter,- IPermissionService permissionService,- IContextAccessor contextAccessor,- IPageService pageService,- StoreInformationSettings storeInformationSettings)- {- _ignoreFilter = ignoreFilter;- _permissionService = permissionService;- _contextAccessor = contextAccessor;- _pageService = pageService;- _storeInformationSettings = storeInformationSettings;- }-- #endregion-#region Methods/// <summary>@@ -66,7 +53,7 @@ public class ClosedStoreAttribute : TypeFilterAttribute.Where(f => f.Scope == FilterScope.Action).Select(f => f.Filter).OfType<ClosedStoreAttribute>().FirstOrDefault();- if (actionFilter?.IgnoreFilter ?? _ignoreFilter)+ if (actionFilter?.IgnoreFilter ?? ignoreFilter){await next();return;@@ -79,7 +66,7 @@ public class ClosedStoreAttribute : TypeFilterAttribute}//store isn't closed- if (!_storeInformationSettings.StoreClosed)+ if (!storeInformationSettings.StoreClosed){await next();return;@@ -104,7 +91,7 @@ public class ClosedStoreAttribute : TypeFilterAttribute{//get identifiers of pages are accessible when a store is closedvar now = DateTime.UtcNow;- var allowedPageIds = (await _pageService.GetAllPages(_contextAccessor.StoreContext.CurrentStore.Id))+ var allowedPageIds = (await pageService.GetAllPages(contextAccessor.StoreContext.CurrentStore.Id)).Where(t => t.AccessibleWhenStoreClosed &&(!t.StartDateUtc.HasValue || t.StartDateUtc < now) &&(!t.EndDateUtc.HasValue || t.EndDateUtc > now))@@ -120,7 +107,7 @@ public class ClosedStoreAttribute : TypeFilterAttribute}//check whether current customer has access to a closed store- if (await _permissionService.Authorize(StandardPermission.AccessClosedStore))+ if (await permissionService.Authorize(StandardPermission.AccessClosedStore)){await next();return;@@ -131,16 +118,6 @@ public class ClosedStoreAttribute : TypeFilterAttribute}#endregion-- #region Fields-- private readonly bool _ignoreFilter;- private readonly IPermissionService _permissionService;- private readonly IContextAccessor _contextAccessor;- private readonly IPageService _pageService;- private readonly StoreInformationSettings _storeInformationSettings;-- #endregion}#endregiondiff --git a/src/Web/Grand.Web.Common/Filters/CustomerActivityAttribute.cs b/src/Web/Grand.Web.Common/Filters/CustomerActivityAttribute.csindex 68e63a201..f5ae2d36d 100644--- a/src/Web/Grand.Web.Common/Filters/CustomerActivityAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/CustomerActivityAttribute.cs@@ -26,22 +26,11 @@ public class CustomerActivityAttribute : TypeFilterAttribute/// <summary>/// Represents a filter that saves last customer activity date/// </summary>- private class CustomerActivityFilter : IAsyncActionFilter+ private class CustomerActivityFilter(+ ICustomerService customerService,+ IContextAccessor contextAccessor,+ CustomerSettings customerSettings) : IAsyncActionFilter{- #region Ctor-- public CustomerActivityFilter(- ICustomerService customerService,- IContextAccessor contextAccessor,- CustomerSettings customerSettings)- {- _customerService = customerService;- _contextAccessor = contextAccessor;- _customerSettings = customerSettings;- }-- #endregion-#region Methods/// <summary>@@ -61,12 +50,12 @@ public class CustomerActivityAttribute : TypeFilterAttributereturn;//whether is need to store last visited page URL- if (!_customerSettings.StoreLastVisitedPage)+ if (!customerSettings.StoreLastVisitedPage)return;//update last activity date- if (_contextAccessor.WorkContext.CurrentCustomer.LastActivityDateUtc.AddMinutes(3.0) < DateTime.UtcNow)- await _customerService.UpdateCustomerField(_contextAccessor.WorkContext.CurrentCustomer, x => x.LastActivityDateUtc,+ if (contextAccessor.WorkContext.CurrentCustomer.LastActivityDateUtc.AddMinutes(3.0) < DateTime.UtcNow)+ await customerService.UpdateCustomerField(contextAccessor.WorkContext.CurrentCustomer, x => x.LastActivityDateUtc,DateTime.UtcNow);//get current IP address@@ -74,11 +63,11 @@ public class CustomerActivityAttribute : TypeFilterAttribute//update customer's IP addressif (!string.IsNullOrEmpty(currentIpAddress) &&- !currentIpAddress.Equals(_contextAccessor.WorkContext.CurrentCustomer.LastIpAddress,+ !currentIpAddress.Equals(contextAccessor.WorkContext.CurrentCustomer.LastIpAddress,StringComparison.OrdinalIgnoreCase)){- _contextAccessor.WorkContext.CurrentCustomer.LastIpAddress = currentIpAddress;- await _customerService.UpdateCustomerField(_contextAccessor.WorkContext.CurrentCustomer, x => x.LastIpAddress,+ contextAccessor.WorkContext.CurrentCustomer.LastIpAddress = currentIpAddress;+ await customerService.UpdateCustomerField(contextAccessor.WorkContext.CurrentCustomer, x => x.LastIpAddress,currentIpAddress);}@@ -88,22 +77,14 @@ public class CustomerActivityAttribute : TypeFilterAttributereturn;//save new one if don't match- if (!pageUrl.Equals(_contextAccessor.WorkContext.CurrentCustomer.LastVisitedPage, StringComparison.OrdinalIgnoreCase))+ if (!pageUrl.Equals(contextAccessor.WorkContext.CurrentCustomer.LastVisitedPage, StringComparison.OrdinalIgnoreCase)){- _contextAccessor.WorkContext.CurrentCustomer.LastVisitedPage = pageUrl;- await _customerService.UpdateCustomerField(_contextAccessor.WorkContext.CurrentCustomer, x => x.LastVisitedPage, pageUrl);+ contextAccessor.WorkContext.CurrentCustomer.LastVisitedPage = pageUrl;+ await customerService.UpdateCustomerField(contextAccessor.WorkContext.CurrentCustomer, x => x.LastVisitedPage, pageUrl);}}#endregion-- #region Fields-- private readonly ICustomerService _customerService;- private readonly IContextAccessor _contextAccessor;- private readonly CustomerSettings _customerSettings;-- #endregion}#endregiondiff --git a/src/Web/Grand.Web.Common/Filters/DenySystemAccountAttribute.cs b/src/Web/Grand.Web.Common/Filters/DenySystemAccountAttribute.csindex 25dbc14ec..7fa0a253e 100644--- a/src/Web/Grand.Web.Common/Filters/DenySystemAccountAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/DenySystemAccountAttribute.cs@@ -29,18 +29,8 @@ public class DenySystemAccountAttribute : TypeFilterAttribute/// <summary>/// Represents a filter that deny access for system accounts to resources/// </summary>- private class DenySystemAccountFilter : IAsyncAuthorizationFilter+ private class DenySystemAccountFilter(bool ignoreFilter, IContextAccessor contextAccessor) : IAsyncAuthorizationFilter{- #region Ctor-- public DenySystemAccountFilter(bool ignoreFilter, IContextAccessor contextAccessor)- {- _ignoreFilter = ignoreFilter;- _contextAccessor = contextAccessor;- }-- #endregion-#region Methods/// <summary>@@ -57,26 +47,19 @@ public class DenySystemAccountAttribute : TypeFilterAttribute.Select(f => f.Filter).OfType<DenySystemAccountAttribute>().FirstOrDefault();//ignore filter- if (actionFilter?.IgnoreFilter ?? _ignoreFilter)+ if (actionFilter?.IgnoreFilter ?? ignoreFilter)return Task.CompletedTask;if (!DataSettingsManager.DatabaseIsInstalled())return Task.CompletedTask;- if (_contextAccessor.WorkContext.CurrentCustomer.IsSystemAccount())+ if (contextAccessor.WorkContext.CurrentCustomer.IsSystemAccount())context.Result = new RedirectToRouteResult("HomePage", new RouteValueDictionary());return Task.CompletedTask;}#endregion-- #region Fields-- private readonly bool _ignoreFilter;- private readonly IContextAccessor _contextAccessor;-- #endregion}#endregiondiff --git a/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs b/src/Web/Grand.Web.Common/Filters/LanguageAttribute.csindex d4c29f38a..c1210bc01 100644--- a/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs@@ -29,29 +29,10 @@ public class LanguageAttribute : TypeFilterAttribute/// <summary>/// Represents a filter that checks SEO friendly URLs for multiple languages and properly redirect if necessary/// </summary>- private class LanguageSeoCodeFilter : IAsyncActionFilter+ private class LanguageSeoCodeFilter(+ IContextAccessor contextAccessor, ILanguageService languageService,+ AppConfig config) : IAsyncActionFilter{- #region Ctor-- public LanguageSeoCodeFilter(- IContextAccessor contextAccessor, ILanguageService languageService,- AppConfig config)- {- _contextAccessor = contextAccessor;- _languageService = languageService;- _config = config;- }-- #endregion-- #region Fields-- private readonly IContextAccessor _contextAccessor;- private readonly ILanguageService _languageService;- private readonly AppConfig _config;-- #endregion-#region Methods/// <summary>@@ -75,7 +56,7 @@ public class LanguageAttribute : TypeFilterAttribute}//whether SEO friendly URLs are enabled- if (!_config.SeoFriendlyUrlsForLanguagesEnabled)+ if (!config.SeoFriendlyUrlsForLanguagesEnabled){await next();return;@@ -96,7 +77,7 @@ public class LanguageAttribute : TypeFilterAttributereturn;}- pageUrl = AddLanguageSeo(pageUrl, _contextAccessor.WorkContext.WorkingLanguage);+ pageUrl = AddLanguageSeo(pageUrl, contextAccessor.WorkContext.WorkingLanguage);context.Result = new RedirectResult(pageUrl, false);}@@ -111,7 +92,7 @@ public class LanguageAttribute : TypeFilterAttributereturn false;//suppose that the first segment is the language code and try to get language- var language = (await _languageService.GetAllLanguages())+ var language = (await languageService.GetAllLanguages()).FirstOrDefault(urlLanguage =>urlLanguage.UniqueSeoCode.Equals(firstSegment, StringComparison.OrdinalIgnoreCase));diff --git a/src/Web/Grand.Web.Common/Filters/PasswordExpiredAttribute.cs b/src/Web/Grand.Web.Common/Filters/PasswordExpiredAttribute.csindex 7139b848e..329a70bb2 100644--- a/src/Web/Grand.Web.Common/Filters/PasswordExpiredAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/PasswordExpiredAttribute.cs@@ -26,18 +26,8 @@ public class PasswordExpiredAttribute : TypeFilterAttribute/// <summary>/// Represents a filter that validates customer password expiration/// </summary>- private class PasswordFilter : IAsyncAuthorizationFilter+ private class PasswordFilter(IContextAccessor contextAccessor, IMediator mediator) : IAsyncAuthorizationFilter{- #region Ctor-- public PasswordFilter(IContextAccessor contextAccessor, IMediator mediator)- {- _contextAccessor = contextAccessor;- _mediator = mediator;- }-- #endregion-#region Methods/// <summary>@@ -66,8 +56,8 @@ public class PasswordExpiredAttribute : TypeFilterAttribute){//check password expiration- var passwordIsExpired = await _mediator.Send(new GetPasswordIsExpiredQuery- { Customer = _contextAccessor.WorkContext.CurrentCustomer });+ var passwordIsExpired = await mediator.Send(new GetPasswordIsExpiredQuery+ { Customer = contextAccessor.WorkContext.CurrentCustomer });if (passwordIsExpired)//redirect to ChangePassword page if expirescontext.Result = new RedirectToRouteResult("CustomerChangePassword", new RouteValueDictionary());@@ -75,13 +65,6 @@ public class PasswordExpiredAttribute : TypeFilterAttribute}#endregion-- #region Fields-- private readonly IContextAccessor _contextAccessor;- private readonly IMediator _mediator;-- #endregion}#endregiondiff --git a/src/Web/Grand.Web.Common/Filters/PublicStoreAttribute.cs b/src/Web/Grand.Web.Common/Filters/PublicStoreAttribute.csindex 757e761ab..503c9986b 100644--- a/src/Web/Grand.Web.Common/Filters/PublicStoreAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/PublicStoreAttribute.cs@@ -30,19 +30,9 @@ public class PublicStoreAttribute : TypeFilterAttribute/// <summary>/// Represents a filter that confirms access to public store/// </summary>- private class AccessPublicStoreFilter : IAsyncAuthorizationFilter+ private class AccessPublicStoreFilter(bool ignoreFilter, IPermissionService permissionService,+ StoreInformationSettings storeInformationSettings) : IAsyncAuthorizationFilter{- #region Ctor-- public AccessPublicStoreFilter(bool ignoreFilter, IPermissionService permissionService,- StoreInformationSettings storeInformationSettings)- {- _ignoreFilter = ignoreFilter;- _permissionService = permissionService;- _storeInformationSettings = storeInformationSettings;- }-- #endregion#region Methods@@ -62,17 +52,17 @@ public class PublicStoreAttribute : TypeFilterAttribute//ignore filter (the action is available even if navigation is not allowed)- if (actionFilter?.IgnoreFilter ?? _ignoreFilter)+ if (actionFilter?.IgnoreFilter ?? ignoreFilter)return;if (!DataSettingsManager.DatabaseIsInstalled())return;//check whether current customer has access to a public store- if (await _permissionService.Authorize(StandardPermission.PublicStoreAllowNavigation))+ if (await permissionService.Authorize(StandardPermission.PublicStoreAllowNavigation))return;- filterContext.Result = _storeInformationSettings.StoreClosed+ filterContext.Result = storeInformationSettings.StoreClosed? new RedirectToRouteResult("StoreClosed", new RouteValueDictionary())://customer has not access to a public store@@ -80,14 +70,6 @@ public class PublicStoreAttribute : TypeFilterAttribute}#endregion-- #region Fields-- private readonly bool _ignoreFilter;- private readonly IPermissionService _permissionService;- private readonly StoreInformationSettings _storeInformationSettings;-- #endregion}#endregiondiff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminInputTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminInputTagHelper.csindex a144f719d..fd1e57d50 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminInputTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminInputTagHelper.cs@@ -158,10 +158,8 @@ public class AdminInputTagHelper : TagHelperprivate object GetPrivateFieldValue(object target, string fieldName){- if (target == null) throw new ArgumentNullException(nameof(target), "The assignment target cannot be null.");-- if (string.IsNullOrEmpty(fieldName))- throw new ArgumentException("fieldName", "The field name cannot be null or empty.");+ ArgumentNullException.ThrowIfNull(target);+ ArgumentNullException.ThrowIfNullOrEmpty(fieldName);var t = target.GetType();FieldInfo fi = null;diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/DefaultHtmlGenerator.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/DefaultHtmlGenerator.csindex b08dc3aee..8f333d907 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/DefaultHtmlGenerator.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/DefaultHtmlGenerator.cs@@ -404,7 +404,7 @@ public class DefaultHtmlGenerator : IHtmlGenerator(htmlAttributeDictionary == null || !htmlAttributeDictionary.ContainsKey("checked"))){// Note value may be null if isChecked is non-null.- if (value == null) throw new ArgumentNullException(nameof(value));+ ArgumentNullException.ThrowIfNull(value);// isChecked not provided nor found in the given attributes; fall back to view data.var valueString = Convert.ToString(value, CultureInfo.CurrentCulture);diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ViewBuffer.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ViewBuffer.csindex 6d71a72cb..0df53c73b 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ViewBuffer.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ViewBuffer.cs@@ -267,11 +267,6 @@ internal class ViewBuffer : IHtmlContentBuilder}}- private string DebuggerToString()- {- return _name;- }-private void MoveTo(ViewBuffer destination){for (var i = 0; i < Count; i++)diff --git a/src/Web/Grand.Web.Common/TagHelpers/PageNavigationTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/PageNavigationTagHelper.csindex 2eae7072b..a0017c9dd 100644--- a/src/Web/Grand.Web.Common/TagHelpers/PageNavigationTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/PageNavigationTagHelper.cs@@ -106,11 +106,11 @@ public class PageNavigationTagHelper : TagHelperif (string.IsNullOrEmpty(links)) return Task.CompletedTask;var sb = new StringBuilder();- sb.AppendFormat("<nav aria-label=\"Page navigation\">");+ sb.Append("<nav aria-label=\"Page navigation\">");sb.Append(Environment.NewLine);sb.AppendFormat(links);sb.Append(Environment.NewLine);- sb.AppendFormat("</nav>");+ sb.Append("</nav>");sb.Append(Environment.NewLine);output.Content.SetHtmlContent(sb.ToString());return Task.CompletedTask;diff --git a/src/Web/Grand.Web.Common/ViewRender/ViewRenderService.cs b/src/Web/Grand.Web.Common/ViewRender/ViewRenderService.csindex 3ad936589..cf9605427 100644--- a/src/Web/Grand.Web.Common/ViewRender/ViewRenderService.cs+++ b/src/Web/Grand.Web.Common/ViewRender/ViewRenderService.cs@@ -38,7 +38,7 @@ public class ViewRenderService : IViewRenderServiceawait using var sw = new StringWriter();var viewResult = _razorViewEngine.GetView(viewPath, viewPath, false);- if (viewResult.View == null) throw new ArgumentNullException($"{viewPath} does not match any available view");+ ArgumentNullException.ThrowIfNull(viewResult.View);var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) {Model = modeldiff --git a/src/Web/Grand.Web/Commands/Handler/Contact/ContactAttributeChangeCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Contact/ContactAttributeChangeCommandHandler.csindex d9a0dfcbe..d70defa47 100644--- a/src/Web/Grand.Web/Commands/Handler/Contact/ContactAttributeChangeCommandHandler.cs+++ b/src/Web/Grand.Web/Commands/Handler/Contact/ContactAttributeChangeCommandHandler.cs@@ -1,5 +1,4 @@using Grand.Business.Core.Interfaces.Marketing.Contacts;-using Grand.Business.Core.Interfaces.Storage;using Grand.Domain.Catalog;using Grand.Domain.Common;using Grand.Web.Commands.Models.Contact;@@ -12,15 +11,12 @@ public class ContactAttributeChangeCommandHandler : IRequestHandler<ContactAttri{private readonly IContactAttributeParser _contactAttributeParser;private readonly IContactAttributeService _contactAttributeService;- private readonly IDownloadService _downloadService;public ContactAttributeChangeCommandHandler(IContactAttributeService contactAttributeService,- IContactAttributeParser contactAttributeParser,- IDownloadService downloadService)+ IContactAttributeParser contactAttributeParser){_contactAttributeService = contactAttributeService;_contactAttributeParser = contactAttributeParser;- _downloadService = downloadService;}public async Task<(IList<string> enabledAttributeIds, IList<string> disabledAttributeIds)> Handle(@@ -55,75 +51,65 @@ public class ContactAttributeChangeCommandHandler : IRequestHandler<ContactAttricase AttributeControlType.RadioList:case AttributeControlType.ColorSquares:case AttributeControlType.ImageSquares:- {- var ctrlAttributes = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(ctrlAttributes))- customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,- attribute, ctrlAttributes).ToList();- }+ {+ var ctrlAttributes = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(ctrlAttributes))+ customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,+ attribute, ctrlAttributes).ToList();+ }break;case AttributeControlType.Checkboxes:- {- var cblAttributes = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(cblAttributes))- foreach (var item in cblAttributes.Split(','))- customAttributes = _contactAttributeParser- .AddContactAttribute(customAttributes, attribute, item).ToList();- }+ {+ var cblAttributes = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(cblAttributes))+ foreach (var item in cblAttributes.Split(','))+ customAttributes = _contactAttributeParser+ .AddContactAttribute(customAttributes, attribute, item).ToList();+ }break;case AttributeControlType.ReadonlyCheckboxes:- {- //load read-only (already server-side selected) values- var attributeValues = attribute.ContactAttributeValues;- foreach (var selectedAttributeId in attributeValues- .Where(v => v.IsPreSelected)- .Select(v => v.Id)- .ToList())- customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,- attribute, selectedAttributeId).ToList();- }+ {+ //load read-only (already server-side selected) values+ var attributeValues = attribute.ContactAttributeValues;+ foreach (var selectedAttributeId in attributeValues+ .Where(v => v.IsPreSelected)+ .Select(v => v.Id)+ .ToList())+ customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,+ attribute, selectedAttributeId).ToList();+ }break;case AttributeControlType.TextBox:case AttributeControlType.MultilineTextbox:- {- var ctrlAttributes = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(ctrlAttributes))+ case AttributeControlType.FileUpload:{- var enteredText = ctrlAttributes.Trim();- customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,- attribute, enteredText).ToList();+ var ctrlAttributes = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(ctrlAttributes))+ {+ var enteredText = ctrlAttributes.Trim();+ customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes, attribute, enteredText).ToList();+ }}- }break;case AttributeControlType.Datepicker:- {- var date = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id + "_day")?.Value;- var month = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id + "_month")?.Value;- var year = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id + "_year")?.Value;- DateTime? selectedDate = null;- try{- selectedDate = new DateTime(int.Parse(year), int.Parse(month), int.Parse(date));- }- catch- {- // ignored- }+ var date = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id + "_day")?.Value;+ var month = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id + "_month")?.Value;+ var year = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id + "_year")?.Value;+ DateTime? selectedDate = null;+ try+ {+ selectedDate = new DateTime(int.Parse(year), int.Parse(month), int.Parse(date));+ }+ catch+ {+ // ignored+ }- if (selectedDate.HasValue)- customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,- attribute, selectedDate.Value.ToString("D")).ToList();- }- break;- case AttributeControlType.FileUpload:- {- var guid = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- Guid.TryParse(guid, out var downloadGuid);- var download = await _downloadService.GetDownloadByGuid(downloadGuid);- if (download != null)- customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,- attribute, download.DownloadGuid.ToString()).ToList();- }+ if (selectedDate.HasValue)+ customAttributes = _contactAttributeParser.AddContactAttribute(customAttributes,+ attribute, selectedDate.Value.ToString("D")).ToList();+ }break;}diff --git a/src/Web/Grand.Web/Commands/Handler/Customers/CurrentPositionCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Customers/CurrentPositionCommandHandler.csindex c385ef8fe..5aed9b047 100644--- a/src/Web/Grand.Web/Commands/Handler/Customers/CurrentPositionCommandHandler.cs+++ b/src/Web/Grand.Web/Commands/Handler/Customers/CurrentPositionCommandHandler.cs@@ -15,11 +15,8 @@ public class CurrentPositionCommandHandler : IRequestHandler<CurrentPositionCommpublic async Task<bool> Handle(CurrentPositionCommand request, CancellationToken cancellationToken){- if (request.Customer == null)- throw new ArgumentNullException(nameof(request.Customer));-- if (request.Model == null)- throw new ArgumentNullException(nameof(request.Model));+ ArgumentNullException.ThrowIfNull(request.Customer);+ ArgumentNullException.ThrowIfNull(request.Model);await _customerCoordinateService.SaveGeoCoordinate(request.Customer, request.Model.Longitude,request.Model.Latitude);diff --git a/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountDeleteCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountDeleteCommandHandler.csindex f194f3570..8c1e4281e 100644--- a/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountDeleteCommandHandler.cs+++ b/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountDeleteCommandHandler.cs@@ -16,7 +16,7 @@ public class SubAccountDeleteCommandHandler : IRequestHandler<SubAccountDeleteCopublic async Task<(bool success, string error)> Handle(SubAccountDeleteCommand request,CancellationToken cancellationToken){- if (request.CurrentCustomer == null) throw new ArgumentNullException(nameof(request.CurrentCustomer));+ ArgumentNullException.ThrowIfNull(request.CurrentCustomer);var customer = await _customerService.GetCustomerById(request.CustomerId);if (customer == null || customer.OwnerId != request.CurrentCustomer.Id)diff --git a/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountEditCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountEditCommandHandler.csindex 0ef2f16ea..6af8544b9 100644--- a/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountEditCommandHandler.cs+++ b/src/Web/Grand.Web/Commands/Handler/Customers/SubAccountEditCommandHandler.cs@@ -24,8 +24,7 @@ public class SubAccountEditCommandHandler : IRequestHandler<SubAccountEditCommanpublic async Task<bool> Handle(SubAccountEditCommand request, CancellationToken cancellationToken){- if (request.CurrentCustomer == null) throw new ArgumentNullException(nameof(request.CurrentCustomer));-+ ArgumentNullException.ThrowIfNull(request.CurrentCustomer);var customer = await _customerService.GetCustomerById(request.EditModel.Id);//update emaildiff --git a/src/Web/Grand.Web/Commands/Handler/ShoppingCart/SaveCheckoutAttributesCommandHandler.cs b/src/Web/Grand.Web/Commands/Handler/ShoppingCart/SaveCheckoutAttributesCommandHandler.csindex 18dff48fa..df6036c50 100644--- a/src/Web/Grand.Web/Commands/Handler/ShoppingCart/SaveCheckoutAttributesCommandHandler.cs+++ b/src/Web/Grand.Web/Commands/Handler/ShoppingCart/SaveCheckoutAttributesCommandHandler.cs@@ -1,7 +1,5 @@using Grand.Business.Core.Interfaces.Checkout.CheckoutAttributes;-using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Customers;-using Grand.Business.Core.Interfaces.Storage;using Grand.Domain.Catalog;using Grand.Domain.Common;using Grand.Domain.Customers;@@ -10,35 +8,27 @@ using Grand.Web.Commands.Models.ShoppingCart;using MediatR;namespace Grand.Web.Commands.Handler.ShoppingCart;--public class- SaveCheckoutAttributesCommandHandler : IRequestHandler<SaveCheckoutAttributesCommand, IList<CustomAttribute>>+public class SaveCheckoutAttributesCommandHandler : IRequestHandler<SaveCheckoutAttributesCommand, IList<CustomAttribute>>{private readonly ICheckoutAttributeParser _checkoutAttributeParser;private readonly ICheckoutAttributeService _checkoutAttributeService;- private readonly IDownloadService _downloadService;private readonly ICustomerService _customerService;public SaveCheckoutAttributesCommandHandler(ICheckoutAttributeService checkoutAttributeService,ICheckoutAttributeParser checkoutAttributeParser,- IDownloadService downloadService,ICustomerService customerService){_checkoutAttributeService = checkoutAttributeService;_checkoutAttributeParser = checkoutAttributeParser;- _downloadService = downloadService;_customerService = customerService;}public async Task<IList<CustomAttribute>> Handle(SaveCheckoutAttributesCommand request,CancellationToken cancellationToken){- if (request.Cart == null)- throw new ArgumentNullException(nameof(request.Cart));-- if (request.SelectedAttributes == null)- throw new ArgumentNullException(nameof(request.SelectedAttributes));+ ArgumentNullException.ThrowIfNull(request.Cart);+ ArgumentNullException.ThrowIfNull(request.SelectedAttributes);var customAttributes = new List<CustomAttribute>();var checkoutAttributes =@@ -51,57 +41,47 @@ public classcase AttributeControlType.RadioList:case AttributeControlType.ColorSquares:case AttributeControlType.ImageSquares:- {- var ctrlAttributes = request.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(ctrlAttributes))- customAttributes = _checkoutAttributeParser.AddCheckoutAttribute(customAttributes,- attribute, ctrlAttributes).ToList();- }+ {+ var ctrlAttributes = request.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(ctrlAttributes))+ customAttributes = _checkoutAttributeParser.AddCheckoutAttribute(customAttributes,+ attribute, ctrlAttributes).ToList();+ }break;case AttributeControlType.Checkboxes:- {- var cblAttributes = request.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(cblAttributes))- foreach (var item in cblAttributes.Split(','))- if (!string.IsNullOrEmpty(item))- customAttributes = _checkoutAttributeParser.AddCheckoutAttribute(customAttributes,- attribute, item).ToList();- }+ {+ var cblAttributes = request.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(cblAttributes))+ foreach (var item in cblAttributes.Split(','))+ if (!string.IsNullOrEmpty(item))+ customAttributes = _checkoutAttributeParser.AddCheckoutAttribute(customAttributes,+ attribute, item).ToList();+ }break;case AttributeControlType.ReadonlyCheckboxes:- {- //load read-only (already server-side selected) values- var attributeValues = attribute.CheckoutAttributeValues;- foreach (var selectedAttributeId in attributeValues- .Where(v => v.IsPreSelected)- .Select(v => v.Id)- .ToList())- customAttributes = _checkoutAttributeParser.AddCheckoutAttribute(customAttributes,- attribute, selectedAttributeId).ToList();- }+ {+ //load read-only (already server-side selected) values+ var attributeValues = attribute.CheckoutAttributeValues;+ foreach (var selectedAttributeId in attributeValues+ .Where(v => v.IsPreSelected)+ .Select(v => v.Id)+ .ToList())+ customAttributes = _checkoutAttributeParser.AddCheckoutAttribute(customAttributes,+ attribute, selectedAttributeId).ToList();+ }break;case AttributeControlType.TextBox:case AttributeControlType.MultilineTextbox:case AttributeControlType.Datepicker:- {- var ctrlAttributes = request.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(ctrlAttributes))+ case AttributeControlType.FileUpload:{- var enteredText = ctrlAttributes.Trim();- customAttributes = _checkoutAttributeParser.AddCheckoutAttribute(customAttributes,- attribute, enteredText).ToList();+ var ctrlAttributes = request.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(ctrlAttributes))+ {+ var enteredText = ctrlAttributes.Trim();+ customAttributes = _checkoutAttributeParser.AddCheckoutAttribute(customAttributes, attribute, enteredText).ToList();+ }}- }- break;- case AttributeControlType.FileUpload:- {- var guid = request.SelectedAttributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- Guid.TryParse(guid, out var downloadGuid);- var download = await _downloadService.GetDownloadByGuid(downloadGuid);- if (download != null)- customAttributes = _checkoutAttributeParser.AddCheckoutAttribute(customAttributes,- attribute, download.DownloadGuid.ToString()).ToList();- }break;}@@ -111,8 +91,7 @@ public class{var conditionMet = await _checkoutAttributeParser.IsConditionMet(attribute, customAttributes);if (conditionMet.HasValue && !conditionMet.Value)- customAttributes = _checkoutAttributeParser.RemoveCheckoutAttribute(customAttributes, attribute)- .ToList();+ customAttributes = _checkoutAttributeParser.RemoveCheckoutAttribute(customAttributes, attribute).ToList();}await _customerService.UpdateUserField(request.Customer, SystemCustomerFieldNames.CheckoutAttributes,diff --git a/src/Web/Grand.Web/Controllers/ActionCartController.cs b/src/Web/Grand.Web/Controllers/ActionCartController.csindex 04c3c3cae..161d1f6c7 100644--- a/src/Web/Grand.Web/Controllers/ActionCartController.cs+++ b/src/Web/Grand.Web/Controllers/ActionCartController.cs@@ -730,8 +730,7 @@ public class ActionCartController : BasePublicController});var product = await _productService.GetProductById(model.ProductId);- if (product == null)- throw new ArgumentNullException(nameof(product));+ ArgumentNullException.ThrowIfNull(product);if (product.HighestBidder == customer.Id)return Json(new {diff --git a/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostHandler.cs b/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostHandler.csindex bb42eeef8..da6743ad1 100644--- a/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Blogs/GetBlogPostHandler.cs@@ -54,8 +54,7 @@ public class GetBlogPostHandler : IRequestHandler<GetBlogPost, BlogPostModel>public async Task<BlogPostModel> Handle(GetBlogPost request, CancellationToken cancellationToken){- if (request.BlogPost == null)- throw new ArgumentNullException(nameof(request.BlogPost));+ ArgumentNullException.ThrowIfNull(request.BlogPost);var model = new BlogPostModel {Id = request.BlogPost.Id,diff --git a/src/Web/Grand.Web/Features/Handlers/Catalog/GetFormatBasePriceHandler.cs b/src/Web/Grand.Web/Features/Handlers/Catalog/GetFormatBasePriceHandler.csindex fa2b689c3..1b3b748d7 100644--- a/src/Web/Grand.Web/Features/Handlers/Catalog/GetFormatBasePriceHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Catalog/GetFormatBasePriceHandler.cs@@ -24,8 +24,7 @@ public class GetFormatBasePriceHandler : IRequestHandler<GetFormatBasePrice, strpublic async Task<string> Handle(GetFormatBasePrice request, CancellationToken cancellationToken){- if (request.Product == null)- throw new ArgumentNullException(nameof(request.Product));+ ArgumentNullException.ThrowIfNull(request.Product);if (!request.Product.BasepriceEnabled)return null;diff --git a/src/Web/Grand.Web/Features/Handlers/Catalog/GetProductAttributeHandler.cs b/src/Web/Grand.Web/Features/Handlers/Catalog/GetProductAttributeHandler.csindex 6a74cc7cc..1140b374a 100644--- a/src/Web/Grand.Web/Features/Handlers/Catalog/GetProductAttributeHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Catalog/GetProductAttributeHandler.cs@@ -16,8 +16,7 @@ public class GetProductAttributeHandler : IRequestHandler<GetProductAttribute, Ppublic async Task<ProductAttribute> Handle(GetProductAttribute request, CancellationToken cancellationToken){- if (string.IsNullOrEmpty(request.Id))- throw new ArgumentNullException(nameof(request.Id));+ ArgumentNullException.ThrowIfNullOrEmpty(request.Id);return await _productAttributeService.GetProductAttributeById(request.Id);}diff --git a/src/Web/Grand.Web/Features/Handlers/Catalog/GetViewSortSizeOptionsHandler.cs b/src/Web/Grand.Web/Features/Handlers/Catalog/GetViewSortSizeOptionsHandler.csindex 68c09788f..d440fdce7 100644--- a/src/Web/Grand.Web/Features/Handlers/Catalog/GetViewSortSizeOptionsHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Catalog/GetViewSortSizeOptionsHandler.cs@@ -39,11 +39,8 @@ public class GetViewSortSizeOptionsHandler : IRequestHandler<GetViewSortSizeOptiprivate void PrepareSortingOptions(GetViewSortSizeOptions request){- if (request.PagingFilteringModel == null)- throw new ArgumentNullException(nameof(request.PagingFilteringModel));-- if (request.Command == null)- throw new ArgumentNullException(nameof(request.Command));+ ArgumentNullException.ThrowIfNull(request.PageSizeOptions);+ ArgumentNullException.ThrowIfNull(request.Command);var allDisabled = _catalogSettings.ProductSortingEnumDisabled.Count ==Enum.GetValues(typeof(ProductSortingEnum)).Length;diff --git a/src/Web/Grand.Web/Features/Handlers/Common/GetParseCustomAddressAttributesHandler.cs b/src/Web/Grand.Web/Features/Handlers/Common/GetParseCustomAddressAttributesHandler.csindex a45f1ecb8..5f1a8e25b 100644--- a/src/Web/Grand.Web/Features/Handlers/Common/GetParseCustomAddressAttributesHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Common/GetParseCustomAddressAttributesHandler.cs@@ -23,8 +23,7 @@ public classpublic async Task<IList<CustomAttribute>> Handle(GetParseCustomAddressAttributes request,CancellationToken cancellationToken){- if (request.SelectedAttributes == null)- throw new ArgumentNullException(nameof(request.SelectedAttributes));+ ArgumentNullException.ThrowIfNull(request.SelectedAttributes);var customAttributes = new List<CustomAttribute>();var attributes = await _addressAttributeService.GetAllAddressAttributes();diff --git a/src/Web/Grand.Web/Features/Handlers/Customers/GetSubAccountHandler.cs b/src/Web/Grand.Web/Features/Handlers/Customers/GetSubAccountHandler.csindex 334d91df5..364f0b61a 100644--- a/src/Web/Grand.Web/Features/Handlers/Customers/GetSubAccountHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Customers/GetSubAccountHandler.cs@@ -18,8 +18,7 @@ public class GetSubAccountHandler : IRequestHandler<GetSubAccount, SubAccountEdipublic async Task<SubAccountEditModel> Handle(GetSubAccount request, CancellationToken cancellationToken){- if (request.CurrentCustomer == null)- throw new ArgumentNullException(nameof(request.CurrentCustomer));+ ArgumentNullException.ThrowIfNull(request.CurrentCustomer);var model = new SubAccountEditModel();diff --git a/src/Web/Grand.Web/Features/Handlers/Orders/GetShipmentDetailsHandler.cs b/src/Web/Grand.Web/Features/Handlers/Orders/GetShipmentDetailsHandler.csindex e590efe0b..6d3dca97d 100644--- a/src/Web/Grand.Web/Features/Handlers/Orders/GetShipmentDetailsHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Orders/GetShipmentDetailsHandler.cs@@ -45,8 +45,7 @@ public class GetShipmentDetailsHandler : IRequestHandler<GetShipmentDetails, Shipublic async Task<ShipmentDetailsModel> Handle(GetShipmentDetails request, CancellationToken cancellationToken){- if (request.Shipment == null)- throw new ArgumentNullException(nameof(request.Shipment));+ ArgumentNullException.ThrowIfNull(request.Shipment);var model = new ShipmentDetailsModel {Id = request.Shipment.Id,diff --git a/src/Web/Grand.Web/Features/Handlers/Products/GetProductLayoutViewPathHandler.cs b/src/Web/Grand.Web/Features/Handlers/Products/GetProductLayoutViewPathHandler.csindex 1eec6a9a0..4b8193931 100644--- a/src/Web/Grand.Web/Features/Handlers/Products/GetProductLayoutViewPathHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Products/GetProductLayoutViewPathHandler.cs@@ -15,8 +15,7 @@ public class GetProductLayoutViewPathHandler : IRequestHandler<GetProductLayoutVpublic async Task<string> Handle(GetProductLayoutViewPath request, CancellationToken cancellationToken){- if (string.IsNullOrEmpty(request.ProductLayoutId))- throw new ArgumentNullException(nameof(request.ProductLayoutId));+ ArgumentNullException.ThrowIfNullOrEmpty(request.ProductLayoutId);var layout = await _productLayoutService.GetProductLayoutById(request.ProductLayoutId) ??(await _productLayoutService.GetAllProductLayouts()).FirstOrDefault();diff --git a/src/Web/Grand.Web/Features/Handlers/Products/GetProductOverviewHandler.cs b/src/Web/Grand.Web/Features/Handlers/Products/GetProductOverviewHandler.csindex 824c1e4a2..04602d7ff 100644--- a/src/Web/Grand.Web/Features/Handlers/Products/GetProductOverviewHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Products/GetProductOverviewHandler.cs@@ -72,8 +72,7 @@ public class GetProductOverviewHandler : IRequestHandler<GetProductOverview, IEnpublic async Task<IEnumerable<ProductOverviewModel>> Handle(GetProductOverview request,CancellationToken cancellationToken){- if (request.Products == null)- throw new ArgumentNullException(nameof(request.Products));+ ArgumentNullException.ThrowIfNull(request.Products);var displayPrices =await _permissionService.Authorize(StandardPermission.DisplayPrices, _contextAccessor.WorkContext.CurrentCustomer);diff --git a/src/Web/Grand.Web/Features/Handlers/Products/GetProductReviewsHandler.cs b/src/Web/Grand.Web/Features/Handlers/Products/GetProductReviewsHandler.csindex a1b9e55d8..f42d71baa 100644--- a/src/Web/Grand.Web/Features/Handlers/Products/GetProductReviewsHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Products/GetProductReviewsHandler.cs@@ -41,8 +41,7 @@ public class GetProductReviewsHandler : IRequestHandler<GetProductReviews, Produpublic async Task<ProductReviewsModel> Handle(GetProductReviews request, CancellationToken cancellationToken){- if (request.Product == null)- throw new ArgumentNullException(nameof(request.Product));+ ArgumentNullException.ThrowIfNull(request.Product);var model = new ProductReviewsModel {ProductId = request.Product.Id,diff --git a/src/Web/Grand.Web/Features/Handlers/Products/GetProductSpecificationHandler.cs b/src/Web/Grand.Web/Features/Handlers/Products/GetProductSpecificationHandler.csindex 1d416b907..4741673a1 100644--- a/src/Web/Grand.Web/Features/Handlers/Products/GetProductSpecificationHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Products/GetProductSpecificationHandler.cs@@ -20,8 +20,7 @@ public class GetProductSpecificationHandler : IRequestHandler<GetProductSpecificpublic async Task<IList<ProductSpecificationModel>> Handle(GetProductSpecification request,CancellationToken cancellationToken){- if (request.Product == null)- throw new ArgumentNullException(nameof(request.Product));+ ArgumentNullException.ThrowIfNull(request.Product);var spa = new List<ProductSpecificationModel>();foreach (var item in request.Product.ProductSpecificationAttributes.Where(x => x.ShowOnProductPage)diff --git a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetParseProductAttributesHandler.cs b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetParseProductAttributesHandler.csindex 5cac84f41..f4071f9c5 100644--- a/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetParseProductAttributesHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/ShoppingCart/GetParseProductAttributesHandler.cs@@ -1,5 +1,4 @@using Grand.Business.Core.Interfaces.Catalog.Products;-using Grand.Business.Core.Interfaces.Storage;using Grand.Domain.Catalog;using Grand.Domain.Common;using Grand.Web.Features.Models.ShoppingCart;@@ -9,14 +8,11 @@ namespace Grand.Web.Features.Handlers.ShoppingCart;public class GetParseProductAttributesHandler : IRequestHandler<GetParseProductAttributes, IList<CustomAttribute>>{- private readonly IDownloadService _downloadService;private readonly IProductService _productService;public GetParseProductAttributesHandler(- IDownloadService downloadService,IProductService productService){- _downloadService = downloadService;_productService = productService;}@@ -43,57 +39,47 @@ public class GetParseProductAttributesHandler : IRequestHandler<GetParseProductAcase AttributeControlType.RadioList:case AttributeControlType.ColorSquares:case AttributeControlType.ImageSquares:- {- var ctrlAttributes = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(ctrlAttributes))- customAttributes = ProductExtensions.AddProductAttribute(customAttributes,- attribute, ctrlAttributes).ToList();- }+ {+ var ctrlAttributes = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(ctrlAttributes))+ customAttributes = ProductExtensions.AddProductAttribute(customAttributes,+ attribute, ctrlAttributes).ToList();+ }break;case AttributeControlType.Checkboxes:- {- var cblAttributes = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(cblAttributes))- foreach (var item in cblAttributes.Split(','))- if (!string.IsNullOrEmpty(item))- customAttributes = ProductExtensions.AddProductAttribute(customAttributes,- attribute, item).ToList();- }+ {+ var cblAttributes = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(cblAttributes))+ foreach (var item in cblAttributes.Split(','))+ if (!string.IsNullOrEmpty(item))+ customAttributes = ProductExtensions.AddProductAttribute(customAttributes,+ attribute, item).ToList();+ }break;case AttributeControlType.ReadonlyCheckboxes:- {- //load read-only (already server-side selected) values- var attributeValues = attribute.ProductAttributeValues;- foreach (var selectedAttributeId in attributeValues- .Where(v => v.IsPreSelected)- .Select(v => v.Id)- .ToList())- customAttributes = ProductExtensions.AddProductAttribute(customAttributes,- attribute, selectedAttributeId).ToList();- }+ {+ //load read-only (already server-side selected) values+ var attributeValues = attribute.ProductAttributeValues;+ foreach (var selectedAttributeId in attributeValues+ .Where(v => v.IsPreSelected)+ .Select(v => v.Id)+ .ToList())+ customAttributes = ProductExtensions.AddProductAttribute(customAttributes,+ attribute, selectedAttributeId).ToList();+ }break;case AttributeControlType.TextBox:case AttributeControlType.MultilineTextbox:case AttributeControlType.Datepicker:- {- var ctrlAttributes = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- if (!string.IsNullOrEmpty(ctrlAttributes))+ case AttributeControlType.FileUpload:{- var enteredText = ctrlAttributes.Trim();- customAttributes = ProductExtensions.AddProductAttribute(customAttributes,- attribute, enteredText).ToList();+ var ctrlAttributes = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;+ if (!string.IsNullOrEmpty(ctrlAttributes))+ {+ var enteredText = ctrlAttributes.Trim();+ customAttributes = ProductExtensions.AddProductAttribute(customAttributes, attribute, enteredText).ToList();+ }}- }- break;- case AttributeControlType.FileUpload:- {- var guid = request.Attributes.FirstOrDefault(x => x.Key == attribute.Id)?.Value;- Guid.TryParse(guid, out var downloadGuid);- var download = await _downloadService.GetDownloadByGuid(downloadGuid);- if (download != null)- customAttributes = ProductExtensions.AddProductAttribute(customAttributes,- attribute, download.DownloadGuid.ToString()).ToList();- }break;}diff --git a/src/Web/Grand.Web/Features/Handlers/Vendors/GetVendorReviewsHandler.cs b/src/Web/Grand.Web/Features/Handlers/Vendors/GetVendorReviewsHandler.csindex f2932f438..6ef1f1207 100644--- a/src/Web/Grand.Web/Features/Handlers/Vendors/GetVendorReviewsHandler.cs+++ b/src/Web/Grand.Web/Features/Handlers/Vendors/GetVendorReviewsHandler.cs@@ -44,8 +44,7 @@ public class GetVendorReviewsHandler : IRequestHandler<GetVendorReviews, VendorRpublic async Task<VendorReviewsModel> Handle(GetVendorReviews request, CancellationToken cancellationToken){- if (request.Vendor == null)- throw new ArgumentNullException(nameof(request.Vendor));+ ArgumentNullException.ThrowIfNull(request.Vendor);var model = new VendorReviewsModel {VendorId = request.Vendor.Id,diff --git a/src/Web/Grand.Web/Views/Product/Partials/ProductAttributes.cshtml b/src/Web/Grand.Web/Views/Product/Partials/ProductAttributes.cshtmlindex ae69e8a35..4e5d51198 100644--- a/src/Web/Grand.Web/Views/Product/Partials/ProductAttributes.cshtml+++ b/src/Web/Grand.Web/Views/Product/Partials/ProductAttributes.cshtml@@ -3,42 +3,8 @@<div id="product-attributes"></div>@{//dynamic update support- var attributeChangeScriptsBuilder = new StringBuilder();var attributeChangeHandlerFuncName = $"attribute_change_handler_{Model.Id}";var fileLink = Url.RouteUrl("UploadFileProductAttribute");- //generate change event script- foreach (var attribute in Model.ProductAttributes)- {- var controlId = $"product_attribute_{attribute.Id}";- switch (attribute.AttributeControlType)- {- case AttributeControlType.DropdownList:- {- attributeChangeScriptsBuilder.Append($"document.querySelector('#{controlId}').addEventListener('change', function (){{{attributeChangeHandlerFuncName}();}});\n");- }- break;- case AttributeControlType.RadioList:- case AttributeControlType.ColorSquares:- case AttributeControlType.ImageSquares:- {- foreach (var attributeValue in attribute.Values)- {- attributeChangeScriptsBuilder.Append($"document.querySelector('#{controlId}_{attributeValue.Id}').addEventListener('click',function(e){{{attributeChangeHandlerFuncName}();}},false);\n");- }- }- break;- case AttributeControlType.Checkboxes:- case AttributeControlType.ReadonlyCheckboxes:- {- foreach (var attributeValue in attribute.Values)- {- attributeChangeScriptsBuilder.Append($"document.querySelector('#{controlId}_{attributeValue.Id}').addEventListener('click',function(e){{{attributeChangeHandlerFuncName}();}},false);\n");- }- }- break;- }- }-//render scripts<div id="product-attributes"><template v-if="standardProductAttributes_@(Model.Id).ProductAttributes !== 'undefined'">