diff --git a/src/API/Grand.Api/ApiExplorer/MetadataApiDescriptionProvider.cs b/src/API/Grand.Api/ApiExplorer/MetadataApiDescriptionProvider.cs index 334a1ccd0..ffadf7e8b 100644 --- a/src/API/Grand.Api/ApiExplorer/MetadataApiDescriptionProvider.cs +++ b/src/API/Grand.Api/ApiExplorer/MetadataApiDescriptionProvider.cs @@ -58,10 +58,7 @@ public MetadataApiDescriptionProvider( /// public void OnProvidersExecuting(ApiDescriptionProviderContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); foreach (var action in context.Actions.OfType()) { diff --git a/src/API/Grand.Api/Filters/AuthorizeApiAdminAttribute.cs b/src/API/Grand.Api/Filters/AuthorizeApiAdminAttribute.cs index ea69068b2..c5f044c0b 100644 --- a/src/API/Grand.Api/Filters/AuthorizeApiAdminAttribute.cs +++ b/src/API/Grand.Api/Filters/AuthorizeApiAdminAttribute.cs @@ -61,9 +61,7 @@ public AuthorizeApiAdminFilter(bool ignoreFilter, IPermissionService permissionS /// Authorization filter context public async Task OnAuthorizationAsync(AuthorizationFilterContext filterContext) { - - if (filterContext == null) - throw new ArgumentNullException(nameof(filterContext)); + ArgumentNullException.ThrowIfNull(filterContext); //check whether this filter has been overridden for the action var actionFilter = filterContext.ActionDescriptor.FilterDescriptors diff --git a/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs index 276dafd6d..699547801 100644 --- a/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs +++ b/src/Business/Grand.Business.Authentication/Services/CookieAuthenticationService.cs @@ -74,8 +74,7 @@ public CookieAuthenticationService( /// Whether the authentication session is persisted across multiple requests public virtual async Task SignIn(Customer customer, bool isPersistent) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); //create claims for customer's username and email var claims = new List(); diff --git a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs index b10e12227..ebc385dc7 100644 --- a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs +++ b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs @@ -252,8 +252,7 @@ public virtual bool AuthenticationProviderIsAvailable(string systemName) /// Result of an authentication public virtual async Task Authenticate(ExternalAuthParam parameters, string returnUrl = null) { - if (parameters == null) - throw new ArgumentNullException(nameof(parameters)); + ArgumentNullException.ThrowIfNull(parameters); if (!AuthenticationProviderIsAvailable(parameters.ProviderSystemName)) return Error(new[] { "External authentication method cannot be loaded" }); @@ -279,8 +278,7 @@ public virtual async Task Authenticate(ExternalAuthParam paramete /// External authentication parameters public virtual async Task AssociateCustomer(Customer customer, ExternalAuthParam parameters) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); var externalAuthenticationRecord = new ExternalAuthentication { CustomerId = customer.Id, @@ -301,8 +299,7 @@ public virtual async Task AssociateCustomer(Customer customer, ExternalAuthParam /// Customer public virtual async Task GetCustomer(ExternalAuthParam parameters) { - if (parameters == null) - throw new ArgumentNullException(nameof(parameters)); + ArgumentNullException.ThrowIfNull(parameters); var associationRecord = (from q in _externalAuthenticationRecordRepository.Table where q.ExternalIdentifier.ToLowerInvariant() == parameters.Identifier @@ -317,8 +314,8 @@ where q.ExternalIdentifier.ToLowerInvariant() == parameters.Identifier public virtual async Task> GetExternalIdentifiers(Customer customer) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); + var query = from p in _externalAuthenticationRecordRepository.Table where p.CustomerId == customer.Id select p; @@ -331,8 +328,7 @@ public virtual async Task> GetExternalIdentifiers( /// External authentication public virtual async Task DeleteExternalAuthentication(ExternalAuthentication externalAuthentication) { - if (externalAuthentication == null) - throw new ArgumentNullException(nameof(externalAuthentication)); + ArgumentNullException.ThrowIfNull(externalAuthentication); await _externalAuthenticationRecordRepository.DeleteAsync(externalAuthentication); } diff --git a/src/Business/Grand.Business.Catalog/Services/Brands/BrandLayoutService.cs b/src/Business/Grand.Business.Catalog/Services/Brands/BrandLayoutService.cs index d97750220..407fce196 100644 --- a/src/Business/Grand.Business.Catalog/Services/Brands/BrandLayoutService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Brands/BrandLayoutService.cs @@ -74,8 +74,7 @@ public virtual Task GetBrandLayoutById(string brandLayoutId) /// Brand layout public virtual async Task InsertBrandLayout(BrandLayout brandLayout) { - if (brandLayout == null) - throw new ArgumentNullException(nameof(brandLayout)); + ArgumentNullException.ThrowIfNull(brandLayout); await _brandLayoutRepository.InsertAsync(brandLayout); @@ -92,8 +91,7 @@ public virtual async Task InsertBrandLayout(BrandLayout brandLayout) /// Brand layout public virtual async Task UpdateBrandLayout(BrandLayout brandLayout) { - if (brandLayout == null) - throw new ArgumentNullException(nameof(brandLayout)); + ArgumentNullException.ThrowIfNull(brandLayout); await _brandLayoutRepository.UpdateAsync(brandLayout); @@ -110,8 +108,7 @@ public virtual async Task UpdateBrandLayout(BrandLayout brandLayout) /// Brand layout public virtual async Task DeleteBrandLayout(BrandLayout brandLayout) { - if (brandLayout == null) - throw new ArgumentNullException(nameof(brandLayout)); + ArgumentNullException.ThrowIfNull(brandLayout); await _brandLayoutRepository.DeleteAsync(brandLayout); diff --git a/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs b/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs index c3d03ec19..2b77811fb 100644 --- a/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs @@ -110,8 +110,7 @@ public virtual Task GetBrandById(string brandId) /// Brand public virtual async Task InsertBrand(Brand brand) { - if (brand == null) - throw new ArgumentNullException(nameof(brand)); + ArgumentNullException.ThrowIfNull(brand); await _brandRepository.InsertAsync(brand); @@ -128,8 +127,7 @@ public virtual async Task InsertBrand(Brand brand) /// Brand public virtual async Task UpdateBrand(Brand brand) { - if (brand == null) - throw new ArgumentNullException(nameof(brand)); + ArgumentNullException.ThrowIfNull(brand); await _brandRepository.UpdateAsync(brand); @@ -145,8 +143,7 @@ public virtual async Task UpdateBrand(Brand brand) /// Brand public virtual async Task DeleteBrand(Brand brand) { - if (brand == null) - throw new ArgumentNullException(nameof(brand)); + ArgumentNullException.ThrowIfNull(brand); await _cacheBase.RemoveByPrefix(CacheKey.BRANDS_PATTERN_KEY); diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryLayoutService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryLayoutService.cs index 1f42f5daf..e84707fbc 100644 --- a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryLayoutService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryLayoutService.cs @@ -74,8 +74,7 @@ public virtual Task GetCategoryLayoutById(string categoryLayoutI /// Category layout public virtual async Task InsertCategoryLayout(CategoryLayout categoryLayout) { - if (categoryLayout == null) - throw new ArgumentNullException(nameof(categoryLayout)); + ArgumentNullException.ThrowIfNull(categoryLayout); await _categoryLayoutRepository.InsertAsync(categoryLayout); @@ -92,8 +91,7 @@ public virtual async Task InsertCategoryLayout(CategoryLayout categoryLayout) /// Category layout public virtual async Task UpdateCategoryLayout(CategoryLayout categoryLayout) { - if (categoryLayout == null) - throw new ArgumentNullException(nameof(categoryLayout)); + ArgumentNullException.ThrowIfNull(categoryLayout); await _categoryLayoutRepository.UpdateAsync(categoryLayout); @@ -110,8 +108,7 @@ public virtual async Task UpdateCategoryLayout(CategoryLayout categoryLayout) /// Category layout public virtual async Task DeleteCategoryLayout(CategoryLayout categoryLayout) { - if (categoryLayout == null) - throw new ArgumentNullException(nameof(categoryLayout)); + ArgumentNullException.ThrowIfNull(categoryLayout); await _categoryLayoutRepository.DeleteAsync(categoryLayout); diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs index 4c3d98531..aeb1f53c5 100644 --- a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs @@ -397,8 +397,7 @@ public virtual async Task GetCategoryById(string categoryId) /// Category public virtual async Task InsertCategory(Category category) { - if (category == null) - throw new ArgumentNullException(nameof(category)); + ArgumentNullException.ThrowIfNull(category); await _categoryRepository.InsertAsync(category); @@ -416,8 +415,7 @@ public virtual async Task InsertCategory(Category category) /// Category public virtual async Task UpdateCategory(Category category) { - if (category == null) - throw new ArgumentNullException(nameof(category)); + ArgumentNullException.ThrowIfNull(category); if (string.IsNullOrEmpty(category.ParentCategoryId)) category.ParentCategoryId = ""; @@ -448,8 +446,7 @@ public virtual async Task UpdateCategory(Category category) /// Category public virtual async Task DeleteCategory(Category category) { - if (category == null) - throw new ArgumentNullException(nameof(category)); + ArgumentNullException.ThrowIfNull(category); //reset a "Parent category" property of all child subcategories var subcategories = await GetAllCategoriesByParentCategoryId(category.Id, true); diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs index 03be306bb..e4c90c998 100644 --- a/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Categories/ProductCategoryService.cs @@ -103,8 +103,7 @@ orderby pm.DisplayOrder /// Product ident public virtual async Task InsertProductCategory(ProductCategory productCategory, string productId) { - if (productCategory == null) - throw new ArgumentNullException(nameof(productCategory)); + ArgumentNullException.ThrowIfNull(productCategory); await _productRepository.AddToSet(productId, x => x.ProductCategories, productCategory); @@ -123,8 +122,7 @@ public virtual async Task InsertProductCategory(ProductCategory productCategory, /// Product ident public virtual async Task UpdateProductCategory(ProductCategory productCategory, string productId) { - if (productCategory == null) - throw new ArgumentNullException(nameof(productCategory)); + ArgumentNullException.ThrowIfNull(productCategory); await _productRepository.UpdateToSet(productId, x => x.ProductCategories, z => z.Id, productCategory.Id, productCategory); @@ -142,8 +140,7 @@ public virtual async Task UpdateProductCategory(ProductCategory productCategory, /// Product ident public virtual async Task DeleteProductCategory(ProductCategory productCategory, string productId) { - if (productCategory == null) - throw new ArgumentNullException(nameof(productCategory)); + ArgumentNullException.ThrowIfNull(productCategory); await _productRepository.PullFilter(productId, x => x.ProductCategories, z => z.Id, productCategory.Id); diff --git a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionLayoutService.cs b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionLayoutService.cs index e980c1397..5a35286a7 100644 --- a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionLayoutService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionLayoutService.cs @@ -74,8 +74,7 @@ public virtual Task GetCollectionLayoutById(string collectionL /// Collection layout public virtual async Task InsertCollectionLayout(CollectionLayout collectionLayout) { - if (collectionLayout == null) - throw new ArgumentNullException(nameof(collectionLayout)); + ArgumentNullException.ThrowIfNull(collectionLayout); await _collectionLayoutRepository.InsertAsync(collectionLayout); @@ -92,8 +91,7 @@ public virtual async Task InsertCollectionLayout(CollectionLayout collectionLayo /// Collection layout public virtual async Task UpdateCollectionLayout(CollectionLayout collectionLayout) { - if (collectionLayout == null) - throw new ArgumentNullException(nameof(collectionLayout)); + ArgumentNullException.ThrowIfNull(collectionLayout); await _collectionLayoutRepository.UpdateAsync(collectionLayout); @@ -110,8 +108,7 @@ public virtual async Task UpdateCollectionLayout(CollectionLayout collectionLayo /// Collection layout public virtual async Task DeleteCollectionLayout(CollectionLayout collectionLayout) { - if (collectionLayout == null) - throw new ArgumentNullException(nameof(collectionLayout)); + ArgumentNullException.ThrowIfNull(collectionLayout); await _collectionLayoutRepository.DeleteAsync(collectionLayout); diff --git a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs index 0f7b9a333..542c5707a 100644 --- a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs @@ -136,8 +136,7 @@ public virtual Task GetCollectionById(string collectionId) /// Collection public virtual async Task InsertCollection(Collection collection) { - if (collection == null) - throw new ArgumentNullException(nameof(collection)); + ArgumentNullException.ThrowIfNull(collection); await _collectionRepository.InsertAsync(collection); @@ -155,8 +154,7 @@ public virtual async Task InsertCollection(Collection collection) /// Collection public virtual async Task UpdateCollection(Collection collection) { - if (collection == null) - throw new ArgumentNullException(nameof(collection)); + ArgumentNullException.ThrowIfNull(collection); await _collectionRepository.UpdateAsync(collection); @@ -173,8 +171,7 @@ public virtual async Task UpdateCollection(Collection collection) /// Collection public virtual async Task DeleteCollection(Collection collection) { - if (collection == null) - throw new ArgumentNullException(nameof(collection)); + ArgumentNullException.ThrowIfNull(collection); await _cacheBase.RemoveByPrefix(CacheKey.COLLECTIONS_PATTERN_KEY); diff --git a/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs b/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs index f9b1e0be9..e81c8fcdf 100644 --- a/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Collections/ProductCollectionService.cs @@ -104,8 +104,7 @@ orderby pm.DisplayOrder /// Product ident public virtual async Task InsertProductCollection(ProductCollection productCollection, string productId) { - if (productCollection == null) - throw new ArgumentNullException(nameof(productCollection)); + ArgumentNullException.ThrowIfNull(productCollection); await _productRepository.AddToSet(productId, x => x.ProductCollections, productCollection); @@ -124,8 +123,7 @@ public virtual async Task InsertProductCollection(ProductCollection productColle /// Product id public virtual async Task UpdateProductCollection(ProductCollection productCollection, string productId) { - if (productCollection == null) - throw new ArgumentNullException(nameof(productCollection)); + ArgumentNullException.ThrowIfNull(productCollection); await _productRepository.UpdateToSet(productId, x => x.ProductCollections, z => z.Id, productCollection.Id, productCollection); @@ -144,8 +142,7 @@ public virtual async Task UpdateProductCollection(ProductCollection productColle /// Product id public virtual async Task DeleteProductCollection(ProductCollection productCollection, string productId) { - if (productCollection == null) - throw new ArgumentNullException(nameof(productCollection)); + ArgumentNullException.ThrowIfNull(productCollection); await _productRepository.PullFilter(productId, x => x.ProductCollections, z => z.Id, productCollection.Id); diff --git a/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs b/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs index 55ac020b5..702a0cdf8 100644 --- a/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs @@ -104,8 +104,7 @@ orderby md.DisplayOrder /// Measure dimension public virtual async Task InsertMeasureDimension(MeasureDimension measure) { - if (measure == null) - throw new ArgumentNullException(nameof(measure)); + ArgumentNullException.ThrowIfNull(measure); await _measureDimensionRepository.InsertAsync(measure); @@ -121,8 +120,7 @@ public virtual async Task InsertMeasureDimension(MeasureDimension measure) /// Measure dimension public virtual async Task UpdateMeasureDimension(MeasureDimension measure) { - if (measure == null) - throw new ArgumentNullException(nameof(measure)); + ArgumentNullException.ThrowIfNull(measure); await _measureDimensionRepository.UpdateAsync(measure); @@ -138,8 +136,7 @@ public virtual async Task UpdateMeasureDimension(MeasureDimension measure) /// Measure dimension public virtual async Task DeleteMeasureDimension(MeasureDimension measureDimension) { - if (measureDimension == null) - throw new ArgumentNullException(nameof(measureDimension)); + ArgumentNullException.ThrowIfNull(measureDimension); await _measureDimensionRepository.DeleteAsync(measureDimension); @@ -160,11 +157,8 @@ public virtual async Task DeleteMeasureDimension(MeasureDimension measureDimensi public virtual async Task ConvertDimension(double value, MeasureDimension sourceMeasureDimension, MeasureDimension targetMeasureDimension, bool round = true) { - if (sourceMeasureDimension == null) - throw new ArgumentNullException(nameof(sourceMeasureDimension)); - - if (targetMeasureDimension == null) - throw new ArgumentNullException(nameof(targetMeasureDimension)); + ArgumentNullException.ThrowIfNull(sourceMeasureDimension); + ArgumentNullException.ThrowIfNull(targetMeasureDimension); var result = value; if (result != 0 && sourceMeasureDimension.Id != targetMeasureDimension.Id) @@ -186,8 +180,7 @@ public virtual async Task ConvertDimension(double value, public virtual async Task ConvertToPrimaryMeasureDimension(double value, MeasureDimension sourceMeasureDimension) { - if (sourceMeasureDimension == null) - throw new ArgumentNullException(nameof(sourceMeasureDimension)); + ArgumentNullException.ThrowIfNull(sourceMeasureDimension); var result = value; var baseDimensionIn = await GetMeasureDimensionById(_measureSettings.BaseDimensionId); @@ -208,8 +201,7 @@ public virtual async Task ConvertToPrimaryMeasureDimension(double value, public virtual async Task ConvertFromPrimaryMeasureDimension(double value, MeasureDimension targetMeasureDimension) { - if (targetMeasureDimension == null) - throw new ArgumentNullException(nameof(targetMeasureDimension)); + ArgumentNullException.ThrowIfNull(targetMeasureDimension); var result = value; var baseDimensionIn = await GetMeasureDimensionById(_measureSettings.BaseDimensionId); @@ -272,8 +264,7 @@ orderby mw.DisplayOrder /// Measure weight public virtual async Task InsertMeasureWeight(MeasureWeight measure) { - if (measure == null) - throw new ArgumentNullException(nameof(measure)); + ArgumentNullException.ThrowIfNull(measure); await _measureWeightRepository.InsertAsync(measure); @@ -289,8 +280,7 @@ public virtual async Task InsertMeasureWeight(MeasureWeight measure) /// Measure weight public virtual async Task UpdateMeasureWeight(MeasureWeight measure) { - if (measure == null) - throw new ArgumentNullException(nameof(measure)); + ArgumentNullException.ThrowIfNull(measure); await _measureWeightRepository.UpdateAsync(measure); @@ -306,8 +296,7 @@ public virtual async Task UpdateMeasureWeight(MeasureWeight measure) /// Measure weight public virtual async Task DeleteMeasureWeight(MeasureWeight measureWeight) { - if (measureWeight == null) - throw new ArgumentNullException(nameof(measureWeight)); + ArgumentNullException.ThrowIfNull(measureWeight); await _measureWeightRepository.DeleteAsync(measureWeight); @@ -328,11 +317,8 @@ public virtual async Task DeleteMeasureWeight(MeasureWeight measureWeight) public virtual async Task ConvertWeight(double value, MeasureWeight sourceMeasureWeight, MeasureWeight targetMeasureWeight, bool round = true) { - if (sourceMeasureWeight == null) - throw new ArgumentNullException(nameof(sourceMeasureWeight)); - - if (targetMeasureWeight == null) - throw new ArgumentNullException(nameof(targetMeasureWeight)); + ArgumentNullException.ThrowIfNull(sourceMeasureWeight); + ArgumentNullException.ThrowIfNull(targetMeasureWeight); var result = value; if (result != 0 && sourceMeasureWeight.Id != targetMeasureWeight.Id) @@ -353,8 +339,7 @@ public virtual async Task ConvertWeight(double value, /// Converted value public virtual async Task ConvertToPrimaryMeasureWeight(double value, MeasureWeight sourceMeasureWeight) { - if (sourceMeasureWeight == null) - throw new ArgumentNullException(nameof(sourceMeasureWeight)); + ArgumentNullException.ThrowIfNull(sourceMeasureWeight); var result = value; var baseWeightIn = await GetMeasureWeightById(_measureSettings.BaseWeightId); @@ -375,8 +360,7 @@ public virtual async Task ConvertToPrimaryMeasureWeight(double value, Me public virtual async Task ConvertFromPrimaryMeasureWeight(double value, MeasureWeight targetMeasureWeight) { - if (targetMeasureWeight == null) - throw new ArgumentNullException(nameof(targetMeasureWeight)); + ArgumentNullException.ThrowIfNull(targetMeasureWeight); var result = value; var baseWeightIn = await GetMeasureWeightById(_measureSettings.BaseWeightId); @@ -427,8 +411,7 @@ orderby md.DisplayOrder /// Measure unit public virtual async Task InsertMeasureUnit(MeasureUnit measure) { - if (measure == null) - throw new ArgumentNullException(nameof(measure)); + ArgumentNullException.ThrowIfNull(measure); await _measureUnitRepository.InsertAsync(measure); @@ -444,8 +427,7 @@ public virtual async Task InsertMeasureUnit(MeasureUnit measure) /// Measure unit public virtual async Task UpdateMeasureUnit(MeasureUnit measure) { - if (measure == null) - throw new ArgumentNullException(nameof(measure)); + ArgumentNullException.ThrowIfNull(measure); await _measureUnitRepository.UpdateAsync(measure); @@ -461,8 +443,7 @@ public virtual async Task UpdateMeasureUnit(MeasureUnit measure) /// Measure unit public virtual async Task DeleteMeasureUnit(MeasureUnit measureUnit) { - if (measureUnit == null) - throw new ArgumentNullException(nameof(measureUnit)); + ArgumentNullException.ThrowIfNull(measureUnit); //delete await _measureUnitRepository.DeleteAsync(measureUnit); diff --git a/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs b/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs index 1d10e8d60..bab95e591 100644 --- a/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs @@ -39,8 +39,7 @@ public SearchTermService(IRepository searchTermRepository, /// Search term public virtual async Task DeleteSearchTerm(SearchTerm searchTerm) { - if (searchTerm == null) - throw new ArgumentNullException(nameof(searchTerm)); + ArgumentNullException.ThrowIfNull(searchTerm); await _searchTermRepository.DeleteAsync(searchTerm); @@ -104,8 +103,7 @@ group st by st.Keyword into groupedResult /// Search term public virtual async Task InsertSearchTerm(SearchTerm searchTerm) { - if (searchTerm == null) - throw new ArgumentNullException(nameof(searchTerm)); + ArgumentNullException.ThrowIfNull(searchTerm); await _searchTermRepository.InsertAsync(searchTerm); @@ -119,8 +117,7 @@ public virtual async Task InsertSearchTerm(SearchTerm searchTerm) /// Search term public virtual async Task UpdateSearchTerm(SearchTerm searchTerm) { - if (searchTerm == null) - throw new ArgumentNullException(nameof(searchTerm)); + ArgumentNullException.ThrowIfNull(searchTerm); await _searchTermRepository.UpdateAsync(searchTerm); diff --git a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs index 57da598f5..2598d4d06 100644 --- a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs @@ -105,7 +105,7 @@ public virtual async Task> GetAllDiscounts(DiscountType? discoun } if (!string.IsNullOrEmpty(couponCode)) { - var coupon = _discountCouponRepository.Table.FirstOrDefault(x => x.CouponCode == couponCode); + var coupon = await _discountCouponRepository.GetOneAsync(x => x.CouponCode == couponCode); if (coupon != null) query = query.Where(d => d.Id == coupon.DiscountId); } @@ -135,9 +135,8 @@ public virtual async Task> GetAllDiscounts(DiscountType? discoun /// Discount public virtual async Task InsertDiscount(Discount discount) { - if (discount == null) - throw new ArgumentNullException(nameof(discount)); - + ArgumentNullException.ThrowIfNull(discount); + await _discountRepository.InsertAsync(discount); await _cacheBase.RemoveByPrefix(CacheKey.DISCOUNTS_PATTERN_KEY); @@ -152,8 +151,7 @@ public virtual async Task InsertDiscount(Discount discount) /// Discount public virtual async Task UpdateDiscount(Discount discount) { - if (discount == null) - throw new ArgumentNullException(nameof(discount)); + ArgumentNullException.ThrowIfNull(discount); await _discountRepository.UpdateAsync(discount); @@ -169,8 +167,7 @@ public virtual async Task UpdateDiscount(Discount discount) /// Discount public virtual async Task DeleteDiscount(Discount discount) { - if (discount == null) - throw new ArgumentNullException(nameof(discount)); + ArgumentNullException.ThrowIfNull(discount); var usageHistory = await GetAllDiscountUsageHistory(discount.Id); if (usageHistory.Count > 0) @@ -224,9 +221,7 @@ public virtual async Task GetDiscountByCouponCode(string couponCode, b if (string.IsNullOrWhiteSpace(couponCode)) return null; - var query = _discountCouponRepository.Table.Where(x => x.CouponCode == couponCode).ToList(); - - var coupon = query.FirstOrDefault(); + var coupon = await _discountCouponRepository.GetOneAsync(x => x.CouponCode == couponCode); if (coupon == null) return null; @@ -293,8 +288,7 @@ public virtual Task GetDiscountCodeById(string id) /// public virtual async Task GetDiscountCodeByCode(string couponCode) { - var query = await Task.FromResult(_discountCouponRepository.Table.Where(x => x.CouponCode == couponCode).ToList()); - return query.FirstOrDefault(); + return await _discountCouponRepository.GetOneAsync(x => x.CouponCode == couponCode); } @@ -367,8 +361,7 @@ public virtual async Task CancelDiscount(string orderId) /// Discount validation result public virtual async Task ValidateDiscount(Discount discount, Customer customer, Currency currency) { - if (discount == null) - throw new ArgumentNullException(nameof(discount)); + ArgumentNullException.ThrowIfNull(discount); string[] couponCodesToValidate = null; if (customer != null) @@ -403,11 +396,8 @@ public virtual Task ValidateDiscount(Discount discount /// Discount validation result public virtual async Task ValidateDiscount(Discount discount, Customer customer, Currency currency, string[] couponCodesToValidate) { - if (discount == null) - throw new ArgumentNullException(nameof(discount)); - - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(discount); + ArgumentNullException.ThrowIfNull(customer); var result = new DiscountValidationResult(); @@ -585,8 +575,7 @@ public virtual async Task> GetAllDiscountUsageH /// Discount usage history item public virtual async Task InsertDiscountUsageHistory(DiscountUsageHistory discountUsageHistory) { - if (discountUsageHistory == null) - throw new ArgumentNullException(nameof(discountUsageHistory)); + ArgumentNullException.ThrowIfNull(discountUsageHistory); await _discountUsageHistoryRepository.InsertAsync(discountUsageHistory); @@ -605,8 +594,7 @@ public virtual async Task InsertDiscountUsageHistory(DiscountUsageHistory discou /// Discount usage history item public virtual async Task UpdateDiscountUsageHistory(DiscountUsageHistory discountUsageHistory) { - if (discountUsageHistory == null) - throw new ArgumentNullException(nameof(discountUsageHistory)); + ArgumentNullException.ThrowIfNull(discountUsageHistory); await _discountUsageHistoryRepository.UpdateAsync(discountUsageHistory); @@ -622,8 +610,7 @@ public virtual async Task UpdateDiscountUsageHistory(DiscountUsageHistory discou /// Discount usage history record public virtual async Task DeleteDiscountUsageHistory(DiscountUsageHistory discountUsageHistory) { - if (discountUsageHistory == null) - throw new ArgumentNullException(nameof(discountUsageHistory)); + ArgumentNullException.ThrowIfNull(discountUsageHistory); await _discountUsageHistoryRepository.DeleteAsync(discountUsageHistory); @@ -643,8 +630,7 @@ public virtual async Task DeleteDiscountUsageHistory(DiscountUsageHistory discou /// Product public virtual async Task GetDiscountAmount(Discount discount, Customer customer, Currency currency, Product product, double amount) { - if (discount == null) - throw new ArgumentNullException(nameof(discount)); + ArgumentNullException.ThrowIfNull(discount); //calculate discount amount double result; @@ -687,8 +673,7 @@ public virtual async Task GetDiscountAmount(Discount discount, Customer IList discounts, Customer customer, Currency currency, Product product, double amount) { - if (discounts == null) - throw new ArgumentNullException(nameof(discounts)); + ArgumentNullException.ThrowIfNull(discounts); var appliedDiscount = new List(); double discountAmount = 0; diff --git a/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs b/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs index a2e3286a3..f01741132 100644 --- a/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs @@ -323,9 +323,8 @@ protected virtual async Task> GetAllowedDiscounts(Product p protected virtual async Task<(double discountAmount, List appliedDiscounts)> GetDiscountAmount(Product product, Customer customer, Currency currency, double productPriceWithoutDiscount) { - if (product == null) - throw new ArgumentNullException(nameof(product)); - + ArgumentNullException.ThrowIfNull(product); + //we don't apply discounts to products with price entered by a customer if (product.EnteredPrice) return (0, null); @@ -393,8 +392,7 @@ protected virtual async Task> GetAllowedDiscounts(Product p DateTime? rentalStartDate, DateTime? rentalEndDate) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); double discountAmount = 0; var appliedDiscounts = new List(); @@ -482,8 +480,7 @@ async Task PrepareModel() public virtual async Task<(double unitprice, double discountAmount, List appliedDiscounts)> GetUnitPrice(ShoppingCartItem shoppingCartItem, Product product, bool includeDiscounts = true) { - if (shoppingCartItem == null) - throw new ArgumentNullException(nameof(shoppingCartItem)); + ArgumentNullException.ThrowIfNull(shoppingCartItem); return await GetUnitPrice(product, _workContext.CurrentCustomer, @@ -522,11 +519,8 @@ async Task PrepareModel() DateTime? rentalEndDate, bool includeDiscounts) { - if (product == null) - throw new ArgumentNullException(nameof(product)); - - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(product); + ArgumentNullException.ThrowIfNull(customer); double discountAmount = 0; var appliedDiscounts = new List(); @@ -631,8 +625,7 @@ async Task PrepareModel() public virtual async Task<(double subTotal, double discountAmount, List appliedDiscounts)> GetSubTotal(ShoppingCartItem shoppingCartItem, Product product, bool includeDiscounts = true) { - if (shoppingCartItem == null) - throw new ArgumentNullException(nameof(shoppingCartItem)); + ArgumentNullException.ThrowIfNull(shoppingCartItem); double subTotal; //unit price @@ -687,8 +680,7 @@ async Task PrepareModel() /// Product cost (one item) public virtual async Task GetProductCost(Product product, IList attributes) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var cost = product.ProductCost; var attributeValues = product.ParseProductAttributeValues(attributes); @@ -722,8 +714,7 @@ public virtual async Task GetProductCost(Product product, IListPrice adjustment public virtual async Task GetProductAttributeValuePriceAdjustment(ProductAttributeValue value) { - if (value == null) - throw new ArgumentNullException(nameof(value)); + ArgumentNullException.ThrowIfNull(value); double adjustment = 0; switch (value.AttributeValueTypeId) diff --git a/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs b/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs index 92dafdcb2..8da39d21d 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs @@ -63,8 +63,7 @@ public virtual async Task> GetBidsByCustomerId(string customerId public virtual async Task InsertBid(Bid bid) { - if (bid == null) - throw new ArgumentNullException(nameof(bid)); + ArgumentNullException.ThrowIfNull(bid); await _bidRepository.InsertAsync(bid); await _mediator.EntityInserted(bid); @@ -72,16 +71,14 @@ public virtual async Task InsertBid(Bid bid) public virtual async Task UpdateBid(Bid bid) { - if (bid == null) - throw new ArgumentNullException(nameof(bid)); + ArgumentNullException.ThrowIfNull(bid); await _bidRepository.UpdateAsync(bid); await _mediator.EntityUpdated(bid); } public virtual async Task DeleteBid(Bid bid) { - if (bid == null) - throw new ArgumentNullException(nameof(bid)); + ArgumentNullException.ThrowIfNull(bid); await _bidRepository.DeleteAsync(bid); await _mediator.EntityDeleted(bid); @@ -167,7 +164,7 @@ await _mediator.Send(new SendOutBidCustomerCommand { /// OrderId public virtual async Task CancelBidByOrder(string orderId) { - var bid = _bidRepository.Table.FirstOrDefault(x => x.OrderId == orderId); + var bid = await _bidRepository.GetOneAsync(x => x.OrderId == orderId); if (bid != null) { await _bidRepository.DeleteAsync(bid); diff --git a/src/Business/Grand.Business.Catalog/Services/Products/CopyProductService.cs b/src/Business/Grand.Business.Catalog/Services/Products/CopyProductService.cs index 932f60d10..e4609c967 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/CopyProductService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/CopyProductService.cs @@ -48,8 +48,7 @@ public CopyProductService(IProductService productService, public virtual async Task CopyProduct(Product product, string newName, bool isPublished = true, bool copyAssociatedProducts = true) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); if (string.IsNullOrEmpty(newName)) newName = $"{product.Name} - CopyProduct"; diff --git a/src/Business/Grand.Business.Catalog/Services/Products/CustomerGroupProductService.cs b/src/Business/Grand.Business.Catalog/Services/Products/CustomerGroupProductService.cs index 918c564d9..da1a4b018 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/CustomerGroupProductService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/CustomerGroupProductService.cs @@ -32,8 +32,7 @@ public CustomerGroupProductService(IRepository customerGro /// Customer group product public virtual async Task DeleteCustomerGroupProduct(CustomerGroupProduct customerGroupProduct) { - if (customerGroupProduct == null) - throw new ArgumentNullException(nameof(customerGroupProduct)); + ArgumentNullException.ThrowIfNull(customerGroupProduct); await _customerGroupProductRepository.DeleteAsync(customerGroupProduct); @@ -52,8 +51,7 @@ public virtual async Task DeleteCustomerGroupProduct(CustomerGroupProduct custom /// Customer group product public virtual async Task InsertCustomerGroupProduct(CustomerGroupProduct customerGroupProduct) { - if (customerGroupProduct == null) - throw new ArgumentNullException(nameof(customerGroupProduct)); + ArgumentNullException.ThrowIfNull(customerGroupProduct); await _customerGroupProductRepository.InsertAsync(customerGroupProduct); @@ -71,8 +69,7 @@ public virtual async Task InsertCustomerGroupProduct(CustomerGroupProduct custom /// Customer group product public virtual async Task UpdateCustomerGroupProduct(CustomerGroupProduct customerGroupProduct) { - if (customerGroupProduct == null) - throw new ArgumentNullException(nameof(customerGroupProduct)); + ArgumentNullException.ThrowIfNull(customerGroupProduct); await _customerGroupProductRepository.UpdateAsync(customerGroupProduct); diff --git a/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs b/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs index 613090535..fd95232b9 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs @@ -274,8 +274,7 @@ private async Task InsertInventoryJournal(Product product, Shipment shipment, Sh /// Warehouse ident public virtual async Task AdjustReserved(Product product, int quantityToChange, IList attributes = null, string warehouseId = "") { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); if (quantityToChange == 0) return; @@ -447,8 +446,7 @@ await _mediator.Send(new SendQuantityBelowStoreOwnerCommand { /// protected virtual async Task ReserveInventory(Product product, int quantity, string warehouseId) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); if (quantity >= 0) throw new ArgumentException("Value must be negative.", nameof(quantity)); @@ -491,11 +489,8 @@ protected virtual async Task ReserveInventory(Product product, int quantity, str /// Warehouse ident protected virtual async Task ReserveInventoryCombination(Product product, ProductAttributeCombination combination, int quantity, string warehouseId) { - if (product == null) - throw new ArgumentNullException(nameof(product)); - - if (combination == null) - throw new ArgumentNullException(nameof(combination)); + ArgumentNullException.ThrowIfNull(product); + ArgumentNullException.ThrowIfNull(combination); if (quantity >= 0) throw new ArgumentException("Value must be negative.", nameof(quantity)); @@ -549,8 +544,7 @@ protected virtual async Task ReserveInventoryCombination(Product product, Produc /// Warehouse ident protected virtual async Task UnblockReservedInventory(Product product, int quantity, string warehouseId) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); if (quantity < 0) throw new ArgumentException("Value must be positive.", nameof(quantity)); @@ -595,8 +589,7 @@ protected virtual async Task UnblockReservedInventory(Product product, int quant /// Warehouse ident protected virtual async Task UnblockReservedInventoryCombination(Product product, ProductAttributeCombination combination, int quantity, string warehouseId) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); if (quantity < 0) throw new ArgumentException("Value must be positive.", nameof(quantity)); @@ -645,14 +638,9 @@ protected virtual async Task UnblockReservedInventoryCombination(Product product /// Shipment item public virtual async Task BookReservedInventory(Product product, Shipment shipment, ShipmentItem shipmentItem) { - if (product == null) - throw new ArgumentNullException(nameof(product)); - - if (shipment == null) - throw new ArgumentNullException(nameof(shipment)); - - if (shipmentItem == null) - throw new ArgumentNullException(nameof(shipmentItem)); + ArgumentNullException.ThrowIfNull(product); + ArgumentNullException.ThrowIfNull(shipment); + ArgumentNullException.ThrowIfNull(shipmentItem); //standard manage stock if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock) @@ -697,12 +685,8 @@ public virtual async Task BookReservedInventory(Product product, Shipment shipme /// Quantity reversed public virtual async Task ReverseBookedInventory(Shipment shipment, ShipmentItem shipmentItem) { - - if (shipment == null) - throw new ArgumentNullException(nameof(shipment)); - - if (shipmentItem == null) - throw new ArgumentNullException(nameof(shipmentItem)); + ArgumentNullException.ThrowIfNull(shipment); + ArgumentNullException.ThrowIfNull(shipmentItem); var inventoryJournals = _inventoryJournalRepository.Table.Where(j => j.PositionId == shipmentItem.Id); @@ -726,8 +710,8 @@ public virtual async Task ReverseBookedInventory(Shipment shipment, ShipmentItem public virtual async Task UpdateStockProduct(Product product, bool mediator = true) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); + if (product.ReservedQuantity < 0) product.ReservedQuantity = 0; diff --git a/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs b/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs index 9013f0106..05fbe65bd 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs @@ -107,8 +107,7 @@ public virtual async Task GetSubscriptionById(string sub /// Subscription public virtual async Task InsertSubscription(OutOfStockSubscription subscription) { - if (subscription == null) - throw new ArgumentNullException(nameof(subscription)); + ArgumentNullException.ThrowIfNull(subscription); await _outOfStockSubscriptionRepository.InsertAsync(subscription); @@ -122,8 +121,7 @@ public virtual async Task InsertSubscription(OutOfStockSubscription subscription /// Subscription public virtual async Task UpdateSubscription(OutOfStockSubscription subscription) { - if (subscription == null) - throw new ArgumentNullException(nameof(subscription)); + ArgumentNullException.ThrowIfNull(subscription); await _outOfStockSubscriptionRepository.UpdateAsync(subscription); @@ -136,8 +134,7 @@ public virtual async Task UpdateSubscription(OutOfStockSubscription subscription /// Subscription public virtual async Task DeleteSubscription(OutOfStockSubscription subscription) { - if (subscription == null) - throw new ArgumentNullException(nameof(subscription)); + ArgumentNullException.ThrowIfNull(subscription); await _outOfStockSubscriptionRepository.DeleteAsync(subscription); @@ -153,8 +150,7 @@ public virtual async Task DeleteSubscription(OutOfStockSubscription subscription /// Number of sent email public virtual async Task SendNotificationsToSubscribers(Product product, string warehouse) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var subscriptions = await _mediator.Send(new SendNotificationsToSubscribersCommand { Product = product, @@ -174,8 +170,7 @@ public virtual async Task SendNotificationsToSubscribers(Product product, string /// Number of sent email public virtual async Task SendNotificationsToSubscribers(Product product, IList attributes, string warehouse) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var subscriptions = await _mediator.Send(new SendNotificationsToSubscribersCommand { Product = product, diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs index df79d9489..087bebee6 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs @@ -85,8 +85,7 @@ public virtual Task GetProductAttributeById(string productAttr /// Product attribute public virtual async Task InsertProductAttribute(ProductAttribute productAttribute) { - if (productAttribute == null) - throw new ArgumentNullException(nameof(productAttribute)); + ArgumentNullException.ThrowIfNull(productAttribute); await _productAttributeRepository.InsertAsync(productAttribute); @@ -106,8 +105,7 @@ public virtual async Task InsertProductAttribute(ProductAttribute productAttribu /// Product attribute public virtual async Task UpdateProductAttribute(ProductAttribute productAttribute) { - if (productAttribute == null) - throw new ArgumentNullException(nameof(productAttribute)); + ArgumentNullException.ThrowIfNull(productAttribute); await _productAttributeRepository.UpdateAsync(productAttribute); @@ -127,8 +125,7 @@ public virtual async Task UpdateProductAttribute(ProductAttribute productAttribu /// Product attribute public virtual async Task DeleteProductAttribute(ProductAttribute productAttribute) { - if (productAttribute == null) - throw new ArgumentNullException(nameof(productAttribute)); + ArgumentNullException.ThrowIfNull(productAttribute); //delete from all product collections await _productRepository.PullFilter(string.Empty, x => x.ProductAttributeMappings, z => z.ProductAttributeId, productAttribute.Id); @@ -158,8 +155,7 @@ public virtual async Task DeleteProductAttribute(ProductAttribute productAttribu /// Product ident public virtual async Task DeleteProductAttributeMapping(ProductAttributeMapping productAttributeMapping, string productId) { - if (productAttributeMapping == null) - throw new ArgumentNullException(nameof(productAttributeMapping)); + ArgumentNullException.ThrowIfNull(productAttributeMapping); await _productRepository.PullFilter(productId, x => x.ProductAttributeMappings, z => z.Id, productAttributeMapping.Id); @@ -177,8 +173,7 @@ public virtual async Task DeleteProductAttributeMapping(ProductAttributeMapping /// Product ident public virtual async Task InsertProductAttributeMapping(ProductAttributeMapping productAttributeMapping, string productId) { - if (productAttributeMapping == null) - throw new ArgumentNullException(nameof(productAttributeMapping)); + ArgumentNullException.ThrowIfNull(productAttributeMapping); await _productRepository.AddToSet(productId, x => x.ProductAttributeMappings, productAttributeMapping); @@ -197,8 +192,7 @@ public virtual async Task InsertProductAttributeMapping(ProductAttributeMapping /// Update values public virtual async Task UpdateProductAttributeMapping(ProductAttributeMapping productAttributeMapping, string productId, bool values = false) { - if (productAttributeMapping == null) - throw new ArgumentNullException(nameof(productAttributeMapping)); + ArgumentNullException.ThrowIfNull(productAttributeMapping); await _productRepository.UpdateToSet(productId, x => x.ProductAttributeMappings, z => z.Id, productAttributeMapping.Id, productAttributeMapping); @@ -221,8 +215,7 @@ public virtual async Task UpdateProductAttributeMapping(ProductAttributeMapping /// Product attr mapping ident public virtual async Task DeleteProductAttributeValue(ProductAttributeValue productAttributeValue, string productId, string productAttributeMappingId) { - if (productAttributeValue == null) - throw new ArgumentNullException(nameof(productAttributeValue)); + ArgumentNullException.ThrowIfNull(productAttributeValue); var p = await _productRepository.GetByIdAsync(productId); if (p != null) @@ -252,8 +245,7 @@ public virtual async Task DeleteProductAttributeValue(ProductAttributeValue prod /// Product attr mapping ident public virtual async Task InsertProductAttributeValue(ProductAttributeValue productAttributeValue, string productId, string productAttributeMappingId) { - if (productAttributeValue == null) - throw new ArgumentNullException(nameof(productAttributeValue)); + ArgumentNullException.ThrowIfNull(productAttributeValue); var p = await _productRepository.GetByIdAsync(productId); if (p == null) @@ -281,8 +273,7 @@ public virtual async Task InsertProductAttributeValue(ProductAttributeValue prod /// Product attr mapping ident public virtual async Task UpdateProductAttributeValue(ProductAttributeValue productAttributeValue, string productId, string productAttributeMappingId) { - if (productAttributeValue == null) - throw new ArgumentNullException(nameof(productAttributeValue)); + ArgumentNullException.ThrowIfNull(productAttributeValue); var p = await _productRepository.GetByIdAsync(productId); var pavs = p?.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMappingId); @@ -324,8 +315,7 @@ public virtual async Task UpdateProductAttributeValue(ProductAttributeValue prod /// Product ident public virtual async Task DeleteProductAttributeCombination(ProductAttributeCombination combination, string productId) { - if (combination == null) - throw new ArgumentNullException(nameof(combination)); + ArgumentNullException.ThrowIfNull(combination); await _productRepository.PullFilter(productId, x => x.ProductAttributeCombinations, z => z.Id, combination.Id); //cache @@ -342,8 +332,7 @@ public virtual async Task DeleteProductAttributeCombination(ProductAttributeComb /// Product ident public virtual async Task InsertProductAttributeCombination(ProductAttributeCombination combination, string productId) { - if (combination == null) - throw new ArgumentNullException(nameof(combination)); + ArgumentNullException.ThrowIfNull(combination); await _productRepository.AddToSet(productId, x => x.ProductAttributeCombinations, combination); @@ -361,8 +350,7 @@ public virtual async Task InsertProductAttributeCombination(ProductAttributeComb /// Product ident public virtual async Task UpdateProductAttributeCombination(ProductAttributeCombination combination, string productId) { - if (combination == null) - throw new ArgumentNullException(nameof(combination)); + ArgumentNullException.ThrowIfNull(combination); await _productRepository.UpdateToSet(productId, x => x.ProductAttributeCombinations, z => z.Id, combination.Id, combination); diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs index 979c0110e..9f8083797 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs @@ -18,12 +18,12 @@ public ProductCourseService(IRepository productRepository, IRepository< public virtual async Task GetCourseByProductId(string productId) { - return await Task.FromResult(_courseRepository.Table.FirstOrDefault(p => p.ProductId == productId)); + return await _courseRepository.GetOneAsync(p => p.ProductId == productId); } public virtual async Task GetProductByCourseId(string courseId) { - return await Task.FromResult(_productRepository.Table.FirstOrDefault(p => p.CourseId == courseId)); + return await _productRepository.GetOneAsync(p => p.CourseId == courseId); } public virtual async Task UpdateCourseOnProduct(string productId, string courseId) diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductLayoutService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductLayoutService.cs index b12737e44..9fb4cf98a 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductLayoutService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductLayoutService.cs @@ -75,8 +75,7 @@ public virtual Task GetProductLayoutById(string productLayoutId) /// Product layout public virtual async Task InsertProductLayout(ProductLayout productLayout) { - if (productLayout == null) - throw new ArgumentNullException(nameof(productLayout)); + ArgumentNullException.ThrowIfNull(productLayout); await _productLayoutRepository.InsertAsync(productLayout); @@ -93,8 +92,7 @@ public virtual async Task InsertProductLayout(ProductLayout productLayout) /// Product layout public virtual async Task UpdateProductLayout(ProductLayout productLayout) { - if (productLayout == null) - throw new ArgumentNullException(nameof(productLayout)); + ArgumentNullException.ThrowIfNull(productLayout); await _productLayoutRepository.UpdateAsync(productLayout); @@ -111,8 +109,7 @@ public virtual async Task UpdateProductLayout(ProductLayout productLayout) /// Product layout public virtual async Task DeleteProductLayout(ProductLayout productLayout) { - if (productLayout == null) - throw new ArgumentNullException(nameof(productLayout)); + ArgumentNullException.ThrowIfNull(productLayout); await _productLayoutRepository.DeleteAsync(productLayout); diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs index e77b7f0af..8df95601f 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs @@ -64,8 +64,7 @@ public virtual async Task> GetProductReservations /// Product reservation public virtual async Task InsertProductReservation(ProductReservation productReservation) { - if (productReservation == null) - throw new ArgumentNullException(nameof(productReservation)); + ArgumentNullException.ThrowIfNull(productReservation); await _productReservationRepository.InsertAsync(productReservation); @@ -79,8 +78,7 @@ public virtual async Task InsertProductReservation(ProductReservation productRes /// Product reservation public virtual async Task UpdateProductReservation(ProductReservation productReservation) { - if (productReservation == null) - throw new ArgumentNullException(nameof(productReservation)); + ArgumentNullException.ThrowIfNull(productReservation); await _productReservationRepository.UpdateAsync(productReservation); @@ -94,8 +92,7 @@ public virtual async Task UpdateProductReservation(ProductReservation productRes /// Product reservation public virtual async Task DeleteProductReservation(ProductReservation productReservation) { - if (productReservation == null) - throw new ArgumentNullException(nameof(productReservation)); + ArgumentNullException.ThrowIfNull(productReservation); await _productReservationRepository.DeleteAsync(productReservation); @@ -119,8 +116,7 @@ public virtual Task GetProductReservation(string id) /// public virtual async Task InsertCustomerReservationsHelper(CustomerReservationsHelper crh) { - if (crh == null) - throw new ArgumentNullException(nameof(crh)); + ArgumentNullException.ThrowIfNull(crh); await _customerReservationsHelperRepository.InsertAsync(crh); @@ -134,8 +130,7 @@ public virtual async Task InsertCustomerReservationsHelper(CustomerReservationsH /// public virtual async Task DeleteCustomerReservationsHelper(CustomerReservationsHelper crh) { - if (crh == null) - throw new ArgumentNullException(nameof(crh)); + ArgumentNullException.ThrowIfNull(crh); await _customerReservationsHelperRepository.DeleteAsync(crh); diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs index 334622cff..0f0db8be1 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs @@ -76,8 +76,7 @@ public virtual async Task> GetAllProductReviews(string /// Product review public virtual async Task InsertProductReview(ProductReview productReview) { - if (productReview == null) - throw new ArgumentNullException(nameof(productReview)); + ArgumentNullException.ThrowIfNull(productReview); await _productReviewRepository.InsertAsync(productReview); @@ -86,8 +85,7 @@ public virtual async Task InsertProductReview(ProductReview productReview) } public virtual async Task UpdateProductReview(ProductReview productReview) { - if (productReview == null) - throw new ArgumentNullException(nameof(productReview)); + ArgumentNullException.ThrowIfNull(productReview); var update = UpdateBuilder.Create() .Set(x => x.Title, productReview.Title) @@ -111,8 +109,7 @@ public virtual async Task UpdateProductReview(ProductReview productReview) /// Product review public virtual async Task DeleteProductReview(ProductReview productReview) { - if (productReview == null) - throw new ArgumentNullException(nameof(productReview)); + ArgumentNullException.ThrowIfNull(productReview); await _productReviewRepository.DeleteAsync(productReview); diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs index 41af576bf..c56a5fce3 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs @@ -157,8 +157,7 @@ where c.AppliedDiscounts.Any(x => x == discountId) /// Product public virtual async Task InsertProduct(Product product) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); //insert await _productRepository.InsertAsync(product); @@ -176,8 +175,7 @@ public virtual async Task InsertProduct(Product product) /// Product public virtual async Task UpdateProduct(Product product) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var oldProduct = await _productRepository.GetByIdAsync(product.Id); //update @@ -335,8 +333,7 @@ public virtual async Task UpdateProduct(Product product) public virtual async Task UpdateProductField(Product product, Expression> expression, T value) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); //update field await _productRepository.UpdateField(product.Id, expression, value); @@ -360,8 +357,7 @@ public virtual async Task UpdateProductField(Product product, public virtual async Task IncrementProductField(Product product, Expression> expression, T value) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); //inc field await _productRepository.IncField(product.Id, expression, value); @@ -373,8 +369,7 @@ public virtual async Task IncrementProductField(Product product, /// Product public virtual async Task DeleteProduct(Product product) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); //deleted product await _productRepository.DeleteAsync(product); @@ -630,13 +625,12 @@ public virtual async Task GetProductBySku(string sku) return null; sku = sku.Trim(); - return await Task.FromResult(_productRepository.Table.FirstOrDefault(x => x.Sku == sku)); + return await _productRepository.GetOneAsync(x => x.Sku == sku); } public virtual async Task UpdateAssociatedProduct(Product product) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var update = UpdateBuilder.Create() .Set(x => x.DisplayOrder, product.DisplayOrder) @@ -664,8 +658,7 @@ public virtual async Task UpdateAssociatedProduct(Product product) public virtual async Task InsertRelatedProduct(RelatedProduct relatedProduct, string productId) { - if (relatedProduct == null) - throw new ArgumentNullException(nameof(relatedProduct)); + ArgumentNullException.ThrowIfNull(relatedProduct); await _productRepository.AddToSet(productId, x => x.RelatedProducts, relatedProduct); @@ -682,8 +675,7 @@ public virtual async Task InsertRelatedProduct(RelatedProduct relatedProduct, st /// Product ident public virtual async Task DeleteRelatedProduct(RelatedProduct relatedProduct, string productId) { - if (relatedProduct == null) - throw new ArgumentNullException(nameof(relatedProduct)); + ArgumentNullException.ThrowIfNull(relatedProduct); await _productRepository.PullFilter(productId, x => x.RelatedProducts, z => z.Id, relatedProduct.Id); @@ -701,8 +693,7 @@ public virtual async Task DeleteRelatedProduct(RelatedProduct relatedProduct, st /// Product ident public virtual async Task UpdateRelatedProduct(RelatedProduct relatedProduct, string productId) { - if (relatedProduct == null) - throw new ArgumentNullException(nameof(relatedProduct)); + ArgumentNullException.ThrowIfNull(relatedProduct); await _productRepository.UpdateToSet(productId, x => x.RelatedProducts, z => z.Id, relatedProduct.Id, relatedProduct); @@ -719,8 +710,7 @@ public virtual async Task UpdateRelatedProduct(RelatedProduct relatedProduct, st public virtual async Task InsertSimilarProduct(SimilarProduct similarProduct) { - if (similarProduct == null) - throw new ArgumentNullException(nameof(similarProduct)); + ArgumentNullException.ThrowIfNull(similarProduct); await _productRepository.AddToSet(similarProduct.ProductId1, x => x.SimilarProducts, similarProduct); @@ -737,8 +727,7 @@ public virtual async Task InsertSimilarProduct(SimilarProduct similarProduct) /// Similar product public virtual async Task UpdateSimilarProduct(SimilarProduct similarProduct) { - if (similarProduct == null) - throw new ArgumentNullException(nameof(similarProduct)); + ArgumentNullException.ThrowIfNull(similarProduct); await _productRepository.UpdateToSet(similarProduct.ProductId1, x => x.SimilarProducts, z => z.Id, similarProduct.Id, similarProduct); @@ -754,8 +743,7 @@ public virtual async Task UpdateSimilarProduct(SimilarProduct similarProduct) /// Similar product public virtual async Task DeleteSimilarProduct(SimilarProduct similarProduct) { - if (similarProduct == null) - throw new ArgumentNullException(nameof(similarProduct)); + ArgumentNullException.ThrowIfNull(similarProduct); await _productRepository.PullFilter(similarProduct.ProductId1, x => x.SimilarProducts, z => z.Id, similarProduct.Id); @@ -777,8 +765,7 @@ public virtual async Task DeleteSimilarProduct(SimilarProduct similarProduct) /// Product bundle ident public virtual async Task InsertBundleProduct(BundleProduct bundleProduct, string productBundleId) { - if (bundleProduct == null) - throw new ArgumentNullException(nameof(bundleProduct)); + ArgumentNullException.ThrowIfNull(bundleProduct); await _productRepository.AddToSet(productBundleId, x => x.BundleProducts, bundleProduct); @@ -797,8 +784,7 @@ public virtual async Task InsertBundleProduct(BundleProduct bundleProduct, strin /// Product bundle ident public virtual async Task UpdateBundleProduct(BundleProduct bundleProduct, string productBundleId) { - if (bundleProduct == null) - throw new ArgumentNullException(nameof(bundleProduct)); + ArgumentNullException.ThrowIfNull(bundleProduct); await _productRepository.UpdateToSet(productBundleId, x => x.BundleProducts, z => z.Id, bundleProduct.Id, bundleProduct); @@ -816,8 +802,7 @@ public virtual async Task UpdateBundleProduct(BundleProduct bundleProduct, strin /// Product bundle ident public virtual async Task DeleteBundleProduct(BundleProduct bundleProduct, string productBundleId) { - if (bundleProduct == null) - throw new ArgumentNullException(nameof(bundleProduct)); + ArgumentNullException.ThrowIfNull(bundleProduct); await _productRepository.PullFilter(productBundleId, x => x.BundleProducts, z => z.Id, bundleProduct.Id); @@ -838,8 +823,7 @@ public virtual async Task DeleteBundleProduct(BundleProduct bundleProduct, strin /// Cross-sell product public virtual async Task InsertCrossSellProduct(CrossSellProduct crossSellProduct) { - if (crossSellProduct == null) - throw new ArgumentNullException(nameof(crossSellProduct)); + ArgumentNullException.ThrowIfNull(crossSellProduct); await _productRepository.AddToSet(crossSellProduct.ProductId1, x => x.CrossSellProduct, crossSellProduct.ProductId2); @@ -856,8 +840,7 @@ public virtual async Task InsertCrossSellProduct(CrossSellProduct crossSellProdu /// Cross-sell identifier public virtual async Task DeleteCrossSellProduct(CrossSellProduct crossSellProduct) { - if (crossSellProduct == null) - throw new ArgumentNullException(nameof(crossSellProduct)); + ArgumentNullException.ThrowIfNull(crossSellProduct); await _productRepository.Pull(crossSellProduct.ProductId1, x => x.CrossSellProduct, crossSellProduct.ProductId2); @@ -930,11 +913,8 @@ public virtual async Task> GetCrossSellProductsByShoppingCart(ILi /// Recommended product public virtual async Task InsertRecommendedProduct(string productId, string recommendedProductId) { - if (productId == null) - throw new ArgumentNullException(nameof(productId)); - - if (recommendedProductId == null) - throw new ArgumentNullException(nameof(recommendedProductId)); + ArgumentNullException.ThrowIfNull(productId); + ArgumentNullException.ThrowIfNull(recommendedProductId); await _productRepository.AddToSet(productId, x => x.RecommendedProduct, recommendedProductId); @@ -950,11 +930,8 @@ public virtual async Task InsertRecommendedProduct(string productId, string reco /// Recommended identifier public virtual async Task DeleteRecommendedProduct(string productId, string recommendedProductId) { - if (productId == null) - throw new ArgumentNullException(nameof(productId)); - - if (recommendedProductId == null) - throw new ArgumentNullException(nameof(recommendedProductId)); + ArgumentNullException.ThrowIfNull(productId); + ArgumentNullException.ThrowIfNull(recommendedProductId); await _productRepository.Pull(productId, x => x.RecommendedProduct, recommendedProductId); @@ -974,8 +951,7 @@ public virtual async Task DeleteRecommendedProduct(string productId, string reco /// Product ident public virtual async Task InsertTierPrice(TierPrice tierPrice, string productId) { - if (tierPrice == null) - throw new ArgumentNullException(nameof(tierPrice)); + ArgumentNullException.ThrowIfNull(tierPrice); await _productRepository.AddToSet(productId, x => x.TierPrices, tierPrice); @@ -993,8 +969,7 @@ public virtual async Task InsertTierPrice(TierPrice tierPrice, string productId) /// Product ident public virtual async Task UpdateTierPrice(TierPrice tierPrice, string productId) { - if (tierPrice == null) - throw new ArgumentNullException(nameof(tierPrice)); + ArgumentNullException.ThrowIfNull(tierPrice); await _productRepository.UpdateToSet(productId, x => x.TierPrices, z => z.Id, tierPrice.Id, tierPrice); @@ -1011,8 +986,7 @@ public virtual async Task UpdateTierPrice(TierPrice tierPrice, string productId) /// Product ident public virtual async Task DeleteTierPrice(TierPrice tierPrice, string productId) { - if (tierPrice == null) - throw new ArgumentNullException(nameof(tierPrice)); + ArgumentNullException.ThrowIfNull(tierPrice); await _productRepository.PullFilter(productId, x => x.TierPrices, x => x.Id, tierPrice.Id); @@ -1033,8 +1007,7 @@ public virtual async Task DeleteTierPrice(TierPrice tierPrice, string productId) /// Product price public virtual async Task InsertProductPrice(ProductPrice productPrice) { - if (productPrice == null) - throw new ArgumentNullException(nameof(productPrice)); + ArgumentNullException.ThrowIfNull(productPrice); await _productRepository.AddToSet(productPrice.ProductId, x => x.ProductPrices, productPrice); @@ -1051,8 +1024,7 @@ public virtual async Task InsertProductPrice(ProductPrice productPrice) /// Tier price public virtual async Task UpdateProductPrice(ProductPrice productPrice) { - if (productPrice == null) - throw new ArgumentNullException(nameof(productPrice)); + ArgumentNullException.ThrowIfNull(productPrice); await _productRepository.UpdateToSet(productPrice.ProductId, x => x.ProductPrices, z => z.Id, productPrice.Id, productPrice); @@ -1069,8 +1041,7 @@ public virtual async Task UpdateProductPrice(ProductPrice productPrice) /// Product price public virtual async Task DeleteProductPrice(ProductPrice productPrice) { - if (productPrice == null) - throw new ArgumentNullException(nameof(productPrice)); + ArgumentNullException.ThrowIfNull(productPrice); await _productRepository.PullFilter(productPrice.ProductId, x => x.ProductPrices, x => x.Id, productPrice.Id); @@ -1091,8 +1062,7 @@ public virtual async Task DeleteProductPrice(ProductPrice productPrice) /// Product ident public virtual async Task InsertProductPicture(ProductPicture productPicture, string productId) { - if (productPicture == null) - throw new ArgumentNullException(nameof(productPicture)); + ArgumentNullException.ThrowIfNull(productPicture); await _productRepository.AddToSet(productId, x => x.ProductPictures, productPicture); @@ -1110,8 +1080,7 @@ public virtual async Task InsertProductPicture(ProductPicture productPicture, st /// Product ident public virtual async Task UpdateProductPicture(ProductPicture productPicture, string productId) { - if (productPicture == null) - throw new ArgumentNullException(nameof(productPicture)); + ArgumentNullException.ThrowIfNull(productPicture); await _productRepository.UpdateToSet(productId, x => x.ProductPictures, z => z.Id, productPicture.Id, productPicture); @@ -1128,8 +1097,7 @@ public virtual async Task UpdateProductPicture(ProductPicture productPicture, st /// Product ident public virtual async Task DeleteProductPicture(ProductPicture productPicture, string productId) { - if (productPicture == null) - throw new ArgumentNullException(nameof(productPicture)); + ArgumentNullException.ThrowIfNull(productPicture); await _productRepository.PullFilter(productId, x => x.ProductPictures, x => x.Id, productPicture.Id); @@ -1150,8 +1118,7 @@ public virtual async Task DeleteProductPicture(ProductPicture productPicture, st /// public virtual async Task InsertProductWarehouseInventory(ProductWarehouseInventory pwi, string productId) { - if (pwi == null) - throw new ArgumentNullException(nameof(pwi)); + ArgumentNullException.ThrowIfNull(pwi); await _productRepository.AddToSet(productId, x => x.ProductWarehouseInventory, pwi); @@ -1169,8 +1136,7 @@ public virtual async Task InsertProductWarehouseInventory(ProductWarehouseInvent /// public virtual async Task UpdateProductWarehouseInventory(ProductWarehouseInventory pwi, string productId) { - if (pwi == null) - throw new ArgumentNullException(nameof(pwi)); + ArgumentNullException.ThrowIfNull(pwi); await _productRepository.UpdateToSet(productId, x => x.ProductWarehouseInventory, z => z.Id, pwi.Id, pwi); @@ -1186,8 +1152,7 @@ public virtual async Task UpdateProductWarehouseInventory(ProductWarehouseInvent /// Product ident public virtual async Task DeleteProductWarehouseInventory(ProductWarehouseInventory pwi, string productId) { - if (pwi == null) - throw new ArgumentNullException(nameof(pwi)); + ArgumentNullException.ThrowIfNull(pwi); await _productRepository.PullFilter(productId, x => x.ProductWarehouseInventory, x => x.Id, pwi.Id); diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs index 7fb883fea..497071bc4 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs @@ -94,11 +94,7 @@ public virtual Task GetProductTagById(string productTagId) /// Product tag public virtual Task GetProductTagByName(string name) { - var query = from pt in _productTagRepository.Table - where pt.Name == name - select pt; - - return Task.FromResult(query.FirstOrDefault()); + return _productTagRepository.GetOneAsync(x=>x.Name == name); } /// @@ -108,10 +104,7 @@ public virtual Task GetProductTagByName(string name) /// Product tag public virtual Task GetProductTagBySeName(string sename) { - var query = from pt in _productTagRepository.Table - where pt.SeName == sename - select pt; - return Task.FromResult(query.FirstOrDefault()); + return _productTagRepository.GetOneAsync(x=>x.SeName == sename); } /// @@ -120,8 +113,7 @@ public virtual Task GetProductTagBySeName(string sename) /// Product tag public virtual async Task InsertProductTag(ProductTag productTag) { - if (productTag == null) - throw new ArgumentNullException(nameof(productTag)); + ArgumentNullException.ThrowIfNull(productTag); await _productTagRepository.InsertAsync(productTag); @@ -138,8 +130,7 @@ public virtual async Task InsertProductTag(ProductTag productTag) /// Product tag public virtual async Task UpdateProductTag(ProductTag productTag) { - if (productTag == null) - throw new ArgumentNullException(nameof(productTag)); + ArgumentNullException.ThrowIfNull(productTag); var previous = await GetProductTagById(productTag.Id); @@ -160,8 +151,7 @@ public virtual async Task UpdateProductTag(ProductTag productTag) /// Product tag public virtual async Task DeleteProductTag(ProductTag productTag) { - if (productTag == null) - throw new ArgumentNullException(nameof(productTag)); + ArgumentNullException.ThrowIfNull(productTag); //update product await _productRepository.Pull(string.Empty, x => x.ProductTags, productTag.Name); @@ -184,8 +174,7 @@ public virtual async Task DeleteProductTag(ProductTag productTag) /// Product ident public virtual async Task AttachProductTag(ProductTag productTag, string productId) { - if (productTag == null) - throw new ArgumentNullException(nameof(productTag)); + ArgumentNullException.ThrowIfNull(productTag); //assign to product await _productRepository.AddToSet(productId, x => x.ProductTags, productTag.Name); @@ -208,9 +197,7 @@ public virtual async Task AttachProductTag(ProductTag productTag, string product /// Product ident public virtual async Task DetachProductTag(ProductTag productTag, string productId) { - if (productTag == null) - throw new ArgumentNullException(nameof(productTag)); - + ArgumentNullException.ThrowIfNull(productTag); await _productRepository.Pull(productId, x => x.ProductTags, productTag.Name); diff --git a/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs b/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs index e598eb5a1..64d05dee5 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs @@ -96,8 +96,7 @@ orderby sa.DisplayOrder /// The specification attribute public virtual async Task InsertSpecificationAttribute(SpecificationAttribute specificationAttribute) { - if (specificationAttribute == null) - throw new ArgumentNullException(nameof(specificationAttribute)); + ArgumentNullException.ThrowIfNull(specificationAttribute); await _specificationAttributeRepository.InsertAsync(specificationAttribute); @@ -114,8 +113,7 @@ public virtual async Task InsertSpecificationAttribute(SpecificationAttribute sp /// The specification attribute public virtual async Task UpdateSpecificationAttribute(SpecificationAttribute specificationAttribute) { - if (specificationAttribute == null) - throw new ArgumentNullException(nameof(specificationAttribute)); + ArgumentNullException.ThrowIfNull(specificationAttribute); await _specificationAttributeRepository.UpdateAsync(specificationAttribute); @@ -131,8 +129,7 @@ public virtual async Task UpdateSpecificationAttribute(SpecificationAttribute sp /// The specification attribute public virtual async Task DeleteSpecificationAttribute(SpecificationAttribute specificationAttribute) { - if (specificationAttribute == null) - throw new ArgumentNullException(nameof(specificationAttribute)); + ArgumentNullException.ThrowIfNull(specificationAttribute); //delete from all product collections await _productRepository.PullFilter(string.Empty, x => x.ProductSpecificationAttributes, z => z.SpecificationAttributeId, specificationAttribute.Id); @@ -177,8 +174,7 @@ where p.SpecificationAttributeOptions.Any(x => x.Id == specificationAttributeOpt /// The specification attribute option public virtual async Task DeleteSpecificationAttributeOption(SpecificationAttributeOption specificationAttributeOption) { - if (specificationAttributeOption == null) - throw new ArgumentNullException(nameof(specificationAttributeOption)); + ArgumentNullException.ThrowIfNull(specificationAttributeOption); //delete from all product collections await _productRepository.PullFilter(string.Empty, x => x.ProductSpecificationAttributes, z => z.SpecificationAttributeOptionId, specificationAttributeOption.Id); @@ -212,8 +208,7 @@ public virtual async Task DeleteSpecificationAttributeOption(SpecificationAttrib /// Product ident public virtual async Task InsertProductSpecificationAttribute(ProductSpecificationAttribute productSpecificationAttribute, string productId) { - if (productSpecificationAttribute == null) - throw new ArgumentNullException(nameof(productSpecificationAttribute)); + ArgumentNullException.ThrowIfNull(productSpecificationAttribute); await _productRepository.AddToSet(productId, x => x.ProductSpecificationAttributes, productSpecificationAttribute); @@ -231,8 +226,7 @@ public virtual async Task InsertProductSpecificationAttribute(ProductSpecificati /// Product ident public virtual async Task UpdateProductSpecificationAttribute(ProductSpecificationAttribute productSpecificationAttribute, string productId) { - if (productSpecificationAttribute == null) - throw new ArgumentNullException(nameof(productSpecificationAttribute)); + ArgumentNullException.ThrowIfNull(productSpecificationAttribute); await _productRepository.UpdateToSet(productId, x => x.ProductSpecificationAttributes, z => z.Id, productSpecificationAttribute.Id, productSpecificationAttribute); @@ -249,8 +243,7 @@ public virtual async Task UpdateProductSpecificationAttribute(ProductSpecificati /// Product ident public virtual async Task DeleteProductSpecificationAttribute(ProductSpecificationAttribute productSpecificationAttribute, string productId) { - if (productSpecificationAttribute == null) - throw new ArgumentNullException(nameof(productSpecificationAttribute)); + ArgumentNullException.ThrowIfNull(productSpecificationAttribute); await _productRepository.PullFilter(productId, x => x.ProductSpecificationAttributes, x => x.Id, productSpecificationAttribute.Id); diff --git a/src/Business/Grand.Business.Catalog/Services/Products/StockQuantityService.cs b/src/Business/Grand.Business.Catalog/Services/Products/StockQuantityService.cs index e4bb5d2b5..436b9f422 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/StockQuantityService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/StockQuantityService.cs @@ -11,8 +11,7 @@ public class StockQuantityService : IStockQuantityService public virtual int GetTotalStockQuantity(Product product, bool useReservedQuantity = true, string warehouseId = "", bool total = false) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); if (product.ManageInventoryMethodId != ManageInventoryMethod.ManageStock) { @@ -51,11 +50,8 @@ public virtual int GetTotalStockQuantity(Product product, bool useReservedQuanti public virtual int GetTotalStockQuantityForCombination(Product product, ProductAttributeCombination combination, bool useReservedQuantity = true, string warehouseId = "") { - if (product == null) - throw new ArgumentNullException(nameof(product)); - - if (combination == null) - throw new ArgumentNullException(nameof(combination)); + ArgumentNullException.ThrowIfNull(product); + ArgumentNullException.ThrowIfNull(combination); if (product.ManageInventoryMethodId != ManageInventoryMethod.ManageStockByAttributes) { @@ -87,8 +83,7 @@ public virtual int GetTotalStockQuantityForCombination(Product product, ProductA public virtual (string resource, object? arg0) FormatStockMessage(Product product, string warehouseId, IList attributes) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var stockMessage = string.Empty; diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs index 80ce87b76..b2bfe1f33 100644 --- a/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs @@ -75,8 +75,7 @@ public virtual Task GetTaxCategoryById(string taxCategoryId) /// Tax category public virtual async Task InsertTaxCategory(TaxCategory taxCategory) { - if (taxCategory == null) - throw new ArgumentNullException(nameof(taxCategory)); + ArgumentNullException.ThrowIfNull(taxCategory); await _taxCategoryRepository.InsertAsync(taxCategory); @@ -92,8 +91,7 @@ public virtual async Task InsertTaxCategory(TaxCategory taxCategory) /// Tax category public virtual async Task UpdateTaxCategory(TaxCategory taxCategory) { - if (taxCategory == null) - throw new ArgumentNullException(nameof(taxCategory)); + ArgumentNullException.ThrowIfNull(taxCategory); await _taxCategoryRepository.UpdateAsync(taxCategory); @@ -108,8 +106,7 @@ public virtual async Task UpdateTaxCategory(TaxCategory taxCategory) /// Tax category public virtual async Task DeleteTaxCategory(TaxCategory taxCategory) { - if (taxCategory == null) - throw new ArgumentNullException(nameof(taxCategory)); + ArgumentNullException.ThrowIfNull(taxCategory); await _taxCategoryRepository.DeleteAsync(taxCategory); diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs index 740082568..71bc87a0a 100644 --- a/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs @@ -71,8 +71,7 @@ public TaxService( /// Result protected virtual async Task IsEuConsumer(Customer customer) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); Country country = null; @@ -116,8 +115,7 @@ protected virtual async Task IsEuConsumer(Customer customer) protected virtual async Task CreateCalculateTaxRequest(Product product, string taxCategoryId, Customer customer, double price) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); var calculateTaxRequest = new TaxRequest { Customer = customer, @@ -598,11 +596,8 @@ bool priceIncludesTax /// Price public virtual async Task<(double checkoutPrice, double taxRate)> GetCheckoutAttributePrice(CheckoutAttribute ca, CheckoutAttributeValue cav, bool includingTax, Customer customer) { - if (ca == null) - throw new ArgumentNullException(nameof(ca)); - - if (cav == null) - throw new ArgumentNullException(nameof(cav)); + ArgumentNullException.ThrowIfNull(ca); + ArgumentNullException.ThrowIfNull(cav); var price = cav.PriceAdjustment; if (ca.IsTaxExempt) diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandler.cs index 8c91187df..a47663a9a 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ValidateMinShoppingCartSubtotalAmountCommandHandler.cs @@ -31,8 +31,7 @@ public async Task Handle(ValidateMinShoppingCartSubtotalAmountCommand requ protected virtual async Task ValidateMinOrderSubtotalAmount(IList cart) { - if (cart == null) - throw new ArgumentNullException(nameof(cart)); + ArgumentNullException.ThrowIfNull(cart); if (!cart.Any()) return false; diff --git a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeParser.cs b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeParser.cs index f57e8ff3a..f382142cb 100644 --- a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeParser.cs +++ b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeParser.cs @@ -130,8 +130,7 @@ public virtual async Task> EnsureOnlyActiveAttributes(ILi /// Result public virtual async Task IsConditionMet(CheckoutAttribute attribute, IList customAttributes) { - if (attribute == null) - throw new ArgumentNullException(nameof(attribute)); + ArgumentNullException.ThrowIfNull(attribute); customAttributes ??= new List(); diff --git a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs index b37ac213b..7339c96be 100644 --- a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs +++ b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs @@ -109,8 +109,7 @@ public virtual Task GetCheckoutAttributeById(string checkoutA /// Checkout attribute public virtual async Task InsertCheckoutAttribute(CheckoutAttribute checkoutAttribute) { - if (checkoutAttribute == null) - throw new ArgumentNullException(nameof(checkoutAttribute)); + ArgumentNullException.ThrowIfNull(checkoutAttribute); await _checkoutAttributeRepository.InsertAsync(checkoutAttribute); @@ -127,8 +126,7 @@ public virtual async Task InsertCheckoutAttribute(CheckoutAttribute checkoutAttr /// Checkout attribute public virtual async Task UpdateCheckoutAttribute(CheckoutAttribute checkoutAttribute) { - if (checkoutAttribute == null) - throw new ArgumentNullException(nameof(checkoutAttribute)); + ArgumentNullException.ThrowIfNull(checkoutAttribute); await _checkoutAttributeRepository.UpdateAsync(checkoutAttribute); @@ -144,8 +142,7 @@ public virtual async Task UpdateCheckoutAttribute(CheckoutAttribute checkoutAttr /// Checkout attribute public virtual async Task DeleteCheckoutAttribute(CheckoutAttribute checkoutAttribute) { - if (checkoutAttribute == null) - throw new ArgumentNullException(nameof(checkoutAttribute)); + ArgumentNullException.ThrowIfNull(checkoutAttribute); await _checkoutAttributeRepository.DeleteAsync(checkoutAttribute); diff --git a/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs b/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs index cc361cd2d..168d1ddbf 100644 --- a/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs +++ b/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs @@ -97,8 +97,7 @@ from h in g.GiftVoucherUsageHistory /// Gift voucher public virtual async Task InsertGiftVoucher(GiftVoucher giftVoucher) { - if (giftVoucher == null) - throw new ArgumentNullException(nameof(giftVoucher)); + ArgumentNullException.ThrowIfNull(giftVoucher); giftVoucher.Code = giftVoucher.Code.ToLowerInvariant(); @@ -114,8 +113,7 @@ public virtual async Task InsertGiftVoucher(GiftVoucher giftVoucher) /// Gift voucher public virtual async Task UpdateGiftVoucher(GiftVoucher giftVoucher) { - if (giftVoucher == null) - throw new ArgumentNullException(nameof(giftVoucher)); + ArgumentNullException.ThrowIfNull(giftVoucher); giftVoucher.Code = giftVoucher.Code.ToLowerInvariant(); @@ -130,8 +128,7 @@ public virtual async Task UpdateGiftVoucher(GiftVoucher giftVoucher) /// Gift voucher public virtual async Task DeleteGiftVoucher(GiftVoucher giftVoucher) { - if (giftVoucher == null) - throw new ArgumentNullException(nameof(giftVoucher)); + ArgumentNullException.ThrowIfNull(giftVoucher); await _giftVoucherRepository.DeleteAsync(giftVoucher); diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs index 018fe9726..c0d68d2a3 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs @@ -145,8 +145,7 @@ public virtual Task GetMerchandiseReturnActionById(stri /// Merchandise return public virtual async Task InsertMerchandiseReturn(MerchandiseReturn merchandiseReturn) { - if (merchandiseReturn == null) - throw new ArgumentNullException(nameof(merchandiseReturn)); + ArgumentNullException.ThrowIfNull(merchandiseReturn); lock (Locker) { @@ -166,8 +165,7 @@ public virtual async Task InsertMerchandiseReturn(MerchandiseReturn merchandiseR /// public virtual async Task UpdateMerchandiseReturn(MerchandiseReturn merchandiseReturn) { - if (merchandiseReturn == null) - throw new ArgumentNullException(nameof(merchandiseReturn)); + ArgumentNullException.ThrowIfNull(merchandiseReturn); await _merchandiseReturnRepository.UpdateAsync(merchandiseReturn); @@ -180,8 +178,7 @@ public virtual async Task UpdateMerchandiseReturn(MerchandiseReturn merchandiseR /// Merchandise return public virtual async Task DeleteMerchandiseReturn(MerchandiseReturn merchandiseReturn) { - if (merchandiseReturn == null) - throw new ArgumentNullException(nameof(merchandiseReturn)); + ArgumentNullException.ThrowIfNull(merchandiseReturn); await _merchandiseReturnRepository.DeleteAsync(merchandiseReturn); @@ -195,8 +192,7 @@ public virtual async Task DeleteMerchandiseReturn(MerchandiseReturn merchandiseR /// Merchandise return action public virtual async Task InsertMerchandiseReturnAction(MerchandiseReturnAction merchandiseReturnAction) { - if (merchandiseReturnAction == null) - throw new ArgumentNullException(nameof(merchandiseReturnAction)); + ArgumentNullException.ThrowIfNull(merchandiseReturnAction); await _merchandiseReturnActionRepository.InsertAsync(merchandiseReturnAction); @@ -212,8 +208,7 @@ public virtual async Task InsertMerchandiseReturnAction(MerchandiseReturnAction /// Merchandise return action public virtual async Task UpdateMerchandiseReturnAction(MerchandiseReturnAction merchandiseReturnAction) { - if (merchandiseReturnAction == null) - throw new ArgumentNullException(nameof(merchandiseReturnAction)); + ArgumentNullException.ThrowIfNull(merchandiseReturnAction); await _merchandiseReturnActionRepository.UpdateAsync(merchandiseReturnAction); @@ -230,8 +225,7 @@ public virtual async Task UpdateMerchandiseReturnAction(MerchandiseReturnAction /// Merchandise return action public virtual async Task DeleteMerchandiseReturnAction(MerchandiseReturnAction merchandiseReturnAction) { - if (merchandiseReturnAction == null) - throw new ArgumentNullException(nameof(merchandiseReturnAction)); + ArgumentNullException.ThrowIfNull(merchandiseReturnAction); await _merchandiseReturnActionRepository.DeleteAsync(merchandiseReturnAction); @@ -244,8 +238,7 @@ public virtual async Task DeleteMerchandiseReturnAction(MerchandiseReturnAction /// Merchandise return reason public virtual async Task DeleteMerchandiseReturnReason(MerchandiseReturnReason merchandiseReturnReason) { - if (merchandiseReturnReason == null) - throw new ArgumentNullException(nameof(merchandiseReturnReason)); + ArgumentNullException.ThrowIfNull(merchandiseReturnReason); await _merchandiseReturnReasonRepository.DeleteAsync(merchandiseReturnReason); @@ -288,8 +281,7 @@ public virtual Task GetMerchandiseReturnReasonById(stri /// Merchandise return reasons public virtual async Task InsertMerchandiseReturnReason(MerchandiseReturnReason merchandiseReturnReason) { - if (merchandiseReturnReason == null) - throw new ArgumentNullException(nameof(merchandiseReturnReason)); + ArgumentNullException.ThrowIfNull(merchandiseReturnReason); await _merchandiseReturnReasonRepository.InsertAsync(merchandiseReturnReason); @@ -306,8 +298,7 @@ public virtual async Task InsertMerchandiseReturnReason(MerchandiseReturnReason /// Merchandise return reasons public virtual async Task UpdateMerchandiseReturnReason(MerchandiseReturnReason merchandiseReturnReason) { - if (merchandiseReturnReason == null) - throw new ArgumentNullException(nameof(merchandiseReturnReason)); + ArgumentNullException.ThrowIfNull(merchandiseReturnReason); await _merchandiseReturnReasonRepository.UpdateAsync(merchandiseReturnReason); @@ -327,8 +318,7 @@ public virtual async Task UpdateMerchandiseReturnReason(MerchandiseReturnReason /// The merchandise return note public virtual async Task DeleteMerchandiseReturnNote(MerchandiseReturnNote merchandiseReturnNote) { - if (merchandiseReturnNote == null) - throw new ArgumentNullException(nameof(merchandiseReturnNote)); + ArgumentNullException.ThrowIfNull(merchandiseReturnNote); await _merchandiseReturnNoteRepository.DeleteAsync(merchandiseReturnNote); @@ -342,8 +332,7 @@ public virtual async Task DeleteMerchandiseReturnNote(MerchandiseReturnNote merc /// The merchandise return note public virtual async Task InsertMerchandiseReturnNote(MerchandiseReturnNote merchandiseReturnNote) { - if (merchandiseReturnNote == null) - throw new ArgumentNullException(nameof(merchandiseReturnNote)); + ArgumentNullException.ThrowIfNull(merchandiseReturnNote); await _merchandiseReturnNoteRepository.InsertAsync(merchandiseReturnNote); diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs index c0a37ff7e..d408baa54 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderCalculationService.cs @@ -633,8 +633,7 @@ public virtual async Task IsFreeShipping(IList cart) /// Tax total public virtual async Task<(double taxtotal, SortedDictionary taxRates)> GetTaxTotal(IList cart, bool usePaymentMethodAdditionalFee = true) { - if (cart == null) - throw new ArgumentNullException(nameof(cart)); + ArgumentNullException.ThrowIfNull(cart); var taxRates = new SortedDictionary(); diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs index fe9b065fa..4d972ea61 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs @@ -197,8 +197,7 @@ public virtual async Task> SearchOrders(string storeId = "", /// Order public virtual async Task InsertOrder(Order order) { - if (order == null) - throw new ArgumentNullException(nameof(order)); + ArgumentNullException.ThrowIfNull(order); var orderExists = _orderRepository.Table.OrderByDescending(x => x.OrderNumber).Select(x => x.OrderNumber).FirstOrDefault(); order.OrderNumber = orderExists != 0 ? orderExists + 1 : 1; @@ -215,8 +214,7 @@ public virtual async Task InsertOrder(Order order) /// The order public virtual async Task UpdateOrder(Order order) { - if (order == null) - throw new ArgumentNullException(nameof(order)); + ArgumentNullException.ThrowIfNull(order); await _orderRepository.UpdateAsync(order); @@ -272,8 +270,7 @@ from orderItem in order.OrderItems /// The order note public virtual async Task DeleteOrderNote(OrderNote orderNote) { - if (orderNote == null) - throw new ArgumentNullException(nameof(orderNote)); + ArgumentNullException.ThrowIfNull(orderNote); await _orderNoteRepository.DeleteAsync(orderNote); @@ -287,8 +284,7 @@ public virtual async Task DeleteOrderNote(OrderNote orderNote) /// The order note public virtual async Task InsertOrderNote(OrderNote orderNote) { - if (orderNote == null) - throw new ArgumentNullException(nameof(orderNote)); + ArgumentNullException.ThrowIfNull(orderNote); await _orderNoteRepository.InsertAsync(orderNote); diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderStatusService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderStatusService.cs index e25de76b7..179bdc1b9 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderStatusService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderStatusService.cs @@ -48,8 +48,7 @@ public virtual async Task GetByStatusId(int statusId) public virtual async Task Insert(OrderStatus orderStatus) { - if (orderStatus == null) - throw new ArgumentNullException(nameof(orderStatus)); + ArgumentNullException.ThrowIfNull(orderStatus); //insert order status await _orderStatusRepository.InsertAsync(orderStatus); @@ -63,8 +62,7 @@ public virtual async Task Insert(OrderStatus orderStatus) public virtual async Task Update(OrderStatus orderStatus) { - if (orderStatus == null) - throw new ArgumentNullException(nameof(orderStatus)); + ArgumentNullException.ThrowIfNull(orderStatus); //update order status await _orderStatusRepository.UpdateAsync(orderStatus); @@ -77,8 +75,7 @@ public virtual async Task Update(OrderStatus orderStatus) } public virtual async Task Delete(OrderStatus orderStatus) { - if (orderStatus == null) - throw new ArgumentNullException(nameof(orderStatus)); + ArgumentNullException.ThrowIfNull(orderStatus); if (orderStatus.IsSystem) throw new Exception("You can't delete system status"); diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs index fb6999927..efa5d2051 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs @@ -87,11 +87,7 @@ public virtual Task GetOrderTagById(string orderTagId) /// Order's tag public virtual Task GetOrderTagByName(string name) { - var query = from pt in _orderTagRepository.Table - where pt.Name == name - select pt; - - return Task.FromResult(query.FirstOrDefault()); + return _orderTagRepository.GetOneAsync(x=>x.Name == name); } /// @@ -100,8 +96,7 @@ public virtual Task GetOrderTagByName(string name) /// Order's tag public virtual async Task InsertOrderTag(OrderTag orderTag) { - if (orderTag == null) - throw new ArgumentNullException(nameof(orderTag)); + ArgumentNullException.ThrowIfNull(orderTag); await _orderTagRepository.InsertAsync(orderTag); @@ -118,8 +113,7 @@ public virtual async Task InsertOrderTag(OrderTag orderTag) /// Order tag public virtual async Task UpdateOrderTag(OrderTag orderTag) { - if (orderTag == null) - throw new ArgumentNullException(nameof(orderTag)); + ArgumentNullException.ThrowIfNull(orderTag); await _orderTagRepository.UpdateAsync(orderTag); @@ -135,8 +129,7 @@ public virtual async Task UpdateOrderTag(OrderTag orderTag) /// Order's tag public virtual async Task DeleteOrderTag(OrderTag orderTag) { - if (orderTag == null) - throw new ArgumentNullException(nameof(orderTag)); + ArgumentNullException.ThrowIfNull(orderTag); //update orders await _orderRepository.Pull(string.Empty, x => x.OrderTags, orderTag.Id); @@ -196,7 +189,6 @@ public virtual async Task DetachOrderTag(string orderTagId, string orderId) /// Get number of orders /// /// Order's tag identifier - /// Store identifier /// Number of orders public virtual async Task GetOrderCount(string orderTagId, string storeId) { diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs index 530bb5aec..9fe05f01e 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs @@ -106,8 +106,7 @@ public virtual async Task FindShoppingCartItem(IList a.ShoppingCartTypeId == shoppingCartType)) { @@ -193,8 +192,7 @@ public virtual async Task FindShoppingCartItem(IList> UpdateShoppingCartItem(Customer custome DateTime? rentalStartDate = null, DateTime? rentalEndDate = null, int quantity = 1, bool resetCheckoutData = true, string reservationId = "", string sciId = "") { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); var warnings = new List(); @@ -373,8 +370,7 @@ public virtual async Task> UpdateShoppingCartItem(Customer custome public virtual async Task DeleteShoppingCartItem(Customer customer, ShoppingCartItem shoppingCartItem, bool resetCheckoutData = true, bool ensureOnlyActiveCheckoutAttributes = false) { - if (shoppingCartItem == null) - throw new ArgumentNullException(nameof(shoppingCartItem)); + ArgumentNullException.ThrowIfNull(shoppingCartItem); //reset checkout data if (resetCheckoutData) @@ -399,10 +395,8 @@ public virtual async Task DeleteShoppingCartItem(Customer customer, ShoppingCart /// A value indicating whether to coupon codes (discount and gift voucher) should be also re-applied public virtual async Task MigrateShoppingCart(Customer fromCustomer, Customer toCustomer, bool includeCouponCodes) { - if (fromCustomer == null) - throw new ArgumentNullException(nameof(fromCustomer)); - if (toCustomer == null) - throw new ArgumentNullException(nameof(toCustomer)); + ArgumentNullException.ThrowIfNull(fromCustomer); + ArgumentNullException.ThrowIfNull(toCustomer); if (fromCustomer.Id == toCustomer.Id) return; //the same customer diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs index b5a9401a2..88abf5753 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs @@ -31,11 +31,8 @@ public ShoppingCartValidator( public virtual async Task> GetStandardWarnings(Customer customer, Product product, ShoppingCartItem shoppingCartItem) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); - - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(customer); + ArgumentNullException.ThrowIfNull(product); var warnings = new List(); @@ -48,8 +45,7 @@ public virtual async Task> GetStandardWarnings(Customer customer, public virtual async Task> GetShoppingCartItemAttributeWarnings(Customer customer, Product product, ShoppingCartItem shoppingCartItem, bool ignoreNonCombinableAttributes = false) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var warnings = new List(); @@ -64,8 +60,7 @@ public virtual async Task> GetShoppingCartItemAttributeWarnings(Cu public virtual async Task> GetShoppingCartItemGiftVoucherWarnings(Customer customer, Product product, ShoppingCartItem shoppingCartItem) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var warnings = new List(); @@ -165,8 +160,7 @@ public async Task> CheckCommonWarnings(Customer customer, IList> GetShoppingCartItemWarnings(Customer customer, ShoppingCartItem shoppingCartItem, Product product, ShoppingCartValidatorOptions options) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var warnings = new List(); @@ -203,11 +197,8 @@ public virtual async Task> GetShoppingCartItemWarnings(Customer cu public virtual async Task> GetRequiredProductWarnings(Customer customer, ShoppingCartItem shoppingCartItem, Product product, string storeId) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); - - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(customer); + ArgumentNullException.ThrowIfNull(product); var warnings = new List(); diff --git a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs index fb4aeda7f..53dfe5abf 100644 --- a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs @@ -111,8 +111,7 @@ public virtual IList LoadAllPaymentMethods(Customer customer = /// A list of country identifiers public virtual IList GetRestrictedCountryIds(IPaymentProvider paymentMethod) { - if (paymentMethod == null) - throw new ArgumentNullException(nameof(paymentMethod)); + ArgumentNullException.ThrowIfNull(paymentMethod); var settingKey = $"PaymentMethodRestictions.{paymentMethod.SystemName}"; var restrictedCountryIds = _settingService.GetSettingByKey(settingKey); @@ -126,8 +125,7 @@ public virtual IList GetRestrictedCountryIds(IPaymentProvider paymentMet /// A list of role identifiers public virtual IList GetRestrictedShippingIds(IPaymentProvider paymentMethod) { - if (paymentMethod == null) - throw new ArgumentNullException(nameof(paymentMethod)); + ArgumentNullException.ThrowIfNull(paymentMethod); var settingKey = $"PaymentMethodRestictionsShipping.{paymentMethod.SystemName}"; var restrictedShippingIds = _settingService.GetSettingByKey(settingKey); @@ -140,8 +138,7 @@ public virtual IList GetRestrictedShippingIds(IPaymentProvider paymentMe /// A list of country identifiers public virtual async Task SaveRestrictedCountryIds(IPaymentProvider paymentMethod, List countryIds) { - if (paymentMethod == null) - throw new ArgumentNullException(nameof(paymentMethod)); + ArgumentNullException.ThrowIfNull(paymentMethod); var settingKey = $"PaymentMethodRestictions.{paymentMethod.SystemName}"; await _settingService.SetSetting(settingKey, new PaymentRestrictedSettings { Ids = countryIds }); @@ -154,8 +151,7 @@ public virtual async Task SaveRestrictedCountryIds(IPaymentProvider paymentMetho /// A list of group identifiers public virtual async Task SaveRestrictedGroupIds(IPaymentProvider paymentMethod, List groupIds) { - if (paymentMethod == null) - throw new ArgumentNullException(nameof(paymentMethod)); + ArgumentNullException.ThrowIfNull(paymentMethod); var settingKey = $"PaymentMethodRestictionsGroup.{paymentMethod.SystemName}"; await _settingService.SetSetting(settingKey, new PaymentRestrictedSettings { Ids = groupIds }); @@ -168,8 +164,7 @@ public virtual async Task SaveRestrictedGroupIds(IPaymentProvider paymentMethod, /// A list of country identifiers public virtual async Task SaveRestrictedShippingIds(IPaymentProvider paymentMethod, List shippingIds) { - if (paymentMethod == null) - throw new ArgumentNullException(nameof(paymentMethod)); + ArgumentNullException.ThrowIfNull(paymentMethod); var settingKey = $"PaymentMethodRestictionsShipping.{paymentMethod.SystemName}"; await _settingService.SetSetting(settingKey, new PaymentRestrictedSettings { Ids = shippingIds }); @@ -182,8 +177,7 @@ public virtual async Task SaveRestrictedShippingIds(IPaymentProvider paymentMeth /// Process payment result public virtual async Task ProcessPayment(PaymentTransaction paymentTransaction) { - if (paymentTransaction == null) - throw new ArgumentNullException(nameof(paymentTransaction)); + ArgumentNullException.ThrowIfNull(paymentTransaction); if (paymentTransaction.TransactionAmount == 0) { @@ -206,8 +200,7 @@ public virtual async Task ProcessPayment(PaymentTransactio /// Payment transaction public virtual async Task PostProcessPayment(PaymentTransaction paymentTransaction) { - if (paymentTransaction == null) - throw new ArgumentNullException(nameof(paymentTransaction)); + ArgumentNullException.ThrowIfNull(paymentTransaction); if (paymentTransaction.TransactionStatus == TransactionStatus.Paid) return; @@ -224,8 +217,7 @@ public virtual async Task PostProcessPayment(PaymentTransaction paymentTransacti /// Payment Transaction public virtual async Task PostRedirectPayment(PaymentTransaction paymentTransaction) { - if (paymentTransaction == null) - throw new ArgumentNullException(nameof(paymentTransaction)); + ArgumentNullException.ThrowIfNull(paymentTransaction); //already paid or order.OrderTotal == 0 if (paymentTransaction.TransactionStatus == TransactionStatus.Paid) @@ -243,8 +235,7 @@ public virtual async Task PostRedirectPayment(PaymentTransaction paymentTransact /// Payment transaction public virtual async Task CancelPayment(PaymentTransaction paymentTransaction) { - if (paymentTransaction == null) - throw new ArgumentNullException(nameof(paymentTransaction)); + ArgumentNullException.ThrowIfNull(paymentTransaction); var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName); if (paymentMethod == null) @@ -261,8 +252,7 @@ public virtual async Task CancelPayment(PaymentTransaction paymentTransaction) /// Result public virtual async Task CanRePostRedirectPayment(PaymentTransaction paymentTransaction) { - if (paymentTransaction == null) - throw new ArgumentNullException(nameof(paymentTransaction)); + ArgumentNullException.ThrowIfNull(paymentTransaction); if (!_paymentSettings.AllowRePostingPayments) return false; @@ -323,8 +313,7 @@ public virtual async Task SupportCapture(string paymentMethodSystemName) /// Capture payment result public virtual async Task Capture(PaymentTransaction paymentTransaction) { - if (paymentTransaction == null) - throw new ArgumentNullException(nameof(paymentTransaction)); + ArgumentNullException.ThrowIfNull(paymentTransaction); var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName); if (paymentMethod == null) @@ -395,8 +384,7 @@ public virtual async Task SupportVoid(string paymentMethodSystemName) /// Result public virtual async Task Void(PaymentTransaction paymentTransaction) { - if (paymentTransaction == null) - throw new ArgumentNullException(nameof(paymentTransaction)); + ArgumentNullException.ThrowIfNull(paymentTransaction); var paymentMethod = LoadPaymentMethodBySystemName(paymentTransaction.PaymentMethodSystemName); if (paymentMethod == null) diff --git a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs index 6c1bfad37..98f9a488d 100644 --- a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs @@ -26,8 +26,7 @@ public PaymentTransactionService( /// payment transaction public virtual async Task InsertPaymentTransaction(PaymentTransaction paymentTransaction) { - if (paymentTransaction == null) - throw new ArgumentNullException(nameof(paymentTransaction)); + ArgumentNullException.ThrowIfNull(paymentTransaction); await _repositoryPaymentTransaction.InsertAsync(paymentTransaction); @@ -41,8 +40,7 @@ public virtual async Task InsertPaymentTransaction(PaymentTransaction paymentTra /// payment transaction public virtual async Task UpdatePaymentTransaction(PaymentTransaction paymentTransaction) { - if (paymentTransaction == null) - throw new ArgumentNullException(nameof(paymentTransaction)); + ArgumentNullException.ThrowIfNull(paymentTransaction); await _repositoryPaymentTransaction.UpdateAsync(paymentTransaction); @@ -57,8 +55,7 @@ public virtual async Task UpdatePaymentTransaction(PaymentTransaction paymentTra /// payment transaction public virtual async Task DeletePaymentTransaction(PaymentTransaction paymentTransaction) { - if (paymentTransaction == null) - throw new ArgumentNullException(nameof(paymentTransaction)); + ArgumentNullException.ThrowIfNull(paymentTransaction); await _repositoryPaymentTransaction.DeleteAsync(paymentTransaction); diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs index a5c5bba53..5935f3164 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs @@ -69,8 +69,7 @@ orderby dd.DisplayOrder /// Delivery date public virtual async Task InsertDeliveryDate(DeliveryDate deliveryDate) { - if (deliveryDate == null) - throw new ArgumentNullException(nameof(deliveryDate)); + ArgumentNullException.ThrowIfNull(deliveryDate); await _deliveryDateRepository.InsertAsync(deliveryDate); @@ -87,8 +86,7 @@ public virtual async Task InsertDeliveryDate(DeliveryDate deliveryDate) /// Delivery date public virtual async Task UpdateDeliveryDate(DeliveryDate deliveryDate) { - if (deliveryDate == null) - throw new ArgumentNullException(nameof(deliveryDate)); + ArgumentNullException.ThrowIfNull(deliveryDate); await _deliveryDateRepository.UpdateAsync(deliveryDate); @@ -105,8 +103,7 @@ public virtual async Task UpdateDeliveryDate(DeliveryDate deliveryDate) /// The delivery date public virtual async Task DeleteDeliveryDate(DeliveryDate deliveryDate) { - if (deliveryDate == null) - throw new ArgumentNullException(nameof(deliveryDate)); + ArgumentNullException.ThrowIfNull(deliveryDate); await _deliveryDateRepository.DeleteAsync(deliveryDate); diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs index d4bfb3f3e..8941b9088 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs @@ -79,8 +79,7 @@ public virtual async Task> LoadActivePickupPoints(string stor /// Pickup Point public virtual async Task InsertPickupPoint(PickupPoint pickupPoint) { - if (pickupPoint == null) - throw new ArgumentNullException(nameof(pickupPoint)); + ArgumentNullException.ThrowIfNull(pickupPoint); await _pickupPointsRepository.InsertAsync(pickupPoint); @@ -97,8 +96,7 @@ public virtual async Task InsertPickupPoint(PickupPoint pickupPoint) /// Pickup Point public virtual async Task UpdatePickupPoint(PickupPoint pickupPoint) { - if (pickupPoint == null) - throw new ArgumentNullException(nameof(pickupPoint)); + ArgumentNullException.ThrowIfNull(pickupPoint); await _pickupPointsRepository.UpdateAsync(pickupPoint); @@ -115,8 +113,7 @@ public virtual async Task UpdatePickupPoint(PickupPoint pickupPoint) /// pickup point public virtual async Task DeletePickupPoint(PickupPoint pickupPoint) { - if (pickupPoint == null) - throw new ArgumentNullException(nameof(pickupPoint)); + ArgumentNullException.ThrowIfNull(pickupPoint); await _pickupPointsRepository.DeleteAsync(pickupPoint); diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs index 6362af620..4c531c3e1 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs @@ -130,8 +130,7 @@ public virtual Task GetShipmentById(string shipmentId) /// Shipment public virtual async Task InsertShipment(Shipment shipment) { - if (shipment == null) - throw new ArgumentNullException(nameof(shipment)); + ArgumentNullException.ThrowIfNull(shipment); var shipmentExists = _shipmentRepository.Table.FirstOrDefault(); shipment.ShipmentNumber = shipmentExists != null ? _shipmentRepository.Table.Max(x => x.ShipmentNumber) + 1 : 1; await _shipmentRepository.InsertAsync(shipment); @@ -146,8 +145,7 @@ public virtual async Task InsertShipment(Shipment shipment) /// Shipment public virtual async Task UpdateShipment(Shipment shipment) { - if (shipment == null) - throw new ArgumentNullException(nameof(shipment)); + ArgumentNullException.ThrowIfNull(shipment); await _shipmentRepository.UpdateAsync(shipment); @@ -161,8 +159,7 @@ public virtual async Task UpdateShipment(Shipment shipment) /// Shipment public virtual async Task DeleteShipment(Shipment shipment) { - if (shipment == null) - throw new ArgumentNullException(nameof(shipment)); + ArgumentNullException.ThrowIfNull(shipment); await _shipmentRepository.DeleteAsync(shipment); @@ -178,8 +175,7 @@ public virtual async Task DeleteShipment(Shipment shipment) /// The order note public virtual async Task DeleteShipmentNote(ShipmentNote shipmentNote) { - if (shipmentNote == null) - throw new ArgumentNullException(nameof(shipmentNote)); + ArgumentNullException.ThrowIfNull(shipmentNote); await _shipmentNoteRepository.DeleteAsync(shipmentNote); @@ -193,8 +189,7 @@ public virtual async Task DeleteShipmentNote(ShipmentNote shipmentNote) /// The shipment note public virtual async Task InsertShipmentNote(ShipmentNote shipmentNote) { - if (shipmentNote == null) - throw new ArgumentNullException(nameof(shipmentNote)); + ArgumentNullException.ThrowIfNull(shipmentNote); await _shipmentNoteRepository.InsertAsync(shipmentNote); diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.cs index 4bbbae133..52f92b965 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.cs @@ -46,8 +46,7 @@ public ShippingMethodService( /// The shipping method public virtual async Task DeleteShippingMethod(ShippingMethod shippingMethod) { - if (shippingMethod == null) - throw new ArgumentNullException(nameof(shippingMethod)); + ArgumentNullException.ThrowIfNull(shippingMethod); await _shippingMethodRepository.DeleteAsync(shippingMethod); @@ -103,8 +102,7 @@ orderby sm.DisplayOrder /// Shipping method public virtual async Task InsertShippingMethod(ShippingMethod shippingMethod) { - if (shippingMethod == null) - throw new ArgumentNullException(nameof(shippingMethod)); + ArgumentNullException.ThrowIfNull(shippingMethod); await _shippingMethodRepository.InsertAsync(shippingMethod); @@ -121,8 +119,7 @@ public virtual async Task InsertShippingMethod(ShippingMethod shippingMethod) /// Shipping method public virtual async Task UpdateShippingMethod(ShippingMethod shippingMethod) { - if (shippingMethod == null) - throw new ArgumentNullException(nameof(shippingMethod)); + ArgumentNullException.ThrowIfNull(shippingMethod); await _shippingMethodRepository.UpdateAsync(shippingMethod); diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs index cb4cb259d..8bfed5f0e 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs @@ -158,8 +158,7 @@ public virtual async Task GetShippingOptions(Customer Address shippingAddress, string allowedShippingRateMethodSystemName = "", Store store = null) { - if (cart == null) - throw new ArgumentNullException(nameof(cart)); + ArgumentNullException.ThrowIfNull(cart); var result = new GetShippingOptionResponse(); diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs index cafb374f8..6d2f7f3d4 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs @@ -69,8 +69,7 @@ orderby wh.DisplayOrder /// Warehouse public virtual async Task InsertWarehouse(Warehouse warehouse) { - if (warehouse == null) - throw new ArgumentNullException(nameof(warehouse)); + ArgumentNullException.ThrowIfNull(warehouse); await _warehouseRepository.InsertAsync(warehouse); @@ -87,8 +86,7 @@ public virtual async Task InsertWarehouse(Warehouse warehouse) /// Warehouse public virtual async Task UpdateWarehouse(Warehouse warehouse) { - if (warehouse == null) - throw new ArgumentNullException(nameof(warehouse)); + ArgumentNullException.ThrowIfNull(warehouse); await _warehouseRepository.UpdateAsync(warehouse); @@ -105,8 +103,7 @@ public virtual async Task UpdateWarehouse(Warehouse warehouse) /// The warehouse public virtual async Task DeleteWarehouse(Warehouse warehouse) { - if (warehouse == null) - throw new ArgumentNullException(nameof(warehouse)); + ArgumentNullException.ThrowIfNull(warehouse); await _warehouseRepository.DeleteAsync(warehouse); diff --git a/src/Business/Grand.Business.Cms/Services/BlogService.cs b/src/Business/Grand.Business.Cms/Services/BlogService.cs index aab60a19a..2cf52a11e 100644 --- a/src/Business/Grand.Business.Cms/Services/BlogService.cs +++ b/src/Business/Grand.Business.Cms/Services/BlogService.cs @@ -77,7 +77,7 @@ public virtual async Task> GetAllBlogPosts(string storeId = if (!string.IsNullOrEmpty(categoryId)) { - var category = _blogCategoryRepository.Table.FirstOrDefault(x => x.Id == categoryId); + var category = await _blogCategoryRepository.GetOneAsync(x => x.Id == categoryId); if (category != null) { var postsIds = category.BlogPosts.Select(x => x.BlogPostId); @@ -182,8 +182,7 @@ public virtual async Task> GetAllBlogPostTags(string storeId, /// Blog post public virtual async Task InsertBlogPost(BlogPost blogPost) { - if (blogPost == null) - throw new ArgumentNullException(nameof(blogPost)); + ArgumentNullException.ThrowIfNull(blogPost); await _blogPostRepository.InsertAsync(blogPost); @@ -197,8 +196,7 @@ public virtual async Task InsertBlogPost(BlogPost blogPost) /// Blog post public virtual async Task UpdateBlogPost(BlogPost blogPost) { - if (blogPost == null) - throw new ArgumentNullException(nameof(blogPost)); + ArgumentNullException.ThrowIfNull(blogPost); await _blogPostRepository.UpdateAsync(blogPost); @@ -211,8 +209,7 @@ public virtual async Task UpdateBlogPost(BlogPost blogPost) /// Blog post public virtual async Task DeleteBlogPost(BlogPost blogPost) { - if (blogPost == null) - throw new ArgumentNullException(nameof(blogPost)); + ArgumentNullException.ThrowIfNull(blogPost); await _blogPostRepository.DeleteAsync(blogPost); @@ -280,8 +277,7 @@ where commentIds.Contains(bc.Id) /// Blog post comment public virtual async Task InsertBlogComment(BlogComment blogComment) { - if (blogComment == null) - throw new ArgumentNullException(nameof(blogComment)); + ArgumentNullException.ThrowIfNull(blogComment); await _blogCommentRepository.InsertAsync(blogComment); @@ -291,8 +287,7 @@ public virtual async Task InsertBlogComment(BlogComment blogComment) public virtual async Task DeleteBlogComment(BlogComment blogComment) { - if (blogComment == null) - throw new ArgumentNullException(nameof(blogComment)); + ArgumentNullException.ThrowIfNull(blogComment); await _blogCommentRepository.DeleteAsync(blogComment); } @@ -329,7 +324,7 @@ public virtual async Task GetBlogCategoryBySeName(string blogCateg if (string.IsNullOrEmpty(blogCategorySeName)) throw new ArgumentNullException(nameof(blogCategorySeName)); - return await Task.FromResult(_blogCategoryRepository.Table.FirstOrDefault(x => x.SeName == blogCategorySeName.ToLowerInvariant())); + return await _blogCategoryRepository.GetOneAsync(x => x.SeName == blogCategorySeName.ToLowerInvariant()); } /// @@ -355,8 +350,7 @@ public virtual async Task> GetAllBlogCategories(string store /// Blog category public virtual async Task InsertBlogCategory(BlogCategory blogCategory) { - if (blogCategory == null) - throw new ArgumentNullException(nameof(blogCategory)); + ArgumentNullException.ThrowIfNull(blogCategory); await _blogCategoryRepository.InsertAsync(blogCategory); @@ -372,8 +366,7 @@ public virtual async Task InsertBlogCategory(BlogCategory blogCate /// Blog category public virtual async Task UpdateBlogCategory(BlogCategory blogCategory) { - if (blogCategory == null) - throw new ArgumentNullException(nameof(blogCategory)); + ArgumentNullException.ThrowIfNull(blogCategory); await _blogCategoryRepository.UpdateAsync(blogCategory); @@ -389,8 +382,7 @@ public virtual async Task UpdateBlogCategory(BlogCategory blogCate /// Blog category public virtual async Task DeleteBlogCategory(BlogCategory blogCategory) { - if (blogCategory == null) - throw new ArgumentNullException(nameof(blogCategory)); + ArgumentNullException.ThrowIfNull(blogCategory); await _blogCategoryRepository.DeleteAsync(blogCategory); @@ -418,8 +410,7 @@ public virtual Task GetBlogProductById(string id) /// Blog product public virtual async Task InsertBlogProduct(BlogProduct blogProduct) { - if (blogProduct == null) - throw new ArgumentNullException(nameof(blogProduct)); + ArgumentNullException.ThrowIfNull(blogProduct); await _blogProductRepository.InsertAsync(blogProduct); @@ -434,8 +425,7 @@ public virtual async Task InsertBlogProduct(BlogProduct blogProduct) /// Blog product public virtual async Task UpdateBlogProduct(BlogProduct blogProduct) { - if (blogProduct == null) - throw new ArgumentNullException(nameof(blogProduct)); + ArgumentNullException.ThrowIfNull(blogProduct); await _blogProductRepository.UpdateAsync(blogProduct); @@ -450,8 +440,7 @@ public virtual async Task UpdateBlogProduct(BlogProduct blogProduct) /// Blog product public virtual async Task DeleteBlogProduct(BlogProduct blogProduct) { - if (blogProduct == null) - throw new ArgumentNullException(nameof(blogProduct)); + ArgumentNullException.ThrowIfNull(blogProduct); await _blogProductRepository.DeleteAsync(blogProduct); diff --git a/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs b/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs index fd18cc55c..4c07eb75b 100644 --- a/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs +++ b/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs @@ -81,7 +81,7 @@ public virtual async Task UpdateKnowledgebaseCategory(KnowledgebaseCategory kc) /// knowledge base category public virtual async Task GetKnowledgebaseCategory(string id) { - return await Task.FromResult(_knowledgebaseCategoryRepository.Table.FirstOrDefault(x => x.Id == id)); + return await _knowledgebaseCategoryRepository.GetOneAsync(x => x.Id == id); } /// @@ -545,8 +545,7 @@ public virtual async Task> GetRelatedKnowledgeb /// Article comment public virtual async Task InsertArticleComment(KnowledgebaseArticleComment articleComment) { - if (articleComment == null) - throw new ArgumentNullException(nameof(articleComment)); + ArgumentNullException.ThrowIfNull(articleComment); await _articleCommentRepository.InsertAsync(articleComment); @@ -613,8 +612,7 @@ orderby c.CreatedOnUtc public virtual async Task DeleteArticleComment(KnowledgebaseArticleComment articleComment) { - if (articleComment == null) - throw new ArgumentNullException(nameof(articleComment)); + ArgumentNullException.ThrowIfNull(articleComment); await _articleCommentRepository.DeleteAsync(articleComment); } diff --git a/src/Business/Grand.Business.Cms/Services/NewsService.cs b/src/Business/Grand.Business.Cms/Services/NewsService.cs index e9785b390..84fa97c6e 100644 --- a/src/Business/Grand.Business.Cms/Services/NewsService.cs +++ b/src/Business/Grand.Business.Cms/Services/NewsService.cs @@ -106,8 +106,7 @@ public virtual async Task> GetAllNews(string storeId = "", /// News item public virtual async Task InsertNews(NewsItem news) { - if (news == null) - throw new ArgumentNullException(nameof(news)); + ArgumentNullException.ThrowIfNull(news); await _newsItemRepository.InsertAsync(news); @@ -121,8 +120,7 @@ public virtual async Task InsertNews(NewsItem news) /// News item public virtual async Task UpdateNews(NewsItem news) { - if (news == null) - throw new ArgumentNullException(nameof(news)); + ArgumentNullException.ThrowIfNull(news); await _newsItemRepository.UpdateAsync(news); @@ -135,8 +133,7 @@ public virtual async Task UpdateNews(NewsItem news) /// News item public virtual async Task DeleteNews(NewsItem newsItem) { - if (newsItem == null) - throw new ArgumentNullException(nameof(newsItem)); + ArgumentNullException.ThrowIfNull(newsItem); await _newsItemRepository.DeleteAsync(newsItem); diff --git a/src/Business/Grand.Business.Cms/Services/PageLayoutService.cs b/src/Business/Grand.Business.Cms/Services/PageLayoutService.cs index 62789401d..9463b15c0 100644 --- a/src/Business/Grand.Business.Cms/Services/PageLayoutService.cs +++ b/src/Business/Grand.Business.Cms/Services/PageLayoutService.cs @@ -76,8 +76,7 @@ public virtual Task GetPageLayoutById(string pageLayoutId) /// Page layout public virtual async Task InsertPageLayout(PageLayout pageLayout) { - if (pageLayout == null) - throw new ArgumentNullException(nameof(pageLayout)); + ArgumentNullException.ThrowIfNull(pageLayout); await _pageLayoutRepository.InsertAsync(pageLayout); @@ -94,8 +93,7 @@ public virtual async Task InsertPageLayout(PageLayout pageLayout) /// Page layout public virtual async Task UpdatePageLayout(PageLayout pageLayout) { - if (pageLayout == null) - throw new ArgumentNullException(nameof(pageLayout)); + ArgumentNullException.ThrowIfNull(pageLayout); await _pageLayoutRepository.UpdateAsync(pageLayout); @@ -111,8 +109,7 @@ public virtual async Task UpdatePageLayout(PageLayout pageLayout) /// Page layout public virtual async Task DeletePageLayout(PageLayout pageLayout) { - if (pageLayout == null) - throw new ArgumentNullException(nameof(pageLayout)); + ArgumentNullException.ThrowIfNull(pageLayout); await _pageLayoutRepository.DeleteAsync(pageLayout); diff --git a/src/Business/Grand.Business.Cms/Services/PageService.cs b/src/Business/Grand.Business.Cms/Services/PageService.cs index aa234189d..7c9f52623 100644 --- a/src/Business/Grand.Business.Cms/Services/PageService.cs +++ b/src/Business/Grand.Business.Cms/Services/PageService.cs @@ -133,8 +133,7 @@ public virtual async Task> GetAllPages(string storeId, bool ignoreAc /// Page public virtual async Task InsertPage(Page page) { - if (page == null) - throw new ArgumentNullException(nameof(page)); + ArgumentNullException.ThrowIfNull(page); await _pageRepository.InsertAsync(page); @@ -150,8 +149,7 @@ public virtual async Task InsertPage(Page page) /// Page public virtual async Task UpdatePage(Page page) { - if (page == null) - throw new ArgumentNullException(nameof(page)); + ArgumentNullException.ThrowIfNull(page); await _pageRepository.UpdateAsync(page); @@ -167,8 +165,7 @@ public virtual async Task UpdatePage(Page page) /// Page public virtual async Task DeletePage(Page page) { - if (page == null) - throw new ArgumentNullException(nameof(page)); + ArgumentNullException.ThrowIfNull(page); await _pageRepository.DeleteAsync(page); diff --git a/src/Business/Grand.Business.Cms/Services/RobotsTxtService.cs b/src/Business/Grand.Business.Cms/Services/RobotsTxtService.cs index 9f41ff9b2..94c1b9128 100644 --- a/src/Business/Grand.Business.Cms/Services/RobotsTxtService.cs +++ b/src/Business/Grand.Business.Cms/Services/RobotsTxtService.cs @@ -51,11 +51,7 @@ public virtual async Task GetRobotsTxt(string storeId = "") return await _cacheBase.GetAsync(key, async () => { - var query = from p in _robotsRepository.Table - where p.StoreId == storeId - select p; - - var robotsTxt = await Task.FromResult(query.FirstOrDefault()); + var robotsTxt = await _robotsRepository.GetOneAsync(x=>x.StoreId == storeId); return robotsTxt; }); } @@ -66,8 +62,7 @@ public virtual async Task GetRobotsTxt(string storeId = "") /// robotsTxt public virtual async Task InsertRobotsTxt(RobotsTxt robotsTxt) { - if (robotsTxt == null) - throw new ArgumentNullException(nameof(robotsTxt)); + ArgumentNullException.ThrowIfNull(robotsTxt); await _robotsRepository.InsertAsync(robotsTxt); @@ -83,8 +78,7 @@ public virtual async Task InsertRobotsTxt(RobotsTxt robotsTxt) /// robotsTxt public virtual async Task UpdateRobotsTxt(RobotsTxt robotsTxt) { - if (robotsTxt == null) - throw new ArgumentNullException(nameof(robotsTxt)); + ArgumentNullException.ThrowIfNull(robotsTxt); await _robotsRepository.UpdateAsync(robotsTxt); @@ -100,8 +94,7 @@ public virtual async Task UpdateRobotsTxt(RobotsTxt robotsTxt) /// robotsTxt public virtual async Task DeleteRobotsTxt(RobotsTxt robotsTxt) { - if (robotsTxt == null) - throw new ArgumentNullException(nameof(robotsTxt)); + ArgumentNullException.ThrowIfNull(robotsTxt); await _robotsRepository.DeleteAsync(robotsTxt); diff --git a/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeService.cs b/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeService.cs index 51a55cd68..aa29c4c83 100644 --- a/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeService.cs +++ b/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeService.cs @@ -79,8 +79,7 @@ public virtual async Task GetAddressAttributeById(string addre /// Address attribute public virtual async Task InsertAddressAttribute(AddressAttribute addressAttribute) { - if (addressAttribute == null) - throw new ArgumentNullException(nameof(addressAttribute)); + ArgumentNullException.ThrowIfNull(addressAttribute); await _addressAttributeRepository.InsertAsync(addressAttribute); @@ -97,8 +96,7 @@ public virtual async Task InsertAddressAttribute(AddressAttribute addressAttribu /// Address attribute public virtual async Task UpdateAddressAttribute(AddressAttribute addressAttribute) { - if (addressAttribute == null) - throw new ArgumentNullException(nameof(addressAttribute)); + ArgumentNullException.ThrowIfNull(addressAttribute); await _addressAttributeRepository.UpdateAsync(addressAttribute); @@ -114,8 +112,7 @@ public virtual async Task UpdateAddressAttribute(AddressAttribute addressAttribu /// Address attribute public virtual async Task DeleteAddressAttribute(AddressAttribute addressAttribute) { - if (addressAttribute == null) - throw new ArgumentNullException(nameof(addressAttribute)); + ArgumentNullException.ThrowIfNull(addressAttribute); await _addressAttributeRepository.DeleteAsync(addressAttribute); @@ -132,8 +129,7 @@ public virtual async Task DeleteAddressAttribute(AddressAttribute addressAttribu /// Address attribute value public virtual async Task InsertAddressAttributeValue(AddressAttributeValue addressAttributeValue) { - if (addressAttributeValue == null) - throw new ArgumentNullException(nameof(addressAttributeValue)); + ArgumentNullException.ThrowIfNull(addressAttributeValue); await _addressAttributeRepository.AddToSet(addressAttributeValue.AddressAttributeId, x => x.AddressAttributeValues, addressAttributeValue); @@ -150,8 +146,7 @@ public virtual async Task InsertAddressAttributeValue(AddressAttributeValue addr /// Address attribute value public virtual async Task UpdateAddressAttributeValue(AddressAttributeValue addressAttributeValue) { - if (addressAttributeValue == null) - throw new ArgumentNullException(nameof(addressAttributeValue)); + ArgumentNullException.ThrowIfNull(addressAttributeValue); await _addressAttributeRepository.UpdateToSet(addressAttributeValue.AddressAttributeId, x => x.AddressAttributeValues, z => z.Id, addressAttributeValue.Id, addressAttributeValue); @@ -169,8 +164,7 @@ await _addressAttributeRepository.UpdateToSet(addressAttributeValue.AddressAttri /// Address attribute value public virtual async Task DeleteAddressAttributeValue(AddressAttributeValue addressAttributeValue) { - if (addressAttributeValue == null) - throw new ArgumentNullException(nameof(addressAttributeValue)); + ArgumentNullException.ThrowIfNull(addressAttributeValue); await _addressAttributeRepository.PullFilter(addressAttributeValue.AddressAttributeId, x => x.AddressAttributeValues, z => z.Id, addressAttributeValue.Id); diff --git a/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs b/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs index 1b0f70431..d28d2b5b3 100644 --- a/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs +++ b/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs @@ -61,8 +61,7 @@ private IList GetSettingsByName(string name) /// A value indicating whether to clear cache after setting update public virtual async Task InsertSetting(Setting setting, bool clearCache = true) { - if (setting == null) - throw new ArgumentNullException(nameof(setting)); + ArgumentNullException.ThrowIfNull(setting); await _settingRepository.InsertAsync(setting); @@ -79,8 +78,7 @@ public virtual async Task InsertSetting(Setting setting, bool clearCache = true) /// A value indicating whether to clear cache after setting update public virtual async Task UpdateSetting(Setting setting, bool clearCache = true) { - if (setting == null) - throw new ArgumentNullException(nameof(setting)); + ArgumentNullException.ThrowIfNull(setting); await _settingRepository.UpdateAsync(setting); @@ -96,8 +94,7 @@ public virtual async Task UpdateSetting(Setting setting, bool clearCache = true) /// Setting public virtual async Task DeleteSetting(Setting setting) { - if (setting == null) - throw new ArgumentNullException(nameof(setting)); + ArgumentNullException.ThrowIfNull(setting); await _settingRepository.DeleteAsync(setting); @@ -152,8 +149,7 @@ public virtual T GetSettingByKey(string key, T defaultValue = default, string /// A value indicating whether to clear cache after setting update public virtual async Task SetSetting(string key, T value, string storeId = "", bool clearCache = true) { - if (key == null) - throw new ArgumentNullException(nameof(key)); + ArgumentNullException.ThrowIfNull(key); key = key.Trim().ToLowerInvariant(); diff --git a/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs b/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs index de677e8c7..6bd301201 100644 --- a/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs +++ b/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs @@ -156,7 +156,7 @@ public virtual async Task GetCountryByTwoLetterIsoCode(string twoLetter var key = string.Format(CacheKey.COUNTRIES_BY_TWOLETTER, twoLetterIsoCode); return await _cacheBase.GetAsync(key, async () => { - return await Task.FromResult(_countryRepository.Table.FirstOrDefault(x => x.TwoLetterIsoCode == twoLetterIsoCode)); + return await _countryRepository.GetOneAsync(x => x.TwoLetterIsoCode == twoLetterIsoCode); }); } @@ -170,7 +170,7 @@ public virtual async Task GetCountryByThreeLetterIsoCode(string threeLe var key = string.Format(CacheKey.COUNTRIES_BY_THREELETTER, threeLetterIsoCode); return await _cacheBase.GetAsync(key, async () => { - return await Task.FromResult(_countryRepository.Table.FirstOrDefault(x => x.ThreeLetterIsoCode == threeLetterIsoCode)); + return await _countryRepository.GetOneAsync(x => x.ThreeLetterIsoCode == threeLetterIsoCode); }); } @@ -180,8 +180,7 @@ public virtual async Task GetCountryByThreeLetterIsoCode(string threeLe /// Country public virtual async Task InsertCountry(Country country) { - if (country == null) - throw new ArgumentNullException(nameof(country)); + ArgumentNullException.ThrowIfNull(country); await _countryRepository.InsertAsync(country); @@ -197,8 +196,7 @@ public virtual async Task InsertCountry(Country country) /// Country public virtual async Task UpdateCountry(Country country) { - if (country == null) - throw new ArgumentNullException(nameof(country)); + ArgumentNullException.ThrowIfNull(country); await _countryRepository.UpdateAsync(country); @@ -213,8 +211,7 @@ public virtual async Task UpdateCountry(Country country) /// Country public virtual async Task DeleteCountry(Country country) { - if (country == null) - throw new ArgumentNullException(nameof(country)); + ArgumentNullException.ThrowIfNull(country); await _countryRepository.DeleteAsync(country); @@ -252,8 +249,7 @@ public virtual async Task> GetStateProvincesByCountryId(str /// Country ident public virtual async Task InsertStateProvince(StateProvince stateProvince, string countryId) { - if (stateProvince == null) - throw new ArgumentNullException(nameof(stateProvince)); + ArgumentNullException.ThrowIfNull(stateProvince); var country = await GetCountryById(countryId); if (country == null) @@ -271,8 +267,7 @@ public virtual async Task InsertStateProvince(StateProvince stateProvince, strin /// Country ident public virtual async Task UpdateStateProvince(StateProvince stateProvince, string countryId) { - if (stateProvince == null) - throw new ArgumentNullException(nameof(stateProvince)); + ArgumentNullException.ThrowIfNull(stateProvince); var country = await GetCountryById(countryId); if (country == null) @@ -299,8 +294,7 @@ public virtual async Task UpdateStateProvince(StateProvince stateProvince, strin /// Country ident public virtual async Task DeleteStateProvince(StateProvince stateProvince, string countryId) { - if (stateProvince == null) - throw new ArgumentNullException(nameof(stateProvince)); + ArgumentNullException.ThrowIfNull(stateProvince); var country = await GetCountryById(countryId); if (country == null) diff --git a/src/Business/Grand.Business.Common/Services/Directory/CurrencyService.cs b/src/Business/Grand.Business.Common/Services/Directory/CurrencyService.cs index 3425d96a4..36cbdf433 100644 --- a/src/Business/Grand.Business.Common/Services/Directory/CurrencyService.cs +++ b/src/Business/Grand.Business.Common/Services/Directory/CurrencyService.cs @@ -137,8 +137,7 @@ public virtual async Task> GetAllCurrencies(bool showHidden = fa /// Currency public virtual async Task InsertCurrency(Currency currency) { - if (currency == null) - throw new ArgumentNullException(nameof(currency)); + ArgumentNullException.ThrowIfNull(currency); await _currencyRepository.InsertAsync(currency); @@ -154,8 +153,7 @@ public virtual async Task InsertCurrency(Currency currency) /// Currency public virtual async Task UpdateCurrency(Currency currency) { - if (currency == null) - throw new ArgumentNullException(nameof(currency)); + ArgumentNullException.ThrowIfNull(currency); await _currencyRepository.UpdateAsync(currency); @@ -171,8 +169,7 @@ public virtual async Task UpdateCurrency(Currency currency) /// Currency public virtual async Task DeleteCurrency(Currency currency) { - if (currency == null) - throw new ArgumentNullException(nameof(currency)); + ArgumentNullException.ThrowIfNull(currency); await _currencyRepository.DeleteAsync(currency); @@ -205,11 +202,8 @@ public virtual double ConvertCurrency(double amount, double exchangeRate) /// Converted value public virtual async Task ConvertCurrency(double amount, Currency sourceCurrencyCode, Currency targetCurrencyCode) { - if (sourceCurrencyCode == null) - throw new ArgumentNullException(nameof(sourceCurrencyCode)); - - if (targetCurrencyCode == null) - throw new ArgumentNullException(nameof(targetCurrencyCode)); + ArgumentNullException.ThrowIfNull(sourceCurrencyCode); + ArgumentNullException.ThrowIfNull(targetCurrencyCode); var result = amount; @@ -231,8 +225,7 @@ public virtual async Task ConvertCurrency(double amount, Currency source /// Converted value public virtual async Task ConvertToPrimaryExchangeRateCurrency(double amount, Currency sourceCurrencyCode) { - if (sourceCurrencyCode == null) - throw new ArgumentNullException(nameof(sourceCurrencyCode)); + ArgumentNullException.ThrowIfNull(sourceCurrencyCode); var primaryExchangeRateCurrency = await GetPrimaryExchangeRateCurrency(); if (primaryExchangeRateCurrency == null) @@ -254,8 +247,7 @@ public virtual async Task ConvertToPrimaryExchangeRateCurrency(double am /// Converted value public virtual async Task ConvertFromPrimaryExchangeRateCurrency(double amount, Currency targetCurrencyCode) { - if (targetCurrencyCode == null) - throw new ArgumentNullException(nameof(targetCurrencyCode)); + ArgumentNullException.ThrowIfNull(targetCurrencyCode); var primaryExchangeRateCurrency = await GetPrimaryExchangeRateCurrency(); if (primaryExchangeRateCurrency == null) @@ -280,8 +272,7 @@ public virtual async Task ConvertFromPrimaryExchangeRateCurrency(double /// Converted value public virtual async Task ConvertToPrimaryStoreCurrency(double amount, Currency sourceCurrencyCode) { - if (sourceCurrencyCode == null) - throw new ArgumentNullException(nameof(sourceCurrencyCode)); + ArgumentNullException.ThrowIfNull(sourceCurrencyCode); var primaryStoreCurrency = await GetPrimaryStoreCurrency(); var result = await ConvertCurrency(amount, sourceCurrencyCode, primaryStoreCurrency); diff --git a/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs b/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs index 08ffe2e33..2691ad43a 100644 --- a/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs +++ b/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs @@ -84,8 +84,7 @@ public virtual async Task> GetAllCustomerGroups(string /// Customer group public virtual async Task InsertCustomerGroup(CustomerGroup customerGroup) { - if (customerGroup == null) - throw new ArgumentNullException(nameof(customerGroup)); + ArgumentNullException.ThrowIfNull(customerGroup); await _customerGroupRepository.InsertAsync(customerGroup); @@ -101,8 +100,7 @@ public virtual async Task InsertCustomerGroup(CustomerGroup customerGroup) /// Customer group public virtual async Task UpdateCustomerGroup(CustomerGroup customerGroup) { - if (customerGroup == null) - throw new ArgumentNullException(nameof(customerGroup)); + ArgumentNullException.ThrowIfNull(customerGroup); await _customerGroupRepository.UpdateAsync(customerGroup); @@ -118,8 +116,7 @@ public virtual async Task UpdateCustomerGroup(CustomerGroup customerGroup) /// Customer group public virtual async Task DeleteCustomerGroup(CustomerGroup customerGroup) { - if (customerGroup == null) - throw new ArgumentNullException(nameof(customerGroup)); + ArgumentNullException.ThrowIfNull(customerGroup); if (customerGroup.IsSystem) throw new GrandException("System group could not be deleted"); @@ -146,8 +143,7 @@ public virtual async Task IsInCustomerGroup(Customer customer, bool onlyActiveCustomerGroups = true, bool? isSystem = null) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); if (string.IsNullOrEmpty(customerGroupSystemName)) throw new ArgumentNullException(nameof(customerGroupSystemName)); diff --git a/src/Business/Grand.Business.Common/Services/Directory/HistoryService.cs b/src/Business/Grand.Business.Common/Services/Directory/HistoryService.cs index 53ef245d0..ac0f8a849 100644 --- a/src/Business/Grand.Business.Common/Services/Directory/HistoryService.cs +++ b/src/Business/Grand.Business.Common/Services/Directory/HistoryService.cs @@ -19,8 +19,7 @@ public HistoryService(IRepository historyRepository) public virtual async Task SaveObject(T entity) where T : BaseEntity { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); + ArgumentNullException.ThrowIfNull(entity); var history = new HistoryObject { Object = entity @@ -30,8 +29,7 @@ public virtual async Task SaveObject(T entity) where T : BaseEntity public virtual async Task> GetHistoryForEntity(BaseEntity entity) where T : BaseEntity { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); + ArgumentNullException.ThrowIfNull(entity); var history = await Task.FromResult(_historyRepository.Table.Where(x => x.Object.Id == entity.Id).Select(x => (T)x.Object).ToList()); return history; @@ -39,8 +37,7 @@ public virtual async Task> GetHistoryForEntity(BaseEntity entity) wh public virtual async Task> GetHistoryObjectForEntity(BaseEntity entity) { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); + ArgumentNullException.ThrowIfNull(entity); var history = await Task.FromResult(_historyRepository.Table.Where(x => x.Object.Id == entity.Id).ToList()); return history; diff --git a/src/Business/Grand.Business.Common/Services/Directory/UserFieldService.cs b/src/Business/Grand.Business.Common/Services/Directory/UserFieldService.cs index 622744df9..a7d9d972f 100644 --- a/src/Business/Grand.Business.Common/Services/Directory/UserFieldService.cs +++ b/src/Business/Grand.Business.Common/Services/Directory/UserFieldService.cs @@ -38,11 +38,8 @@ public UserFieldService( /// Store identifier; pass "" if this attribute will be available for all stores public virtual async Task SaveField(BaseEntity entity, string key, TPropType value, string storeId = "") { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); - - if (key == null) - throw new ArgumentNullException(nameof(key)); + ArgumentNullException.ThrowIfNull(entity); + ArgumentNullException.ThrowIfNull(key); var collectionName = entity.GetType().Name; @@ -98,8 +95,7 @@ public virtual async Task SaveField(BaseEntity entity, string key, TP public virtual async Task GetFieldsForEntity(BaseEntity entity, string key, string storeId = "") { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); + ArgumentNullException.ThrowIfNull(entity); var collectionName = entity.GetType().Name; _ = _userFieldBaseEntityRepository.SetCollection(collectionName); diff --git a/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs b/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs index 54cb4386d..469a9885c 100644 --- a/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs +++ b/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs @@ -111,8 +111,7 @@ where q.UniqueSeoCode.ToLowerInvariant() == languageCode.ToLowerInvariant() /// Language public virtual async Task InsertLanguage(Language language) { - if (language == null) - throw new ArgumentNullException(nameof(language)); + ArgumentNullException.ThrowIfNull(language); await _languageRepository.InsertAsync(language); @@ -129,8 +128,7 @@ public virtual async Task InsertLanguage(Language language) /// Language public virtual async Task UpdateLanguage(Language language) { - if (language == null) - throw new ArgumentNullException(nameof(language)); + ArgumentNullException.ThrowIfNull(language); //update language await _languageRepository.UpdateAsync(language); @@ -147,8 +145,7 @@ public virtual async Task UpdateLanguage(Language language) /// Language public virtual async Task DeleteLanguage(Language language) { - if (language == null) - throw new ArgumentNullException(nameof(language)); + ArgumentNullException.ThrowIfNull(language); await _languageRepository.DeleteAsync(language); diff --git a/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs b/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs index cf9854ce2..5c89e22fa 100644 --- a/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs +++ b/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs @@ -193,8 +193,7 @@ public virtual string GetResource(string name, string languageId, string default /// Result in XML format public virtual async Task ExportResourcesToXml(Language language) { - if (language == null) - throw new ArgumentNullException(nameof(language)); + ArgumentNullException.ThrowIfNull(language); var sb = new StringBuilder(); var xwSettings = new XmlWriterSettings { @@ -231,8 +230,7 @@ public virtual async Task ExportResourcesToXml(Language language) /// XML public virtual async Task ImportResourcesFromXml(Language language, string xml) { - if (language == null) - throw new ArgumentNullException(nameof(language)); + ArgumentNullException.ThrowIfNull(language); if (string.IsNullOrEmpty(xml)) return; @@ -290,8 +288,7 @@ await _translationRepository.InsertAsync(new TranslationResource { /// XML public virtual async Task ImportResourcesFromXmlInstall(Language language, string xml) { - if (language == null) - throw new ArgumentNullException(nameof(language)); + ArgumentNullException.ThrowIfNull(language); if (string.IsNullOrEmpty(xml)) return; diff --git a/src/Business/Grand.Business.Common/Services/Pdf/HtmlToPdfService.cs b/src/Business/Grand.Business.Common/Services/Pdf/HtmlToPdfService.cs index 6fa3a6aa3..7dec69f3c 100644 --- a/src/Business/Grand.Business.Common/Services/Pdf/HtmlToPdfService.cs +++ b/src/Business/Grand.Business.Common/Services/Pdf/HtmlToPdfService.cs @@ -33,11 +33,8 @@ public HtmlToPdfService(IViewRenderService viewRenderService, IRepository orders, string languageId = "", string vendorId = "") { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - - if (orders == null) - throw new ArgumentNullException(nameof(orders)); + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(orders); var html = await _viewRenderService.RenderToStringAsync<(IList, string)>(OrderTemplate, new(orders, vendorId)); @@ -48,8 +45,7 @@ public async Task PrintOrdersToPdf(Stream stream, IList orders, string la public async Task PrintOrderToPdf(Order order, string languageId, string vendorId = "") { - if (order == null) - throw new ArgumentNullException(nameof(order)); + ArgumentNullException.ThrowIfNull(order); var fileName = $"order_{order.OrderGuid}_{CommonHelper.GenerateRandomDigitCode(4)}.pdf"; @@ -73,11 +69,8 @@ public async Task PrintOrderToPdf(Order order, string languageId, string public async Task PrintPackagingSlipsToPdf(Stream stream, IList shipments, string languageId = "") { - if (stream == null) - throw new ArgumentNullException(nameof(stream)); - - if (shipments == null) - throw new ArgumentNullException(nameof(shipments)); + ArgumentNullException.ThrowIfNull(stream); + ArgumentNullException.ThrowIfNull(shipments); var lang = await _languageService.GetLanguageById(languageId); if (lang == null) @@ -91,8 +84,7 @@ public async Task PrintPackagingSlipsToPdf(Stream stream, IList shipme public async Task SaveOrderToBinary(Order order, string languageId, string vendorId = "") { - if (order == null) - throw new ArgumentNullException(nameof(order)); + ArgumentNullException.ThrowIfNull(order); var fileName = $"order_{order.OrderGuid}_{CommonHelper.GenerateRandomDigitCode(4)}"; using MemoryStream ms = new MemoryStream(); diff --git a/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs b/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs index ec9e3e309..00c0e12d3 100644 --- a/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs +++ b/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs @@ -81,8 +81,7 @@ protected virtual async Task Authorize(string permissionSystemName, Custom /// Permission public virtual async Task DeletePermission(Permission permission) { - if (permission == null) - throw new ArgumentNullException(nameof(permission)); + ArgumentNullException.ThrowIfNull(permission); await _permissionRepository.DeleteAsync(permission); @@ -134,8 +133,7 @@ orderby pr.Name /// Permission public virtual async Task InsertPermission(Permission permission) { - if (permission == null) - throw new ArgumentNullException(nameof(permission)); + ArgumentNullException.ThrowIfNull(permission); await _permissionRepository.InsertAsync(permission); @@ -148,8 +146,7 @@ public virtual async Task InsertPermission(Permission permission) /// Permission public virtual async Task UpdatePermission(Permission permission) { - if (permission == null) - throw new ArgumentNullException(nameof(permission)); + ArgumentNullException.ThrowIfNull(permission); await _permissionRepository.UpdateAsync(permission); @@ -232,8 +229,7 @@ public virtual async Task> GetPermissionActions(string s /// Permission action public virtual async Task InsertPermissionAction(PermissionAction permissionAction) { - if (permissionAction == null) - throw new ArgumentNullException(nameof(permissionAction)); + ArgumentNullException.ThrowIfNull(permissionAction); //insert await _permissionActionRepository.InsertAsync(permissionAction); @@ -247,8 +243,7 @@ public virtual async Task InsertPermissionAction(PermissionAction permissionActi /// Permission action public virtual async Task DeletePermissionAction(PermissionAction permissionAction) { - if (permissionAction == null) - throw new ArgumentNullException(nameof(permissionAction)); + ArgumentNullException.ThrowIfNull(permissionAction); //delete await _permissionActionRepository.DeleteAsync(permissionAction); diff --git a/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs b/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs index 962fa9869..90d342d81 100644 --- a/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs +++ b/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs @@ -51,8 +51,7 @@ public virtual Task GetEntityUrlById(string urlEntityId) /// URL Entity public virtual async Task InsertEntityUrl(EntityUrl urlEntity) { - if (urlEntity == null) - throw new ArgumentNullException(nameof(urlEntity)); + ArgumentNullException.ThrowIfNull(urlEntity); await _urlEntityRepository.InsertAsync(urlEntity); @@ -66,8 +65,7 @@ public virtual async Task InsertEntityUrl(EntityUrl urlEntity) /// URL Entity public virtual async Task UpdateEntityUrl(EntityUrl urlEntity) { - if (urlEntity == null) - throw new ArgumentNullException(nameof(urlEntity)); + ArgumentNullException.ThrowIfNull(urlEntity); await _urlEntityRepository.UpdateAsync(urlEntity); @@ -81,8 +79,7 @@ public virtual async Task UpdateEntityUrl(EntityUrl urlEntity) /// URL Entity public virtual async Task DeleteEntityUrl(EntityUrl urlEntity) { - if (urlEntity == null) - throw new ArgumentNullException(nameof(urlEntity)); + ArgumentNullException.ThrowIfNull(urlEntity); await _urlEntityRepository.DeleteAsync(urlEntity); @@ -189,8 +186,7 @@ public virtual async Task GetActiveSlug(string entityId, string entityNa public virtual async Task SaveSlug(T entity, string slug, string languageId) where T : BaseEntity, ISlugEntity { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); + ArgumentNullException.ThrowIfNull(entity); var entityId = entity.Id; var entityName = typeof(T).Name; diff --git a/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs b/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs index 4147a37ab..c65533b68 100644 --- a/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs +++ b/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs @@ -85,8 +85,7 @@ public virtual Task GetStoreById(string storeId) /// Store public virtual async Task InsertStore(Store store) { - if (store == null) - throw new ArgumentNullException(nameof(store)); + ArgumentNullException.ThrowIfNull(store); await _storeRepository.InsertAsync(store); @@ -103,8 +102,7 @@ public virtual async Task InsertStore(Store store) /// Store public virtual async Task UpdateStore(Store store) { - if (store == null) - throw new ArgumentNullException(nameof(store)); + ArgumentNullException.ThrowIfNull(store); await _storeRepository.UpdateAsync(store); @@ -121,8 +119,7 @@ public virtual async Task UpdateStore(Store store) /// Store public virtual async Task DeleteStore(Store store) { - if (store == null) - throw new ArgumentNullException(nameof(store)); + ArgumentNullException.ThrowIfNull(store); var allStores = await GetAllStores(); if (allStores.Count == 1) diff --git a/src/Business/Grand.Business.Core/Extensions/AffiliateExtensions.cs b/src/Business/Grand.Business.Core/Extensions/AffiliateExtensions.cs index 30f9b85ed..552edb61e 100644 --- a/src/Business/Grand.Business.Core/Extensions/AffiliateExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/AffiliateExtensions.cs @@ -15,8 +15,7 @@ public static class AffiliateExtensions /// Affiliate full name public static string GetFullName(this Affiliate affiliate) { - if (affiliate == null) - throw new ArgumentNullException(nameof(affiliate)); + ArgumentNullException.ThrowIfNull(affiliate); var firstName = affiliate.Address.FirstName; var lastName = affiliate.Address.LastName; @@ -44,8 +43,7 @@ public static string GetFullName(this Affiliate affiliate) /// Generated affiliate URL public static string GenerateUrl(this Affiliate affiliate, string host) { - if (affiliate == null) - throw new ArgumentNullException(nameof(affiliate)); + ArgumentNullException.ThrowIfNull(affiliate); if (string.IsNullOrEmpty(host)) throw new ArgumentNullException(nameof(host)); @@ -68,8 +66,7 @@ public static string GenerateUrl(this Affiliate affiliate, string host) /// Valid friendly name public static async Task ValidateFriendlyUrlName(this Affiliate affiliate, IAffiliateService affiliateService, SeoSettings seoSettings, string friendlyUrlName, string name) { - if (affiliate == null) - throw new ArgumentNullException(nameof(affiliate)); + ArgumentNullException.ThrowIfNull(affiliate); if (string.IsNullOrEmpty(friendlyUrlName)) friendlyUrlName = name; diff --git a/src/Business/Grand.Business.Core/Extensions/ExternalAuthenticationProviderExtensions.cs b/src/Business/Grand.Business.Core/Extensions/ExternalAuthenticationProviderExtensions.cs index af0626e57..f4d9af6a4 100644 --- a/src/Business/Grand.Business.Core/Extensions/ExternalAuthenticationProviderExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/ExternalAuthenticationProviderExtensions.cs @@ -16,11 +16,8 @@ public static class ExternalAuthenticationProviderExtensions /// True if method is active; otherwise false public static bool IsMethodActive(this IExternalAuthenticationProvider method, ExternalAuthenticationSettings settings) { - if (method == null) - throw new ArgumentNullException(nameof(method)); - - if (settings == null) - throw new ArgumentNullException(nameof(settings)); + ArgumentNullException.ThrowIfNull(method); + ArgumentNullException.ThrowIfNull(settings); return settings.ActiveAuthenticationMethodSystemNames != null && settings.ActiveAuthenticationMethodSystemNames.Any(activeMethodSystemName => method.SystemName.Equals(activeMethodSystemName, StringComparison.OrdinalIgnoreCase)); } diff --git a/src/Business/Grand.Business.Core/Extensions/HistoryExtensions.cs b/src/Business/Grand.Business.Core/Extensions/HistoryExtensions.cs index 66d8a3095..1e22cce51 100644 --- a/src/Business/Grand.Business.Core/Extensions/HistoryExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/HistoryExtensions.cs @@ -13,8 +13,7 @@ public static class HistoryExtensions /// public static async Task SaveHistory(this BaseEntity entity, IHistoryService historyService) where T : BaseEntity, IHistory { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); + ArgumentNullException.ThrowIfNull(entity); await historyService.SaveObject(entity); } diff --git a/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs b/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs index db19c3d75..507579b84 100644 --- a/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs @@ -19,11 +19,8 @@ public static class PaymentExtensions public static bool IsPaymentMethodActive(this IPaymentProvider paymentMethod, PaymentSettings paymentSettings) { - if (paymentMethod == null) - throw new ArgumentNullException(nameof(paymentMethod)); - - if (paymentSettings == null) - throw new ArgumentNullException(nameof(paymentSettings)); + ArgumentNullException.ThrowIfNull(paymentMethod); + ArgumentNullException.ThrowIfNull(paymentSettings); return paymentSettings.ActivePaymentProviderSystemNames != null && paymentSettings.ActivePaymentProviderSystemNames.Any(activeMethodSystemName => paymentMethod.SystemName.Equals(activeMethodSystemName, StringComparison.OrdinalIgnoreCase)); } @@ -41,8 +38,7 @@ public static async Task CalculateAdditionalFee(this IPaymentProvider pa IOrderCalculationService orderTotalCalculationService, IList cart, double fee, bool usePercentage) { - if (paymentMethod == null) - throw new ArgumentNullException(nameof(paymentMethod)); + ArgumentNullException.ThrowIfNull(paymentMethod); if (fee <= 0) return fee; diff --git a/src/Business/Grand.Business.Core/Extensions/SeoExtensions.cs b/src/Business/Grand.Business.Core/Extensions/SeoExtensions.cs index e54ee971e..8cd083ed4 100644 --- a/src/Business/Grand.Business.Core/Extensions/SeoExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/SeoExtensions.cs @@ -27,8 +27,7 @@ public static class SeoExtensions /// Product tag SE (search engine) name public static string GetSeName(this ProductTag productTag, string languageId) { - if (productTag == null) - throw new ArgumentNullException(nameof(productTag)); + ArgumentNullException.ThrowIfNull(productTag); var seName = GenerateSlug(productTag.GetTranslation(x => x.Name, languageId), false, false, false); return seName; } @@ -48,8 +47,7 @@ public static string GetSeName(this ProductTag productTag, string languageId) public static string GetSeName(this T entity, string languageId, bool returnDefaultValue = true) where T : BaseEntity, ISlugEntity, ITranslationEntity { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); + ArgumentNullException.ThrowIfNull(entity); var seName = string.Empty; if (!string.IsNullOrEmpty(languageId)) @@ -84,8 +82,7 @@ public static async Task ValidateSeName(this T entity, string seName, SeoSettings seoSettings, ISlugService slugService, ILanguageService languageService) where T : BaseEntity, ISlugEntity { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); + ArgumentNullException.ThrowIfNull(entity); //use name if se-name is not specified if (string.IsNullOrWhiteSpace(seName) && !string.IsNullOrWhiteSpace(name)) diff --git a/src/Business/Grand.Business.Core/Extensions/ShippingExtensions.cs b/src/Business/Grand.Business.Core/Extensions/ShippingExtensions.cs index eec154019..deeedb0b3 100644 --- a/src/Business/Grand.Business.Core/Extensions/ShippingExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/ShippingExtensions.cs @@ -8,11 +8,8 @@ public static class ShippingExtensions public static bool IsShippingRateMethodActive(this IShippingRateCalculationProvider srcm, ShippingProviderSettings shippingProviderSettings) { - if (srcm == null) - throw new ArgumentNullException(nameof(srcm)); - - if (shippingProviderSettings == null) - throw new ArgumentNullException(nameof(shippingProviderSettings)); + ArgumentNullException.ThrowIfNull(srcm); + ArgumentNullException.ThrowIfNull(shippingProviderSettings); return shippingProviderSettings.ActiveSystemNames != null && shippingProviderSettings.ActiveSystemNames.Any(activeMethodSystemName => srcm.SystemName.Equals(activeMethodSystemName, StringComparison.OrdinalIgnoreCase)); } @@ -20,8 +17,7 @@ public static bool IsShippingRateMethodActive(this IShippingRateCalculationProvi public static bool CountryRestrictionExists(this ShippingMethod shippingMethod, string countryId) { - if (shippingMethod == null) - throw new ArgumentNullException(nameof(shippingMethod)); + ArgumentNullException.ThrowIfNull(shippingMethod); var result = shippingMethod.RestrictedCountries.ToList().Find(c => c.Id == countryId) != null; return result; @@ -29,8 +25,7 @@ public static bool CountryRestrictionExists(this ShippingMethod shippingMethod, public static bool CustomerGroupRestrictionExists(this ShippingMethod shippingMethod, string roleId) { - if (shippingMethod == null) - throw new ArgumentNullException(nameof(shippingMethod)); + ArgumentNullException.ThrowIfNull(shippingMethod); var result = shippingMethod.RestrictedGroups.ToList().Find(c => c == roleId) != null; return result; @@ -39,8 +34,7 @@ public static bool CustomerGroupRestrictionExists(this ShippingMethod shippingMe public static bool CustomerGroupRestrictionExists(this ShippingMethod shippingMethod, List roleIds) { - if (shippingMethod == null) - throw new ArgumentNullException(nameof(shippingMethod)); + ArgumentNullException.ThrowIfNull(shippingMethod); var result = shippingMethod.RestrictedGroups.ToList().Find(roleIds.Contains) != null; return result; diff --git a/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs b/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs index 76055b730..3c2ada54d 100644 --- a/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs @@ -27,8 +27,7 @@ public static string GetTranslation(this T entity, bool returnDefaultValue = true) where T : ParentEntity, ITranslationEntity { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); + ArgumentNullException.ThrowIfNull(entity); if (keySelector.Body is not MemberExpression member) throw new ArgumentException($"Expression '{keySelector}' refers to a method, not a property."); @@ -77,8 +76,7 @@ public static string GetTranslationEnum(this T enumValue, IWorkContext workContext) where T : struct { - if (workContext == null) - throw new ArgumentNullException(nameof(workContext)); + ArgumentNullException.ThrowIfNull(workContext); return GetTranslationEnum(enumValue, translationService, workContext.WorkingLanguage.Id); } @@ -94,8 +92,7 @@ public static string GetTranslationEnum(this T enumValue, ITranslationService translationService, string languageId) where T : struct { - if (translationService == null) - throw new ArgumentNullException(nameof(translationService)); + ArgumentNullException.ThrowIfNull(translationService); if (!typeof(T).GetTypeInfo().IsEnum) throw new ArgumentException("T must be enum type"); @@ -122,8 +119,7 @@ public static string GetTranslationEnum(this T enumValue, public static string GetTranslationPermissionName(this Permission permissionRecord, ITranslationService translationService, IWorkContext workContext) { - if (workContext == null) - throw new ArgumentNullException(nameof(workContext)); + ArgumentNullException.ThrowIfNull(workContext); return GetTranslationPermissionName(permissionRecord, translationService, workContext.WorkingLanguage.Id); } @@ -138,11 +134,8 @@ public static string GetTranslationPermissionName(this Permission permissionReco public static string GetTranslationPermissionName(this Permission permissionRecord, ITranslationService translationService, string languageId) { - if (permissionRecord == null) - throw new ArgumentNullException(nameof(permissionRecord)); - - if (translationService == null) - throw new ArgumentNullException(nameof(translationService)); + ArgumentNullException.ThrowIfNull(permissionRecord); + ArgumentNullException.ThrowIfNull(translationService); //Translation value var name = $"Permission.{permissionRecord.SystemName}"; @@ -164,12 +157,9 @@ public static string GetTranslationPermissionName(this Permission permissionReco public static async Task SaveTranslationPermissionName(this Permission permissionRecord, ITranslationService translationService, ILanguageService languageService) { - if (permissionRecord == null) - throw new ArgumentNullException(nameof(permissionRecord)); - if (translationService == null) - throw new ArgumentNullException(nameof(translationService)); - if (languageService == null) - throw new ArgumentNullException(nameof(languageService)); + ArgumentNullException.ThrowIfNull(permissionRecord); + ArgumentNullException.ThrowIfNull(translationService); + ArgumentNullException.ThrowIfNull(languageService); var name = $"Permission.{permissionRecord.SystemName}"; var value = permissionRecord.Name; @@ -203,12 +193,9 @@ public static async Task SaveTranslationPermissionName(this Permission permissio public static async Task DeleteTranslationPermissionName(this Permission permissionRecord, ITranslationService translationService, ILanguageService languageService) { - if (permissionRecord == null) - throw new ArgumentNullException(nameof(permissionRecord)); - if (translationService == null) - throw new ArgumentNullException(nameof(translationService)); - if (languageService == null) - throw new ArgumentNullException(nameof(languageService)); + ArgumentNullException.ThrowIfNull(permissionRecord); + ArgumentNullException.ThrowIfNull(translationService); + ArgumentNullException.ThrowIfNull(languageService); var name = $"Permission.{permissionRecord.SystemName}"; foreach (var lang in await languageService.GetAllLanguages(true)) @@ -230,12 +217,9 @@ public static async Task DeletePluginTranslationResource(this BasePlugin plugin, ITranslationService translationService, ILanguageService languageService, string name) { - if (plugin == null) - throw new ArgumentNullException(nameof(plugin)); - if (translationService == null) - throw new ArgumentNullException(nameof(translationService)); - if (languageService == null) - throw new ArgumentNullException(nameof(languageService)); + ArgumentNullException.ThrowIfNull(plugin); + ArgumentNullException.ThrowIfNull(translationService); + ArgumentNullException.ThrowIfNull(languageService); if (!string.IsNullOrEmpty(name)) name = name.ToLowerInvariant(); foreach (var lang in await languageService.GetAllLanguages(true)) @@ -261,12 +245,9 @@ public static async Task AddOrUpdatePluginTranslateResource(this BasePlugin plug string name, string value, TranslationResourceArea area = TranslationResourceArea.Common, string languageCulture = null) { //actually plugin instance is not required - if (plugin == null) - throw new ArgumentNullException(nameof(plugin)); - if (translationService == null) - throw new ArgumentNullException(nameof(translationService)); - if (languageService == null) - throw new ArgumentNullException(nameof(languageService)); + ArgumentNullException.ThrowIfNull(plugin); + ArgumentNullException.ThrowIfNull(translationService); + ArgumentNullException.ThrowIfNull(languageService); if (!string.IsNullOrEmpty(name)) name = name.ToLowerInvariant(); foreach (var lang in await languageService.GetAllLanguages(true)) diff --git a/src/Business/Grand.Business.Core/Extensions/UserFieldExtensions.cs b/src/Business/Grand.Business.Core/Extensions/UserFieldExtensions.cs index 0e130f3e0..5c9df1bcb 100644 --- a/src/Business/Grand.Business.Core/Extensions/UserFieldExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/UserFieldExtensions.cs @@ -16,8 +16,7 @@ public static class UserFieldExtensions /// Attribute public static async Task GetUserField(this BaseEntity entity, IUserFieldService userFieldService, string key, string storeId = "") { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); + ArgumentNullException.ThrowIfNull(entity); return await userFieldService.GetFieldsForEntity(entity, key, storeId); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs index 9bddf3bff..4ee367450 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs @@ -2,7 +2,6 @@ using Grand.Domain.Common; using Grand.Domain.Customers; using Grand.Domain.Orders; -using Grand.Domain.Stores; using System.Linq.Expressions; namespace Grand.Business.Core.Interfaces.Customers diff --git a/src/Business/Grand.Business.Customers/Services/AffiliateService.cs b/src/Business/Grand.Business.Customers/Services/AffiliateService.cs index 0531b9cf4..f38bf0061 100644 --- a/src/Business/Grand.Business.Customers/Services/AffiliateService.cs +++ b/src/Business/Grand.Business.Customers/Services/AffiliateService.cs @@ -114,8 +114,7 @@ public virtual async Task> GetAllAffiliates(string friendl /// Affiliate public virtual async Task InsertAffiliate(Affiliate affiliate) { - if (affiliate == null) - throw new ArgumentNullException(nameof(affiliate)); + ArgumentNullException.ThrowIfNull(affiliate); await _affiliateRepository.InsertAsync(affiliate); @@ -129,8 +128,7 @@ public virtual async Task InsertAffiliate(Affiliate affiliate) /// Affiliate public virtual async Task UpdateAffiliate(Affiliate affiliate) { - if (affiliate == null) - throw new ArgumentNullException(nameof(affiliate)); + ArgumentNullException.ThrowIfNull(affiliate); await _affiliateRepository.UpdateAsync(affiliate); @@ -144,8 +142,7 @@ public virtual async Task UpdateAffiliate(Affiliate affiliate) /// Affiliate public virtual async Task DeleteAffiliate(Affiliate affiliate) { - if (affiliate == null) - throw new ArgumentNullException(nameof(affiliate)); + ArgumentNullException.ThrowIfNull(affiliate); await _affiliateRepository.DeleteAsync(affiliate); diff --git a/src/Business/Grand.Business.Customers/Services/CustomerAttributeService.cs b/src/Business/Grand.Business.Customers/Services/CustomerAttributeService.cs index f16c2c212..da17517de 100644 --- a/src/Business/Grand.Business.Customers/Services/CustomerAttributeService.cs +++ b/src/Business/Grand.Business.Customers/Services/CustomerAttributeService.cs @@ -75,8 +75,7 @@ public virtual Task GetCustomerAttributeById(string customerA /// Customer attribute public virtual async Task InsertCustomerAttribute(CustomerAttribute customerAttribute) { - if (customerAttribute == null) - throw new ArgumentNullException(nameof(customerAttribute)); + ArgumentNullException.ThrowIfNull(customerAttribute); await _customerAttributeRepository.InsertAsync(customerAttribute); @@ -93,8 +92,7 @@ public virtual async Task InsertCustomerAttribute(CustomerAttribute customerAttr /// Customer attribute public virtual async Task UpdateCustomerAttribute(CustomerAttribute customerAttribute) { - if (customerAttribute == null) - throw new ArgumentNullException(nameof(customerAttribute)); + ArgumentNullException.ThrowIfNull(customerAttribute); await _customerAttributeRepository.UpdateAsync(customerAttribute); @@ -111,8 +109,7 @@ public virtual async Task UpdateCustomerAttribute(CustomerAttribute customerAttr /// Customer attribute public virtual async Task DeleteCustomerAttribute(CustomerAttribute customerAttribute) { - if (customerAttribute == null) - throw new ArgumentNullException(nameof(customerAttribute)); + ArgumentNullException.ThrowIfNull(customerAttribute); await _customerAttributeRepository.DeleteAsync(customerAttribute); @@ -130,8 +127,7 @@ public virtual async Task DeleteCustomerAttribute(CustomerAttribute customerAttr /// Customer attribute value public virtual async Task InsertCustomerAttributeValue(CustomerAttributeValue customerAttributeValue) { - if (customerAttributeValue == null) - throw new ArgumentNullException(nameof(customerAttributeValue)); + ArgumentNullException.ThrowIfNull(customerAttributeValue); var ca = await _customerAttributeRepository.GetByIdAsync(customerAttributeValue.CustomerAttributeId); ca.CustomerAttributeValues.Add(customerAttributeValue); @@ -151,8 +147,7 @@ public virtual async Task InsertCustomerAttributeValue(CustomerAttributeValue cu /// Customer attribute value public virtual async Task UpdateCustomerAttributeValue(CustomerAttributeValue customerAttributeValue) { - if (customerAttributeValue == null) - throw new ArgumentNullException(nameof(customerAttributeValue)); + ArgumentNullException.ThrowIfNull(customerAttributeValue); var ca = await _customerAttributeRepository.GetByIdAsync(customerAttributeValue.CustomerAttributeId); ca.CustomerAttributeValues.Remove(ca.CustomerAttributeValues.FirstOrDefault(c => c.Id == customerAttributeValue.Id)); @@ -173,8 +168,7 @@ public virtual async Task UpdateCustomerAttributeValue(CustomerAttributeValue cu /// Customer attribute value public virtual async Task DeleteCustomerAttributeValue(CustomerAttributeValue customerAttributeValue) { - if (customerAttributeValue == null) - throw new ArgumentNullException(nameof(customerAttributeValue)); + ArgumentNullException.ThrowIfNull(customerAttributeValue); var ca = await _customerAttributeRepository.GetByIdAsync(customerAttributeValue.CustomerAttributeId); ca.CustomerAttributeValues.Remove(ca.CustomerAttributeValues.FirstOrDefault(c => c.Id == customerAttributeValue.Id)); diff --git a/src/Business/Grand.Business.Customers/Services/CustomerHistoryPasswordService.cs b/src/Business/Grand.Business.Customers/Services/CustomerHistoryPasswordService.cs index a01b0bad2..2678eddd9 100644 --- a/src/Business/Grand.Business.Customers/Services/CustomerHistoryPasswordService.cs +++ b/src/Business/Grand.Business.Customers/Services/CustomerHistoryPasswordService.cs @@ -24,8 +24,7 @@ public CustomerHistoryPasswordService(IRepository custo /// Customer public virtual async Task InsertCustomerPassword(Customer customer) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); var chp = new CustomerHistoryPassword { diff --git a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs index 38e43007e..d2c9ed5fe 100644 --- a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs +++ b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs @@ -107,8 +107,7 @@ public virtual async Task LoginCustomer(string usernameOrE /// Result public virtual async Task RegisterCustomer(RegistrationRequest request) { - if (request == null) - throw new ArgumentNullException(nameof(request)); + ArgumentNullException.ThrowIfNull(request); if (request.Customer == null) throw new ArgumentException("Can't load current customer"); @@ -165,8 +164,7 @@ public virtual async Task RegisterCustomer(RegistrationRequest request) /// Request public virtual async Task ChangePassword(ChangePasswordRequest request) { - if (request == null) - throw new ArgumentNullException(nameof(request)); + ArgumentNullException.ThrowIfNull(request); var customer = await _customerService.GetCustomerByEmail(request.Email); if (customer == null) diff --git a/src/Business/Grand.Business.Customers/Services/CustomerNoteService.cs b/src/Business/Grand.Business.Customers/Services/CustomerNoteService.cs index 7d16b07f7..547b8631c 100644 --- a/src/Business/Grand.Business.Customers/Services/CustomerNoteService.cs +++ b/src/Business/Grand.Business.Customers/Services/CustomerNoteService.cs @@ -36,8 +36,7 @@ public virtual Task GetCustomerNote(string id) /// The customer note public virtual async Task InsertCustomerNote(CustomerNote customerNote) { - if (customerNote == null) - throw new ArgumentNullException(nameof(customerNote)); + ArgumentNullException.ThrowIfNull(customerNote); await _customerNoteRepository.InsertAsync(customerNote); @@ -51,8 +50,7 @@ public virtual async Task InsertCustomerNote(CustomerNote customerNote) /// The customer note public virtual async Task DeleteCustomerNote(CustomerNote customerNote) { - if (customerNote == null) - throw new ArgumentNullException(nameof(customerNote)); + ArgumentNullException.ThrowIfNull(customerNote); await _customerNoteRepository.DeleteAsync(customerNote); diff --git a/src/Business/Grand.Business.Customers/Services/CustomerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerService.cs index d3e5e55e5..f120d9c2b 100644 --- a/src/Business/Grand.Business.Customers/Services/CustomerService.cs +++ b/src/Business/Grand.Business.Customers/Services/CustomerService.cs @@ -7,7 +7,6 @@ using Grand.Data; using Grand.Domain.Orders; using Grand.Domain.Shipping; -using Grand.Domain.Stores; using Grand.Infrastructure.Extensions; using Grand.SharedKernel; using MediatR; @@ -198,7 +197,7 @@ where customerIds.Contains(c.Id) /// A customer public virtual async Task GetCustomerByGuid(Guid customerGuid) { - return await Task.FromResult(_customerRepository.Table.FirstOrDefault(x => x.CustomerGuid == customerGuid)); + return await _customerRepository.GetOneAsync(x => x.CustomerGuid == customerGuid); } /// @@ -208,10 +207,7 @@ public virtual async Task GetCustomerByGuid(Guid customerGuid) /// Customer public virtual async Task GetCustomerByEmail(string email) { - if (string.IsNullOrWhiteSpace(email)) - return null; - - return await Task.FromResult(_customerRepository.Table.FirstOrDefault(x => x.Email == email.ToLowerInvariant())); + return string.IsNullOrWhiteSpace(email) ? null : await _customerRepository.GetOneAsync(x => x.Email == email.ToLowerInvariant()); } /// @@ -224,7 +220,7 @@ public virtual async Task GetCustomerBySystemName(string systemName) if (string.IsNullOrWhiteSpace(systemName)) return null; - return await Task.FromResult(_customerRepository.Table.FirstOrDefault(x => x.SystemName == systemName)); + return await _customerRepository.GetOneAsync(x => x.SystemName == systemName); } /// @@ -237,7 +233,7 @@ public virtual async Task GetCustomerByUsername(string username) if (string.IsNullOrWhiteSpace(username)) return null; - return await Task.FromResult(_customerRepository.Table.FirstOrDefault(x => x.Username == username.ToLowerInvariant())); + return await _customerRepository.GetOneAsync(x => x.Username == username.ToLowerInvariant()); } /// @@ -268,8 +264,7 @@ public virtual async Task InsertGuestCustomer(Customer customer) /// Customer public virtual async Task InsertCustomer(Customer customer) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); if (!string.IsNullOrEmpty(customer.Email)) customer.Email = customer.Email.ToLowerInvariant(); @@ -292,8 +287,7 @@ public virtual async Task InsertCustomer(Customer customer) public virtual async Task UpdateCustomerField(Customer customer, Expression> expression, T value) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); await UpdateCustomerField(customer.Id, expression, value); @@ -320,8 +314,7 @@ public virtual async Task UpdateCustomerField(string customerId, /// Customer public virtual async Task UpdateCustomer(Customer customer) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); if (customer.IsSystemAccount) throw new GrandException($"System customer account ({(string.IsNullOrEmpty(customer.SystemName) ? customer.Email : customer.SystemName)}) could not be updated"); @@ -351,8 +344,7 @@ public virtual async Task UpdateCustomer(Customer customer) /// Hard delete from database public virtual async Task DeleteCustomer(Customer customer, bool hard = false) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); if (customer.IsSystemAccount) throw new GrandException($"System customer account ({(string.IsNullOrEmpty(customer.SystemName) ? customer.Email : customer.SystemName)}) could not be deleted"); @@ -390,8 +382,7 @@ public virtual async Task DeleteCustomer(Customer customer, bool hard = false) /// Customer public virtual async Task UpdateCustomerLastLoginDate(Customer customer) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); var update = UpdateBuilder.Create() .Set(x => x.LastLoginDateUtc, customer.LastLoginDateUtc) @@ -404,8 +395,7 @@ public virtual async Task UpdateCustomerLastLoginDate(Customer customer) public virtual async Task UpdateCustomerInAdminPanel(Customer customer) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); if (customer.IsSystemAccount) throw new GrandException($"System customer account ({(string.IsNullOrEmpty(customer.SystemName) ? customer.Email : customer.SystemName)}) could not be updated"); @@ -437,8 +427,7 @@ public virtual async Task UpdateCustomerInAdminPanel(Customer customer) public virtual async Task UpdateActive(Customer customer) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); var update = UpdateBuilder.Create() .Set(x => x.Active, customer.Active) @@ -452,8 +441,7 @@ public virtual async Task UpdateActive(Customer customer) public virtual async Task UpdateContributions(Customer customer) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); await UpdateCustomerField(customer.Id, x => x.HasContributions, true); @@ -475,8 +463,7 @@ public virtual async Task ResetCheckoutData(Customer customer, string storeId, bool clearCouponCodes = false, bool clearCheckoutAttributes = false, bool clearLoyaltyPoints = true, bool clearShipping = true, bool clearPayment = true) { - if (customer == null) - throw new ArgumentNullException(); + ArgumentNullException.ThrowIfNull(customer); //clear entered coupon codes if (clearCouponCodes) @@ -557,8 +544,7 @@ public virtual async Task DeleteGuestCustomers(DateTime? createdFromUtc, Da public virtual async Task DeleteCustomerGroupInCustomer(CustomerGroup customerGroup, string customerId) { - if (customerGroup == null) - throw new ArgumentNullException(nameof(customerGroup)); + ArgumentNullException.ThrowIfNull(customerGroup); if (string.IsNullOrEmpty(customerId)) throw new ArgumentNullException(nameof(customerId)); @@ -568,8 +554,7 @@ public virtual async Task DeleteCustomerGroupInCustomer(CustomerGroup customerGr public virtual async Task InsertCustomerGroupInCustomer(CustomerGroup customerGroup, string customerId) { - if (customerGroup == null) - throw new ArgumentNullException(nameof(customerGroup)); + ArgumentNullException.ThrowIfNull(customerGroup); if (string.IsNullOrEmpty(customerId)) throw new ArgumentNullException(nameof(customerId)); @@ -584,8 +569,7 @@ public virtual async Task InsertCustomerGroupInCustomer(CustomerGroup customerGr public virtual async Task DeleteAddress(Address address, string customerId) { - if (address == null) - throw new ArgumentNullException(nameof(address)); + ArgumentNullException.ThrowIfNull(address); if (string.IsNullOrEmpty(customerId)) throw new ArgumentNullException(nameof(customerId)); @@ -599,8 +583,7 @@ public virtual async Task DeleteAddress(Address address, string customerId) public virtual async Task InsertAddress(Address address, string customerId) { - if (address == null) - throw new ArgumentNullException(nameof(address)); + ArgumentNullException.ThrowIfNull(address); if (string.IsNullOrEmpty(customerId)) throw new ArgumentNullException(nameof(customerId)); @@ -616,8 +599,7 @@ public virtual async Task InsertAddress(Address address, string customerId) public virtual async Task UpdateAddress(Address address, string customerId) { - if (address == null) - throw new ArgumentNullException(nameof(address)); + ArgumentNullException.ThrowIfNull(address); if (string.IsNullOrEmpty(customerId)) throw new ArgumentNullException(nameof(customerId)); @@ -631,8 +613,7 @@ public virtual async Task UpdateAddress(Address address, string customerId) public virtual async Task UpdateBillingAddress(Address address, string customerId) { - if (address == null) - throw new ArgumentNullException(nameof(address)); + ArgumentNullException.ThrowIfNull(address); if (string.IsNullOrEmpty(customerId)) throw new ArgumentNullException(nameof(customerId)); @@ -642,8 +623,7 @@ public virtual async Task UpdateBillingAddress(Address address, string customerI } public virtual async Task UpdateShippingAddress(Address address, string customerId) { - if (address == null) - throw new ArgumentNullException(nameof(address)); + ArgumentNullException.ThrowIfNull(address); if (string.IsNullOrEmpty(customerId)) throw new ArgumentNullException(nameof(customerId)); @@ -657,8 +637,7 @@ public virtual async Task UpdateShippingAddress(Address address, string customer public virtual async Task DeleteShoppingCartItem(string customerId, ShoppingCartItem shoppingCartItem) { - if (shoppingCartItem == null) - throw new ArgumentNullException(nameof(shoppingCartItem)); + ArgumentNullException.ThrowIfNull(shoppingCartItem); await _customerRepository.PullFilter(customerId, x => x.ShoppingCartItems, x => x.Id, shoppingCartItem.Id); @@ -684,8 +663,7 @@ public virtual async Task ClearShoppingCartItem(string customerId, IList x.ShoppingCartItems, shoppingCartItem); @@ -697,8 +675,7 @@ public virtual async Task InsertShoppingCartItem(string customerId, ShoppingCart public virtual async Task UpdateShoppingCartItem(string customerId, ShoppingCartItem shoppingCartItem) { - if (shoppingCartItem == null) - throw new ArgumentNullException(nameof(shoppingCartItem)); + ArgumentNullException.ThrowIfNull(shoppingCartItem); await _customerRepository.UpdateToSet(customerId, x => x.ShoppingCartItems, z => z.Id, shoppingCartItem.Id, shoppingCartItem); diff --git a/src/Business/Grand.Business.Customers/Services/SalesEmployeeService.cs b/src/Business/Grand.Business.Customers/Services/SalesEmployeeService.cs index 68150c874..3074cddbc 100644 --- a/src/Business/Grand.Business.Customers/Services/SalesEmployeeService.cs +++ b/src/Business/Grand.Business.Customers/Services/SalesEmployeeService.cs @@ -60,8 +60,7 @@ orderby se.DisplayOrder /// Sales Employee public virtual async Task InsertSalesEmployee(SalesEmployee salesEmployee) { - if (salesEmployee == null) - throw new ArgumentNullException(nameof(salesEmployee)); + ArgumentNullException.ThrowIfNull(salesEmployee); await _salesEmployeeRepository.InsertAsync(salesEmployee); @@ -78,8 +77,7 @@ public virtual async Task InsertSalesEmployee(SalesEmployee salesEmployee) /// Sales Employee public virtual async Task UpdateSalesEmployee(SalesEmployee salesEmployee) { - if (salesEmployee == null) - throw new ArgumentNullException(nameof(salesEmployee)); + ArgumentNullException.ThrowIfNull(salesEmployee); await _salesEmployeeRepository.UpdateAsync(salesEmployee); @@ -96,8 +94,7 @@ public virtual async Task UpdateSalesEmployee(SalesEmployee salesEmployee) /// The sales employee public virtual async Task DeleteSalesEmployee(SalesEmployee salesEmployee) { - if (salesEmployee == null) - throw new ArgumentNullException(nameof(salesEmployee)); + ArgumentNullException.ThrowIfNull(salesEmployee); await _salesEmployeeRepository.DeleteAsync(salesEmployee); diff --git a/src/Business/Grand.Business.Customers/Services/VendorService.cs b/src/Business/Grand.Business.Customers/Services/VendorService.cs index 37b0456cb..93dbe20fa 100644 --- a/src/Business/Grand.Business.Customers/Services/VendorService.cs +++ b/src/Business/Grand.Business.Customers/Services/VendorService.cs @@ -79,8 +79,7 @@ public virtual async Task> GetAllVendors(string name = "", /// Vendor public virtual async Task InsertVendor(Vendor vendor) { - if (vendor == null) - throw new ArgumentNullException(nameof(vendor)); + ArgumentNullException.ThrowIfNull(vendor); await _vendorRepository.InsertAsync(vendor); @@ -94,8 +93,7 @@ public virtual async Task InsertVendor(Vendor vendor) /// Vendor public virtual async Task UpdateVendor(Vendor vendor) { - if (vendor == null) - throw new ArgumentNullException(nameof(vendor)); + ArgumentNullException.ThrowIfNull(vendor); await _vendorRepository.UpdateAsync(vendor); @@ -109,8 +107,7 @@ public virtual async Task UpdateVendor(Vendor vendor) /// Vendor public virtual async Task DeleteVendor(Vendor vendor) { - if (vendor == null) - throw new ArgumentNullException(nameof(vendor)); + ArgumentNullException.ThrowIfNull(vendor); vendor.Deleted = true; await UpdateVendor(vendor); @@ -138,8 +135,7 @@ public virtual async Task GetVendorNoteById(string vendorId, string /// public virtual async Task InsertVendorNote(VendorNote vendorNote, string vendorId) { - if (vendorNote == null) - throw new ArgumentNullException(nameof(vendorNote)); + ArgumentNullException.ThrowIfNull(vendorNote); await _vendorRepository.AddToSet(vendorId, x => x.VendorNotes, vendorNote); @@ -154,8 +150,7 @@ public virtual async Task InsertVendorNote(VendorNote vendorNote, string vendorI /// Vendor ident public virtual async Task DeleteVendorNote(VendorNote vendorNote, string vendorId) { - if (vendorNote == null) - throw new ArgumentNullException(nameof(vendorNote)); + ArgumentNullException.ThrowIfNull(vendorNote); await _vendorRepository.PullFilter(vendorId, x => x.VendorNotes, x => x.Id, vendorNote.Id); @@ -220,8 +215,7 @@ public virtual async Task> GetAllVendorReviews(string c /// Vendor public virtual async Task UpdateVendorReviewTotals(Vendor vendor) { - if (vendor == null) - throw new ArgumentNullException(nameof(vendor)); + ArgumentNullException.ThrowIfNull(vendor); var approvedRatingSum = 0; var notApprovedRatingSum = 0; @@ -261,8 +255,7 @@ public virtual async Task UpdateVendorReviewTotals(Vendor vendor) public virtual async Task UpdateVendorReview(VendorReview vendorReview) { - if (vendorReview == null) - throw new ArgumentNullException(nameof(vendorReview)); + ArgumentNullException.ThrowIfNull(vendorReview); var update = UpdateBuilder.Create() .Set(x => x.Title, vendorReview.Title) @@ -283,8 +276,7 @@ public virtual async Task UpdateVendorReview(VendorReview vendorReview) /// Vendor review public virtual async Task InsertVendorReview(VendorReview vendorReview) { - if (vendorReview == null) - throw new ArgumentNullException(nameof(vendorReview)); + ArgumentNullException.ThrowIfNull(vendorReview); await _vendorReviewRepository.InsertAsync(vendorReview); @@ -298,8 +290,7 @@ public virtual async Task InsertVendorReview(VendorReview vendorReview) /// Vendor review public virtual async Task DeleteVendorReview(VendorReview vendorReview) { - if (vendorReview == null) - throw new ArgumentNullException(nameof(vendorReview)); + ArgumentNullException.ThrowIfNull(vendorReview); await _vendorReviewRepository.DeleteAsync(vendorReview); diff --git a/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs b/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs index b4e1fb644..da7df1bc0 100644 --- a/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs @@ -32,8 +32,7 @@ public class CampaignService( /// Campaign public virtual async Task InsertCampaign(Campaign campaign) { - if (campaign == null) - throw new ArgumentNullException(nameof(campaign)); + ArgumentNullException.ThrowIfNull(campaign); await campaignRepository.InsertAsync(campaign); @@ -47,8 +46,7 @@ public virtual async Task InsertCampaign(Campaign campaign) /// Campaign public virtual async Task InsertCampaignHistory(CampaignHistory campaignHistory) { - if (campaignHistory == null) - throw new ArgumentNullException(nameof(campaignHistory)); + ArgumentNullException.ThrowIfNull(campaignHistory); await campaignHistoryRepository.InsertAsync(campaignHistory); @@ -60,8 +58,7 @@ public virtual async Task InsertCampaignHistory(CampaignHistory campaignHistory) /// Campaign public virtual async Task UpdateCampaign(Campaign campaign) { - if (campaign == null) - throw new ArgumentNullException(nameof(campaign)); + ArgumentNullException.ThrowIfNull(campaign); await campaignRepository.UpdateAsync(campaign); @@ -75,8 +72,7 @@ public virtual async Task UpdateCampaign(Campaign campaign) /// Campaign public virtual async Task DeleteCampaign(Campaign campaign) { - if (campaign == null) - throw new ArgumentNullException(nameof(campaign)); + ArgumentNullException.ThrowIfNull(campaign); await campaignRepository.DeleteAsync(campaign); @@ -110,8 +106,7 @@ orderby c.CreatedOnUtc public virtual async Task> GetCampaignHistory(Campaign campaign, int pageIndex = 0, int pageSize = int.MaxValue) { - if (campaign == null) - throw new ArgumentNullException(nameof(campaign)); + ArgumentNullException.ThrowIfNull(campaign); var query = from c in campaignHistoryRepository.Table where c.CampaignId == campaign.Id @@ -121,8 +116,7 @@ orderby c.CreatedDateUtc descending } public virtual async Task> CustomerSubscriptions(Campaign campaign, int pageIndex = 0, int pageSize = int.MaxValue) { - if (campaign == null) - throw new ArgumentNullException(nameof(campaign)); + ArgumentNullException.ThrowIfNull(campaign); PagedList model; if (campaign.CustomerCreatedDateFrom.HasValue || campaign.CustomerCreatedDateTo.HasValue || @@ -261,11 +255,8 @@ private class CampaignCustomerHelp public virtual async Task SendCampaign(Campaign campaign, EmailAccount emailAccount, IEnumerable subscriptions) { - if (campaign == null) - throw new ArgumentNullException(nameof(campaign)); - - if (emailAccount == null) - throw new ArgumentNullException(nameof(emailAccount)); + ArgumentNullException.ThrowIfNull(campaign); + ArgumentNullException.ThrowIfNull(emailAccount); var totalEmailsSent = 0; var language = await languageService.GetLanguageById(campaign.LanguageId) ?? (await languageService.GetAllLanguages()).FirstOrDefault(); @@ -327,11 +318,8 @@ public virtual async Task SendCampaign(Campaign campaign, EmailAccount emai /// Email public virtual async Task SendCampaign(Campaign campaign, EmailAccount emailAccount, string email) { - if (campaign == null) - throw new ArgumentNullException(nameof(campaign)); - - if (emailAccount == null) - throw new ArgumentNullException(nameof(emailAccount)); + ArgumentNullException.ThrowIfNull(campaign); + ArgumentNullException.ThrowIfNull(emailAccount); var language = await languageService.GetLanguageById(campaign.LanguageId) ?? (await languageService.GetAllLanguages()).FirstOrDefault(); diff --git a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs index 17449997a..0f7eb3338 100644 --- a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs +++ b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs @@ -106,9 +106,7 @@ public virtual IList AddContactAttribute(IList public virtual async Task IsConditionMet(ContactAttribute attribute, IList customAttributes) { - if (attribute == null) - throw new ArgumentNullException(nameof(attribute)); - + ArgumentNullException.ThrowIfNull(attribute); customAttributes ??= new List(); var conditionAttribute = attribute.ConditionAttribute; diff --git a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs index d8e22cf18..d737fa0a0 100644 --- a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs @@ -55,8 +55,7 @@ public ContactAttributeService(ICacheBase cacheBase, /// Contact attribute public virtual async Task DeleteContactAttribute(ContactAttribute contactAttribute) { - if (contactAttribute == null) - throw new ArgumentNullException(nameof(contactAttribute)); + ArgumentNullException.ThrowIfNull(contactAttribute); await _contactAttributeRepository.DeleteAsync(contactAttribute); @@ -121,8 +120,7 @@ public virtual Task GetContactAttributeById(string contactAttr /// Contact attribute public virtual async Task InsertContactAttribute(ContactAttribute contactAttribute) { - if (contactAttribute == null) - throw new ArgumentNullException(nameof(contactAttribute)); + ArgumentNullException.ThrowIfNull(contactAttribute); await _contactAttributeRepository.InsertAsync(contactAttribute); @@ -139,8 +137,7 @@ public virtual async Task InsertContactAttribute(ContactAttribute contactAttribu /// Contact attribute public virtual async Task UpdateContactAttribute(ContactAttribute contactAttribute) { - if (contactAttribute == null) - throw new ArgumentNullException(nameof(contactAttribute)); + ArgumentNullException.ThrowIfNull(contactAttribute); await _contactAttributeRepository.UpdateAsync(contactAttribute); diff --git a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs index 0737ae77f..fba07d19b 100644 --- a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs @@ -29,8 +29,7 @@ public ContactUsService( /// ContactUs item public virtual async Task DeleteContactUs(ContactUs contactus) { - if (contactus == null) - throw new ArgumentNullException(nameof(contactus)); + ArgumentNullException.ThrowIfNull(contactus); await _contactusRepository.DeleteAsync(contactus); @@ -103,8 +102,7 @@ public virtual Task GetContactUsById(string contactUsId) /// A contactus item public virtual async Task InsertContactUs(ContactUs contactus) { - if (contactus == null) - throw new ArgumentNullException(nameof(contactus)); + ArgumentNullException.ThrowIfNull(contactus); await _contactusRepository.InsertAsync(contactus); diff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseActionService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseActionService.cs index 8a3067273..15b4e68ee 100644 --- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseActionService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseActionService.cs @@ -41,8 +41,7 @@ public virtual async Task CustomerLessonCompleted(string customerId, strin public virtual async Task InsertAsync(CourseAction courseAction) { - if (courseAction == null) - throw new ArgumentNullException(nameof(courseAction)); + ArgumentNullException.ThrowIfNull(courseAction); await _courseActionRepository.InsertAsync(courseAction); @@ -54,8 +53,7 @@ public virtual async Task InsertAsync(CourseAction courseAction) public virtual async Task Update(CourseAction courseAction) { - if (courseAction == null) - throw new ArgumentNullException(nameof(courseAction)); + ArgumentNullException.ThrowIfNull(courseAction); await _courseActionRepository.UpdateAsync(courseAction); diff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs index 293380c0f..a9f6d8632 100644 --- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs @@ -19,8 +19,7 @@ public CourseLessonService(IRepository courseLessonRepository, IMe public virtual async Task Delete(CourseLesson courseLesson) { - if (courseLesson == null) - throw new ArgumentNullException(nameof(courseLesson)); + ArgumentNullException.ThrowIfNull(courseLesson); await _courseLessonRepository.DeleteAsync(courseLesson); @@ -47,8 +46,7 @@ public virtual Task GetById(string id) public virtual async Task Insert(CourseLesson courseLesson) { - if (courseLesson == null) - throw new ArgumentNullException(nameof(courseLesson)); + ArgumentNullException.ThrowIfNull(courseLesson); await _courseLessonRepository.InsertAsync(courseLesson); @@ -60,8 +58,7 @@ public virtual async Task Insert(CourseLesson courseLesson) public virtual async Task Update(CourseLesson courseLesson) { - if (courseLesson == null) - throw new ArgumentNullException(nameof(courseLesson)); + ArgumentNullException.ThrowIfNull(courseLesson); await _courseLessonRepository.UpdateAsync(courseLesson); diff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseLevelService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseLevelService.cs index 3edc41029..5d1a7f08c 100644 --- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseLevelService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseLevelService.cs @@ -19,8 +19,7 @@ public CourseLevelService(IRepository courseLevelRepository, IMedia public virtual async Task Delete(CourseLevel courseLevel) { - if (courseLevel == null) - throw new ArgumentNullException(nameof(courseLevel)); + ArgumentNullException.ThrowIfNull(courseLevel); await _courseLevelRepository.DeleteAsync(courseLevel); @@ -44,8 +43,7 @@ public virtual Task GetById(string id) public virtual async Task Insert(CourseLevel courseLevel) { - if (courseLevel == null) - throw new ArgumentNullException(nameof(courseLevel)); + ArgumentNullException.ThrowIfNull(courseLevel); await _courseLevelRepository.InsertAsync(courseLevel); @@ -57,8 +55,7 @@ public virtual async Task Insert(CourseLevel courseLevel) public virtual async Task Update(CourseLevel courseLevel) { - if (courseLevel == null) - throw new ArgumentNullException(nameof(courseLevel)); + ArgumentNullException.ThrowIfNull(courseLevel); await _courseLevelRepository.UpdateAsync(courseLevel); diff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs index 83c4355d7..4ddc17cda 100644 --- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs @@ -30,8 +30,7 @@ public CourseService(IRepository courseRepository, public virtual async Task Delete(Course course) { - if (course == null) - throw new ArgumentNullException(nameof(course)); + ArgumentNullException.ThrowIfNull(course); await _courseRepository.DeleteAsync(course); @@ -94,8 +93,7 @@ public virtual Task GetById(string id) public virtual async Task Insert(Course course) { - if (course == null) - throw new ArgumentNullException(nameof(course)); + ArgumentNullException.ThrowIfNull(course); await _courseRepository.InsertAsync(course); @@ -107,8 +105,7 @@ public virtual async Task Insert(Course course) public virtual async Task Update(Course course) { - if (course == null) - throw new ArgumentNullException(nameof(course)); + ArgumentNullException.ThrowIfNull(course); await _courseRepository.UpdateAsync(course); diff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseSubjectService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseSubjectService.cs index 812b305c7..752891a49 100644 --- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseSubjectService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseSubjectService.cs @@ -19,8 +19,7 @@ public CourseSubjectService(IRepository courseSubjectRepository, public virtual async Task Delete(CourseSubject courseSubject) { - if (courseSubject == null) - throw new ArgumentNullException(nameof(courseSubject)); + ArgumentNullException.ThrowIfNull(courseSubject); await _courseSubjectRepository.DeleteAsync(courseSubject); @@ -48,8 +47,7 @@ public virtual Task GetById(string id) public virtual async Task Insert(CourseSubject courseSubject) { - if (courseSubject == null) - throw new ArgumentNullException(nameof(courseSubject)); + ArgumentNullException.ThrowIfNull(courseSubject); await _courseSubjectRepository.InsertAsync(courseSubject); @@ -61,8 +59,7 @@ public virtual async Task Insert(CourseSubject courseSubject) public virtual async Task Update(CourseSubject courseSubject) { - if (courseSubject == null) - throw new ArgumentNullException(nameof(courseSubject)); + ArgumentNullException.ThrowIfNull(courseSubject); await _courseSubjectRepository.UpdateAsync(courseSubject); diff --git a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerCoordinatesService.cs b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerCoordinatesService.cs index d4695b58e..4195c7d34 100644 --- a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerCoordinatesService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerCoordinatesService.cs @@ -30,8 +30,7 @@ public CustomerCoordinatesService( public async Task<(double longitude, double latitude)> GetGeoCoordinate(Customer customer) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); if (customer.Coordinates == null) await Task.FromResult((0, 0)); diff --git a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs index ade41bfed..9c0e596b1 100644 --- a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs @@ -70,8 +70,7 @@ public virtual Task GetCustomerProductPriceById(string id) /// Customer product price public virtual async Task InsertCustomerProductPrice(CustomerProductPrice customerProductPrice) { - if (customerProductPrice == null) - throw new ArgumentNullException(nameof(customerProductPrice)); + ArgumentNullException.ThrowIfNull(customerProductPrice); await _customerProductPriceRepository.InsertAsync(customerProductPrice); @@ -88,8 +87,7 @@ public virtual async Task InsertCustomerProductPrice(CustomerProductPrice custom /// Customer product price public virtual async Task UpdateCustomerProductPrice(CustomerProductPrice customerProductPrice) { - if (customerProductPrice == null) - throw new ArgumentNullException(nameof(customerProductPrice)); + ArgumentNullException.ThrowIfNull(customerProductPrice); await _customerProductPriceRepository.UpdateAsync(customerProductPrice); @@ -106,8 +104,7 @@ public virtual async Task UpdateCustomerProductPrice(CustomerProductPrice custom /// Customer product price public virtual async Task DeleteCustomerProductPrice(CustomerProductPrice customerProductPrice) { - if (customerProductPrice == null) - throw new ArgumentNullException(nameof(customerProductPrice)); + ArgumentNullException.ThrowIfNull(customerProductPrice); await _customerProductPriceRepository.DeleteAsync(customerProductPrice); @@ -161,8 +158,7 @@ public virtual async Task GetCustomerProduct(string customerId, /// Customer product public virtual async Task InsertCustomerProduct(CustomerProduct customerProduct) { - if (customerProduct == null) - throw new ArgumentNullException(nameof(customerProduct)); + ArgumentNullException.ThrowIfNull(customerProduct); await _customerProductRepository.InsertAsync(customerProduct); @@ -179,8 +175,7 @@ public virtual async Task InsertCustomerProduct(CustomerProduct customerProduct) /// Customer product public virtual async Task UpdateCustomerProduct(CustomerProduct customerProduct) { - if (customerProduct == null) - throw new ArgumentNullException(nameof(customerProduct)); + ArgumentNullException.ThrowIfNull(customerProduct); await _customerProductRepository.UpdateAsync(customerProduct); @@ -197,8 +192,7 @@ public virtual async Task UpdateCustomerProduct(CustomerProduct customerProduct) /// Customer product public virtual async Task DeleteCustomerProduct(CustomerProduct customerProduct) { - if (customerProduct == null) - throw new ArgumentNullException(nameof(customerProduct)); + ArgumentNullException.ThrowIfNull(customerProduct); await _customerProductRepository.DeleteAsync(customerProduct); diff --git a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs index d3838fd44..859a1e7c3 100644 --- a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs @@ -63,8 +63,7 @@ where c.CustomerTags.Contains(customerTagId) /// Customer tag public virtual async Task DeleteCustomerTag(CustomerTag customerTag) { - if (customerTag == null) - throw new ArgumentNullException(nameof(customerTag)); + ArgumentNullException.ThrowIfNull(customerTag); //update customer await _customerRepository.Pull(string.Empty, x => x.CustomerTags, customerTag.Id); @@ -128,8 +127,7 @@ where pt.Name.ToLower().Contains(name.ToLower()) /// Customer tag public virtual async Task InsertCustomerTag(CustomerTag customerTag) { - if (customerTag == null) - throw new ArgumentNullException(nameof(customerTag)); + ArgumentNullException.ThrowIfNull(customerTag); await _customerTagRepository.InsertAsync(customerTag); @@ -159,8 +157,7 @@ public virtual async Task DeleteTagFromCustomer(string customerTagId, string cus /// Customer tag public virtual async Task UpdateCustomerTag(CustomerTag customerTag) { - if (customerTag == null) - throw new ArgumentNullException(nameof(customerTag)); + ArgumentNullException.ThrowIfNull(customerTag); await _customerTagRepository.UpdateAsync(customerTag); @@ -234,8 +231,7 @@ public virtual Task GetCustomerTagProductById(string id) /// Customer tag product public virtual async Task InsertCustomerTagProduct(CustomerTagProduct customerTagProduct) { - if (customerTagProduct == null) - throw new ArgumentNullException(nameof(customerTagProduct)); + ArgumentNullException.ThrowIfNull(customerTagProduct); await _customerTagProductRepository.InsertAsync(customerTagProduct); @@ -253,8 +249,7 @@ public virtual async Task InsertCustomerTagProduct(CustomerTagProduct customerTa /// Customer tag product public virtual async Task UpdateCustomerTagProduct(CustomerTagProduct customerTagProduct) { - if (customerTagProduct == null) - throw new ArgumentNullException(nameof(customerTagProduct)); + ArgumentNullException.ThrowIfNull(customerTagProduct); await _customerTagProductRepository.UpdateAsync(customerTagProduct); @@ -272,8 +267,7 @@ public virtual async Task UpdateCustomerTagProduct(CustomerTagProduct customerTa /// Customer tag product public virtual async Task DeleteCustomerTagProduct(CustomerTagProduct customerTagProduct) { - if (customerTagProduct == null) - throw new ArgumentNullException(nameof(customerTagProduct)); + ArgumentNullException.ThrowIfNull(customerTagProduct); await _customerTagProductRepository.DeleteAsync(customerTagProduct); diff --git a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs index dd3fb40d6..269a0eaa5 100644 --- a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs @@ -21,8 +21,7 @@ public DocumentService(IRepository documentRepository, IMediator media public virtual async Task Delete(Document document) { - if (document == null) - throw new ArgumentNullException(nameof(document)); + ArgumentNullException.ThrowIfNull(document); await _documentRepository.DeleteAsync(document); @@ -71,8 +70,7 @@ public virtual Task GetById(string id) public virtual async Task Insert(Document document) { - if (document == null) - throw new ArgumentNullException(nameof(document)); + ArgumentNullException.ThrowIfNull(document); await _documentRepository.InsertAsync(document); @@ -83,8 +81,7 @@ public virtual async Task Insert(Document document) public virtual async Task Update(Document document) { - if (document == null) - throw new ArgumentNullException(nameof(document)); + ArgumentNullException.ThrowIfNull(document); await _documentRepository.UpdateAsync(document); diff --git a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentTypeService.cs b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentTypeService.cs index b138de552..e71a17660 100644 --- a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentTypeService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentTypeService.cs @@ -19,8 +19,7 @@ public DocumentTypeService(IRepository documentTypeRepository, IMe public virtual async Task Delete(DocumentType documentType) { - if (documentType == null) - throw new ArgumentNullException(nameof(documentType)); + ArgumentNullException.ThrowIfNull(documentType); await _documentTypeRepository.DeleteAsync(documentType); @@ -43,8 +42,7 @@ public virtual Task GetById(string id) public virtual async Task Insert(DocumentType documentType) { - if (documentType == null) - throw new ArgumentNullException(nameof(documentType)); + ArgumentNullException.ThrowIfNull(documentType); await _documentTypeRepository.InsertAsync(documentType); @@ -54,8 +52,7 @@ public virtual async Task Insert(DocumentType documentType) public virtual async Task Update(DocumentType documentType) { - if (documentType == null) - throw new ArgumentNullException(nameof(documentType)); + ArgumentNullException.ThrowIfNull(documentType); await _documentTypeRepository.UpdateAsync(documentType); diff --git a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs index d417d354c..ceb63d43f 100644 --- a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs @@ -72,10 +72,7 @@ private async Task PublishSubscriptionEvent(string email, bool isSubscribe, bool /// if set to true [publish subscription events]. public virtual async Task InsertNewsLetterSubscription(NewsLetterSubscription newsLetterSubscription, bool publishSubscriptionEvents = true) { - if (newsLetterSubscription == null) - { - throw new ArgumentNullException(nameof(newsLetterSubscription)); - } + ArgumentNullException.ThrowIfNull(newsLetterSubscription); //Handle e-mail newsLetterSubscription.Email = CommonHelper.EnsureSubscriberEmailOrThrow(newsLetterSubscription.Email); @@ -103,10 +100,7 @@ public virtual async Task InsertNewsLetterSubscription(NewsLetterSubscription ne /// if set to true [publish subscription events]. public virtual async Task UpdateNewsLetterSubscription(NewsLetterSubscription newsLetterSubscription, bool publishSubscriptionEvents = true) { - if (newsLetterSubscription == null) - { - throw new ArgumentNullException(nameof(newsLetterSubscription)); - } + ArgumentNullException.ThrowIfNull(newsLetterSubscription); //Handle e-mail newsLetterSubscription.Email = CommonHelper.EnsureSubscriberEmailOrThrow(newsLetterSubscription.Email); @@ -144,8 +138,7 @@ public virtual async Task UpdateNewsLetterSubscription(NewsLetterSubscription ne /// if set to true [publish subscription events]. public virtual async Task DeleteNewsLetterSubscription(NewsLetterSubscription newsLetterSubscription, bool publishSubscriptionEvents = true) { - if (newsLetterSubscription == null) - throw new ArgumentNullException(nameof(newsLetterSubscription)); + ArgumentNullException.ThrowIfNull(newsLetterSubscription); await _subscriptionRepository.DeleteAsync(newsLetterSubscription); @@ -257,8 +250,7 @@ public virtual async Task> GetAllNewsLetterSu /// Result in TXT (string) format public virtual string ExportNewsletterSubscribersToTxt(IList subscriptions) { - if (subscriptions == null) - throw new ArgumentNullException(nameof(subscriptions)); + ArgumentNullException.ThrowIfNull(subscriptions); const char separator = ','; var sb = new StringBuilder(); diff --git a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsletterCategoryService.cs b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsletterCategoryService.cs index 80011b8ef..73b5e7dfb 100644 --- a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsletterCategoryService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsletterCategoryService.cs @@ -31,8 +31,7 @@ public NewsletterCategoryService(IRepository newsletterCateg /// NewsletterCategory public virtual async Task InsertNewsletterCategory(NewsletterCategory newsletterCategory) { - if (newsletterCategory == null) - throw new ArgumentNullException(nameof(newsletterCategory)); + ArgumentNullException.ThrowIfNull(newsletterCategory); await _newsletterCategoryRepository.InsertAsync(newsletterCategory); @@ -46,8 +45,7 @@ public virtual async Task InsertNewsletterCategory(NewsletterCategory newsletter /// NewsletterCategory public virtual async Task UpdateNewsletterCategory(NewsletterCategory newsletterCategory) { - if (newsletterCategory == null) - throw new ArgumentNullException(nameof(newsletterCategory)); + ArgumentNullException.ThrowIfNull(newsletterCategory); await _newsletterCategoryRepository.UpdateAsync(newsletterCategory); @@ -62,8 +60,7 @@ public virtual async Task UpdateNewsletterCategory(NewsletterCategory newsletter /// NewsletterCategory public virtual async Task DeleteNewsletterCategory(NewsletterCategory newsletterCategory) { - if (newsletterCategory == null) - throw new ArgumentNullException(nameof(newsletterCategory)); + ArgumentNullException.ThrowIfNull(newsletterCategory); await _newsletterCategoryRepository.DeleteAsync(newsletterCategory); diff --git a/src/Business/Grand.Business.Messages/Services/EmailAccountService.cs b/src/Business/Grand.Business.Messages/Services/EmailAccountService.cs index 2e44d614a..1e71f197b 100644 --- a/src/Business/Grand.Business.Messages/Services/EmailAccountService.cs +++ b/src/Business/Grand.Business.Messages/Services/EmailAccountService.cs @@ -38,8 +38,7 @@ public EmailAccountService( /// Email account public virtual async Task InsertEmailAccount(EmailAccount emailAccount) { - if (emailAccount == null) - throw new ArgumentNullException(nameof(emailAccount)); + ArgumentNullException.ThrowIfNull(emailAccount); emailAccount.Email = CommonHelper.EnsureNotNull(emailAccount.Email); emailAccount.DisplayName = CommonHelper.EnsureNotNull(emailAccount.DisplayName); @@ -74,8 +73,7 @@ public virtual async Task InsertEmailAccount(EmailAccount emailAccount) /// Email account public virtual async Task UpdateEmailAccount(EmailAccount emailAccount) { - if (emailAccount == null) - throw new ArgumentNullException(nameof(emailAccount)); + ArgumentNullException.ThrowIfNull(emailAccount); emailAccount.Email = CommonHelper.EnsureNotNull(emailAccount.Email); emailAccount.DisplayName = CommonHelper.EnsureNotNull(emailAccount.DisplayName); @@ -110,8 +108,7 @@ public virtual async Task UpdateEmailAccount(EmailAccount emailAccount) /// Email account public virtual async Task DeleteEmailAccount(EmailAccount emailAccount) { - if (emailAccount == null) - throw new ArgumentNullException(nameof(emailAccount)); + ArgumentNullException.ThrowIfNull(emailAccount); var emailAccounts = await GetAllEmailAccounts(); if (emailAccounts.Count == 1) throw new GrandException("You cannot delete this email account. At least one account is required."); diff --git a/src/Business/Grand.Business.Messages/Services/MessageProviderService.cs b/src/Business/Grand.Business.Messages/Services/MessageProviderService.cs index 22035c901..0f382315f 100644 --- a/src/Business/Grand.Business.Messages/Services/MessageProviderService.cs +++ b/src/Business/Grand.Business.Messages/Services/MessageProviderService.cs @@ -137,8 +137,7 @@ protected virtual async Task EnsureLanguageIsActive(string languageId, /// Customer note protected virtual async Task SendCustomerMessage(Customer customer, Store store, string languageId, string templateName, bool toEmailAccount = false, CustomerNote customerNote = null) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -291,8 +290,7 @@ public virtual async Task SendOrderRefundedStoreOwnerMessage(Order order, d /// private async Task SendOrderStoreOwnerMessage(string template, Order order, Customer customer, string languageId, double refundedAmount = 0) { - if (order == null) - throw new ArgumentNullException(nameof(order)); + ArgumentNullException.ThrowIfNull(order); var store = await GetStore(order.StoreId); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -404,8 +402,7 @@ public virtual async Task SendOrderRefundedCustomerMessage(Order order, dou private async Task SendOrderCustomerMessage(string message, Order order, Customer customer, string languageId, string attachmentFilePath = null, string attachmentFileName = null, IEnumerable attachments = null, double refundedAmount = 0) { - if (order == null) - throw new ArgumentNullException(nameof(order)); + ArgumentNullException.ThrowIfNull(order); var store = await GetStore(order.StoreId); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -480,11 +477,8 @@ public virtual async Task SendOrderCancelledVendorMessage(Order order, Vend /// Message language identifier private async Task SendOrderVendorMessage(string message, Order order, Vendor vendor, string languageId) { - if (order == null) - throw new ArgumentNullException(nameof(order)); - - if (vendor == null) - throw new ArgumentNullException(nameof(vendor)); + ArgumentNullException.ThrowIfNull(order); + ArgumentNullException.ThrowIfNull(vendor); var store = await GetStore(order.StoreId); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -546,8 +540,7 @@ public virtual async Task SendShipmentDeliveredCustomerMessage(Shipment shi /// Order private async Task SendShipmentCustomerMessage(string message, Shipment shipment, Order order) { - if (shipment == null) - throw new ArgumentNullException(nameof(shipment)); + ArgumentNullException.ThrowIfNull(shipment); if (order == null) throw new Exception("Order cannot be loaded"); @@ -592,11 +585,8 @@ private async Task SendShipmentCustomerMessage(string message, Shipment shi /// Order note public virtual async Task SendNewOrderNoteAddedCustomerMessage(Order order, OrderNote orderNote) { - if (orderNote == null) - throw new ArgumentNullException(nameof(orderNote)); - - if (order == null) - throw new ArgumentNullException(nameof(order)); + ArgumentNullException.ThrowIfNull(orderNote); + ArgumentNullException.ThrowIfNull(order); var store = await GetStore(order.StoreId); var language = await EnsureLanguageIsActive(order.CustomerLanguageId, store.Id); @@ -663,8 +653,7 @@ public virtual async Task SendNewsLetterSubscriptionDeactivationMessage(New private async Task SendNewsLetterSubscriptionMessage(string message, NewsLetterSubscription subscription, string languageId) { - if (subscription == null) - throw new ArgumentNullException(nameof(subscription)); + ArgumentNullException.ThrowIfNull(subscription); var store = await GetStore(subscription.StoreId); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -708,11 +697,8 @@ private async Task SendNewsLetterSubscriptionMessage(string message, NewsLe public virtual async Task SendProductEmailAFriendMessage(Customer customer, Store store, string languageId, Product product, string customerEmail, string friendsEmail, string personalMessage) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); - - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(customer); + ArgumentNullException.ThrowIfNull(product); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -754,8 +740,7 @@ public virtual async Task SendProductEmailAFriendMessage(Customer customer, public virtual async Task SendWishlistEmailAFriendMessage(Customer customer, Store store, string languageId, string customerEmail, string friendsEmail, string personalMessage) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -793,11 +778,8 @@ public virtual async Task SendWishlistEmailAFriendMessage(Customer customer public virtual async Task SendProductQuestionMessage(Customer customer, Store store, string languageId, Product product, string customerEmail, string fullName, string phone, string message, string ipaddress) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); - - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(customer); + ArgumentNullException.ThrowIfNull(product); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -870,8 +852,7 @@ await _mediator.Send(new InsertContactUsCommand { /// Message language identifier public virtual async Task SendNewMerchandiseReturnStoreOwnerMessage(MerchandiseReturn merchandiseReturn, Order order, string languageId) { - if (merchandiseReturn == null) - throw new ArgumentNullException(nameof(merchandiseReturn)); + ArgumentNullException.ThrowIfNull(merchandiseReturn); var store = await GetStore(order.StoreId); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -926,8 +907,7 @@ await SendNotification(messageTemplate, emailAccount, /// Message language identifier public virtual async Task SendMerchandiseReturnStatusChangedCustomerMessage(MerchandiseReturn merchandiseReturn, Order order, string languageId) { - if (merchandiseReturn == null) - throw new ArgumentNullException(nameof(merchandiseReturn)); + ArgumentNullException.ThrowIfNull(merchandiseReturn); var store = await GetStore(order.StoreId); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -971,8 +951,7 @@ public virtual async Task SendMerchandiseReturnStatusChangedCustomerMessage /// Message language identifier public virtual async Task SendNewMerchandiseReturnCustomerMessage(MerchandiseReturn merchandiseReturn, Order order, string languageId) { - if (merchandiseReturn == null) - throw new ArgumentNullException(nameof(merchandiseReturn)); + ArgumentNullException.ThrowIfNull(merchandiseReturn); var store = await GetStore(order.StoreId); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -1016,11 +995,8 @@ public virtual async Task SendNewMerchandiseReturnCustomerMessage(Merchandi /// Order public virtual async Task SendNewMerchandiseReturnNoteAddedCustomerMessage(MerchandiseReturn merchandiseReturn, MerchandiseReturnNote merchandiseReturnNote, Order order) { - if (merchandiseReturnNote == null) - throw new ArgumentNullException(nameof(merchandiseReturnNote)); - - if (merchandiseReturn == null) - throw new ArgumentNullException(nameof(merchandiseReturn)); + ArgumentNullException.ThrowIfNull(merchandiseReturnNote); + ArgumentNullException.ThrowIfNull(merchandiseReturn); var store = await GetStore(order.StoreId); var language = await EnsureLanguageIsActive(order.CustomerLanguageId, store.Id); @@ -1069,11 +1045,8 @@ public virtual async Task SendNewMerchandiseReturnNoteAddedCustomerMessage( /// Message language identifier public virtual async Task SendNewVendorAccountApplyStoreOwnerMessage(Customer customer, Vendor vendor, Store store, string languageId) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); - - if (vendor == null) - throw new ArgumentNullException(nameof(vendor)); + ArgumentNullException.ThrowIfNull(customer); + ArgumentNullException.ThrowIfNull(vendor); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -1108,8 +1081,7 @@ public virtual async Task SendNewVendorAccountApplyStoreOwnerMessage(Custom /// Message language identifier public virtual async Task SendVendorInformationChangeMessage(Vendor vendor, Store store, string languageId) { - if (vendor == null) - throw new ArgumentNullException(nameof(vendor)); + ArgumentNullException.ThrowIfNull(vendor); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -1143,8 +1115,7 @@ public virtual async Task SendVendorInformationChangeMessage(Vendor vendor, /// Message language identifier public virtual async Task SendGiftVoucherMessage(GiftVoucher giftVoucher, Order order, string languageId) { - if (giftVoucher == null) - throw new ArgumentNullException(nameof(giftVoucher)); + ArgumentNullException.ThrowIfNull(giftVoucher); Store store = null; if (order != null) store = await _storeService.GetStoreById(order.StoreId); @@ -1182,8 +1153,7 @@ public virtual async Task SendGiftVoucherMessage(GiftVoucher giftVoucher, O public virtual async Task SendProductReviewMessage(Product product, ProductReview productReview, Store store, string languageId) { - if (productReview == null) - throw new ArgumentNullException(nameof(productReview)); + ArgumentNullException.ThrowIfNull(productReview); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -1225,8 +1195,7 @@ public virtual async Task SendProductReviewMessage(Product product, Product public virtual async Task SendVendorReviewMessage(VendorReview vendorReview, Store store, string languageId) { - if (vendorReview == null) - throw new ArgumentNullException(nameof(vendorReview)); + ArgumentNullException.ThrowIfNull(vendorReview); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -1269,8 +1238,7 @@ public virtual async Task SendVendorReviewMessage(VendorReview vendorReview /// Message language identifier public virtual async Task SendQuantityBelowStoreOwnerMessage(Product product, string languageId) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var store = await GetStore(""); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -1305,8 +1273,7 @@ public virtual async Task SendQuantityBelowStoreOwnerMessage(Product produc /// Message language identifier public virtual async Task SendQuantityBelowStoreOwnerMessage(Product product, ProductAttributeCombination combination, string languageId) { - if (combination == null) - throw new ArgumentNullException(nameof(combination)); + ArgumentNullException.ThrowIfNull(combination); var store = await GetStore(""); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -1341,8 +1308,7 @@ public virtual async Task SendQuantityBelowStoreOwnerMessage(Product produc /// Message language identifier public virtual async Task SendCustomerDeleteStoreOwnerMessage(Customer customer, string languageId) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); var store = await GetStore(""); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -1373,8 +1339,7 @@ public virtual async Task SendCustomerDeleteStoreOwnerMessage(Customer cust /// public virtual async Task SendBlogCommentMessage(BlogPost blogPost, BlogComment blogComment, string languageId) { - if (blogComment == null) - throw new ArgumentNullException(nameof(blogComment)); + ArgumentNullException.ThrowIfNull(blogComment); var store = await GetStore(blogComment.StoreId); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -1414,8 +1379,7 @@ public virtual async Task SendBlogCommentMessage(BlogPost blogPost, BlogCom /// Message language identifier public virtual async Task SendArticleCommentMessage(KnowledgebaseArticle article, KnowledgebaseArticleComment articleComment, string languageId) { - if (articleComment == null) - throw new ArgumentNullException(nameof(articleComment)); + ArgumentNullException.ThrowIfNull(articleComment); var store = await GetStore(""); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -1453,8 +1417,7 @@ public virtual async Task SendArticleCommentMessage(KnowledgebaseArticle ar /// Message language identifier public virtual async Task SendNewsCommentMessage(NewsItem newsItem, NewsComment newsComment, string languageId) { - if (newsComment == null) - throw new ArgumentNullException(nameof(newsComment)); + ArgumentNullException.ThrowIfNull(newsComment); var store = await GetStore(newsComment.StoreId); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -1493,8 +1456,7 @@ public virtual async Task SendNewsCommentMessage(NewsItem newsItem, NewsCom /// Message language identifier public virtual async Task SendBackInStockMessage(Customer customer, Product product, OutOfStockSubscription subscription, string languageId) { - if (subscription == null) - throw new ArgumentNullException(nameof(subscription)); + ArgumentNullException.ThrowIfNull(subscription); var store = await GetStore(subscription.StoreId); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -1616,8 +1578,7 @@ await _mediator.Send(new InsertContactUsCommand { public virtual async Task SendContactVendorMessage(Customer customer, Store store, Vendor vendor, string languageId, string senderEmail, string senderName, string subject, string body, string ipaddress) { - if (vendor == null) - throw new ArgumentNullException(nameof(vendor)); + ArgumentNullException.ThrowIfNull(vendor); var language = await EnsureLanguageIsActive(languageId, store.Id); @@ -1686,8 +1647,7 @@ await _mediator.Send(new InsertContactUsCommand { public virtual async Task SendAuctionWinEndedCustomerMessage(Product product, string languageId, Bid bid) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = bid.CustomerId }); if (customer == null) return 0; @@ -1725,8 +1685,7 @@ public virtual async Task SendAuctionWinEndedCustomerMessage(Product produc public virtual async Task SendAuctionEndedLostCustomerMessage(Product product, string languageId, Bid bid) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var winner = await _mediator.Send(new GetCustomerByIdQuery { Id = bid.CustomerId }); if (winner == null) return 0; @@ -1774,8 +1733,7 @@ await SendNotification(messageTemplate, emailAccount, public virtual async Task SendAuctionEndedBinCustomerMessage(Product product, string customerId, string languageId, string storeId) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var store = await GetStore(storeId); @@ -1821,8 +1779,7 @@ await SendNotification(messageTemplate, emailAccount, } public virtual async Task SendAuctionEndedStoreOwnerMessage(Product product, string languageId, Bid bid) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var builder = new LiquidObjectBuilder(_mediator); MessageTemplate messageTemplate; @@ -1881,8 +1838,7 @@ public virtual async Task SendAuctionEndedStoreOwnerMessage(Product product /// public virtual async Task SendOutBidCustomerMessage(Product product, string languageId, Bid bid) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = bid.CustomerId }); if (string.IsNullOrEmpty(languageId)) diff --git a/src/Business/Grand.Business.Messages/Services/MessageTemplateService.cs b/src/Business/Grand.Business.Messages/Services/MessageTemplateService.cs index 0139f81df..58f27d2f1 100644 --- a/src/Business/Grand.Business.Messages/Services/MessageTemplateService.cs +++ b/src/Business/Grand.Business.Messages/Services/MessageTemplateService.cs @@ -49,8 +49,7 @@ public MessageTemplateService(ICacheBase cacheBase, /// Message template public virtual async Task InsertMessageTemplate(MessageTemplate messageTemplate) { - if (messageTemplate == null) - throw new ArgumentNullException(nameof(messageTemplate)); + ArgumentNullException.ThrowIfNull(messageTemplate); await _messageTemplateRepository.InsertAsync(messageTemplate); @@ -66,8 +65,7 @@ public virtual async Task InsertMessageTemplate(MessageTemplate messageTemplate) /// Message template public virtual async Task UpdateMessageTemplate(MessageTemplate messageTemplate) { - if (messageTemplate == null) - throw new ArgumentNullException(nameof(messageTemplate)); + ArgumentNullException.ThrowIfNull(messageTemplate); await _messageTemplateRepository.UpdateAsync(messageTemplate); @@ -83,8 +81,7 @@ public virtual async Task UpdateMessageTemplate(MessageTemplate messageTemplate) /// Message template public virtual async Task DeleteMessageTemplate(MessageTemplate messageTemplate) { - if (messageTemplate == null) - throw new ArgumentNullException(nameof(messageTemplate)); + ArgumentNullException.ThrowIfNull(messageTemplate); await _messageTemplateRepository.DeleteAsync(messageTemplate); @@ -172,8 +169,7 @@ public virtual async Task> GetAllMessageTemplates(string /// Message template copy public virtual async Task CopyMessageTemplate(MessageTemplate messageTemplate) { - if (messageTemplate == null) - throw new ArgumentNullException(nameof(messageTemplate)); + ArgumentNullException.ThrowIfNull(messageTemplate); var mtCopy = new MessageTemplate { Name = messageTemplate.Name, diff --git a/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs b/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs index 232047c80..c8ecad649 100644 --- a/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs +++ b/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs @@ -31,8 +31,7 @@ public QueuedEmailService(IRepository queuedEmailRepository, /// Queued email public virtual async Task InsertQueuedEmail(QueuedEmail queuedEmail) { - if (queuedEmail == null) - throw new ArgumentNullException(nameof(queuedEmail)); + ArgumentNullException.ThrowIfNull(queuedEmail); await _queuedEmailRepository.InsertAsync(queuedEmail); @@ -46,8 +45,7 @@ public virtual async Task InsertQueuedEmail(QueuedEmail queuedEmail) /// Queued email public virtual async Task UpdateQueuedEmail(QueuedEmail queuedEmail) { - if (queuedEmail == null) - throw new ArgumentNullException(nameof(queuedEmail)); + ArgumentNullException.ThrowIfNull(queuedEmail); await _queuedEmailRepository.UpdateAsync(queuedEmail); @@ -61,8 +59,7 @@ public virtual async Task UpdateQueuedEmail(QueuedEmail queuedEmail) /// Queued email public virtual async Task DeleteQueuedEmail(QueuedEmail queuedEmail) { - if (queuedEmail == null) - throw new ArgumentNullException(nameof(queuedEmail)); + ArgumentNullException.ThrowIfNull(queuedEmail); await _queuedEmailRepository.DeleteAsync(queuedEmail); @@ -76,8 +73,7 @@ public virtual async Task DeleteQueuedEmail(QueuedEmail queuedEmail) /// email public virtual async Task DeleteCustomerEmail(string email) { - if (email == null) - throw new ArgumentNullException(nameof(email)); + ArgumentNullException.ThrowIfNull(email); var deleteCustomerEmail = _queuedEmailRepository.Table.Where(x => x.To == email); diff --git a/src/Business/Grand.Business.Storage/Services/DownloadService.cs b/src/Business/Grand.Business.Storage/Services/DownloadService.cs index c424b59bc..2a1eb5928 100644 --- a/src/Business/Grand.Business.Storage/Services/DownloadService.cs +++ b/src/Business/Grand.Business.Storage/Services/DownloadService.cs @@ -89,8 +89,7 @@ public virtual async Task GetDownloadByGuid(Guid downloadGuid) /// Download public virtual async Task InsertDownload(Download download) { - if (download == null) - throw new ArgumentNullException(nameof(download)); + ArgumentNullException.ThrowIfNull(download); if (!download.UseDownloadUrl) { download.DownloadObjectId = await _storeFilesContext.BucketUploadFromBytes(download.Filename, download.DownloadBinary); @@ -108,8 +107,7 @@ public virtual async Task InsertDownload(Download download) /// Download public virtual async Task UpdateDownload(Download download) { - if (download == null) - throw new ArgumentNullException(nameof(download)); + ArgumentNullException.ThrowIfNull(download); await _downloadRepository.UpdateAsync(download); @@ -122,8 +120,7 @@ public virtual async Task UpdateDownload(Download download) /// Download public virtual async Task DeleteDownload(Download download) { - if (download == null) - throw new ArgumentNullException(nameof(download)); + ArgumentNullException.ThrowIfNull(download); await _downloadRepository.DeleteAsync(download); diff --git a/src/Business/Grand.Business.Storage/Services/PictureService.cs b/src/Business/Grand.Business.Storage/Services/PictureService.cs index 6a0b9abee..d2f01a04c 100644 --- a/src/Business/Grand.Business.Storage/Services/PictureService.cs +++ b/src/Business/Grand.Business.Storage/Services/PictureService.cs @@ -179,8 +179,7 @@ protected virtual async Task GetPicturePhysicalPath(string fileName) /// Picture binary public virtual async Task LoadPictureBinary(Picture picture, bool fromDb) { - if (picture == null) - throw new ArgumentNullException(nameof(picture)); + ArgumentNullException.ThrowIfNull(picture); var result = fromDb ? (await _pictureRepository.GetByIdAsync(picture.Id)).PictureBinary @@ -446,8 +445,7 @@ public virtual async Task GetPictureById(string pictureId) /// Picture public virtual async Task DeletePicture(Picture picture) { - if (picture == null) - throw new ArgumentNullException(nameof(picture)); + ArgumentNullException.ThrowIfNull(picture); //delete thumbs await DeletePictureThumbs(picture); @@ -469,8 +467,7 @@ public virtual async Task DeletePicture(Picture picture) /// Picture public virtual async Task DeletePictureOnFileSystem(Picture picture) { - if (picture == null) - throw new ArgumentNullException(nameof(picture)); + ArgumentNullException.ThrowIfNull(picture); var lastPart = GetFileExtensionFromMimeType(picture.MimeType); var fileName = $"{picture.Id}_0.{lastPart}"; @@ -646,8 +643,7 @@ public virtual async Task UpdatePicture(string pictureId, byte[] pictur /// Picture public virtual async Task UpdatePicture(Picture picture) { - if (picture == null) - throw new ArgumentNullException(nameof(picture)); + ArgumentNullException.ThrowIfNull(picture); await _pictureRepository.UpdateAsync(picture); @@ -669,8 +665,7 @@ public virtual async Task UpdatePicture(Picture picture) /// Picture public virtual async Task UpdatePictureField(Picture picture, Expression> expression, T value) { - if (picture == null) - throw new ArgumentNullException(nameof(picture)); + ArgumentNullException.ThrowIfNull(picture); await _pictureRepository.UpdateField(picture.Id, expression, value); @@ -830,8 +825,7 @@ private SKEncodedImageFormat EncodedImageFormat(string mimetype) private byte[] ApplyResize(SKBitmap image, SKEncodedImageFormat format, int targetSize) { - if (image == null) - throw new ArgumentNullException(nameof(image)); + ArgumentNullException.ThrowIfNull(image); if (targetSize <= 0) { diff --git a/src/Business/Grand.Business.System/Services/Admin/AdminSiteMapService.cs b/src/Business/Grand.Business.System/Services/Admin/AdminSiteMapService.cs index 6b8ea0eda..eab288c9a 100644 --- a/src/Business/Grand.Business.System/Services/Admin/AdminSiteMapService.cs +++ b/src/Business/Grand.Business.System/Services/Admin/AdminSiteMapService.cs @@ -38,8 +38,7 @@ orderby c.DisplayOrder public virtual async Task InsertSiteMap(AdminSiteMap entity) { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); + ArgumentNullException.ThrowIfNull(entity); await _adminSiteMapRepository.InsertAsync(entity); @@ -53,8 +52,7 @@ public virtual async Task InsertSiteMap(AdminSiteMap entity) public virtual async Task UpdateSiteMap(AdminSiteMap entity) { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); + ArgumentNullException.ThrowIfNull(entity); await _adminSiteMapRepository.UpdateAsync(entity); @@ -67,8 +65,7 @@ public virtual async Task UpdateSiteMap(AdminSiteMap entity) public virtual async Task DeleteSiteMap(AdminSiteMap entity) { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); + ArgumentNullException.ThrowIfNull(entity); await _adminSiteMapRepository.DeleteAsync(entity); diff --git a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ScheduleTaskService.cs b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ScheduleTaskService.cs index a934b77e5..0f646be4e 100644 --- a/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ScheduleTaskService.cs +++ b/src/Business/Grand.Business.System/Services/BackgroundServices/ScheduleTasks/ScheduleTaskService.cs @@ -63,8 +63,7 @@ public virtual async Task> GetAllTasks() /// Task public virtual async Task InsertTask(ScheduleTask task) { - if (task == null) - throw new ArgumentNullException(nameof(task)); + ArgumentNullException.ThrowIfNull(task); return await _taskRepository.InsertAsync(task); } @@ -75,8 +74,7 @@ public virtual async Task InsertTask(ScheduleTask task) /// Task public virtual async Task UpdateTask(ScheduleTask task) { - if (task == null) - throw new ArgumentNullException(nameof(task)); + ArgumentNullException.ThrowIfNull(task); await _taskRepository.UpdateAsync(task); } @@ -87,8 +85,7 @@ public virtual async Task UpdateTask(ScheduleTask task) /// Task public virtual async Task DeleteTask(ScheduleTask task) { - if (task == null) - throw new ArgumentNullException(nameof(task)); + ArgumentNullException.ThrowIfNull(task); await _taskRepository.DeleteAsync(task); } diff --git a/src/Core/Grand.Data/IRepository.cs b/src/Core/Grand.Data/IRepository.cs index 7e07051f2..0a69bef49 100644 --- a/src/Core/Grand.Data/IRepository.cs +++ b/src/Core/Grand.Data/IRepository.cs @@ -29,6 +29,13 @@ public interface IRepository where T : BaseEntity /// Entity Task GetByIdAsync(string id); + /// + /// Get entity by identifier + /// + /// + /// Entity + Task GetOneAsync(Expression> predicate); + /// /// Insert entity /// diff --git a/src/Core/Grand.Data/LiteDb/LiteDBRepository.cs b/src/Core/Grand.Data/LiteDb/LiteDBRepository.cs index e5c3a1372..76577dd79 100644 --- a/src/Core/Grand.Data/LiteDb/LiteDBRepository.cs +++ b/src/Core/Grand.Data/LiteDb/LiteDBRepository.cs @@ -92,6 +92,16 @@ public virtual async Task GetByIdAsync(string id) { return await Task.FromResult(GetById(id)); } + + /// + /// Get async entity by expression + /// + /// + /// Entity + public virtual Task GetOneAsync(Expression> predicate) + { + return Task.FromResult(_collection.Find(predicate).FirstOrDefault()); + } /// /// Insert entity diff --git a/src/Core/Grand.Data/Mongo/MongoRepository.cs b/src/Core/Grand.Data/Mongo/MongoRepository.cs index a4e4594e2..3ab9a7bfe 100644 --- a/src/Core/Grand.Data/Mongo/MongoRepository.cs +++ b/src/Core/Grand.Data/Mongo/MongoRepository.cs @@ -100,6 +100,16 @@ public virtual Task GetByIdAsync(string id) return _collection.Find(e => e.Id == id).FirstOrDefaultAsync(); } + /// + /// Get async entity by expression + /// + /// + /// Entity + public virtual Task GetOneAsync(Expression> predicate) + { + return _collection.Find(predicate).FirstOrDefaultAsync(); + } + /// /// Insert entity /// diff --git a/src/Core/Grand.Domain/Blogs/BlogExtensions.cs b/src/Core/Grand.Domain/Blogs/BlogExtensions.cs index c47f38161..2e65d1fd2 100644 --- a/src/Core/Grand.Domain/Blogs/BlogExtensions.cs +++ b/src/Core/Grand.Domain/Blogs/BlogExtensions.cs @@ -4,8 +4,7 @@ public static class BlogExtensions { public static string[] ParseTags(this BlogPost blogPost) { - if (blogPost == null) - throw new ArgumentNullException(nameof(blogPost)); + ArgumentNullException.ThrowIfNull(blogPost); var parsedTags = new List(); if (!String.IsNullOrEmpty(blogPost.Tags)) diff --git a/src/Core/Grand.Domain/Catalog/ProductExtensions.cs b/src/Core/Grand.Domain/Catalog/ProductExtensions.cs index 9e271a4fa..dfacdee67 100644 --- a/src/Core/Grand.Domain/Catalog/ProductExtensions.cs +++ b/src/Core/Grand.Domain/Catalog/ProductExtensions.cs @@ -44,8 +44,7 @@ public static TierPrice GetPreferredTierPrice(this Product product, Customer cus public static bool ProductTagExists(this Product product, string productTagName) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var result = product.ProductTags.FirstOrDefault(pt => pt == productTagName) != null; return result; @@ -58,8 +57,7 @@ public static bool ProductTagExists(this Product product, /// Result public static int[] ParseAllowedQuantities(this Product product) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var result = new List(); if (!String.IsNullOrWhiteSpace(product.AllowedQuantities)) @@ -91,8 +89,7 @@ public static int[] ParseAllowedQuantities(this Product product) private static void GetSkuMpnGtin(this Product product, IList attributes, out string sku, out string mpn, out string gtin) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); sku = null; mpn = null; @@ -127,8 +124,7 @@ private static void GetSkuMpnGtin(this Product product, IList a public static ProductAttributeCombination FindProductAttributeCombination(this Product product, IList customAttributes, bool ignoreNonCombinableAttributes = true) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var combinations = product.ProductAttributeCombinations; return combinations.FirstOrDefault(x => @@ -221,9 +217,7 @@ public static IList ParseValues(IList customAttributes, /// Attributes public static IList AddProductAttribute(IList customAttributes, ProductAttributeMapping productAttributeMapping, string value) { - if (customAttributes == null) - customAttributes = new List(); - + customAttributes ??= new List(); customAttributes.Add(new CustomAttribute { Key = productAttributeMapping.Id, Value = value }); return customAttributes; @@ -325,11 +319,9 @@ public static bool AreProductAttributesEqual(Product product, IListResult public static bool? IsConditionMet(this Product product, ProductAttributeMapping pam, IList selectedAttributes) { - if (pam == null) - throw new ArgumentNullException(nameof(pam)); + ArgumentNullException.ThrowIfNull(pam); - if (selectedAttributes == null) - selectedAttributes = new List(); + selectedAttributes ??= new List(); var conditionAttribute = pam.ConditionAttribute; if (!conditionAttribute.Any()) @@ -370,8 +362,7 @@ public static bool AreProductAttributesEqual(Product product, IListAttribute combinations public static IList> GenerateAllCombinations(this Product product) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); var allProductAttributMappings = product.ProductAttributeMappings.Where(x => !x.IsNonCombinable()).ToList(); @@ -398,8 +389,7 @@ public static IList> GenerateAllCombinations(this P /// SKU public static string FormatSku(this Product product, IList attributes = null) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); product.GetSkuMpnGtin(attributes, out var sku, out _, out _); @@ -414,8 +404,7 @@ public static string FormatSku(this Product product, IList attr /// Collection part number public static string FormatMpn(this Product product, IList attributes = null) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); product.GetSkuMpnGtin(attributes, out _, out var Mpn, out _); @@ -430,8 +419,7 @@ public static string FormatMpn(this Product product, IList attr /// GTIN public static string FormatGtin(this Product product, IList attributes = null) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); product.GetSkuMpnGtin(attributes, out _, out _, out var gtin); @@ -445,8 +433,7 @@ public static string FormatGtin(this Product product, IList att /// A list of required product IDs public static string[] ParseRequiredProductIds(this Product product) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); if (string.IsNullOrEmpty(product.RequiredProductIds)) return Array.Empty(); @@ -481,8 +468,7 @@ public static bool IsAvailable(this Product product) /// Result public static bool IsAvailable(this Product product, DateTime dateTime) { - if (product == null) - throw new ArgumentNullException(nameof(product)); + ArgumentNullException.ThrowIfNull(product); if (product.AvailableStartDateTimeUtc.HasValue && product.AvailableStartDateTimeUtc.Value > dateTime) { diff --git a/src/Core/Grand.Domain/Catalog/TierPriceExtensions.cs b/src/Core/Grand.Domain/Catalog/TierPriceExtensions.cs index 86e94c247..d718bc15a 100644 --- a/src/Core/Grand.Domain/Catalog/TierPriceExtensions.cs +++ b/src/Core/Grand.Domain/Catalog/TierPriceExtensions.cs @@ -12,11 +12,9 @@ public static class TierPriceExtensions /// Tier prices public static IEnumerable FilterByDate(this IEnumerable source, DateTime? date = null) { - if (source == null) - throw new ArgumentNullException(nameof(source)); + ArgumentNullException.ThrowIfNull(source); - if (!date.HasValue) - date = DateTime.UtcNow; + date ??= DateTime.UtcNow; return source.Where(tierPrice => (!tierPrice.StartDateTimeUtc.HasValue || tierPrice.StartDateTimeUtc.Value < date.Value) && @@ -30,8 +28,7 @@ public static IEnumerable FilterByDate(this IEnumerable so /// Tier prices public static IEnumerable FilterByStore(this IEnumerable source, string storeId) { - if (source == null) - throw new ArgumentNullException(nameof(source)); + ArgumentNullException.ThrowIfNull(source); return source.Where(tierPrice => string.IsNullOrEmpty(tierPrice.StoreId) || tierPrice.StoreId == storeId); } @@ -44,8 +41,7 @@ public static IEnumerable FilterByStore(this IEnumerable s /// Tier prices public static IEnumerable FilterForCustomer(this IEnumerable source, Customer customer) { - if (source == null) - throw new ArgumentNullException(nameof(source)); + ArgumentNullException.ThrowIfNull(source); if (customer == null) return source.Where(tierPrice => string.IsNullOrEmpty(tierPrice.CustomerGroupId)); @@ -62,8 +58,7 @@ public static IEnumerable FilterForCustomer(this IEnumerableTier prices public static IEnumerable FilterByCurrency(this IEnumerable source, string currencyCode) { - if (source == null) - throw new ArgumentNullException(nameof(source)); + ArgumentNullException.ThrowIfNull(source); return source.Where(tierPrice => string.IsNullOrEmpty(tierPrice.CurrencyCode) || tierPrice.CurrencyCode == currencyCode); } @@ -75,8 +70,7 @@ public static IEnumerable FilterByCurrency(this IEnumerableTier prices public static IEnumerable RemoveDuplicatedQuantities(this IEnumerable source) { - if (source == null) - throw new ArgumentNullException(nameof(source)); + ArgumentNullException.ThrowIfNull(source); var result = source.OrderBy(x => x.Price).GroupBy(x => x.Quantity).Select(x => x.First()).OrderBy(x => x.Quantity).ToList(); return result; } diff --git a/src/Core/Grand.Domain/Common/UserFieldExtensions.cs b/src/Core/Grand.Domain/Common/UserFieldExtensions.cs index cb0d39624..0e75acaf5 100644 --- a/src/Core/Grand.Domain/Common/UserFieldExtensions.cs +++ b/src/Core/Grand.Domain/Common/UserFieldExtensions.cs @@ -14,8 +14,7 @@ public static class UserFieldExtensions /// Attribute public static TPropType GetUserFieldFromEntity(this BaseEntity entity, string key, string storeId = "") { - if (entity == null) - throw new ArgumentNullException(nameof(entity)); + ArgumentNullException.ThrowIfNull(entity); var props = entity.UserFields; if (props == null) diff --git a/src/Core/Grand.Domain/Customers/CustomerExtensions.cs b/src/Core/Grand.Domain/Customers/CustomerExtensions.cs index e0fd6287d..dec44651f 100644 --- a/src/Core/Grand.Domain/Customers/CustomerExtensions.cs +++ b/src/Core/Grand.Domain/Customers/CustomerExtensions.cs @@ -13,8 +13,7 @@ public static class CustomerExtensions /// Result public static bool IsSystemAccount(this Customer customer) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); return customer.IsSystemAccount && !string.IsNullOrEmpty(customer.SystemName); } @@ -27,8 +26,7 @@ public static bool IsSystemAccount(this Customer customer) /// Result public static bool IsSearchEngineAccount(this Customer customer) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); if (!customer.IsSystemAccount || string.IsNullOrEmpty(customer.SystemName)) return false; @@ -65,20 +63,19 @@ public static void RemoveAddress(this Customer customer, Address address) /// Customer full name public static string GetFullName(this Customer customer) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); var firstName = customer.GetUserFieldFromEntity(SystemCustomerFieldNames.FirstName); var lastName = customer.GetUserFieldFromEntity(SystemCustomerFieldNames.LastName); var fullName = ""; - if (!String.IsNullOrWhiteSpace(firstName) && !String.IsNullOrWhiteSpace(lastName)) + if (!string.IsNullOrWhiteSpace(firstName) && !string.IsNullOrWhiteSpace(lastName)) fullName = $"{firstName} {lastName}"; else { - if (!String.IsNullOrWhiteSpace(firstName)) + if (!string.IsNullOrWhiteSpace(firstName)) fullName = firstName; - if (!String.IsNullOrWhiteSpace(lastName)) + if (!string.IsNullOrWhiteSpace(lastName)) fullName = lastName; } return fullName; @@ -128,8 +125,7 @@ public static string FormatUserName(this Customer customer, CustomerNameFormat c /// Coupon codes public static string[] ParseAppliedCouponCodes(this Customer customer, string key) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); var existingCouponCodes = customer.GetUserFieldFromEntity(key); @@ -150,8 +146,7 @@ public static string[] ParseAppliedCouponCodes(this Customer customer, string ke /// New coupon codes document public static string ApplyCouponCode(this Customer customer, string key, string couponCode) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); var existingCouponCodes = customer.GetUserFieldFromEntity(key); return string.IsNullOrEmpty(existingCouponCodes) ? couponCode : string.Join(CouponSeparator, existingCouponCodes.Split(CouponSeparator).Append(couponCode).Distinct()); @@ -166,8 +161,7 @@ public static string ApplyCouponCode(this Customer customer, string key, string /// New coupon codes document public static string ApplyCouponCode(this Customer customer, string key, string[] couponCodes) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); var existingCouponCodes = customer.GetUserFieldFromEntity(key); if (string.IsNullOrEmpty(existingCouponCodes)) @@ -189,16 +183,10 @@ public static string ApplyCouponCode(this Customer customer, string key, string[ /// New coupon codes document public static string RemoveCouponCode(this Customer customer, string key, string couponCode) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); var existingCouponCodes = customer.GetUserFieldFromEntity(key); - if (string.IsNullOrEmpty(existingCouponCodes)) - { - return ""; - } - - return string.Join(CouponSeparator, existingCouponCodes.Split(CouponSeparator).Except(new List { couponCode }).Distinct()); + return string.IsNullOrEmpty(existingCouponCodes) ? "" : string.Join(CouponSeparator, existingCouponCodes.Split(CouponSeparator).Except(new List { couponCode }).Distinct()); } /// @@ -209,17 +197,10 @@ public static string RemoveCouponCode(this Customer customer, string key, string /// Result public static bool IsPasswordRecoveryTokenValid(this Customer customer, string token) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); var cPrt = customer.GetUserFieldFromEntity(SystemCustomerFieldNames.PasswordRecoveryToken); - if (String.IsNullOrEmpty(cPrt)) - return false; - - if (!cPrt.Equals(token, StringComparison.OrdinalIgnoreCase)) - return false; - - return true; + return !string.IsNullOrEmpty(cPrt) && cPrt.Equals(token, StringComparison.OrdinalIgnoreCase); } /// @@ -230,11 +211,9 @@ public static bool IsPasswordRecoveryTokenValid(this Customer customer, string t /// Result public static bool IsPasswordRecoveryLinkExpired(this Customer customer, CustomerSettings customerSettings) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); - if (customerSettings == null) - throw new ArgumentNullException(nameof(customerSettings)); + ArgumentNullException.ThrowIfNull(customerSettings); if (customerSettings.PasswordRecoveryLinkDaysValid == 0) return false; @@ -244,10 +223,7 @@ public static bool IsPasswordRecoveryLinkExpired(this Customer customer, Custome return false; var daysPassed = (DateTime.UtcNow - geneatedDate.Value).TotalDays; - if (daysPassed > customerSettings.PasswordRecoveryLinkDaysValid) - return true; - - return false; + return daysPassed > customerSettings.PasswordRecoveryLinkDaysValid; } /// @@ -257,8 +233,7 @@ public static bool IsPasswordRecoveryLinkExpired(this Customer customer, Custome /// Customer group identifiers public static string[] GetCustomerGroupIds(this Customer customer) { - if (customer == null) - throw new ArgumentNullException(nameof(customer)); + ArgumentNullException.ThrowIfNull(customer); return customer.Groups.ToArray(); } diff --git a/src/Core/Grand.Domain/Orders/OrderExtensions.cs b/src/Core/Grand.Domain/Orders/OrderExtensions.cs index 1730d1782..57189cb62 100644 --- a/src/Core/Grand.Domain/Orders/OrderExtensions.cs +++ b/src/Core/Grand.Domain/Orders/OrderExtensions.cs @@ -94,8 +94,7 @@ public static bool IsLicenseDownloadAllowed(this Order order, OrderItem orderIte /// A value indicating whether an order has items to be added to a shipment public static bool HasItemsToAddToShipment(this Order order) { - if (order == null) - throw new ArgumentNullException(nameof(order)); + ArgumentNullException.ThrowIfNull(order); foreach (var orderItem in order.OrderItems) { @@ -120,8 +119,7 @@ public static bool HasItemsToAddToShipment(this Order order) /// Result public static bool OrderTagExists(this Order order, OrderTag orderTag) { - if (order == null) - throw new ArgumentNullException(nameof(order)); + ArgumentNullException.ThrowIfNull(order); var result = order.OrderTags.FirstOrDefault(t => t == orderTag.Id) != null; return result; diff --git a/src/Core/Grand.Domain/PagedList.cs b/src/Core/Grand.Domain/PagedList.cs index c5a14efa2..36ea6d6d0 100644 --- a/src/Core/Grand.Domain/PagedList.cs +++ b/src/Core/Grand.Domain/PagedList.cs @@ -10,8 +10,7 @@ public class PagedList : List, IPagedList private void Initialize(IEnumerable source, int pageIndex, int pageSize, int? totalCount = null) { - if (source == null) - throw new ArgumentNullException(nameof(source)); + ArgumentNullException.ThrowIfNull(source); if (pageSize <= 0) pageSize = 1; @@ -46,8 +45,7 @@ public PagedList(IEnumerable source, int pageIndex, int pageSize, int totalCo private Task InitializeAsync(IQueryable source, int pageIndex, int pageSize, int? totalCount = null) { - if (source == null) - throw new ArgumentNullException(nameof(source)); + ArgumentNullException.ThrowIfNull(source); if (pageSize <= 0) pageSize = 1; diff --git a/src/Core/Grand.Domain/Stores/StoreExtensions.cs b/src/Core/Grand.Domain/Stores/StoreExtensions.cs index c22ca2bb1..32a8f8487 100644 --- a/src/Core/Grand.Domain/Stores/StoreExtensions.cs +++ b/src/Core/Grand.Domain/Stores/StoreExtensions.cs @@ -10,8 +10,7 @@ public static class StoreExtensions /// true - contains, false - no public static bool ContainsHostValue(this Store store, string host) { - if (store == null) - throw new ArgumentNullException(nameof(store)); + ArgumentNullException.ThrowIfNull(store); if (string.IsNullOrEmpty(host)) return false; @@ -28,13 +27,8 @@ public static bool ContainsHostValue(this Store store, string host) /// DomainHost public static DomainHost HostValue(this Store store, string host) { - if (store == null) - throw new ArgumentNullException(nameof(store)); - - if (string.IsNullOrEmpty(host)) - return null; - - return store.Domains.FirstOrDefault(x => x.HostName.Equals(host, StringComparison.OrdinalIgnoreCase)); + ArgumentNullException.ThrowIfNull(store); + return string.IsNullOrEmpty(host) ? null : store.Domains.FirstOrDefault(x => x.HostName.Equals(host, StringComparison.OrdinalIgnoreCase)); } } } diff --git a/src/Core/Grand.Infrastructure/Roslyn/RoslynCompiler.cs b/src/Core/Grand.Infrastructure/Roslyn/RoslynCompiler.cs index 22076ee0f..04914ecca 100644 --- a/src/Core/Grand.Infrastructure/Roslyn/RoslynCompiler.cs +++ b/src/Core/Grand.Infrastructure/Roslyn/RoslynCompiler.cs @@ -29,15 +29,11 @@ public static class RoslynCompiler public static void Load(ApplicationPartManager applicationPartManager, IConfiguration configuration) { + ArgumentNullException.ThrowIfNull(applicationPartManager); + var config = new ExtensionsConfig(); configuration.GetSection("Extensions").Bind(config); - if (applicationPartManager == null) - throw new ArgumentNullException(nameof(applicationPartManager)); - - if (config == null) - throw new ArgumentNullException(nameof(config)); - if (!config.UseRoslynScripts) return; diff --git a/src/Core/Grand.Infrastructure/StartupBase.cs b/src/Core/Grand.Infrastructure/StartupBase.cs index 5a501d2f9..ddcc41ad4 100644 --- a/src/Core/Grand.Infrastructure/StartupBase.cs +++ b/src/Core/Grand.Infrastructure/StartupBase.cs @@ -106,11 +106,8 @@ private static void RegisterValidatorConsumer(IServiceCollection services, IType private static T StartupConfig(this IServiceCollection services, IConfiguration configuration) where T : class, new() { - if (services == null) - throw new ArgumentNullException(nameof(services)); - - if (configuration == null) - throw new ArgumentNullException(nameof(configuration)); + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(configuration); var config = new T(); configuration.Bind(config); diff --git a/src/Plugins/DiscountRules.Standard/Providers/CustomerGroupDiscountRule.cs b/src/Plugins/DiscountRules.Standard/Providers/CustomerGroupDiscountRule.cs index bac6007c1..0fd5bebcf 100644 --- a/src/Plugins/DiscountRules.Standard/Providers/CustomerGroupDiscountRule.cs +++ b/src/Plugins/DiscountRules.Standard/Providers/CustomerGroupDiscountRule.cs @@ -12,8 +12,7 @@ public class CustomerGroupDiscountRule : IDiscountRule /// true - requirement is met; otherwise, false public async Task CheckRequirement(DiscountRuleValidationRequest request) { - if (request == null) - throw new ArgumentNullException(nameof(request)); + ArgumentNullException.ThrowIfNull(request); //invalid by default var result = new DiscountRuleValidationResult(); diff --git a/src/Plugins/DiscountRules.Standard/Providers/HadSpentAmountDiscountRule.cs b/src/Plugins/DiscountRules.Standard/Providers/HadSpentAmountDiscountRule.cs index b8aaa147f..0f85cd95e 100644 --- a/src/Plugins/DiscountRules.Standard/Providers/HadSpentAmountDiscountRule.cs +++ b/src/Plugins/DiscountRules.Standard/Providers/HadSpentAmountDiscountRule.cs @@ -24,8 +24,7 @@ public HadSpentAmountDiscountRule(IOrderService orderService, ITranslationServic /// true - requirement is met; otherwise, false public async Task CheckRequirement(DiscountRuleValidationRequest request) { - if (request == null) - throw new ArgumentNullException(nameof(request)); + ArgumentNullException.ThrowIfNull(request); //invalid by default var result = new DiscountRuleValidationResult(); diff --git a/src/Plugins/DiscountRules.Standard/Providers/HasAllProductsDiscountRule.cs b/src/Plugins/DiscountRules.Standard/Providers/HasAllProductsDiscountRule.cs index 0a78bd28a..9f6883fbd 100644 --- a/src/Plugins/DiscountRules.Standard/Providers/HasAllProductsDiscountRule.cs +++ b/src/Plugins/DiscountRules.Standard/Providers/HasAllProductsDiscountRule.cs @@ -20,8 +20,7 @@ public HasAllProductsDiscountRule(ShoppingCartSettings shoppingCartSettings) /// true - requirement is met; otherwise, false public async Task CheckRequirement(DiscountRuleValidationRequest request) { - if (request == null) - throw new ArgumentNullException(nameof(request)); + ArgumentNullException.ThrowIfNull(request); //invalid by default var result = new DiscountRuleValidationResult(); diff --git a/src/Plugins/DiscountRules.Standard/Providers/HasOneProductDiscountRule.cs b/src/Plugins/DiscountRules.Standard/Providers/HasOneProductDiscountRule.cs index af724d510..6e6dd1019 100644 --- a/src/Plugins/DiscountRules.Standard/Providers/HasOneProductDiscountRule.cs +++ b/src/Plugins/DiscountRules.Standard/Providers/HasOneProductDiscountRule.cs @@ -20,8 +20,7 @@ public HasOneProductDiscountRule(ShoppingCartSettings shoppingCartSettings) /// true - requirement is met; otherwise, false public async Task CheckRequirement(DiscountRuleValidationRequest request) { - if (request == null) - throw new ArgumentNullException(nameof(request)); + ArgumentNullException.ThrowIfNull(request); //invalid by default var result = new DiscountRuleValidationResult(); diff --git a/src/Plugins/DiscountRules.Standard/Providers/ShoppingCartDiscountRule.cs b/src/Plugins/DiscountRules.Standard/Providers/ShoppingCartDiscountRule.cs index ff19ec0a1..0de79ba08 100644 --- a/src/Plugins/DiscountRules.Standard/Providers/ShoppingCartDiscountRule.cs +++ b/src/Plugins/DiscountRules.Standard/Providers/ShoppingCartDiscountRule.cs @@ -35,8 +35,7 @@ public ShoppingCartDiscountRule( /// true - requirement is met; otherwise, false public async Task CheckRequirement(DiscountRuleValidationRequest request) { - if (request == null) - throw new ArgumentNullException(nameof(request)); + ArgumentNullException.ThrowIfNull(request); var result = new DiscountRuleValidationResult(); diff --git a/src/Plugins/Payments.BrainTree/BrainTreePaymentProvider.cs b/src/Plugins/Payments.BrainTree/BrainTreePaymentProvider.cs index 1c3c38d6b..6d894cd1a 100644 --- a/src/Plugins/Payments.BrainTree/BrainTreePaymentProvider.cs +++ b/src/Plugins/Payments.BrainTree/BrainTreePaymentProvider.cs @@ -295,8 +295,7 @@ public Task CancelPayment(PaymentTransaction paymentTransaction) /// Result public async Task CanRePostRedirectPayment(PaymentTransaction paymentTransaction) { - if (paymentTransaction == null) - throw new ArgumentNullException(nameof(paymentTransaction)); + ArgumentNullException.ThrowIfNull(paymentTransaction); //it's not a redirection payment method. So we always return false return await Task.FromResult(false); diff --git a/src/Plugins/Payments.CashOnDelivery/CashOnDeliveryPaymentProvider.cs b/src/Plugins/Payments.CashOnDelivery/CashOnDeliveryPaymentProvider.cs index 87c4c493e..38cd4730c 100644 --- a/src/Plugins/Payments.CashOnDelivery/CashOnDeliveryPaymentProvider.cs +++ b/src/Plugins/Payments.CashOnDelivery/CashOnDeliveryPaymentProvider.cs @@ -132,8 +132,7 @@ public async Task Capture(PaymentTransaction paymentTransa public async Task CanRePostRedirectPayment(PaymentTransaction paymentTransaction) { - if (paymentTransaction == null) - throw new ArgumentNullException(nameof(paymentTransaction)); + ArgumentNullException.ThrowIfNull(paymentTransaction); //it's not a redirection payment method. So we always return false return await Task.FromResult(false); diff --git a/src/Plugins/Shipping.ByWeight/ByWeightShippingProvider.cs b/src/Plugins/Shipping.ByWeight/ByWeightShippingProvider.cs index 72fe6f76d..c20d0ac2a 100644 --- a/src/Plugins/Shipping.ByWeight/ByWeightShippingProvider.cs +++ b/src/Plugins/Shipping.ByWeight/ByWeightShippingProvider.cs @@ -106,8 +106,7 @@ public ByWeightShippingCalcPlugin( /// Shopping cart item weight private async Task GetShoppingCartItemWeight(ShoppingCartItem shoppingCartItem) { - if (shoppingCartItem == null) - throw new ArgumentNullException(nameof(shoppingCartItem)); + ArgumentNullException.ThrowIfNull(shoppingCartItem); var product = await _productService.GetProductById(shoppingCartItem.ProductId); if (product == null) @@ -152,8 +151,7 @@ private async Task GetShoppingCartItemWeight(ShoppingCartItem shoppingCa /// Total weight private async Task GetTotalWeight(GetShippingOptionRequest request, bool includeCheckoutAttributes = true) { - if (request == null) - throw new ArgumentNullException(nameof(request)); + ArgumentNullException.ThrowIfNull(request); Customer customer = request.Customer; @@ -185,8 +183,7 @@ private async Task GetTotalWeight(GetShippingOptionRequest request, bool /// Represents a response of getting shipping rate options public async Task GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest) { - if (getShippingOptionRequest == null) - throw new ArgumentNullException(nameof(getShippingOptionRequest)); + ArgumentNullException.ThrowIfNull(getShippingOptionRequest); var response = new GetShippingOptionResponse(); diff --git a/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs b/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs index ea6328025..a847ade3e 100644 --- a/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs +++ b/src/Plugins/Shipping.ByWeight/Services/ShippingByWeightService.cs @@ -34,8 +34,7 @@ public ShippingByWeightService(ICacheBase cacheBase, public virtual async Task DeleteShippingByWeightRecord(ShippingByWeightRecord shippingByWeightRecord) { - if (shippingByWeightRecord == null) - throw new ArgumentNullException(nameof(shippingByWeightRecord)); + ArgumentNullException.ThrowIfNull(shippingByWeightRecord); await _sbwRepository.DeleteAsync(shippingByWeightRecord); @@ -101,8 +100,7 @@ public virtual Task GetById(string shippingByWeightRecor public virtual async Task InsertShippingByWeightRecord(ShippingByWeightRecord shippingByWeightRecord) { - if (shippingByWeightRecord == null) - throw new ArgumentNullException(nameof(shippingByWeightRecord)); + ArgumentNullException.ThrowIfNull(shippingByWeightRecord); await _sbwRepository.InsertAsync(shippingByWeightRecord); @@ -111,8 +109,7 @@ public virtual async Task InsertShippingByWeightRecord(ShippingByWeightRecord sh public virtual async Task UpdateShippingByWeightRecord(ShippingByWeightRecord shippingByWeightRecord) { - if (shippingByWeightRecord == null) - throw new ArgumentNullException(nameof(shippingByWeightRecord)); + ArgumentNullException.ThrowIfNull(shippingByWeightRecord); await _sbwRepository.UpdateAsync(shippingByWeightRecord); diff --git a/src/Plugins/Shipping.FixedRateShipping/FixedRateShippingProvider.cs b/src/Plugins/Shipping.FixedRateShipping/FixedRateShippingProvider.cs index e8fc51e3d..d1e3d2f68 100644 --- a/src/Plugins/Shipping.FixedRateShipping/FixedRateShippingProvider.cs +++ b/src/Plugins/Shipping.FixedRateShipping/FixedRateShippingProvider.cs @@ -58,8 +58,7 @@ private double GetRate(string shippingMethodId) /// Represents a response of getting shipping rate options public async Task GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest) { - if (getShippingOptionRequest == null) - throw new ArgumentNullException(nameof(getShippingOptionRequest)); + ArgumentNullException.ThrowIfNull(getShippingOptionRequest); var response = new GetShippingOptionResponse(); @@ -92,8 +91,7 @@ public async Task GetShippingOptions(GetShippingOptio /// Fixed shipping rate; or null in case there's no fixed shipping rate public async Task GetFixedRate(GetShippingOptionRequest getShippingOptionRequest) { - if (getShippingOptionRequest == null) - throw new ArgumentNullException(nameof(getShippingOptionRequest)); + ArgumentNullException.ThrowIfNull(getShippingOptionRequest); var restrictByCountryId = getShippingOptionRequest.ShippingAddress != null && !string.IsNullOrEmpty(getShippingOptionRequest.ShippingAddress.CountryId) ? getShippingOptionRequest.ShippingAddress.CountryId : ""; var shippingMethods = await _shippingMethodService.GetAllShippingMethods(restrictByCountryId); diff --git a/src/Plugins/Shipping.ShippingPoint/Services/ShippingPointService.cs b/src/Plugins/Shipping.ShippingPoint/Services/ShippingPointService.cs index 44c69f0a2..e152ac84f 100644 --- a/src/Plugins/Shipping.ShippingPoint/Services/ShippingPointService.cs +++ b/src/Plugins/Shipping.ShippingPoint/Services/ShippingPointService.cs @@ -85,8 +85,7 @@ public virtual Task GetStoreShippingPointById(string pickupPoint /// Pickup point public virtual async Task InsertStoreShippingPoint(ShippingPoints pickupPoint) { - if (pickupPoint == null) - throw new ArgumentNullException(nameof(pickupPoint)); + ArgumentNullException.ThrowIfNull(pickupPoint); await _shippingPointRepository.InsertAsync(pickupPoint); await _cacheBase.RemoveByPrefix(PICKUP_POINT_PATTERN_KEY); @@ -98,8 +97,7 @@ public virtual async Task InsertStoreShippingPoint(ShippingPoints pickupPoint) /// Pickup point public virtual async Task UpdateStoreShippingPoint(ShippingPoints pickupPoint) { - if (pickupPoint == null) - throw new ArgumentNullException(nameof(pickupPoint)); + ArgumentNullException.ThrowIfNull(pickupPoint); await _shippingPointRepository.UpdateAsync(pickupPoint); await _cacheBase.RemoveByPrefix(PICKUP_POINT_PATTERN_KEY); @@ -111,8 +109,7 @@ public virtual async Task UpdateStoreShippingPoint(ShippingPoints pickupPoint) /// Pickup point public virtual async Task DeleteStoreShippingPoint(ShippingPoints pickupPoint) { - if (pickupPoint == null) - throw new ArgumentNullException(nameof(pickupPoint)); + ArgumentNullException.ThrowIfNull(pickupPoint); await _shippingPointRepository.DeleteAsync(pickupPoint); await _cacheBase.RemoveByPrefix(PICKUP_POINT_PATTERN_KEY); diff --git a/src/Plugins/Shipping.ShippingPoint/ShippingPointRateProvider.cs b/src/Plugins/Shipping.ShippingPoint/ShippingPointRateProvider.cs index 1c791fb03..c1b35613b 100644 --- a/src/Plugins/Shipping.ShippingPoint/ShippingPointRateProvider.cs +++ b/src/Plugins/Shipping.ShippingPoint/ShippingPointRateProvider.cs @@ -58,8 +58,7 @@ ShippingPointRateSettings shippingPointRateSettings /// Represents a response of getting shipping rate options public async Task GetShippingOptions(GetShippingOptionRequest getShippingOptionRequest) { - if (getShippingOptionRequest == null) - throw new ArgumentNullException(nameof(getShippingOptionRequest)); + ArgumentNullException.ThrowIfNull(getShippingOptionRequest); var response = new GetShippingOptionResponse(); diff --git a/src/Plugins/Tax.CountryStateZip/Infrastructure/Cache/ModelCacheEventConsumer.cs b/src/Plugins/Tax.CountryStateZip/Infrastructure/Cache/ModelCacheEventConsumer.cs index c5aaf19c9..a9be130ef 100644 --- a/src/Plugins/Tax.CountryStateZip/Infrastructure/Cache/ModelCacheEventConsumer.cs +++ b/src/Plugins/Tax.CountryStateZip/Infrastructure/Cache/ModelCacheEventConsumer.cs @@ -1,7 +1,6 @@ using Grand.Infrastructure.Caching; using Grand.Infrastructure.Events; using MediatR; -using Microsoft.Extensions.DependencyInjection; using Tax.CountryStateZip.Domain; namespace Tax.CountryStateZip.Infrastructure.Cache diff --git a/src/Plugins/Tax.CountryStateZip/Services/TaxRateService.cs b/src/Plugins/Tax.CountryStateZip/Services/TaxRateService.cs index 8311011a5..7bcab898c 100644 --- a/src/Plugins/Tax.CountryStateZip/Services/TaxRateService.cs +++ b/src/Plugins/Tax.CountryStateZip/Services/TaxRateService.cs @@ -52,8 +52,7 @@ public TaxRateService(IMediator mediator, /// Tax rate public virtual async Task DeleteTaxRate(TaxRate taxRate) { - if (taxRate == null) - throw new ArgumentNullException(nameof(taxRate)); + ArgumentNullException.ThrowIfNull(taxRate); await _taxRateRepository.DeleteAsync(taxRate); @@ -95,8 +94,7 @@ public virtual Task GetTaxRateById(string taxRateId) /// Tax rate public virtual async Task InsertTaxRate(TaxRate taxRate) { - if (taxRate == null) - throw new ArgumentNullException(nameof(taxRate)); + ArgumentNullException.ThrowIfNull(taxRate); await _taxRateRepository.InsertAsync(taxRate); @@ -112,8 +110,7 @@ public virtual async Task InsertTaxRate(TaxRate taxRate) /// Tax rate public virtual async Task UpdateTaxRate(TaxRate taxRate) { - if (taxRate == null) - throw new ArgumentNullException(nameof(taxRate)); + ArgumentNullException.ThrowIfNull(taxRate); await _taxRateRepository.UpdateAsync(taxRate); diff --git a/src/Plugins/Theme.Modern/Views/Modern/Account/AddressAdd.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Account/AddressAdd.cshtml index 28e65128e..b5e1cf3a1 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Account/AddressAdd.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Account/AddressAdd.cshtml @@ -1,5 +1,4 @@ @model CustomerAddressEditModel -@using Grand.Web.Models.Customer; @inject IPageHeadBuilder pagebuilder @{ Layout = "_TwoColumns"; diff --git a/src/Plugins/Theme.Modern/Views/Modern/Account/AddressEdit.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Account/AddressEdit.cshtml index 700e04bad..d926e202f 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Account/AddressEdit.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Account/AddressEdit.cshtml @@ -1,5 +1,4 @@ @model CustomerAddressEditModel -@using Grand.Web.Models.Customer; @inject IPageHeadBuilder pagebuilder @{ Layout = "_TwoColumns"; diff --git a/src/Plugins/Theme.Modern/Views/Modern/Account/Addresses.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Account/Addresses.cshtml index c177c962b..6ad92a4bb 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Account/Addresses.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Account/Addresses.cshtml @@ -1,5 +1,4 @@ @model CustomerAddressListModel -@using Grand.Web.Models.Customer; @inject IPageHeadBuilder pagebuilder @{ Layout = "_TwoColumns"; diff --git a/src/Plugins/Theme.Modern/Views/Modern/Account/Auctions.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Account/Auctions.cshtml index 02d186294..fd5d3c7e3 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Account/Auctions.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Account/Auctions.cshtml @@ -1,5 +1,4 @@ @model CustomerAuctionsModel -@using Grand.Web.Models.Customer; @inject IPageHeadBuilder pagebuilder @{ Layout = "_TwoColumns"; diff --git a/src/Plugins/Theme.Modern/Views/Modern/Account/ChangePassword.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Account/ChangePassword.cshtml index bcbfb0a10..87248a7d2 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Account/ChangePassword.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Account/ChangePassword.cshtml @@ -1,5 +1,4 @@ @model ChangePasswordModel -@using Grand.Web.Models.Customer; @inject IPageHeadBuilder pagebuilder @{ Layout = "_TwoColumns"; diff --git a/src/Plugins/Theme.Modern/Views/Modern/Account/Courses.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Account/Courses.cshtml index cb21246da..9ea461fd6 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Account/Courses.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Account/Courses.cshtml @@ -1,5 +1,4 @@ @model CoursesModel -@using Grand.Web.Models.Customer; @inject IPageHeadBuilder pagebuilder @{ Layout = "_TwoColumns"; diff --git a/src/Plugins/Theme.Modern/Views/Modern/Account/DeleteAccount.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Account/DeleteAccount.cshtml index c273944fb..c80546d43 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Account/DeleteAccount.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Account/DeleteAccount.cshtml @@ -1,5 +1,4 @@ @model DeleteAccountModel -@using Grand.Web.Models.Customer; @inject IPageHeadBuilder pagebuilder @{ Layout = "_TwoColumns"; diff --git a/src/Plugins/Theme.Modern/Views/Modern/Account/Documents.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Account/Documents.cshtml index 5743175e6..70afa183f 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Account/Documents.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Account/Documents.cshtml @@ -1,5 +1,4 @@ @model DocumentsModel -@using Grand.Web.Models.Customer; @inject IPageHeadBuilder pagebuilder @{ Layout = "_TwoColumns"; diff --git a/src/Plugins/Theme.Modern/Views/Modern/Account/DownloadableProducts.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Account/DownloadableProducts.cshtml index 6bdad2c96..9dc54690a 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Account/DownloadableProducts.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Account/DownloadableProducts.cshtml @@ -1,5 +1,4 @@ @model CustomerDownloadableProductsModel -@using Grand.Web.Models.Customer; @inject IPageHeadBuilder pagebuilder @{ Layout = "_TwoColumns"; diff --git a/src/Plugins/Theme.Modern/Views/Modern/Account/Notes.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Account/Notes.cshtml index 19c61a16f..f416b1cbf 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Account/Notes.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Account/Notes.cshtml @@ -1,5 +1,4 @@ @model CustomerNotesModel -@using Grand.Web.Models.Customer; @inject IPageHeadBuilder pagebuilder @{ Layout = "_TwoColumns"; diff --git a/src/Plugins/Theme.Modern/Views/Modern/Account/PasswordRecovery.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Account/PasswordRecovery.cshtml index 82ffbd213..0719ea65a 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Account/PasswordRecovery.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Account/PasswordRecovery.cshtml @@ -1,5 +1,4 @@ @model PasswordRecoveryModel -@using Grand.Web.Models.Customer; @inject IPageHeadBuilder pagebuilder @{ Layout = "_SingleColumn"; diff --git a/src/Plugins/Theme.Modern/Views/Modern/Account/Reviews.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Account/Reviews.cshtml index 0274bc81e..687b11b4d 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Account/Reviews.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Account/Reviews.cshtml @@ -1,5 +1,4 @@ @model CustomerProductReviewsModel -@using Grand.Web.Models.Customer; @inject IPageHeadBuilder pagebuilder @{ Layout = "_TwoColumns"; diff --git a/src/Plugins/Theme.Modern/Views/Modern/Account/SubAccountAdd.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Account/SubAccountAdd.cshtml index f88c3934b..635148af5 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Account/SubAccountAdd.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Account/SubAccountAdd.cshtml @@ -1,5 +1,4 @@ @model SubAccountCreateModel -@using Grand.Web.Models.Customer; @inject IPageHeadBuilder pagebuilder @{ Layout = "_TwoColumns"; diff --git a/src/Plugins/Theme.Modern/Views/Modern/Account/SubAccountEdit.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Account/SubAccountEdit.cshtml index c3cc10bf9..cb464f99c 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Account/SubAccountEdit.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Account/SubAccountEdit.cshtml @@ -1,5 +1,4 @@ @model SubAccountEditModel -@using Grand.Web.Models.Customer; @inject IPageHeadBuilder pagebuilder @{ Layout = "_TwoColumns"; diff --git a/src/Plugins/Theme.Modern/Views/Modern/Account/SubAccounts.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Account/SubAccounts.cshtml index 2d201fbc9..080d13137 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Account/SubAccounts.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Account/SubAccounts.cshtml @@ -1,6 +1,5 @@ @model IList - @using Grand.Web.Models.Customer; - @inject IPageHeadBuilder pagebuilder +@inject IPageHeadBuilder pagebuilder @{ Layout = "_TwoColumns"; diff --git a/src/Plugins/Theme.Modern/Views/Modern/Blog/BlogPost.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Blog/BlogPost.cshtml index 68cc34273..91d183f5a 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Blog/BlogPost.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Blog/BlogPost.cshtml @@ -1,5 +1,4 @@ @model BlogPostModel -@using Grand.Web.Models.Blogs; @inject IWorkContext workContext @inject IPageHeadBuilder pagebuilder @{ diff --git a/src/Plugins/Theme.Modern/Views/Modern/Blog/Components/BlogCategories/Default.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Blog/Components/BlogCategories/Default.cshtml index 8158a8f35..7147f1af0 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Blog/Components/BlogCategories/Default.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Blog/Components/BlogCategories/Default.cshtml @@ -1,5 +1,4 @@ @model IList -@using Grand.Web.Models.Blogs @if (Model.Any()) {
diff --git a/src/Plugins/Theme.Modern/Views/Modern/Blog/Components/BlogMonths/Default.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Blog/Components/BlogMonths/Default.cshtml index 8c1f23956..418ec2849 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Blog/Components/BlogMonths/Default.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Blog/Components/BlogMonths/Default.cshtml @@ -1,5 +1,4 @@ @model IList -@using Grand.Web.Models.Blogs; @if (Model.Any()) {
diff --git a/src/Plugins/Theme.Modern/Views/Modern/Blog/Components/BlogTags/Default.cshtml b/src/Plugins/Theme.Modern/Views/Modern/Blog/Components/BlogTags/Default.cshtml index a8b33a2ce..3d950f231 100644 --- a/src/Plugins/Theme.Modern/Views/Modern/Blog/Components/BlogTags/Default.cshtml +++ b/src/Plugins/Theme.Modern/Views/Modern/Blog/Components/BlogTags/Default.cshtml @@ -1,5 +1,4 @@ @model BlogPostTagListModel -@using Grand.Web.Models.Blogs @if (Model.Tags.Any()) {