From 16021162d6de01786701f52ae6b743a1eaefa133 Mon Sep 17 00:00:00 2001 From: support Date: Wed, 25 Nov 2026 07:39:50 +0100 Subject: [PATCH 01/30] Keep validation in FluentValidation when model projects enable nullable MVC turns every non-nullable reference property of a nullable-enabled project into an implicit [Required]. GrandNode validates through FluentValidation, so the implicit attribute would reject forms that pass today. --- src/Core/Grand.Infrastructure/StartupBase.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Core/Grand.Infrastructure/StartupBase.cs b/src/Core/Grand.Infrastructure/StartupBase.cs index 3e0c8aa5a..d84ea2e73 100644 --- a/src/Core/Grand.Infrastructure/StartupBase.cs +++ b/src/Core/Grand.Infrastructure/StartupBase.cs @@ -205,6 +205,9 @@ private static IMvcCoreBuilder RegisterApplication(IServiceCollection services, var mvcCoreBuilder = services.AddMvcCore(options => { options.Filters.AddService(); + //validation rules live in FluentValidation validators - a non-nullable reference property + //must not become an implicit [Required] just because its project has nullable enabled + options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true; var frontConfig = new FrontendAPIConfig(); configuration.GetSection("FrontendAPI").Bind(frontConfig); if (frontConfig.JsonContentType) From c0ab93352af4c3b569d3e98823a63c6e6feb9fc2 Mon Sep 17 00:00:00 2001 From: support Date: Wed, 25 Nov 2026 07:46:47 +0100 Subject: [PATCH 02/30] Enable nullable in Grand.SharedKernel, Grand.Mediator and Grand.Mapping --- src/Core/Grand.Mapping/Grand.Mapping.csproj | 3 +++ src/Core/Grand.Mediator/Grand.Mediator.csproj | 3 +++ src/Core/Grand.Mediator/IMediator.cs | 2 +- .../Grand.Mediator/Internal/RequestHandlerWrapper.cs | 6 +++--- src/Core/Grand.Mediator/Mediator.cs | 4 ++-- .../MediatorServiceCollectionExtensions.cs | 2 +- src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs | 10 +++++----- .../Grand.SharedKernel/Extensions/XmlExtensions.cs | 4 ++-- src/Core/Grand.SharedKernel/Grand.SharedKernel.csproj | 3 +++ 9 files changed, 23 insertions(+), 14 deletions(-) diff --git a/src/Core/Grand.Mapping/Grand.Mapping.csproj b/src/Core/Grand.Mapping/Grand.Mapping.csproj index b9b0d198f..c7cd47824 100644 --- a/src/Core/Grand.Mapping/Grand.Mapping.csproj +++ b/src/Core/Grand.Mapping/Grand.Mapping.csproj @@ -1,3 +1,6 @@ + + enable + diff --git a/src/Core/Grand.Mediator/Grand.Mediator.csproj b/src/Core/Grand.Mediator/Grand.Mediator.csproj index 6f9930b85..26b18adb5 100644 --- a/src/Core/Grand.Mediator/Grand.Mediator.csproj +++ b/src/Core/Grand.Mediator/Grand.Mediator.csproj @@ -3,4 +3,7 @@ + + enable + diff --git a/src/Core/Grand.Mediator/IMediator.cs b/src/Core/Grand.Mediator/IMediator.cs index d48c0bbcf..9aa1b2061 100644 --- a/src/Core/Grand.Mediator/IMediator.cs +++ b/src/Core/Grand.Mediator/IMediator.cs @@ -28,7 +28,7 @@ public interface IMediator /// Request /// Cancellation token /// Response from the handler, or null for a request returning no response - Task Send(object request, CancellationToken cancellationToken = default); + Task Send(object request, CancellationToken cancellationToken = default); /// /// Publishes a notification to all of its handlers, sequentially diff --git a/src/Core/Grand.Mediator/Internal/RequestHandlerWrapper.cs b/src/Core/Grand.Mediator/Internal/RequestHandlerWrapper.cs index 9f68eea51..13d98d706 100644 --- a/src/Core/Grand.Mediator/Internal/RequestHandlerWrapper.cs +++ b/src/Core/Grand.Mediator/Internal/RequestHandlerWrapper.cs @@ -7,7 +7,7 @@ namespace Grand.Mediator.Internal; /// internal abstract class RequestHandlerBase { - public abstract Task Handle(object request, IServiceProvider provider, + public abstract Task Handle(object request, IServiceProvider provider, CancellationToken cancellationToken); } @@ -29,7 +29,7 @@ public override Task HandleTyped(object request, IServiceProvider pro return Resolve(provider).Handle((TRequest)request, cancellationToken); } - public override async Task Handle(object request, IServiceProvider provider, + public override async Task Handle(object request, IServiceProvider provider, CancellationToken cancellationToken) { return await Resolve(provider).Handle((TRequest)request, cancellationToken); @@ -58,7 +58,7 @@ public override Task HandleVoid(object request, IServiceProvider provider, Cance return Resolve(provider).Handle((TRequest)request, cancellationToken); } - public override async Task Handle(object request, IServiceProvider provider, + public override async Task Handle(object request, IServiceProvider provider, CancellationToken cancellationToken) { await Resolve(provider).Handle((TRequest)request, cancellationToken); diff --git a/src/Core/Grand.Mediator/Mediator.cs b/src/Core/Grand.Mediator/Mediator.cs index 564a6bcfd..224d6bce5 100644 --- a/src/Core/Grand.Mediator/Mediator.cs +++ b/src/Core/Grand.Mediator/Mediator.cs @@ -50,7 +50,7 @@ public Task Send(TRequest request, CancellationToken cancellationToken return wrapper.HandleVoid(request, _provider, cancellationToken); } - public Task Send(object request, CancellationToken cancellationToken = default) + public Task Send(object request, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(request); @@ -104,7 +104,7 @@ private Task PublishNotification(object notification, CancellationToken cancella /// /// Returns the response type of a request, or null when the request returns none. /// - private static Type ResponseTypeOf(Type requestType) + private static Type? ResponseTypeOf(Type requestType) { foreach (var contract in requestType.GetInterfaces()) if (contract.IsGenericType && contract.GetGenericTypeDefinition() == typeof(IRequest<>)) diff --git a/src/Core/Grand.Mediator/MediatorServiceCollectionExtensions.cs b/src/Core/Grand.Mediator/MediatorServiceCollectionExtensions.cs index d9936f38b..f01c8fecd 100644 --- a/src/Core/Grand.Mediator/MediatorServiceCollectionExtensions.cs +++ b/src/Core/Grand.Mediator/MediatorServiceCollectionExtensions.cs @@ -75,7 +75,7 @@ private static IEnumerable GetTypes(Assembly assembly) } catch (ReflectionTypeLoadException ex) { - return ex.Types.Where(type => type != null); + return ex.Types.OfType(); } } } diff --git a/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs b/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs index ae6bb487d..eb418c231 100644 --- a/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs +++ b/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs @@ -82,7 +82,7 @@ public static int GenerateRandomInteger(int min = 0, int max = int.MaxValue) /// Maximum length /// A string to add to the end if the original string was shorten /// Input string if its lengh is OK; otherwise, truncated input string - public static string EnsureMaximumLength(string str, int maxLength, string postfix = null) + public static string EnsureMaximumLength(string str, int maxLength, string? postfix = null) { if (string.IsNullOrEmpty(str)) return str; @@ -170,7 +170,7 @@ public static bool IsSimpleType(Type type) /// The value to convert. /// The type to convert the value to. /// The converted value. - public static object To(object value, Type destinationType) + public static object? To(object value, Type destinationType) { return To(value, destinationType, CultureInfo.InvariantCulture); } @@ -182,7 +182,7 @@ public static object To(object value, Type destinationType) /// The type to convert the value to. /// Culture /// The converted value. - public static object To(object value, Type destinationType, CultureInfo culture) + public static object? To(object value, Type destinationType, CultureInfo culture) { if (value != null) { @@ -212,9 +212,9 @@ public static object To(object value, Type destinationType, CultureInfo culture) /// The value to convert. /// The type to convert the value to. /// The converted value. - public static T To(object value) + public static T? To(object value) { - return (T)To(value, typeof(T)); + return (T?)To(value, typeof(T)); } /// diff --git a/src/Core/Grand.SharedKernel/Extensions/XmlExtensions.cs b/src/Core/Grand.SharedKernel/Extensions/XmlExtensions.cs index 735bae91e..6f21b7039 100644 --- a/src/Core/Grand.SharedKernel/Extensions/XmlExtensions.cs +++ b/src/Core/Grand.SharedKernel/Extensions/XmlExtensions.cs @@ -21,9 +21,9 @@ public static XmlDocument LanguageXmlDocument(string xml) return xmlDoc; } - public static List<(string Name, string Value, string Area)> ParseTranslationResources(XmlDocument xmlDoc) + public static List<(string Name, string Value, string? Area)> ParseTranslationResources(XmlDocument xmlDoc) { - var resources = new List<(string Name, string Value, string Area)>(); + var resources = new List<(string Name, string Value, string? Area)>(); var nodes = xmlDoc.SelectNodes("//Language/Resource"); if (nodes != null) diff --git a/src/Core/Grand.SharedKernel/Grand.SharedKernel.csproj b/src/Core/Grand.SharedKernel/Grand.SharedKernel.csproj index 647a7c8d6..9db1bd6c9 100644 --- a/src/Core/Grand.SharedKernel/Grand.SharedKernel.csproj +++ b/src/Core/Grand.SharedKernel/Grand.SharedKernel.csproj @@ -1,3 +1,6 @@  + + enable + From 0e631f504809928ae5a9874b11b8b00ac5f43f14 Mon Sep 17 00:00:00 2001 From: support Date: Wed, 25 Nov 2026 07:51:27 +0100 Subject: [PATCH 03/30] Enable nullable in Grand.Domain Entity properties without a default are nullable: a document read from MongoDB may lack the field, so the type now says what the code already had to cope with. ParentEntity.Id stays non-null - its setter replaces null with a new identifier. Where a comparison dereferenced such a property it now uses string.Equals or ?., which gives the same result for every non-null value instead of throwing on null. --- src/Core/Grand.Domain/Admin/AdminSiteMap.cs | 12 +-- src/Core/Grand.Domain/Affiliates/Affiliate.cs | 8 +- src/Core/Grand.Domain/Audit/AuditChange.cs | 8 +- src/Core/Grand.Domain/Audit/AuditEntry.cs | 32 +++---- .../Audit/AuditReferenceAttribute.cs | 8 +- src/Core/Grand.Domain/AuditableEntity.cs | 4 +- src/Core/Grand.Domain/BaseEntity.cs | 4 +- src/Core/Grand.Domain/Blogs/BlogCategory.cs | 4 +- .../Grand.Domain/Blogs/BlogCategoryPost.cs | 2 +- src/Core/Grand.Domain/Blogs/BlogComment.cs | 10 +- src/Core/Grand.Domain/Blogs/BlogPost.cs | 18 ++-- src/Core/Grand.Domain/Blogs/BlogPostTag.cs | 2 +- src/Core/Grand.Domain/Blogs/BlogProduct.cs | 4 +- src/Core/Grand.Domain/Catalog/Bid.cs | 10 +- src/Core/Grand.Domain/Catalog/Brand.cs | 26 ++--- src/Core/Grand.Domain/Catalog/BrandLayout.cs | 4 +- .../Grand.Domain/Catalog/BundleProduct.cs | 2 +- .../Grand.Domain/Catalog/CatalogSettings.cs | 12 +-- src/Core/Grand.Domain/Catalog/Category.cs | 32 +++---- .../Grand.Domain/Catalog/CategoryLayout.cs | 4 +- src/Core/Grand.Domain/Catalog/Collection.cs | 26 ++--- .../Grand.Domain/Catalog/CollectionLayout.cs | 4 +- .../Grand.Domain/Catalog/CrossSellProduct.cs | 4 +- .../Catalog/CustomerReservationsHelper.cs | 6 +- .../Grand.Domain/Catalog/InventoryDocument.cs | 18 ++-- .../Catalog/InventoryDocumentLine.cs | 8 +- .../Grand.Domain/Catalog/InventoryJournal.cs | 24 ++--- .../Catalog/OutOfStockSubscription.cs | 10 +- .../PredefinedProductAttributeValue.cs | 2 +- src/Core/Grand.Domain/Catalog/Product.cs | 94 +++++++++---------- .../Catalog/ProductAlsoPurchased.cs | 8 +- .../Grand.Domain/Catalog/ProductAttribute.cs | 6 +- .../Catalog/ProductAttributeCombination.cs | 14 +-- .../Catalog/ProductAttributeMapping.cs | 10 +- .../Catalog/ProductAttributeValue.cs | 10 +- src/Core/Grand.Domain/Catalog/ProductBatch.cs | 26 ++--- .../Grand.Domain/Catalog/ProductCategory.cs | 2 +- .../Grand.Domain/Catalog/ProductCollection.cs | 2 +- .../Catalog/ProductCombinationTierPrices.cs | 4 +- .../ProductCombinationWarehouseInventory.cs | 2 +- .../Grand.Domain/Catalog/ProductExtensions.cs | 22 ++--- .../Grand.Domain/Catalog/ProductLayout.cs | 4 +- .../Grand.Domain/Catalog/ProductPicture.cs | 2 +- src/Core/Grand.Domain/Catalog/ProductPrice.cs | 4 +- .../Catalog/ProductReservation.cs | 10 +- .../Grand.Domain/Catalog/ProductReview.cs | 16 ++-- .../Catalog/ProductReviewHelpfulness.cs | 4 +- .../Catalog/ProductSerialNumber.cs | 34 +++---- .../Catalog/ProductSpecificationAttribute.cs | 8 +- src/Core/Grand.Domain/Catalog/ProductTag.cs | 4 +- .../Catalog/ProductWarehouseInventory.cs | 2 +- .../Catalog/RecentlyViewedProduct.cs | 4 +- .../Grand.Domain/Catalog/RelatedProduct.cs | 2 +- .../Grand.Domain/Catalog/SimilarProduct.cs | 4 +- .../Catalog/SpecificationAttribute.cs | 6 +- .../Catalog/SpecificationAttributeOption.cs | 6 +- .../SpecificationAttributeOptionFilter.cs | 14 +-- src/Core/Grand.Domain/Catalog/TierPrice.cs | 6 +- src/Core/Grand.Domain/Common/Address.cs | 30 +++--- .../Grand.Domain/Common/AddressAttribute.cs | 4 +- .../Common/AddressAttributeValue.cs | 4 +- .../Grand.Domain/Common/AddressExtensions.cs | 2 +- .../Grand.Domain/Common/AdminAreaSettings.cs | 2 +- .../Grand.Domain/Common/CaptchaSettings.cs | 8 +- .../Grand.Domain/Common/CustomAttribute.cs | 4 +- .../Grand.Domain/Common/GrandNodeVersion.cs | 4 +- src/Core/Grand.Domain/Common/PdfSettings.cs | 6 +- src/Core/Grand.Domain/Common/RobotsTxt.cs | 6 +- src/Core/Grand.Domain/Common/SearchTerm.cs | 4 +- src/Core/Grand.Domain/Common/UserField.cs | 6 +- .../Common/UserFieldExtensions.cs | 4 +- .../Grand.Domain/Configuration/Setting.cs | 6 +- src/Core/Grand.Domain/Courses/Course.cs | 20 ++-- src/Core/Grand.Domain/Courses/CourseAction.cs | 6 +- src/Core/Grand.Domain/Courses/CourseLesson.cs | 16 ++-- src/Core/Grand.Domain/Courses/CourseLevel.cs | 2 +- .../Grand.Domain/Courses/CourseSubject.cs | 4 +- src/Core/Grand.Domain/Customers/Customer.cs | 42 ++++----- .../Customers/CustomerAttribute.cs | 4 +- .../Customers/CustomerAttributeValue.cs | 4 +- .../Customers/CustomerExtensions.cs | 2 +- .../Grand.Domain/Customers/CustomerGroup.cs | 4 +- .../Customers/CustomerGroupProduct.cs | 4 +- .../Customers/CustomerHistoryPassword.cs | 6 +- .../Grand.Domain/Customers/CustomerNote.cs | 8 +- .../Grand.Domain/Customers/CustomerProduct.cs | 4 +- .../Customers/CustomerProductPrice.cs | 4 +- .../Customers/CustomerSettings.cs | 2 +- .../Grand.Domain/Customers/CustomerTag.cs | 2 +- .../Customers/CustomerTagProduct.cs | 4 +- .../Customers/ExternalAuthentication.cs | 14 +-- .../Customers/OidcLinkSettings.cs | 2 +- .../Grand.Domain/Customers/OidcSession.cs | 12 +-- .../Customers/OidcTokenRevocation.cs | 2 +- .../Grand.Domain/Customers/SalesEmployee.cs | 6 +- src/Core/Grand.Domain/Customers/ScimGroup.cs | 10 +- src/Core/Grand.Domain/Customers/ScimUser.cs | 6 +- src/Core/Grand.Domain/Customers/UserApi.cs | 8 +- src/Core/Grand.Domain/Directory/Country.cs | 8 +- src/Core/Grand.Domain/Directory/Currency.cs | 8 +- .../Directory/CurrencySettings.cs | 6 +- .../Directory/DateTimeSettings.cs | 2 +- .../Directory/MeasureDimension.cs | 4 +- .../Grand.Domain/Directory/MeasureSettings.cs | 4 +- .../Grand.Domain/Directory/MeasureUnit.cs | 2 +- .../Grand.Domain/Directory/MeasureWeight.cs | 4 +- .../Grand.Domain/Directory/StateProvince.cs | 4 +- src/Core/Grand.Domain/Discounts/Discount.cs | 8 +- .../Grand.Domain/Discounts/DiscountCoupon.cs | 4 +- .../Grand.Domain/Discounts/DiscountRule.cs | 4 +- .../Discounts/DiscountUsageHistory.cs | 8 +- src/Core/Grand.Domain/Documents/Document.cs | 30 +++--- .../Grand.Domain/Documents/DocumentType.cs | 4 +- src/Core/Grand.Domain/Grand.Domain.csproj | 3 + .../Grand.Domain/History/HistoryObject.cs | 2 +- .../Grand.Domain/Knowledgebase/ITreeNode.cs | 4 +- .../Knowledgebase/KnowledgebaseArticle.cs | 14 +-- .../KnowledgebaseArticleComment.cs | 8 +- .../Knowledgebase/KnowledgebaseCategory.cs | 14 +-- .../Grand.Domain/Localization/Language.cs | 10 +- .../Localization/LanguageSettings.cs | 2 +- .../Localization/TranslationEntity.cs | 6 +- .../Localization/TranslationResource.cs | 6 +- src/Core/Grand.Domain/Media/Download.cs | 16 ++-- src/Core/Grand.Domain/Media/MediaSettings.cs | 2 +- src/Core/Grand.Domain/Media/Picture.cs | 16 ++-- src/Core/Grand.Domain/Messages/Campaign.cs | 18 ++-- .../Messages/CampaignCustomerSubscription.cs | 4 +- .../Grand.Domain/Messages/CampaignHistory.cs | 8 +- .../Grand.Domain/Messages/ContactAttribute.cs | 10 +- .../Messages/ContactAttributeValue.cs | 6 +- src/Core/Grand.Domain/Messages/ContactUs.cs | 20 ++-- .../Grand.Domain/Messages/EmailAccount.cs | 12 +-- .../Messages/EmailAccountSettings.cs | 2 +- .../Grand.Domain/Messages/LiquidObject.cs | 54 +++++------ .../Grand.Domain/Messages/MessageTemplate.cs | 12 +-- .../Messages/NewsLetterSubscription.cs | 8 +- .../Messages/NewsletterCategory.cs | 4 +- src/Core/Grand.Domain/Messages/QueuedEmail.cs | 30 +++--- src/Core/Grand.Domain/MigrationDb.cs | 4 +- src/Core/Grand.Domain/News/NewsComment.cs | 10 +- src/Core/Grand.Domain/News/NewsItem.cs | 18 ++-- .../Grand.Domain/Orders/CheckoutAttribute.cs | 12 +-- .../Orders/CheckoutAttributeValue.cs | 6 +- src/Core/Grand.Domain/Orders/GiftVoucher.cs | 20 ++-- .../Orders/GiftVoucherExtensions.cs | 6 +- .../Orders/GiftVoucherUsageHistory.cs | 4 +- .../Orders/LoyaltyPointsHistory.cs | 8 +- .../Grand.Domain/Orders/MerchandiseReturn.cs | 24 ++--- .../Orders/MerchandiseReturnAction.cs | 2 +- .../Orders/MerchandiseReturnItem.cs | 10 +- .../Orders/MerchandiseReturnNote.cs | 8 +- .../Orders/MerchandiseReturnReason.cs | 2 +- .../Orders/MerchandiseReturnRefund.cs | 4 +- .../Orders/MerchandiseReturnShipping.cs | 30 +++--- src/Core/Grand.Domain/Orders/Order.cs | 60 ++++++------ src/Core/Grand.Domain/Orders/OrderApproval.cs | 16 ++-- .../Grand.Domain/Orders/OrderApprovalItem.cs | 12 +-- .../Orders/OrderApprovalSummary.cs | 12 +-- src/Core/Grand.Domain/Orders/OrderItem.cs | 16 ++-- src/Core/Grand.Domain/Orders/OrderNote.cs | 6 +- src/Core/Grand.Domain/Orders/OrderStatus.cs | 2 +- src/Core/Grand.Domain/Orders/OrderTag.cs | 2 +- .../Grand.Domain/Orders/RecurringPayment.cs | 14 +-- .../Orders/RecurringPaymentCycle.cs | 4 +- .../Grand.Domain/Orders/ShoppingCartItem.cs | 14 +-- .../Orders/ShoppingCartSettings.cs | 2 +- src/Core/Grand.Domain/Pages/Page.cs | 18 ++-- src/Core/Grand.Domain/Pages/PageLayout.cs | 4 +- src/Core/Grand.Domain/ParentEntity.cs | 3 + .../Payments/PaymentTransaction.cs | 28 +++--- .../Payments/PaymentTransactionEntry.cs | 8 +- .../Permissions/DefaultPermission.cs | 2 +- .../Grand.Domain/Permissions/Permission.cs | 12 +-- .../Permissions/PermissionAction.cs | 6 +- .../PushNotifications/PushMessage.cs | 4 +- .../PushNotificationsSettings.cs | 20 ++-- .../PushNotifications/PushRegistration.cs | 4 +- .../Grand.Domain/Security/RefreshToken.cs | 4 +- .../Grand.Domain/Security/SecuritySettings.cs | 2 +- src/Core/Grand.Domain/Seo/EntityUrl.cs | 12 +-- src/Core/Grand.Domain/Seo/ISlugEntity.cs | 2 +- src/Core/Grand.Domain/Seo/SeoSettings.cs | 14 +-- .../Grand.Domain/Shipping/DeliveryDate.cs | 6 +- .../Grand.Domain/Shipping/PickupPoints.cs | 12 +-- .../ReturnShippingProviderSettings.cs | 2 +- src/Core/Grand.Domain/Shipping/Shipment.cs | 14 +-- .../Grand.Domain/Shipping/ShipmentItem.cs | 6 +- .../Shipping/ShipmentItemBatch.cs | 2 +- .../Grand.Domain/Shipping/ShipmentNote.cs | 6 +- .../Grand.Domain/Shipping/ShippingMethod.cs | 10 +- .../Grand.Domain/Shipping/ShippingOption.cs | 6 +- .../Grand.Domain/Shipping/ShippingSettings.cs | 2 +- src/Core/Grand.Domain/Shipping/Warehouse.cs | 8 +- .../Shipping/WarehouseLocation.cs | 6 +- src/Core/Grand.Domain/Stores/BankAccount.cs | 8 +- src/Core/Grand.Domain/Stores/DomainHost.cs | 4 +- src/Core/Grand.Domain/Stores/Store.cs | 30 +++--- .../Grand.Domain/Stores/StoreExtensions.cs | 10 +- .../Stores/StoreInformationSettings.cs | 16 ++-- src/Core/Grand.Domain/Tasks/ScheduleTask.cs | 8 +- src/Core/Grand.Domain/Tax/TaxCategory.cs | 4 +- .../Grand.Domain/Tax/TaxProviderSettings.cs | 2 +- src/Core/Grand.Domain/Tax/TaxSettings.cs | 10 +- src/Core/Grand.Domain/Vendors/Vendor.cs | 28 +++--- src/Core/Grand.Domain/Vendors/VendorNote.cs | 2 +- src/Core/Grand.Domain/Vendors/VendorReview.cs | 10 +- .../Vendors/VendorReviewHelpfulness.cs | 4 +- .../Grand.Domain/Vendors/VendorSettings.cs | 2 +- 209 files changed, 1006 insertions(+), 1000 deletions(-) diff --git a/src/Core/Grand.Domain/Admin/AdminSiteMap.cs b/src/Core/Grand.Domain/Admin/AdminSiteMap.cs index 017ed2e5a..664e18834 100644 --- a/src/Core/Grand.Domain/Admin/AdminSiteMap.cs +++ b/src/Core/Grand.Domain/Admin/AdminSiteMap.cs @@ -17,27 +17,27 @@ public AdminSiteMap() /// Gets or sets the system name. /// [AuditName] - public string SystemName { get; set; } + public string? SystemName { get; set; } /// /// Gets or sets the resource name. /// - public string ResourceName { get; set; } + public string? ResourceName { get; set; } /// /// Gets or sets the name of the controller. /// - public string ControllerName { get; set; } + public string? ControllerName { get; set; } /// /// Gets or sets the name of the action. /// - public string ActionName { get; set; } + public string? ActionName { get; set; } /// /// Gets or sets the URL. /// - public string Url { get; set; } + public string? Url { get; set; } /// /// Gets or sets the child nodes. @@ -47,7 +47,7 @@ public AdminSiteMap() /// /// Gets or sets the icon class /// - public string IconClass { get; set; } + public string? IconClass { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Affiliates/Affiliate.cs b/src/Core/Grand.Domain/Affiliates/Affiliate.cs index dd6ae020a..4565b7ef6 100644 --- a/src/Core/Grand.Domain/Affiliates/Affiliate.cs +++ b/src/Core/Grand.Domain/Affiliates/Affiliate.cs @@ -10,17 +10,17 @@ public class Affiliate : BaseEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the admin comment /// - public string AdminComment { get; set; } + public string? AdminComment { get; set; } /// /// Gets or sets the friendly url name for affiliate /// - public string FriendlyUrlName { get; set; } + public string? FriendlyUrlName { get; set; } /// /// Gets or sets a value indicating whether the entity is active @@ -30,5 +30,5 @@ public class Affiliate : BaseEntity /// /// Gets or sets the address /// - public virtual Address Address { get; set; } + public virtual Address? Address { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Audit/AuditChange.cs b/src/Core/Grand.Domain/Audit/AuditChange.cs index 1609c612f..4d13c2497 100644 --- a/src/Core/Grand.Domain/Audit/AuditChange.cs +++ b/src/Core/Grand.Domain/Audit/AuditChange.cs @@ -8,24 +8,24 @@ public class AuditChange /// /// Gets or sets the field path, e.g. Price or TierPrices[id=…].Quantity /// - public string Path { get; set; } + public string? Path { get; set; } /// /// Gets or sets the names of the list elements the path runs through, outermost first (an empty name where an /// element has none), e.g. "Color family" for ProductSpecificationAttributes[id=…].DisplayOrder; null when /// the path runs through no named element /// - public IList ElementNames { get; set; } + public IList? ElementNames { get; set; } /// /// Gets or sets the value before the change (null when masked or when the field was added) /// - public string OldValue { get; set; } + public string? OldValue { get; set; } /// /// Gets or sets the value after the change (null when masked or when the field was removed) /// - public string NewValue { get; set; } + public string? NewValue { get; set; } /// /// Gets or sets a value indicating whether the values are hidden because the field is sensitive diff --git a/src/Core/Grand.Domain/Audit/AuditEntry.cs b/src/Core/Grand.Domain/Audit/AuditEntry.cs index 0a24fe020..e655e2d9b 100644 --- a/src/Core/Grand.Domain/Audit/AuditEntry.cs +++ b/src/Core/Grand.Domain/Audit/AuditEntry.cs @@ -12,72 +12,72 @@ public class AuditEntry : BaseEntity /// /// Gets or sets the staff member who made the change /// - public string ActorCustomerId { get; set; } + public string? ActorCustomerId { get; set; } /// /// Gets or sets the actor's e-mail at the time of the change /// - public string ActorEmail { get; set; } + public string? ActorEmail { get; set; } /// /// Gets or sets the customer the actor was impersonating, if any /// - public string ImpersonatedCustomerId { get; set; } + public string? ImpersonatedCustomerId { get; set; } /// /// Gets or sets the actor's staff store /// - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the actor's vendor /// - public string VendorId { get; set; } + public string? VendorId { get; set; } - public string IpAddress { get; set; } + public string? IpAddress { get; set; } - public string UserAgent { get; set; } + public string? UserAgent { get; set; } /// /// Gets or sets the request's intent as "Area / Controller / Action" /// - public string Action { get; set; } + public string? Action { get; set; } /// /// Gets or sets the identifier shared by every entry of one request or import /// - public string OperationId { get; set; } + public string? OperationId { get; set; } - public string EntityType { get; set; } + public string? EntityType { get; set; } - public string EntityId { get; set; } + public string? EntityId { get; set; } /// /// Gets or sets a display label of the entity at the time of the change /// - public string EntityName { get; set; } + public string? EntityName { get; set; } /// /// Gets or sets the store the changed record belongs to (a setting: empty for all stores); null when the /// record has no store /// - public string EntityStoreId { get; set; } + public string? EntityStoreId { get; set; } /// /// Gets or sets the type of the record the changed record belongs to (Order for an order note, see /// ); null when it belongs to none /// - public string OwnerType { get; set; } + public string? OwnerType { get; set; } /// /// Gets or sets the id of the record the changed record belongs to /// - public string OwnerId { get; set; } + public string? OwnerId { get; set; } public IList Changes { get; set; } = new List(); /// /// Gets or sets free text for events and bulk operations /// - public string Details { get; set; } + public string? Details { get; set; } } diff --git a/src/Core/Grand.Domain/Audit/AuditReferenceAttribute.cs b/src/Core/Grand.Domain/Audit/AuditReferenceAttribute.cs index 1e17ee605..10181c222 100644 --- a/src/Core/Grand.Domain/Audit/AuditReferenceAttribute.cs +++ b/src/Core/Grand.Domain/Audit/AuditReferenceAttribute.cs @@ -7,19 +7,19 @@ namespace Grand.Domain.Audit; /// target record is given by the sibling property named in . /// [AttributeUsage(AttributeTargets.Property)] -public sealed class AuditReferenceAttribute(Type target, string list = null) : Attribute +public sealed class AuditReferenceAttribute(Type target, string? list = null) : Attribute { public Type Target { get; } = target; - public string List { get; } = list; + public string? List { get; } = list; /// /// The sibling property holding the id of the target record that contains /// - public string Owner { get; set; } + public string? Owner { get; set; } /// /// The property of the target that the value matches, when it is not the id (an order status number) /// - public string Key { get; set; } + public string? Key { get; set; } } diff --git a/src/Core/Grand.Domain/AuditableEntity.cs b/src/Core/Grand.Domain/AuditableEntity.cs index 58e40a8b1..630251cfa 100644 --- a/src/Core/Grand.Domain/AuditableEntity.cs +++ b/src/Core/Grand.Domain/AuditableEntity.cs @@ -3,7 +3,7 @@ public interface IAuditableEntity { public DateTime CreatedOnUtc { get; set; } - public string CreatedBy { get; set; } + public string? CreatedBy { get; set; } public DateTime? UpdatedOnUtc { get; set; } - public string UpdatedBy { get; set; } + public string? UpdatedBy { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/BaseEntity.cs b/src/Core/Grand.Domain/BaseEntity.cs index 38639f9e7..ed45760ab 100644 --- a/src/Core/Grand.Domain/BaseEntity.cs +++ b/src/Core/Grand.Domain/BaseEntity.cs @@ -10,7 +10,7 @@ public abstract class BaseEntity : ParentEntity, IAuditableEntity public IList UserFields { get; set; } = new List(); public DateTime CreatedOnUtc { get; set; } - public string CreatedBy { get; set; } + public string? CreatedBy { get; set; } public DateTime? UpdatedOnUtc { get; set; } - public string UpdatedBy { get; set; } + public string? UpdatedBy { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Blogs/BlogCategory.cs b/src/Core/Grand.Domain/Blogs/BlogCategory.cs index 3a81e838a..7ac3ef5f4 100644 --- a/src/Core/Grand.Domain/Blogs/BlogCategory.cs +++ b/src/Core/Grand.Domain/Blogs/BlogCategory.cs @@ -9,12 +9,12 @@ public class BlogCategory : BaseEntity, IStoreLinkEntity, ITranslationEntity /// /// Gets or sets the blog category name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the blog category sename /// - public string SeName { get; set; } + public string? SeName { get; set; } /// /// Gets or sets display order diff --git a/src/Core/Grand.Domain/Blogs/BlogCategoryPost.cs b/src/Core/Grand.Domain/Blogs/BlogCategoryPost.cs index dee13b476..c128e3248 100644 --- a/src/Core/Grand.Domain/Blogs/BlogCategoryPost.cs +++ b/src/Core/Grand.Domain/Blogs/BlogCategoryPost.cs @@ -6,5 +6,5 @@ public class BlogCategoryPost : SubBaseEntity { [AuditReference(typeof(BlogPost))] [AuditName] - public string BlogPostId { get; set; } + public string? BlogPostId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Blogs/BlogComment.cs b/src/Core/Grand.Domain/Blogs/BlogComment.cs index 9936d8698..f0685e590 100644 --- a/src/Core/Grand.Domain/Blogs/BlogComment.cs +++ b/src/Core/Grand.Domain/Blogs/BlogComment.cs @@ -13,29 +13,29 @@ public class BlogComment : BaseEntity /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the comment text /// [AuditName] - public string CommentText { get; set; } + public string? CommentText { get; set; } /// /// Gets or sets the blog post title /// - public string BlogPostTitle { get; set; } + public string? BlogPostTitle { get; set; } /// /// Gets or sets the blog post identifier /// [AuditReference(typeof(BlogPost))] [AuditOwner] - public string BlogPostId { get; set; } + public string? BlogPostId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Blogs/BlogPost.cs b/src/Core/Grand.Domain/Blogs/BlogPost.cs index 73d76af21..919448bc0 100644 --- a/src/Core/Grand.Domain/Blogs/BlogPost.cs +++ b/src/Core/Grand.Domain/Blogs/BlogPost.cs @@ -14,22 +14,22 @@ public class BlogPost : BaseEntity, ISlugEntity, IStoreLinkEntity, ITranslationE /// Gets or sets the blog post title /// [AuditName] - public string Title { get; set; } + public string? Title { get; set; } /// /// Gets or sets the picture identifier /// - public string PictureId { get; set; } + public string? PictureId { get; set; } /// /// Gets or sets the blog post body /// - public string Body { get; set; } + public string? Body { get; set; } /// /// Gets or sets the blog post overview. If specified, then it's used on the blog page instead of the "Body" /// - public string BodyOverview { get; set; } + public string? BodyOverview { get; set; } /// /// Gets or sets a value indicating whether the blog post comments are allowed @@ -47,7 +47,7 @@ public class BlogPost : BaseEntity, ISlugEntity, IStoreLinkEntity, ITranslationE /// /// Gets or sets the blog tags /// - public string Tags { get; set; } + public string? Tags { get; set; } /// /// Gets or sets the blog post start date and time @@ -62,22 +62,22 @@ public class BlogPost : BaseEntity, ISlugEntity, IStoreLinkEntity, ITranslationE /// /// Gets or sets the meta keywords /// - public string MetaKeywords { get; set; } + public string? MetaKeywords { get; set; } /// /// Gets or sets the meta description /// - public string MetaDescription { get; set; } + public string? MetaDescription { get; set; } /// /// Gets or sets the meta title /// - public string MetaTitle { get; set; } + public string? MetaTitle { get; set; } /// /// Gets or sets the sename /// - public string SeName { get; set; } + public string? SeName { get; set; } /// /// Gets or sets a value indicating whether the entity is limited/restricted to certain stores diff --git a/src/Core/Grand.Domain/Blogs/BlogPostTag.cs b/src/Core/Grand.Domain/Blogs/BlogPostTag.cs index 5d1534eec..3b52ea06c 100644 --- a/src/Core/Grand.Domain/Blogs/BlogPostTag.cs +++ b/src/Core/Grand.Domain/Blogs/BlogPostTag.cs @@ -8,7 +8,7 @@ public class BlogPostTag /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the tagged product count diff --git a/src/Core/Grand.Domain/Blogs/BlogProduct.cs b/src/Core/Grand.Domain/Blogs/BlogProduct.cs index a17d93d75..ae7d6e7e9 100644 --- a/src/Core/Grand.Domain/Blogs/BlogProduct.cs +++ b/src/Core/Grand.Domain/Blogs/BlogProduct.cs @@ -5,7 +5,7 @@ namespace Grand.Domain.Blogs; public class BlogProduct : BaseEntity { [AuditReference(typeof(BlogPost))] - public string BlogPostId { get; set; } - public string ProductId { get; set; } + public string? BlogPostId { get; set; } + public string? ProductId { get; set; } public int DisplayOrder { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Catalog/Bid.cs b/src/Core/Grand.Domain/Catalog/Bid.cs index d5954ee9d..ad80188e1 100644 --- a/src/Core/Grand.Domain/Catalog/Bid.cs +++ b/src/Core/Grand.Domain/Catalog/Bid.cs @@ -15,13 +15,13 @@ public class Bid : BaseEntity /// Gets or sets the product identifier /// [AuditReference(typeof(Product))] - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// Gets or sets the warehouse identifier /// [AuditReference(typeof(Warehouse))] - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } /// /// Gets or sets the bid date @@ -32,7 +32,7 @@ public class Bid : BaseEntity /// Gets or sets the customer id /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets Amount @@ -43,14 +43,14 @@ public class Bid : BaseEntity /// Gets or sets Order Id /// [AuditReference(typeof(Order))] - public string OrderId { get; set; } + public string? OrderId { get; set; } /// /// / /// Gets or sets Store Id /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets buy it now diff --git a/src/Core/Grand.Domain/Catalog/Brand.cs b/src/Core/Grand.Domain/Catalog/Brand.cs index cfeb56c1d..dc423d043 100644 --- a/src/Core/Grand.Domain/Catalog/Brand.cs +++ b/src/Core/Grand.Domain/Catalog/Brand.cs @@ -13,48 +13,48 @@ namespace Grand.Domain.Catalog; /// public class Brand : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEntity, IStoreLinkEntity { - private ICollection _appliedDiscounts; + private ICollection? _appliedDiscounts; /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the description /// - public string Description { get; set; } + public string? Description { get; set; } /// /// Gets or sets the description /// - public string BottomDescription { get; set; } + public string? BottomDescription { get; set; } /// /// Gets or sets a value of used brand layout identifier /// [AuditReference(typeof(BrandLayout))] - public string BrandLayoutId { get; set; } + public string? BrandLayoutId { get; set; } /// /// Gets or sets the meta keywords /// - public string MetaKeywords { get; set; } + public string? MetaKeywords { get; set; } /// /// Gets or sets the meta description /// - public string MetaDescription { get; set; } + public string? MetaDescription { get; set; } /// /// Gets or sets the meta title /// - public string MetaTitle { get; set; } + public string? MetaTitle { get; set; } /// /// Gets or sets the picture identifier /// - public string PictureId { get; set; } + public string? PictureId { get; set; } /// /// Gets or sets the page size @@ -69,7 +69,7 @@ public class Brand : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEnti /// /// Gets or sets the available customer selectable page size options /// - public string PageSizeOptions { get; set; } + public string? PageSizeOptions { get; set; } /// /// Gets or sets a value indicating whether to show the collection on home page @@ -84,7 +84,7 @@ public class Brand : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEnti /// /// Gets or sets the Icon /// - public string Icon { get; set; } + public string? Icon { get; set; } /// /// Gets or sets the Default sort @@ -94,7 +94,7 @@ public class Brand : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEnti /// /// Gets or sets the ExternalId /// - public string ExternalId { get; set; } + public string? ExternalId { get; set; } /// /// Gets or sets a value indicating whether the entity is published @@ -126,7 +126,7 @@ public virtual ICollection AppliedDiscounts { /// /// Gets or sets the sename /// - public string SeName { get; set; } + public string? SeName { get; set; } /// /// Gets or sets a value indicating whether the entity is limited/restricted to certain stores diff --git a/src/Core/Grand.Domain/Catalog/BrandLayout.cs b/src/Core/Grand.Domain/Catalog/BrandLayout.cs index 16f639041..91f9180eb 100644 --- a/src/Core/Grand.Domain/Catalog/BrandLayout.cs +++ b/src/Core/Grand.Domain/Catalog/BrandLayout.cs @@ -8,12 +8,12 @@ public class BrandLayout : BaseEntity /// /// Gets or sets the layout name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the view path /// - public string ViewPath { get; set; } + public string? ViewPath { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Catalog/BundleProduct.cs b/src/Core/Grand.Domain/Catalog/BundleProduct.cs index 55e1ced65..872e5c4c7 100644 --- a/src/Core/Grand.Domain/Catalog/BundleProduct.cs +++ b/src/Core/Grand.Domain/Catalog/BundleProduct.cs @@ -12,7 +12,7 @@ public class BundleProduct : SubBaseEntity /// [AuditReference(typeof(Product))] [AuditName] - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// Gets or sets the quantity diff --git a/src/Core/Grand.Domain/Catalog/CatalogSettings.cs b/src/Core/Grand.Domain/Catalog/CatalogSettings.cs index 5d190b856..c87a31f5b 100644 --- a/src/Core/Grand.Domain/Catalog/CatalogSettings.cs +++ b/src/Core/Grand.Domain/Catalog/CatalogSettings.cs @@ -71,7 +71,7 @@ public class CatalogSettings : ISettings /// /// Gets or sets a value indicating whether customers are allowed to change product view mode /// - public string DefaultViewMode { get; set; } + public string? DefaultViewMode { get; set; } /// /// Gets or sets a value indicating whether a category details page should include products from subcategories @@ -106,7 +106,7 @@ public class CatalogSettings : ISettings /// /// Gets or sets a share code (e.g. AddThis button code) /// - public string PageShareCode { get; set; } + public string? PageShareCode { get; set; } /// /// Gets or sets a value indicating product reviews must be approved @@ -131,7 +131,7 @@ public class CatalogSettings : ISettings /// /// Gets or sets a value the filtering by product review /// - public string FilterProductRating { get; set; } + public string? FilterProductRating { get; set; } /// /// Gets or sets a value indicating whether product 'Email a friend' feature is enabled @@ -297,7 +297,7 @@ public class CatalogSettings : ISettings /// /// Gets or sets the available customer selectable page size options on the search products page /// - public string SearchPagePageSizeOptions { get; set; } + public string? SearchPagePageSizeOptions { get; set; } /// /// Gets or sets "List of products purchased by other customers who purchased the above" option is enable @@ -327,7 +327,7 @@ public class CatalogSettings : ISettings /// /// Gets or sets the available customer selectable page size options for 'products by tag' /// - public string ProductsByTagPageSizeOptions { get; set; } + public string? ProductsByTagPageSizeOptions { get; set; } /// /// Gets or sets a value indicating whether to include "Short description" in compare products @@ -387,7 +387,7 @@ public class CatalogSettings : ISettings /// /// Gets or sets the default value to use for Category page size options (for new categories) /// - public string DefaultPageSizeOptions { get; set; } + public string? DefaultPageSizeOptions { get; set; } /// /// Gets or sets the default value to use for Category page size (for new categories) diff --git a/src/Core/Grand.Domain/Catalog/Category.cs b/src/Core/Grand.Domain/Catalog/Category.cs index 62dc1d6b0..2580f9daa 100644 --- a/src/Core/Grand.Domain/Catalog/Category.cs +++ b/src/Core/Grand.Domain/Catalog/Category.cs @@ -13,55 +13,55 @@ namespace Grand.Domain.Catalog; /// public class Category : BaseEntity, ISlugEntity, IGroupLinkEntity, ITranslationEntity, IStoreLinkEntity { - private ICollection _appliedDiscounts; + private ICollection? _appliedDiscounts; /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the description /// - public string Description { get; set; } + public string? Description { get; set; } /// /// Gets or sets the bottom description /// - public string BottomDescription { get; set; } + public string? BottomDescription { get; set; } /// /// Gets or sets a value of used category layout identifier /// [AuditReference(typeof(CategoryLayout))] - public string CategoryLayoutId { get; set; } + public string? CategoryLayoutId { get; set; } /// /// Gets or sets the meta keywords /// - public string MetaKeywords { get; set; } + public string? MetaKeywords { get; set; } /// /// Gets or sets the meta description /// - public string MetaDescription { get; set; } + public string? MetaDescription { get; set; } /// /// Gets or sets the meta title /// - public string MetaTitle { get; set; } + public string? MetaTitle { get; set; } /// /// Gets or sets the parent category identifier /// [AuditReference(typeof(Category))] - public string ParentCategoryId { get; set; } + public string? ParentCategoryId { get; set; } /// /// Gets or sets the picture identifier /// - public string PictureId { get; set; } + public string? PictureId { get; set; } /// /// Gets or sets the page size @@ -76,7 +76,7 @@ public class Category : BaseEntity, ISlugEntity, IGroupLinkEntity, ITranslationE /// /// Gets or sets the available customer selectable page size options /// - public string PageSizeOptions { get; set; } + public string? PageSizeOptions { get; set; } /// /// Gets or sets a value indicating whether to show the category on home page @@ -116,22 +116,22 @@ public class Category : BaseEntity, ISlugEntity, IGroupLinkEntity, ITranslationE /// /// Gets or sets the ExternalId /// - public string ExternalId { get; set; } + public string? ExternalId { get; set; } /// /// Gets or sets the flag /// - public string Flag { get; set; } + public string? Flag { get; set; } /// /// Gets or sets the flag style /// - public string FlagStyle { get; set; } + public string? FlagStyle { get; set; } /// /// Gets or sets the Icon /// - public string Icon { get; set; } + public string? Icon { get; set; } /// /// Gets or sets the Default sort @@ -163,7 +163,7 @@ public virtual ICollection AppliedDiscounts { /// /// Gets or sets the name /// - public string SeName { get; set; } + public string? SeName { get; set; } /// /// Gets or sets a value indicating whether the entity is limited/restricted to certain stores diff --git a/src/Core/Grand.Domain/Catalog/CategoryLayout.cs b/src/Core/Grand.Domain/Catalog/CategoryLayout.cs index a56a707b9..36a9821c8 100644 --- a/src/Core/Grand.Domain/Catalog/CategoryLayout.cs +++ b/src/Core/Grand.Domain/Catalog/CategoryLayout.cs @@ -8,12 +8,12 @@ public class CategoryLayout : BaseEntity /// /// Gets or sets the layout name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the view path /// - public string ViewPath { get; set; } + public string? ViewPath { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Catalog/Collection.cs b/src/Core/Grand.Domain/Catalog/Collection.cs index 5cbda39ad..b12494e9b 100644 --- a/src/Core/Grand.Domain/Catalog/Collection.cs +++ b/src/Core/Grand.Domain/Catalog/Collection.cs @@ -13,48 +13,48 @@ namespace Grand.Domain.Catalog; /// public class Collection : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEntity, IStoreLinkEntity { - private ICollection _appliedDiscounts; + private ICollection? _appliedDiscounts; /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the description /// - public string Description { get; set; } + public string? Description { get; set; } /// /// Gets or sets the description /// - public string BottomDescription { get; set; } + public string? BottomDescription { get; set; } /// /// Gets or sets a value of used collection layout identifier /// [AuditReference(typeof(CollectionLayout))] - public string CollectionLayoutId { get; set; } + public string? CollectionLayoutId { get; set; } /// /// Gets or sets the meta keywords /// - public string MetaKeywords { get; set; } + public string? MetaKeywords { get; set; } /// /// Gets or sets the meta description /// - public string MetaDescription { get; set; } + public string? MetaDescription { get; set; } /// /// Gets or sets the meta title /// - public string MetaTitle { get; set; } + public string? MetaTitle { get; set; } /// /// Gets or sets the picture identifier /// - public string PictureId { get; set; } + public string? PictureId { get; set; } /// /// Gets or sets the page size @@ -69,7 +69,7 @@ public class Collection : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLin /// /// Gets or sets the available customer selectable page size options /// - public string PageSizeOptions { get; set; } + public string? PageSizeOptions { get; set; } /// /// Gets or sets a value indicating whether to show the collection on home page @@ -89,7 +89,7 @@ public class Collection : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLin /// /// Gets or sets the Icon /// - public string Icon { get; set; } + public string? Icon { get; set; } /// /// Gets or sets the Default sort @@ -109,7 +109,7 @@ public class Collection : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLin /// /// Gets or sets the ExternalId /// - public string ExternalId { get; set; } + public string? ExternalId { get; set; } /// /// Gets or sets the collection of applied discounts @@ -131,7 +131,7 @@ public virtual ICollection AppliedDiscounts { /// /// Gets or sets the sename /// - public string SeName { get; set; } + public string? SeName { get; set; } /// /// Gets or sets a value indicating whether the entity is limited/restricted to certain stores diff --git a/src/Core/Grand.Domain/Catalog/CollectionLayout.cs b/src/Core/Grand.Domain/Catalog/CollectionLayout.cs index 9533c1a2d..4bbf636d4 100644 --- a/src/Core/Grand.Domain/Catalog/CollectionLayout.cs +++ b/src/Core/Grand.Domain/Catalog/CollectionLayout.cs @@ -8,12 +8,12 @@ public class CollectionLayout : BaseEntity /// /// Gets or sets the layout name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the view path /// - public string ViewPath { get; set; } + public string? ViewPath { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Catalog/CrossSellProduct.cs b/src/Core/Grand.Domain/Catalog/CrossSellProduct.cs index 6b6b45809..23c365dec 100644 --- a/src/Core/Grand.Domain/Catalog/CrossSellProduct.cs +++ b/src/Core/Grand.Domain/Catalog/CrossSellProduct.cs @@ -8,10 +8,10 @@ public class CrossSellProduct : BaseEntity /// /// Gets or sets the first product identifier /// - public string ProductId1 { get; set; } + public string? ProductId1 { get; set; } /// /// Gets or sets the second product identifier /// - public string ProductId2 { get; set; } + public string? ProductId2 { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Catalog/CustomerReservationsHelper.cs b/src/Core/Grand.Domain/Catalog/CustomerReservationsHelper.cs index 6dfd737e0..91c79f608 100644 --- a/src/Core/Grand.Domain/Catalog/CustomerReservationsHelper.cs +++ b/src/Core/Grand.Domain/Catalog/CustomerReservationsHelper.cs @@ -8,15 +8,15 @@ public class CustomerReservationsHelper : BaseEntity /// /// Gets or sets customer identifier /// - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets shopping cart identifier /// - public string ShoppingCartItemId { get; set; } + public string? ShoppingCartItemId { get; set; } /// /// Gets or sets reservation identifier /// - public string ReservationId { get; set; } + public string? ReservationId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Catalog/InventoryDocument.cs b/src/Core/Grand.Domain/Catalog/InventoryDocument.cs index 19f7767c4..cc7f4e201 100644 --- a/src/Core/Grand.Domain/Catalog/InventoryDocument.cs +++ b/src/Core/Grand.Domain/Catalog/InventoryDocument.cs @@ -9,7 +9,7 @@ public class InventoryDocument : BaseEntity /// /// The number people read: prefix, year and sequence, e.g. PZ/2026/0001 /// - public string Number { get; set; } + public string? Number { get; set; } public int Year { get; set; } @@ -19,38 +19,38 @@ public class InventoryDocument : BaseEntity public InventoryDocumentStatus StatusId { get; set; } - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } /// /// A transfer: the warehouse the stock moves to /// - public string TargetWarehouseId { get; set; } + public string? TargetWarehouseId { get; set; } /// /// The store of the warehouse /// - public string StoreId { get; set; } + public string? StoreId { get; set; } public IList Lines { get; set; } = new List(); /// /// A receipt: the supplier's name /// - public string SupplierName { get; set; } + public string? SupplierName { get; set; } /// /// A receipt: the supplier's invoice or delivery note number /// - public string ExternalReference { get; set; } + public string? ExternalReference { get; set; } /// /// A return receipt: the merchandise return it receives /// - public string MerchandiseReturnId { get; set; } + public string? MerchandiseReturnId { get; set; } - public string Comment { get; set; } + public string? Comment { get; set; } public DateTime? PostedOnUtc { get; set; } - public string PostedBy { get; set; } + public string? PostedBy { get; set; } } diff --git a/src/Core/Grand.Domain/Catalog/InventoryDocumentLine.cs b/src/Core/Grand.Domain/Catalog/InventoryDocumentLine.cs index 6b0c28422..29b6faa86 100644 --- a/src/Core/Grand.Domain/Catalog/InventoryDocumentLine.cs +++ b/src/Core/Grand.Domain/Catalog/InventoryDocumentLine.cs @@ -7,7 +7,7 @@ namespace Grand.Domain.Catalog; /// public class InventoryDocumentLine : SubBaseEntity { - public string ProductId { get; set; } + public string? ProductId { get; set; } public IList Attributes { get; set; } = new List(); @@ -39,14 +39,14 @@ public class InventoryDocumentLine : SubBaseEntity /// /// A return receipt: the merchandise return item the line receives /// - public string MerchandiseReturnItemId { get; set; } + public string? MerchandiseReturnItemId { get; set; } - public string Comment { get; set; } + public string? Comment { get; set; } /// /// A batch-tracked product: the batch the line books; empty for the stock without a batch /// - public string BatchNumber { get; set; } + public string? BatchNumber { get; set; } /// /// A receipt of a batch: its expiry date diff --git a/src/Core/Grand.Domain/Catalog/InventoryJournal.cs b/src/Core/Grand.Domain/Catalog/InventoryJournal.cs index 19ac06c50..2c5f0f35c 100644 --- a/src/Core/Grand.Domain/Catalog/InventoryJournal.cs +++ b/src/Core/Grand.Domain/Catalog/InventoryJournal.cs @@ -7,17 +7,17 @@ namespace Grand.Domain.Catalog; /// public class InventoryJournal : BaseEntity { - public string ObjectId { get; set; } - public string ObjectType { get; set; } - public string PositionId { get; set; } + public string? ObjectId { get; set; } + public string? ObjectType { get; set; } + public string? PositionId { get; set; } public DateTime CreateDateUtc { get; set; } - public string ProductId { get; set; } + public string? ProductId { get; set; } public IList Attributes { get; set; } = new List(); - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } public int InQty { get; set; } public int OutQty { get; set; } - public string Comments { get; set; } - public string Reference { get; set; } + public string? Comments { get; set; } + public string? Reference { get; set; } /// /// What caused the change @@ -27,17 +27,17 @@ public class InventoryJournal : BaseEntity /// /// Who caused it: a staff member or an API user; empty for the system /// - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// The store of the warehouse; empty for a shared warehouse or a product without one /// - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// The combination of a product stocked by attributes /// - public string CombinationId { get; set; } + public string? CombinationId { get; set; } /// /// The product's stock revision this entry brought it to; an entry newer than the product's is applied @@ -48,7 +48,7 @@ public class InventoryJournal : BaseEntity /// /// The batch the change moved; empty for the stock without a batch /// - public string BatchNumber { get; set; } + public string? BatchNumber { get; set; } /// /// The serial numbers the change moved @@ -69,5 +69,5 @@ public class InventoryJournal : BaseEntity /// The idempotency key of a change written through the stock integration API; empty for every other entry. A /// change with a key writes exactly one entry, and a retried call with the same key is not applied again /// - public string IdempotencyKey { get; set; } + public string? IdempotencyKey { get; set; } } diff --git a/src/Core/Grand.Domain/Catalog/OutOfStockSubscription.cs b/src/Core/Grand.Domain/Catalog/OutOfStockSubscription.cs index 3a347cca8..13b2d22cd 100644 --- a/src/Core/Grand.Domain/Catalog/OutOfStockSubscription.cs +++ b/src/Core/Grand.Domain/Catalog/OutOfStockSubscription.cs @@ -15,13 +15,13 @@ public class OutOfStockSubscription : BaseEntity /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the product identifier /// [AuditReference(typeof(Product))] - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// Gets or sets the attribute @@ -31,17 +31,17 @@ public class OutOfStockSubscription : BaseEntity /// /// Gets or sets the attribute info (format) /// - public string AttributeInfo { get; set; } + public string? AttributeInfo { get; set; } /// /// Gets or sets the warehouse identifier /// [AuditReference(typeof(Warehouse))] - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } /// /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Catalog/PredefinedProductAttributeValue.cs b/src/Core/Grand.Domain/Catalog/PredefinedProductAttributeValue.cs index 09fb25ff0..95fed1557 100644 --- a/src/Core/Grand.Domain/Catalog/PredefinedProductAttributeValue.cs +++ b/src/Core/Grand.Domain/Catalog/PredefinedProductAttributeValue.cs @@ -10,7 +10,7 @@ public class PredefinedProductAttributeValue : SubBaseEntity, ITranslationEntity /// /// Gets or sets the product attribute name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the price adjustment diff --git a/src/Core/Grand.Domain/Catalog/Product.cs b/src/Core/Grand.Domain/Catalog/Product.cs index 274661b87..92f5624ef 100644 --- a/src/Core/Grand.Domain/Catalog/Product.cs +++ b/src/Core/Grand.Domain/Catalog/Product.cs @@ -19,22 +19,22 @@ namespace Grand.Domain.Catalog; /// public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEntity, IStoreLinkEntity { - private ICollection _appliedDiscounts; - private ICollection _bundleProduct; - private ICollection _crossSellProduct; - private ICollection _productAttributeCombinations; - private ICollection _productAttributeMappings; - private ICollection _productCategories; - private ICollection _productCollections; - private ICollection _productPictures; - private ICollection _productPrices; - private ICollection _productSpecificationAttributes; - private ICollection _productTags; - private ICollection _productWarehouseInventory; - private ICollection _recommendedProduct; - private ICollection _relatedProduct; - private ICollection _similarProduct; - private ICollection _tierPrices; + private ICollection? _appliedDiscounts; + private ICollection? _bundleProduct; + private ICollection? _crossSellProduct; + private ICollection? _productAttributeCombinations; + private ICollection? _productAttributeMappings; + private ICollection? _productCategories; + private ICollection? _productCollections; + private ICollection? _productPictures; + private ICollection? _productPrices; + private ICollection? _productSpecificationAttributes; + private ICollection? _productTags; + private ICollection? _productWarehouseInventory; + private ICollection? _recommendedProduct; + private ICollection? _relatedProduct; + private ICollection? _similarProduct; + private ICollection? _tierPrices; /// /// Gets or sets the product type identifier @@ -46,7 +46,7 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// products) /// [AuditReference(typeof(Product))] - public string ParentGroupedProductId { get; set; } + public string? ParentGroupedProductId { get; set; } /// /// Gets or sets the values indicating whether this product is visible in catalog or search results. @@ -58,40 +58,40 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the short description /// - public string ShortDescription { get; set; } + public string? ShortDescription { get; set; } /// /// Gets or sets the full description /// - public string FullDescription { get; set; } + public string? FullDescription { get; set; } /// /// Gets or sets the admin comment /// - public string AdminComment { get; set; } + public string? AdminComment { get; set; } /// /// Gets or sets a value of used product layout identifier /// [AuditReference(typeof(ProductLayout))] - public string ProductLayoutId { get; set; } + public string? ProductLayoutId { get; set; } /// /// Gets or sets a brand identifier /// [AuditReference(typeof(Brand))] - public string BrandId { get; set; } + public string? BrandId { get; set; } /// /// Gets or sets a vendor identifier /// [AuditReference(typeof(Vendor))] - public string VendorId { get; set; } + public string? VendorId { get; set; } /// /// Gets or sets a value indicating whether to show the product on home page @@ -106,17 +106,17 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// /// Gets or sets the meta keywords /// - public string MetaKeywords { get; set; } + public string? MetaKeywords { get; set; } /// /// Gets or sets the meta description /// - public string MetaDescription { get; set; } + public string? MetaDescription { get; set; } /// /// Gets or sets the meta title /// - public string MetaTitle { get; set; } + public string? MetaTitle { get; set; } /// /// Gets or sets a value indicating whether the product allows customer reviews @@ -151,23 +151,23 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// /// Gets or sets the ExternalId /// - public string ExternalId { get; set; } + public string? ExternalId { get; set; } /// /// Gets or sets the SKU /// - public string Sku { get; set; } + public string? Sku { get; set; } /// /// Gets or sets the collection part number /// - public string Mpn { get; set; } + public string? Mpn { get; set; } /// /// Gets or sets the Global Trade Item Number (GTIN). These identifiers include UPC (in North America), EAN (in /// Europe), JAN (in Japan), and ISBN (for books). /// - public string Gtin { get; set; } + public string? Gtin { get; set; } /// /// Gets or sets a value indicating whether the product is gift voucher @@ -194,7 +194,7 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// /// Gets or sets a required product identifiers (comma separated) /// - public string RequiredProductIds { get; set; } + public string? RequiredProductIds { get; set; } /// /// Gets or sets a value indicating whether required products are automatically added to the cart @@ -209,7 +209,7 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// /// Gets or sets the download identifier /// - public string DownloadId { get; set; } + public string? DownloadId { get; set; } /// /// Gets or sets a value indicating whether this downloadable product can be downloaded unlimited number of times @@ -239,7 +239,7 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// /// Gets or sets the sample download identifier /// - public string SampleDownloadId { get; set; } + public string? SampleDownloadId { get; set; } /// /// Gets or sets a value indicating whether the product has user agreement @@ -249,7 +249,7 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// /// Gets or sets the text of license agreement /// - public string UserAgreementText { get; set; } + public string? UserAgreementText { get; set; } /// /// Gets or sets a value indicating whether the product is recurring @@ -310,7 +310,7 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// Gets or sets a delivery date identifier /// [AuditReference(typeof(DeliveryDate))] - public string DeliveryDateId { get; set; } + public string? DeliveryDateId { get; set; } /// /// Gets or sets a value indicating whether the product is marked as tax exempt @@ -321,7 +321,7 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// Gets or sets the tax category identifier /// [AuditReference(typeof(TaxCategory))] - public string TaxCategoryId { get; set; } + public string? TaxCategoryId { get; set; } /// /// Gets or sets a value indicating whether the product is telecommunications or broadcasting or electronic services @@ -342,7 +342,7 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// Gets or sets a warehouse identifier /// [AuditReference(typeof(Warehouse))] - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } /// /// Gets or sets the stock quantity @@ -427,7 +427,7 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// /// Gets or sets the comma seperated list of allowed quantities. null or empty if any quantity is allowed /// - public string AllowedQuantities { get; set; } + public string? AllowedQuantities { get; set; } /// /// Gets or sets a value indicating whether this product is returnable (a customer is allowed to submit merchandise @@ -509,7 +509,7 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// Gets or sets a unit of product for PAngV (MeasureWeight entity) /// [AuditReference(typeof(MeasureWeight))] - public string BasepriceUnitId { get; set; } + public string? BasepriceUnitId { get; set; } /// /// Gets or sets a reference amount for PAngV @@ -520,19 +520,19 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// Gets or sets a reference unit for PAngV (MeasureWeight entity) /// [AuditReference(typeof(MeasureWeight))] - public string BasepriceBaseUnitId { get; set; } + public string? BasepriceBaseUnitId { get; set; } /// /// Gets or sets a unit of product /// [AuditReference(typeof(MeasureUnit))] - public string UnitId { get; set; } + public string? UnitId { get; set; } /// /// Gets or sets a course ident /// [AuditReference(typeof(Course))] - public string CourseId { get; set; } + public string? CourseId { get; set; } /// /// Gets or sets a value indicating whether this product is marked as new @@ -594,7 +594,7 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// /// Gets or sets current highest bidder customer id /// - public string HighestBidder { get; set; } + public string? HighestBidder { get; set; } /// /// Gets or sets auction ended @@ -649,7 +649,7 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// /// Gets or sets the flag /// - public string Flag { get; set; } + public string? Flag { get; set; } /// /// Gets or sets the ticks @@ -659,7 +659,7 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// /// Gets or sets the coordinates /// - public GeoCoordinates Coordinates { get; set; } + public GeoCoordinates? Coordinates { get; set; } /// /// Gets or sets the collection of ProductCategory @@ -787,7 +787,7 @@ public virtual ICollection BundleProducts { /// /// Gets or sets the sename /// - public string SeName { get; set; } + public string? SeName { get; set; } /// /// Gets or sets a value indicating whether the entity is limited/restricted to certain stores diff --git a/src/Core/Grand.Domain/Catalog/ProductAlsoPurchased.cs b/src/Core/Grand.Domain/Catalog/ProductAlsoPurchased.cs index fad720fbc..394b1b78f 100644 --- a/src/Core/Grand.Domain/Catalog/ProductAlsoPurchased.cs +++ b/src/Core/Grand.Domain/Catalog/ProductAlsoPurchased.cs @@ -5,10 +5,10 @@ namespace Grand.Domain.Catalog; /// public class ProductAlsoPurchased : BaseEntity { - public string ProductId { get; set; } - public string ProductId2 { get; set; } - public string OrderId { get; set; } + public string? ProductId { get; set; } + public string? ProductId2 { get; set; } + public string? OrderId { get; set; } public DateTime CreatedOrderOnUtc { get; set; } public int Quantity { get; set; } - public string StoreId { get; set; } + public string? StoreId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Catalog/ProductAttribute.cs b/src/Core/Grand.Domain/Catalog/ProductAttribute.cs index 6d012bdab..c9d4e60cd 100644 --- a/src/Core/Grand.Domain/Catalog/ProductAttribute.cs +++ b/src/Core/Grand.Domain/Catalog/ProductAttribute.cs @@ -12,17 +12,17 @@ public class ProductAttribute : BaseEntity, IStoreLinkEntity, ITranslationEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the sename /// - public string SeName { get; set; } + public string? SeName { get; set; } /// /// Gets or sets the description /// - public string Description { get; set; } + public string? Description { get; set; } public IList PredefinedProductAttributeValues { get; set; } = new List(); diff --git a/src/Core/Grand.Domain/Catalog/ProductAttributeCombination.cs b/src/Core/Grand.Domain/Catalog/ProductAttributeCombination.cs index b8660927a..157177a22 100644 --- a/src/Core/Grand.Domain/Catalog/ProductAttributeCombination.cs +++ b/src/Core/Grand.Domain/Catalog/ProductAttributeCombination.cs @@ -8,8 +8,8 @@ namespace Grand.Domain.Catalog; /// public class ProductAttributeCombination : SubBaseEntity, ICloneable { - private ICollection _tierPrices; - private ICollection _warehouseInventory; + private ICollection? _tierPrices; + private ICollection? _warehouseInventory; /// /// Gets or sets the custom attributes (see "ProductAttribute" entity for more info) @@ -34,24 +34,24 @@ public class ProductAttributeCombination : SubBaseEntity, ICloneable /// /// Gets or sets the text /// - public string Text { get; set; } + public string? Text { get; set; } /// /// Gets or sets the SKU /// [AuditName] - public string Sku { get; set; } + public string? Sku { get; set; } /// /// Gets or sets the collection part number /// - public string Mpn { get; set; } + public string? Mpn { get; set; } /// /// Gets or sets the Global Trade Item Number (GTIN). These identifiers include UPC (in North America), EAN (in /// Europe), JAN (in Japan), and ISBN (for books). /// - public string Gtin { get; set; } + public string? Gtin { get; set; } /// /// Gets or sets the attribute combination price. This way a store owner can override the default product price when @@ -67,7 +67,7 @@ public class ProductAttributeCombination : SubBaseEntity, ICloneable /// /// Gets or sets the identifier of picture associated with this combination /// - public string PictureId { get; set; } + public string? PictureId { get; set; } /// /// Gets or sets the collection of "ProductCombinationWarehouseInventory". We use it only when "UseMultipleWarehouses" diff --git a/src/Core/Grand.Domain/Catalog/ProductAttributeMapping.cs b/src/Core/Grand.Domain/Catalog/ProductAttributeMapping.cs index 3b573c7cf..7bc171f40 100644 --- a/src/Core/Grand.Domain/Catalog/ProductAttributeMapping.cs +++ b/src/Core/Grand.Domain/Catalog/ProductAttributeMapping.cs @@ -9,19 +9,19 @@ namespace Grand.Domain.Catalog; /// public class ProductAttributeMapping : SubBaseEntity, ITranslationEntity { - private ICollection _productAttributeValues; + private ICollection? _productAttributeValues; /// /// Gets or sets the product attribute identifier /// [AuditReference(typeof(ProductAttribute))] [AuditName] - public string ProductAttributeId { get; set; } + public string? ProductAttributeId { get; set; } /// /// Gets or sets a value a text prompt /// - public string TextPrompt { get; set; } + public string? TextPrompt { get; set; } /// /// Gets or sets a value indicating whether the entity is required @@ -61,7 +61,7 @@ public class ProductAttributeMapping : SubBaseEntity, ITranslationEntity /// /// Gets or sets the validation rule for file allowed extensions (for file upload) /// - public string ValidationFileAllowedExtensions { get; set; } + public string? ValidationFileAllowedExtensions { get; set; } /// /// Gets or sets the validation rule for file maximum size in kilobytes (for file upload) @@ -71,7 +71,7 @@ public class ProductAttributeMapping : SubBaseEntity, ITranslationEntity /// /// Gets or sets the default value (for textbox and multiline textbox) /// - public string DefaultValue { get; set; } + public string? DefaultValue { get; set; } /// /// Gets or sets the custom attributes (see "ProductAttribute" entity for more info) diff --git a/src/Core/Grand.Domain/Catalog/ProductAttributeValue.cs b/src/Core/Grand.Domain/Catalog/ProductAttributeValue.cs index bff5f0ddb..98348e728 100644 --- a/src/Core/Grand.Domain/Catalog/ProductAttributeValue.cs +++ b/src/Core/Grand.Domain/Catalog/ProductAttributeValue.cs @@ -17,22 +17,22 @@ public class ProductAttributeValue : SubBaseEntity, ITranslationEntity /// Gets or sets the associated product identifier (used only with AttributeValueType.AssociatedToProduct) /// [AuditReference(typeof(Product))] - public string AssociatedProductId { get; set; } + public string? AssociatedProductId { get; set; } /// /// Gets or sets the product attribute name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the color RGB value (used with "Color squares" attribute type) /// - public string ColorSquaresRgb { get; set; } + public string? ColorSquaresRgb { get; set; } /// /// Gets or sets the picture ID for image square (used with "Image squares" attribute type) /// - public string ImageSquaresPictureId { get; set; } + public string? ImageSquaresPictureId { get; set; } /// /// Gets or sets the price adjustment (used only with AttributeValueType.Simple) @@ -68,7 +68,7 @@ public class ProductAttributeValue : SubBaseEntity, ITranslationEntity /// Gets or sets the picture (identifier) associated with this value. This picture should replace a product main /// picture once clicked (selected). /// - public string PictureId { get; set; } + public string? PictureId { get; set; } /// /// Gets or sets the collection of locales diff --git a/src/Core/Grand.Domain/Catalog/ProductBatch.cs b/src/Core/Grand.Domain/Catalog/ProductBatch.cs index 571ed230e..153882655 100644 --- a/src/Core/Grand.Domain/Catalog/ProductBatch.cs +++ b/src/Core/Grand.Domain/Catalog/ProductBatch.cs @@ -8,34 +8,34 @@ namespace Grand.Domain.Catalog; /// public class ProductBatch : BaseEntity { - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// The combination of a product stocked by attributes /// - public string CombinationId { get; set; } + public string? CombinationId { get; set; } public IList Attributes { get; set; } = new List(); /// /// The warehouse of the bucket, as the inventory journal names it; empty for a product without one /// - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } /// /// The store of the warehouse; empty for a shared warehouse /// - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// The batch number as entered /// - public string Number { get; set; } + public string? Number { get; set; } /// /// The number trimmed and upper-cased: what lookups and the unique index compare /// - public string NumberKey { get; set; } + public string? NumberKey { get; set; } /// /// The expiry date, a date without time @@ -54,7 +54,7 @@ public class ProductBatch : BaseEntity /// /// The receipt that brought the batch in /// - public string ReceiptDocumentId { get; set; } + public string? ReceiptDocumentId { get; set; } /// /// The stock revision of the last inventory journal entry that changed the record; an entry not newer than @@ -72,29 +72,29 @@ public class ProductBatch : BaseEntity /// /// The place in the batch's warehouse where it is kept /// - public string LocationId { get; set; } + public string? LocationId { get; set; } /// /// The production date, a date without time /// public DateTime? ManufacturedOnUtc { get; set; } - public string Supplier { get; set; } + public string? Supplier { get; set; } /// /// The number the supplier or manufacturer gave the batch /// - public string SupplierBatchNumber { get; set; } + public string? SupplierBatchNumber { get; set; } /// /// The certificate of analysis or conformity the batch came with /// - public string CertificateNumber { get; set; } + public string? CertificateNumber { get; set; } - public string AdminComment { get; set; } + public string? AdminComment { get; set; } /// /// Shown to the customers who received units of the batch /// - public string CustomerComment { get; set; } + public string? CustomerComment { get; set; } } diff --git a/src/Core/Grand.Domain/Catalog/ProductCategory.cs b/src/Core/Grand.Domain/Catalog/ProductCategory.cs index 59074bc31..be41fb2e7 100644 --- a/src/Core/Grand.Domain/Catalog/ProductCategory.cs +++ b/src/Core/Grand.Domain/Catalog/ProductCategory.cs @@ -12,7 +12,7 @@ public class ProductCategory : SubBaseEntity /// [AuditReference(typeof(Category))] [AuditName] - public string CategoryId { get; set; } + public string? CategoryId { get; set; } /// /// Gets or sets a value indicating whether the product is featured diff --git a/src/Core/Grand.Domain/Catalog/ProductCollection.cs b/src/Core/Grand.Domain/Catalog/ProductCollection.cs index 0c1fb520b..9209edfb0 100644 --- a/src/Core/Grand.Domain/Catalog/ProductCollection.cs +++ b/src/Core/Grand.Domain/Catalog/ProductCollection.cs @@ -12,7 +12,7 @@ public class ProductCollection : SubBaseEntity /// [AuditReference(typeof(Collection))] [AuditName] - public string CollectionId { get; set; } + public string? CollectionId { get; set; } /// /// Gets or sets a value indicating whether the product is featured diff --git a/src/Core/Grand.Domain/Catalog/ProductCombinationTierPrices.cs b/src/Core/Grand.Domain/Catalog/ProductCombinationTierPrices.cs index 83fa0ddcc..75470819b 100644 --- a/src/Core/Grand.Domain/Catalog/ProductCombinationTierPrices.cs +++ b/src/Core/Grand.Domain/Catalog/ProductCombinationTierPrices.cs @@ -13,13 +13,13 @@ public class ProductCombinationTierPrices : SubBaseEntity /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the customer group identifier /// [AuditReference(typeof(CustomerGroup))] - public string CustomerGroupId { get; set; } + public string? CustomerGroupId { get; set; } /// /// Gets or sets the quantity diff --git a/src/Core/Grand.Domain/Catalog/ProductCombinationWarehouseInventory.cs b/src/Core/Grand.Domain/Catalog/ProductCombinationWarehouseInventory.cs index d74b8c597..4677d9f76 100644 --- a/src/Core/Grand.Domain/Catalog/ProductCombinationWarehouseInventory.cs +++ b/src/Core/Grand.Domain/Catalog/ProductCombinationWarehouseInventory.cs @@ -13,7 +13,7 @@ public class ProductCombinationWarehouseInventory : SubBaseEntity /// [AuditReference(typeof(Warehouse))] [AuditName] - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } /// /// Gets or sets the stock quantity diff --git a/src/Core/Grand.Domain/Catalog/ProductExtensions.cs b/src/Core/Grand.Domain/Catalog/ProductExtensions.cs index 7ef26840b..9d6f1fb63 100644 --- a/src/Core/Grand.Domain/Catalog/ProductExtensions.cs +++ b/src/Core/Grand.Domain/Catalog/ProductExtensions.cs @@ -18,7 +18,7 @@ public static class ProductExtensions /// /// Quantity /// Price - public static TierPrice GetPreferredTierPrice(this Product product, Customer customer, string storeId, + public static TierPrice? GetPreferredTierPrice(this Product product, Customer customer, string storeId, string currencyCode, int quantity) { if (!product.TierPrices.Any()) @@ -82,8 +82,8 @@ public static int[] ParseAllowedQuantities(this Product product) /// SKU /// MPN /// GTIN - private static void GetSkuMpnGtin(this Product product, IList attributes, - out string sku, out string mpn, out string gtin) + private static void GetSkuMpnGtin(this Product product, IList? attributes, + out string? sku, out string? mpn, out string? gtin) { ArgumentNullException.ThrowIfNull(product); @@ -117,7 +117,7 @@ private static void GetSkuMpnGtin(this Product product, IList a /// Attributes /// A value indicating whether we should ignore non-combinable attributes /// Found product attribute combination - public static ProductAttributeCombination FindProductAttributeCombination(this Product product, + public static ProductAttributeCombination? FindProductAttributeCombination(this Product product, IList customAttributes, bool ignoreNonCombinableAttributes = true) { ArgumentNullException.ThrowIfNull(product); @@ -188,9 +188,9 @@ public static IList ParseProductAttributeValues(this Prod /// Attributes /// Product attribute mapping identifier /// Product attribute values - public static IList ParseValues(IList customAttributes, string productAttributeMappingId) + public static IList ParseValues(IList customAttributes, string productAttributeMappingId) { - var selectedValues = new List(); + var selectedValues = new List(); if (customAttributes == null || !customAttributes.Any()) return selectedValues; @@ -259,7 +259,7 @@ public static bool AreProductAttributesEqual(Product product, IList str1.Trim() == str2.Trim()); + var hasValue = values2Str.Any(str2 => str1?.Trim() == str2?.Trim()); if (hasValue) continue; attributesEqual = false; break; @@ -333,7 +333,7 @@ public static bool AreProductAttributesEqual(Product product, IList /// Product /// Attribute combinations - public static IList> GenerateAllCombinations(this Product product) + public static IList>? GenerateAllCombinations(this Product product) { ArgumentNullException.ThrowIfNull(product); @@ -360,7 +360,7 @@ public static IList> GenerateAllCombinations(this P /// Product /// Attributes /// SKU - public static string FormatSku(this Product product, IList attributes = null) + public static string? FormatSku(this Product product, IList? attributes = null) { ArgumentNullException.ThrowIfNull(product); @@ -375,7 +375,7 @@ public static string FormatSku(this Product product, IList attr /// Product /// Attributes /// Collection part number - public static string FormatMpn(this Product product, IList attributes = null) + public static string? FormatMpn(this Product product, IList? attributes = null) { ArgumentNullException.ThrowIfNull(product); @@ -390,7 +390,7 @@ public static string FormatMpn(this Product product, IList attr /// Product /// Attributes /// GTIN - public static string FormatGtin(this Product product, IList attributes = null) + public static string? FormatGtin(this Product product, IList? attributes = null) { ArgumentNullException.ThrowIfNull(product); diff --git a/src/Core/Grand.Domain/Catalog/ProductLayout.cs b/src/Core/Grand.Domain/Catalog/ProductLayout.cs index 6272aa959..cdcc6e336 100644 --- a/src/Core/Grand.Domain/Catalog/ProductLayout.cs +++ b/src/Core/Grand.Domain/Catalog/ProductLayout.cs @@ -8,12 +8,12 @@ public class ProductLayout : BaseEntity /// /// Gets or sets the layout name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the view path /// - public string ViewPath { get; set; } + public string? ViewPath { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Catalog/ProductPicture.cs b/src/Core/Grand.Domain/Catalog/ProductPicture.cs index 61cd414c3..5163aba26 100644 --- a/src/Core/Grand.Domain/Catalog/ProductPicture.cs +++ b/src/Core/Grand.Domain/Catalog/ProductPicture.cs @@ -8,7 +8,7 @@ public class ProductPicture : SubBaseEntity /// /// Gets or sets the picture identifier /// - public string PictureId { get; set; } + public string? PictureId { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Catalog/ProductPrice.cs b/src/Core/Grand.Domain/Catalog/ProductPrice.cs index 8e09ccc38..0f09d7a47 100644 --- a/src/Core/Grand.Domain/Catalog/ProductPrice.cs +++ b/src/Core/Grand.Domain/Catalog/ProductPrice.cs @@ -5,8 +5,8 @@ namespace Grand.Domain.Catalog; public class ProductPrice : SubBaseEntity { [AuditReference(typeof(Product))] - public string ProductId { get; set; } + public string? ProductId { get; set; } [AuditName] - public string CurrencyCode { get; set; } + public string? CurrencyCode { get; set; } public double Price { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Catalog/ProductReservation.cs b/src/Core/Grand.Domain/Catalog/ProductReservation.cs index 0bb9602eb..2025c2db7 100644 --- a/src/Core/Grand.Domain/Catalog/ProductReservation.cs +++ b/src/Core/Grand.Domain/Catalog/ProductReservation.cs @@ -12,7 +12,7 @@ public class ProductReservation : BaseEntity /// Gets or sets the product identifier /// [AuditReference(typeof(Product))] - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// Gets or sets the reservation date @@ -23,20 +23,20 @@ public class ProductReservation : BaseEntity /// Gets or sets the order id /// [AuditReference(typeof(Order))] - public string OrderId { get; set; } + public string? OrderId { get; set; } /// /// Gets or sets resource name /// - public string Resource { get; set; } + public string? Resource { get; set; } /// /// Gets or sets parameter name /// - public string Parameter { get; set; } + public string? Parameter { get; set; } /// /// Gets or sets duration /// - public string Duration { get; set; } + public string? Duration { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Catalog/ProductReview.cs b/src/Core/Grand.Domain/Catalog/ProductReview.cs index cf81b9f3f..9e75f3c27 100644 --- a/src/Core/Grand.Domain/Catalog/ProductReview.cs +++ b/src/Core/Grand.Domain/Catalog/ProductReview.cs @@ -9,25 +9,25 @@ namespace Grand.Domain.Catalog; /// public class ProductReview : BaseEntity { - private ICollection _productReviewHelpfulnessEntries; + private ICollection? _productReviewHelpfulnessEntries; /// /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the product identifier /// [AuditReference(typeof(Product))] - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets a value indicating whether the content is approved @@ -38,22 +38,22 @@ public class ProductReview : BaseEntity /// Gets or sets the title /// [AuditName] - public string Title { get; set; } + public string? Title { get; set; } /// /// Gets or sets the review text /// - public string ReviewText { get; set; } + public string? ReviewText { get; set; } /// /// Gets or sets the reply text /// - public string ReplyText { get; set; } + public string? ReplyText { get; set; } /// /// Gets or sets the Signature (for response text) /// - public string Signature { get; set; } + public string? Signature { get; set; } /// /// Gets or sets the review was confirmed by purchased diff --git a/src/Core/Grand.Domain/Catalog/ProductReviewHelpfulness.cs b/src/Core/Grand.Domain/Catalog/ProductReviewHelpfulness.cs index 39ca4330a..4f3927b92 100644 --- a/src/Core/Grand.Domain/Catalog/ProductReviewHelpfulness.cs +++ b/src/Core/Grand.Domain/Catalog/ProductReviewHelpfulness.cs @@ -8,7 +8,7 @@ public class ProductReviewHelpfulness : SubBaseEntity /// /// Gets or sets the product review identifier /// - public string ProductReviewId { get; set; } + public string? ProductReviewId { get; set; } /// /// A value indicating whether a review a helpful @@ -18,5 +18,5 @@ public class ProductReviewHelpfulness : SubBaseEntity /// /// Gets or sets the customer identifier /// - public string CustomerId { get; set; } + public string? CustomerId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Catalog/ProductSerialNumber.cs b/src/Core/Grand.Domain/Catalog/ProductSerialNumber.cs index 6ddd82a9d..b5901f0b7 100644 --- a/src/Core/Grand.Domain/Catalog/ProductSerialNumber.cs +++ b/src/Core/Grand.Domain/Catalog/ProductSerialNumber.cs @@ -7,36 +7,36 @@ namespace Grand.Domain.Catalog; /// public class ProductSerialNumber : BaseEntity { - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// The combination of a product stocked by attributes /// - public string CombinationId { get; set; } + public string? CombinationId { get; set; } public IList Attributes { get; set; } = new List(); /// /// The serial number as entered /// - public string Number { get; set; } + public string? Number { get; set; } /// /// The number trimmed and upper-cased: what lookups and the unique index compare /// - public string NumberKey { get; set; } + public string? NumberKey { get; set; } public SerialNumberStatus StatusId { get; set; } /// /// The warehouse of the bucket the unit is or was last in, as the inventory journal names it /// - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } /// /// The store of the warehouse; empty for a shared warehouse /// - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// The purchase price of the unit, in the primary store currency @@ -48,13 +48,13 @@ public class ProductSerialNumber : BaseEntity /// /// The receipt that brought the unit in /// - public string ReceiptDocumentId { get; set; } + public string? ReceiptDocumentId { get; set; } - public string OrderId { get; set; } + public string? OrderId { get; set; } - public string OrderItemId { get; set; } + public string? OrderItemId { get; set; } - public string ShipmentId { get; set; } + public string? ShipmentId { get; set; } public DateTime? ShippedOnUtc { get; set; } @@ -74,14 +74,14 @@ public class ProductSerialNumber : BaseEntity /// /// The place in the unit's warehouse where it is kept; a location of another warehouse is a stale one /// - public string LocationId { get; set; } + public string? LocationId { get; set; } /// /// The production date, a date without time /// public DateTime? ManufacturedOnUtc { get; set; } - public string Supplier { get; set; } + public string? Supplier { get; set; } /// /// The end of the warranty the supplier or manufacturer gives the store, a date without time @@ -91,16 +91,16 @@ public class ProductSerialNumber : BaseEntity /// /// The IMEI of a device with a mobile modem /// - public string Imei { get; set; } + public string? Imei { get; set; } - public string MacAddress { get; set; } + public string? MacAddress { get; set; } - public string FirmwareVersion { get; set; } + public string? FirmwareVersion { get; set; } - public string AdminComment { get; set; } + public string? AdminComment { get; set; } /// /// Shown to the customer who received the unit /// - public string CustomerComment { get; set; } + public string? CustomerComment { get; set; } } diff --git a/src/Core/Grand.Domain/Catalog/ProductSpecificationAttribute.cs b/src/Core/Grand.Domain/Catalog/ProductSpecificationAttribute.cs index f55ea68d9..92acc1c2b 100644 --- a/src/Core/Grand.Domain/Catalog/ProductSpecificationAttribute.cs +++ b/src/Core/Grand.Domain/Catalog/ProductSpecificationAttribute.cs @@ -17,23 +17,23 @@ public class ProductSpecificationAttribute : SubBaseEntity /// [AuditReference(typeof(SpecificationAttribute))] [AuditName] - public string SpecificationAttributeId { get; set; } + public string? SpecificationAttributeId { get; set; } /// /// Gets or sets the specification attribute identifier /// [AuditReference(typeof(SpecificationAttribute), nameof(SpecificationAttribute.SpecificationAttributeOptions), Owner = nameof(SpecificationAttributeId))] - public string SpecificationAttributeOptionId { get; set; } + public string? SpecificationAttributeOptionId { get; set; } /// /// Gets or sets the custom name /// - public string CustomName { get; set; } + public string? CustomName { get; set; } /// /// Gets or sets the custom value /// - public string CustomValue { get; set; } + public string? CustomValue { get; set; } /// /// Gets or sets whether the attribute can be filtered by diff --git a/src/Core/Grand.Domain/Catalog/ProductTag.cs b/src/Core/Grand.Domain/Catalog/ProductTag.cs index 291f1057a..86a7f0052 100644 --- a/src/Core/Grand.Domain/Catalog/ProductTag.cs +++ b/src/Core/Grand.Domain/Catalog/ProductTag.cs @@ -10,12 +10,12 @@ public class ProductTag : BaseEntity, ITranslationEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the sename /// - public string SeName { get; set; } + public string? SeName { get; set; } /// /// Gets or sets the count diff --git a/src/Core/Grand.Domain/Catalog/ProductWarehouseInventory.cs b/src/Core/Grand.Domain/Catalog/ProductWarehouseInventory.cs index fc16e68d4..abaa95b92 100644 --- a/src/Core/Grand.Domain/Catalog/ProductWarehouseInventory.cs +++ b/src/Core/Grand.Domain/Catalog/ProductWarehouseInventory.cs @@ -13,7 +13,7 @@ public class ProductWarehouseInventory : SubBaseEntity /// [AuditReference(typeof(Warehouse))] [AuditName] - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } /// /// Gets or sets the stock quantity diff --git a/src/Core/Grand.Domain/Catalog/RecentlyViewedProduct.cs b/src/Core/Grand.Domain/Catalog/RecentlyViewedProduct.cs index db1bf0e3e..dcb7978e2 100644 --- a/src/Core/Grand.Domain/Catalog/RecentlyViewedProduct.cs +++ b/src/Core/Grand.Domain/Catalog/RecentlyViewedProduct.cs @@ -2,6 +2,6 @@ public class RecentlyViewedProduct : BaseEntity { - public string CustomerId { get; set; } - public string ProductId { get; set; } + public string? CustomerId { get; set; } + public string? ProductId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Catalog/RelatedProduct.cs b/src/Core/Grand.Domain/Catalog/RelatedProduct.cs index 055c43447..09a00de81 100644 --- a/src/Core/Grand.Domain/Catalog/RelatedProduct.cs +++ b/src/Core/Grand.Domain/Catalog/RelatedProduct.cs @@ -12,7 +12,7 @@ public class RelatedProduct : SubBaseEntity /// [AuditReference(typeof(Product))] [AuditName] - public string ProductId2 { get; set; } + public string? ProductId2 { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Catalog/SimilarProduct.cs b/src/Core/Grand.Domain/Catalog/SimilarProduct.cs index 542046350..797ff9725 100644 --- a/src/Core/Grand.Domain/Catalog/SimilarProduct.cs +++ b/src/Core/Grand.Domain/Catalog/SimilarProduct.cs @@ -10,14 +10,14 @@ public class SimilarProduct : SubBaseEntity /// /// Gets or sets the first product identifier /// - public string ProductId1 { get; set; } + public string? ProductId1 { get; set; } /// /// Gets or sets the second product identifier /// [AuditReference(typeof(Product))] [AuditName] - public string ProductId2 { get; set; } + public string? ProductId2 { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Catalog/SpecificationAttribute.cs b/src/Core/Grand.Domain/Catalog/SpecificationAttribute.cs index e669ab8b7..9e4bcaec1 100644 --- a/src/Core/Grand.Domain/Catalog/SpecificationAttribute.cs +++ b/src/Core/Grand.Domain/Catalog/SpecificationAttribute.cs @@ -9,17 +9,17 @@ namespace Grand.Domain.Catalog; /// public class SpecificationAttribute : BaseEntity, IStoreLinkEntity, ITranslationEntity { - private ICollection _specificationAttributeOptions; + private ICollection? _specificationAttributeOptions; /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the sename /// - public string SeName { get; set; } + public string? SeName { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Catalog/SpecificationAttributeOption.cs b/src/Core/Grand.Domain/Catalog/SpecificationAttributeOption.cs index 736d1b77e..2acc38f9d 100644 --- a/src/Core/Grand.Domain/Catalog/SpecificationAttributeOption.cs +++ b/src/Core/Grand.Domain/Catalog/SpecificationAttributeOption.cs @@ -10,17 +10,17 @@ public class SpecificationAttributeOption : SubBaseEntity, ITranslationEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the sename /// - public string SeName { get; set; } + public string? SeName { get; set; } /// /// Gets or sets the color RGB value (used when you want to display "Color squares" instead of text) /// - public string ColorSquaresRgb { get; set; } + public string? ColorSquaresRgb { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Catalog/SpecificationAttributeOptionFilter.cs b/src/Core/Grand.Domain/Catalog/SpecificationAttributeOptionFilter.cs index 31523d25f..a99f8d086 100644 --- a/src/Core/Grand.Domain/Catalog/SpecificationAttributeOptionFilter.cs +++ b/src/Core/Grand.Domain/Catalog/SpecificationAttributeOptionFilter.cs @@ -8,22 +8,22 @@ public class SpecificationAttributeOptionFilter /// /// Gets or sets the specification attribute identifier /// - public string SpecificationAttributeId { get; set; } + public string? SpecificationAttributeId { get; set; } /// /// Gets or sets the specification attribute name /// - public string SpecificationAttributeName { get; set; } + public string? SpecificationAttributeName { get; set; } /// /// Gets or sets the specification attribute sename /// - public string SpecificationAttributeSeName { get; set; } + public string? SpecificationAttributeSeName { get; set; } /// /// Gets or sets the specification attribute option color (RGB) /// - public string SpecificationAttributeOptionColorRgb { get; set; } + public string? SpecificationAttributeOptionColorRgb { get; set; } /// /// Gets or sets the specification attribute display order @@ -33,17 +33,17 @@ public class SpecificationAttributeOptionFilter /// /// Gets or sets the specification attribute option identifier /// - public string SpecificationAttributeOptionId { get; set; } + public string? SpecificationAttributeOptionId { get; set; } /// /// Gets or sets the specification attribute option name /// - public string SpecificationAttributeOptionName { get; set; } + public string? SpecificationAttributeOptionName { get; set; } /// /// Gets or sets the specification attribute option sename /// - public string SpecificationAttributeOptionSeName { get; set; } + public string? SpecificationAttributeOptionSeName { get; set; } /// /// Gets or sets the specification attribute option display order diff --git a/src/Core/Grand.Domain/Catalog/TierPrice.cs b/src/Core/Grand.Domain/Catalog/TierPrice.cs index 32d0cf031..cb674a590 100644 --- a/src/Core/Grand.Domain/Catalog/TierPrice.cs +++ b/src/Core/Grand.Domain/Catalog/TierPrice.cs @@ -13,18 +13,18 @@ public class TierPrice : SubBaseEntity /// Gets or sets the store identifier (0 - all stores) /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the customer group identifier /// [AuditReference(typeof(CustomerGroup))] - public string CustomerGroupId { get; set; } + public string? CustomerGroupId { get; set; } /// /// Gets or sets the currency code /// - public string CurrencyCode { get; set; } + public string? CurrencyCode { get; set; } /// /// Gets or sets the quantity diff --git a/src/Core/Grand.Domain/Common/Address.cs b/src/Core/Grand.Domain/Common/Address.cs index 002ffe392..1c0feb4d8 100644 --- a/src/Core/Grand.Domain/Common/Address.cs +++ b/src/Core/Grand.Domain/Common/Address.cs @@ -8,79 +8,79 @@ public class Address : SubBaseEntity /// /// Gets or sets the name of address /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the first name /// - public string FirstName { get; set; } + public string? FirstName { get; set; } /// /// Gets or sets the last name /// - public string LastName { get; set; } + public string? LastName { get; set; } /// /// Gets or sets the email /// - public string Email { get; set; } + public string? Email { get; set; } /// /// Gets or sets the company /// - public string Company { get; set; } + public string? Company { get; set; } /// /// Gets or sets the vat numer /// - public string VatNumber { get; set; } + public string? VatNumber { get; set; } /// /// Gets or sets the country identifier /// [AuditReference(typeof(Country))] - public string CountryId { get; set; } + public string? CountryId { get; set; } /// /// Gets or sets the state/province identifier /// [AuditReference(typeof(Country), nameof(Country.StateProvinces), Owner = nameof(CountryId))] - public string StateProvinceId { get; set; } + public string? StateProvinceId { get; set; } /// /// Gets or sets the city /// - public string City { get; set; } + public string? City { get; set; } /// /// Gets or sets the address 1 /// - public string Address1 { get; set; } + public string? Address1 { get; set; } /// /// Gets or sets the address 2 /// - public string Address2 { get; set; } + public string? Address2 { get; set; } /// /// Gets or sets the zip/postal code /// - public string ZipPostalCode { get; set; } + public string? ZipPostalCode { get; set; } /// /// Gets or sets the phone number /// - public string PhoneNumber { get; set; } + public string? PhoneNumber { get; set; } /// /// Gets or sets the fax number /// - public string FaxNumber { get; set; } + public string? FaxNumber { get; set; } /// /// Gets or sets the note /// - public string Note { get; set; } + public string? Note { get; set; } /// /// Gets or sets the custom attributes (see "AddressAttribute" entity for more info) diff --git a/src/Core/Grand.Domain/Common/AddressAttribute.cs b/src/Core/Grand.Domain/Common/AddressAttribute.cs index d088b6287..4769c376a 100644 --- a/src/Core/Grand.Domain/Common/AddressAttribute.cs +++ b/src/Core/Grand.Domain/Common/AddressAttribute.cs @@ -10,12 +10,12 @@ namespace Grand.Domain.Common; /// public class AddressAttribute : BaseEntity, ITranslationEntity, IStoreLinkEntity { - private ICollection _addressAttributeValues; + private ICollection? _addressAttributeValues; /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets a value indicating whether the attribute is required diff --git a/src/Core/Grand.Domain/Common/AddressAttributeValue.cs b/src/Core/Grand.Domain/Common/AddressAttributeValue.cs index 0bc5869b0..3bbdc7cc9 100644 --- a/src/Core/Grand.Domain/Common/AddressAttributeValue.cs +++ b/src/Core/Grand.Domain/Common/AddressAttributeValue.cs @@ -12,12 +12,12 @@ public class AddressAttributeValue : BaseEntity, ITranslationEntity /// Gets or sets the address attribute identifier /// [AuditReference(typeof(AddressAttribute))] - public string AddressAttributeId { get; set; } + public string? AddressAttributeId { get; set; } /// /// Gets or sets the checkout attribute name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets a value indicating whether the value is pre-selected diff --git a/src/Core/Grand.Domain/Common/AddressExtensions.cs b/src/Core/Grand.Domain/Common/AddressExtensions.cs index ea19b5b0f..91e45726c 100644 --- a/src/Core/Grand.Domain/Common/AddressExtensions.cs +++ b/src/Core/Grand.Domain/Common/AddressExtensions.cs @@ -19,7 +19,7 @@ public static class AddressExtensions /// Zip postal code /// Country identifier /// Address - public static Address FindAddress(this IEnumerable
source, + public static Address? FindAddress(this IEnumerable
source, string firstName, string lastName, string phoneNumber, string email, string faxNumber, string company, string address1, string address2, string city, string stateProvinceId, diff --git a/src/Core/Grand.Domain/Common/AdminAreaSettings.cs b/src/Core/Grand.Domain/Common/AdminAreaSettings.cs index eadd4d528..9b4a539bb 100644 --- a/src/Core/Grand.Domain/Common/AdminAreaSettings.cs +++ b/src/Core/Grand.Domain/Common/AdminAreaSettings.cs @@ -12,7 +12,7 @@ public class AdminAreaSettings : ISettings /// /// A comma-separated list of available grid page sizes /// - public string GridPageSizes { get; set; } + public string? GridPageSizes { get; set; } /// /// Gets or sets a value indicating whether to use IsoDateTimeConverter in Json results (used for avoiding issue with diff --git a/src/Core/Grand.Domain/Common/CaptchaSettings.cs b/src/Core/Grand.Domain/Common/CaptchaSettings.cs index d0402c0a1..38625c25b 100644 --- a/src/Core/Grand.Domain/Common/CaptchaSettings.cs +++ b/src/Core/Grand.Domain/Common/CaptchaSettings.cs @@ -85,17 +85,17 @@ public class CaptchaSettings : ISettings /// /// reCAPTCHA public key /// - public string ReCaptchaPublicKey { get; set; } + public string? ReCaptchaPublicKey { get; set; } /// /// reCAPTCHA private key /// - public string ReCaptchaPrivateKey { get; set; } + public string? ReCaptchaPrivateKey { get; set; } /// /// reCAPTCHA theme /// - public string ReCaptchaTheme { get; set; } + public string? ReCaptchaTheme { get; set; } /// /// reCAPTCHA score @@ -110,7 +110,7 @@ public class CaptchaSettings : ISettings /// /// reCAPTCHA language /// - public string ReCaptchaLanguage { get; set; } + public string? ReCaptchaLanguage { get; set; } } /// diff --git a/src/Core/Grand.Domain/Common/CustomAttribute.cs b/src/Core/Grand.Domain/Common/CustomAttribute.cs index 82a0adda2..8300b5331 100644 --- a/src/Core/Grand.Domain/Common/CustomAttribute.cs +++ b/src/Core/Grand.Domain/Common/CustomAttribute.cs @@ -2,6 +2,6 @@ public class CustomAttribute { - public string Key { get; set; } - public string Value { get; set; } + public string? Key { get; set; } + public string? Value { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Common/GrandNodeVersion.cs b/src/Core/Grand.Domain/Common/GrandNodeVersion.cs index 3f1ce4337..2d3ab77e6 100644 --- a/src/Core/Grand.Domain/Common/GrandNodeVersion.cs +++ b/src/Core/Grand.Domain/Common/GrandNodeVersion.cs @@ -2,6 +2,6 @@ public class GrandNodeVersion : BaseEntity { - public string InstalledVersion { get; set; } - public string DataBaseVersion { get; set; } + public string? InstalledVersion { get; set; } + public string? DataBaseVersion { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Common/PdfSettings.cs b/src/Core/Grand.Domain/Common/PdfSettings.cs index 18e3ee8ee..0069bb92d 100644 --- a/src/Core/Grand.Domain/Common/PdfSettings.cs +++ b/src/Core/Grand.Domain/Common/PdfSettings.cs @@ -7,7 +7,7 @@ public class PdfSettings : ISettings /// /// PDF logo picture identifier /// - public string LogoPictureId { get; set; } + public string? LogoPictureId { get; set; } /// /// Gets or sets a value indicating whether to disallow customers to print PDF invoices for pedning orders @@ -17,12 +17,12 @@ public class PdfSettings : ISettings /// /// Gets or sets the text that will appear at the top of invoices /// - public string InvoiceHeaderText { get; set; } + public string? InvoiceHeaderText { get; set; } /// /// Gets or sets the text that will appear at the bottom of invoices /// - public string InvoiceFooterText { get; set; } + public string? InvoiceFooterText { get; set; } /// /// Gets or sets a value indicating whether an order PDF lists the batches and serial numbers its shipments diff --git a/src/Core/Grand.Domain/Common/RobotsTxt.cs b/src/Core/Grand.Domain/Common/RobotsTxt.cs index 0805e78a8..c55b67f55 100644 --- a/src/Core/Grand.Domain/Common/RobotsTxt.cs +++ b/src/Core/Grand.Domain/Common/RobotsTxt.cs @@ -5,15 +5,15 @@ public class RobotsTxt : BaseEntity /// /// Gets or sets the name of robots.txt /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the text of robots.txt /// - public string Text { get; set; } + public string? Text { get; set; } /// /// Gets or sets a value store ident /// - public string StoreId { get; set; } + public string? StoreId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Common/SearchTerm.cs b/src/Core/Grand.Domain/Common/SearchTerm.cs index ef6c0eb83..3994c2e32 100644 --- a/src/Core/Grand.Domain/Common/SearchTerm.cs +++ b/src/Core/Grand.Domain/Common/SearchTerm.cs @@ -8,12 +8,12 @@ public class SearchTerm : BaseEntity /// /// Gets or sets the keyword /// - public string Keyword { get; set; } + public string? Keyword { get; set; } /// /// Gets or sets the store identifier /// - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets search count diff --git a/src/Core/Grand.Domain/Common/UserField.cs b/src/Core/Grand.Domain/Common/UserField.cs index eb13387bb..ec919c7d5 100644 --- a/src/Core/Grand.Domain/Common/UserField.cs +++ b/src/Core/Grand.Domain/Common/UserField.cs @@ -8,15 +8,15 @@ public class UserField /// /// Gets or sets the key /// - public string Key { get; set; } + public string? Key { get; set; } /// /// Gets or sets the value /// - public string Value { get; set; } + public string? Value { get; set; } /// /// Gets or sets the store identifier /// - public string StoreId { get; set; } + public string? StoreId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Common/UserFieldExtensions.cs b/src/Core/Grand.Domain/Common/UserFieldExtensions.cs index 7b2fd20f6..170263334 100644 --- a/src/Core/Grand.Domain/Common/UserFieldExtensions.cs +++ b/src/Core/Grand.Domain/Common/UserFieldExtensions.cs @@ -12,7 +12,7 @@ public static class UserFieldExtensions /// Key /// Load a value specific for a certain store; pass 0 to load a value shared for all stores /// Attribute - public static TPropType GetUserFieldFromEntity(this BaseEntity entity, string key, string storeId = "") + public static TPropType? GetUserFieldFromEntity(this BaseEntity entity, string key, string storeId = "") { ArgumentNullException.ThrowIfNull(entity); @@ -24,7 +24,7 @@ public static TPropType GetUserFieldFromEntity(this BaseEntity entity return default; var prop = props.FirstOrDefault(ga => - ga.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase)); + string.Equals(ga.Key, key, StringComparison.InvariantCultureIgnoreCase)); if (prop == null || string.IsNullOrEmpty(prop.Value)) return default; diff --git a/src/Core/Grand.Domain/Configuration/Setting.cs b/src/Core/Grand.Domain/Configuration/Setting.cs index 698595186..de600313d 100644 --- a/src/Core/Grand.Domain/Configuration/Setting.cs +++ b/src/Core/Grand.Domain/Configuration/Setting.cs @@ -8,15 +8,15 @@ public class Setting : BaseEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the store for which this setting is valid. 0 is set when the setting is for all stores /// - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the metadata settings /// - public string Metadata { get; set; } + public string? Metadata { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Courses/Course.cs b/src/Core/Grand.Domain/Courses/Course.cs index 0065c961b..a62043573 100644 --- a/src/Core/Grand.Domain/Courses/Course.cs +++ b/src/Core/Grand.Domain/Courses/Course.cs @@ -13,17 +13,17 @@ public class Course : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEnt /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the description /// - public string Description { get; set; } + public string? Description { get; set; } /// /// Gets or sets the description /// - public string ShortDescription { get; set; } + public string? ShortDescription { get; set; } /// /// Gets or sets a value indicating whether the entity is published @@ -38,34 +38,34 @@ public class Course : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEnt /// /// Gets or sets the picture /// - public string PictureId { get; set; } + public string? PictureId { get; set; } /// /// Gets or sets the product ident /// [AuditReference(typeof(Product))] - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// Gets or sets the level ident /// [AuditReference(typeof(CourseLevel))] - public string LevelId { get; set; } + public string? LevelId { get; set; } /// /// Gets or sets the meta keywords /// - public string MetaKeywords { get; set; } + public string? MetaKeywords { get; set; } /// /// Gets or sets the meta description /// - public string MetaDescription { get; set; } + public string? MetaDescription { get; set; } /// /// Gets or sets the meta title /// - public string MetaTitle { get; set; } + public string? MetaTitle { get; set; } /// /// Gets or sets a value indicating whether the entity is subject to ACL @@ -78,7 +78,7 @@ public class Course : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEnt /// /// Gets or sets the name /// - public string SeName { get; set; } + public string? SeName { get; set; } /// /// Gets or sets a value indicating whether the entity is limited/restricted to certain stores diff --git a/src/Core/Grand.Domain/Courses/CourseAction.cs b/src/Core/Grand.Domain/Courses/CourseAction.cs index f746fb131..c3a5ed6db 100644 --- a/src/Core/Grand.Domain/Courses/CourseAction.cs +++ b/src/Core/Grand.Domain/Courses/CourseAction.cs @@ -9,19 +9,19 @@ public class CourseAction : BaseEntity /// Gets or sets the customer ident /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the course ident /// [AuditReference(typeof(Course))] - public string CourseId { get; set; } + public string? CourseId { get; set; } /// /// Gets or sets the lesson ident /// [AuditReference(typeof(CourseLesson))] - public string LessonId { get; set; } + public string? LessonId { get; set; } /// /// Gets or sets the finished diff --git a/src/Core/Grand.Domain/Courses/CourseLesson.cs b/src/Core/Grand.Domain/Courses/CourseLesson.cs index 7364808cd..e67436af5 100644 --- a/src/Core/Grand.Domain/Courses/CourseLesson.cs +++ b/src/Core/Grand.Domain/Courses/CourseLesson.cs @@ -7,17 +7,17 @@ public class CourseLesson : BaseEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the short description /// - public string ShortDescription { get; set; } + public string? ShortDescription { get; set; } /// /// Gets or sets the description /// - public string Description { get; set; } + public string? Description { get; set; } /// /// Gets or sets the display order @@ -28,28 +28,28 @@ public class CourseLesson : BaseEntity /// Gets or sets the course ident /// [AuditReference(typeof(Course))] - public string CourseId { get; set; } + public string? CourseId { get; set; } /// /// Gets or sets the subject ident /// [AuditReference(typeof(CourseSubject))] - public string SubjectId { get; set; } + public string? SubjectId { get; set; } /// /// Gets or sets the video file /// - public string VideoFile { get; set; } + public string? VideoFile { get; set; } /// /// Gets or sets the attachment ident /// - public string AttachmentId { get; set; } + public string? AttachmentId { get; set; } /// /// Gets or sets the picture /// - public string PictureId { get; set; } + public string? PictureId { get; set; } /// /// Gets or sets a value indicating whether the entity is published diff --git a/src/Core/Grand.Domain/Courses/CourseLevel.cs b/src/Core/Grand.Domain/Courses/CourseLevel.cs index 874a41e47..261b2ea5a 100644 --- a/src/Core/Grand.Domain/Courses/CourseLevel.cs +++ b/src/Core/Grand.Domain/Courses/CourseLevel.cs @@ -5,7 +5,7 @@ public class CourseLevel : BaseEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Courses/CourseSubject.cs b/src/Core/Grand.Domain/Courses/CourseSubject.cs index 0cf710aec..bfc41a840 100644 --- a/src/Core/Grand.Domain/Courses/CourseSubject.cs +++ b/src/Core/Grand.Domain/Courses/CourseSubject.cs @@ -7,7 +7,7 @@ public class CourseSubject : BaseEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the display order @@ -18,5 +18,5 @@ public class CourseSubject : BaseEntity /// Gets or sets the course ident /// [AuditReference(typeof(Course))] - public string CourseId { get; set; } + public string? CourseId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Customers/Customer.cs b/src/Core/Grand.Domain/Customers/Customer.cs index 333fb5f8c..364ddca7b 100644 --- a/src/Core/Grand.Domain/Customers/Customer.cs +++ b/src/Core/Grand.Domain/Customers/Customer.cs @@ -12,10 +12,10 @@ namespace Grand.Domain.Customers; /// public class Customer : BaseEntity { - private ICollection
_addresses; - private ICollection _customerTags; - private ICollection _groups; - private ICollection _shoppingCartItems; + private ICollection
? _addresses; + private ICollection? _customerTags; + private ICollection? _groups; + private ICollection? _shoppingCartItems; /// /// Ctor @@ -35,18 +35,18 @@ public Customer() /// /// Gets or sets the username /// - public string Username { get; set; } + public string? Username { get; set; } /// /// Gets or sets the email /// [AuditName] - public string Email { get; set; } + public string? Email { get; set; } /// /// Gets or sets the password /// - public string Password { get; set; } + public string? Password { get; set; } /// /// Gets or sets the password format @@ -56,12 +56,12 @@ public Customer() /// /// Gets or sets the password salt /// - public string PasswordSalt { get; set; } + public string? PasswordSalt { get; set; } /// /// Gets or sets the admin comment /// - public string AdminComment { get; set; } + public string? AdminComment { get; set; } /// /// Gets or sets a value indicating whether the customer is tax exempt @@ -77,31 +77,31 @@ public Customer() /// Gets or sets the affiliate identifier /// [AuditReference(typeof(Affiliate))] - public string AffiliateId { get; set; } + public string? AffiliateId { get; set; } /// /// Gets or sets the vendor identifier with which this customer is associated (manager) /// [AuditReference(typeof(Vendor))] - public string VendorId { get; set; } + public string? VendorId { get; set; } /// /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the staff store identifier /// [AuditReference(typeof(Store))] - public string StaffStoreId { get; set; } + public string? StaffStoreId { get; set; } /// /// Gets or sets the owner identifier /// [AuditReference(typeof(Customer))] - public string OwnerId { get; set; } + public string? OwnerId { get; set; } /// /// Gets or sets the purchasing role of a sub-account; meaningful only when is set @@ -129,7 +129,7 @@ public Customer() /// /// Gets or sets the sales employee identifier /// - public string SeId { get; set; } + public string? SeId { get; set; } /// /// Gets or sets the custom attributes (see "CustomerAttribute" entity for more info) @@ -169,17 +169,17 @@ public Customer() /// /// Gets or sets the customer system name /// - public string SystemName { get; set; } + public string? SystemName { get; set; } /// /// Gets or sets the last IP address /// - public string LastIpAddress { get; set; } + public string? LastIpAddress { get; set; } /// /// Gets or sets the last visited page /// - public string LastVisitedPage { get; set; } + public string? LastVisitedPage { get; set; } /// /// Gets or sets the date and time of last login @@ -233,17 +233,17 @@ public virtual ICollection ShoppingCartItems { /// /// Default billing address /// - public virtual Address BillingAddress { get; set; } + public virtual Address? BillingAddress { get; set; } /// /// Default shipping address /// - public virtual Address ShippingAddress { get; set; } + public virtual Address? ShippingAddress { get; set; } /// /// Gets or sets the coordinates /// - public GeoCoordinates Coordinates { get; set; } + public GeoCoordinates? Coordinates { get; set; } /// /// Gets or sets customer addresses diff --git a/src/Core/Grand.Domain/Customers/CustomerAttribute.cs b/src/Core/Grand.Domain/Customers/CustomerAttribute.cs index 8fa2d8742..c433ee185 100644 --- a/src/Core/Grand.Domain/Customers/CustomerAttribute.cs +++ b/src/Core/Grand.Domain/Customers/CustomerAttribute.cs @@ -10,12 +10,12 @@ namespace Grand.Domain.Customers; /// public class CustomerAttribute : BaseEntity, ITranslationEntity, IStoreLinkEntity { - private ICollection _customerAttributeValues; + private ICollection? _customerAttributeValues; /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets a value indicating whether the attribute is required diff --git a/src/Core/Grand.Domain/Customers/CustomerAttributeValue.cs b/src/Core/Grand.Domain/Customers/CustomerAttributeValue.cs index 3fa19b840..1ca512548 100644 --- a/src/Core/Grand.Domain/Customers/CustomerAttributeValue.cs +++ b/src/Core/Grand.Domain/Customers/CustomerAttributeValue.cs @@ -12,12 +12,12 @@ public class CustomerAttributeValue : SubBaseEntity, ITranslationEntity /// Gets or sets the customer attribute identifier /// [AuditReference(typeof(CustomerAttribute))] - public string CustomerAttributeId { get; set; } + public string? CustomerAttributeId { get; set; } /// /// Gets or sets the checkout attribute name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets a value indicating whether the value is pre-selected diff --git a/src/Core/Grand.Domain/Customers/CustomerExtensions.cs b/src/Core/Grand.Domain/Customers/CustomerExtensions.cs index d49901a31..ed876e2ab 100644 --- a/src/Core/Grand.Domain/Customers/CustomerExtensions.cs +++ b/src/Core/Grand.Domain/Customers/CustomerExtensions.cs @@ -90,7 +90,7 @@ public static string GetFullName(this Customer customer) /// Source /// /// Formatted text - public static string FormatUserName(this Customer customer, CustomerNameFormat customerNameFormat) + public static string? FormatUserName(this Customer customer, CustomerNameFormat customerNameFormat) { if (customer == null) return string.Empty; diff --git a/src/Core/Grand.Domain/Customers/CustomerGroup.cs b/src/Core/Grand.Domain/Customers/CustomerGroup.cs index 1d6c1e4eb..2888ccc07 100644 --- a/src/Core/Grand.Domain/Customers/CustomerGroup.cs +++ b/src/Core/Grand.Domain/Customers/CustomerGroup.cs @@ -8,7 +8,7 @@ public class CustomerGroup : BaseEntity /// /// Gets or sets the customer group name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets a value indicating whether the customer group is marked as free shiping @@ -38,7 +38,7 @@ public class CustomerGroup : BaseEntity /// /// Gets or sets the customer group system name /// - public string SystemName { get; set; } + public string? SystemName { get; set; } /// /// Gets or sets a value indicating whether the customers must change passwords after a specified time diff --git a/src/Core/Grand.Domain/Customers/CustomerGroupProduct.cs b/src/Core/Grand.Domain/Customers/CustomerGroupProduct.cs index 9aae08725..18ef275fb 100644 --- a/src/Core/Grand.Domain/Customers/CustomerGroupProduct.cs +++ b/src/Core/Grand.Domain/Customers/CustomerGroupProduct.cs @@ -12,13 +12,13 @@ public class CustomerGroupProduct : BaseEntity /// Gets or sets the customer group id /// [AuditReference(typeof(CustomerGroup))] - public string CustomerGroupId { get; set; } + public string? CustomerGroupId { get; set; } /// /// Gets or sets the product Id /// [AuditReference(typeof(Product))] - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Customers/CustomerHistoryPassword.cs b/src/Core/Grand.Domain/Customers/CustomerHistoryPassword.cs index b87f2ec96..6c0112bd2 100644 --- a/src/Core/Grand.Domain/Customers/CustomerHistoryPassword.cs +++ b/src/Core/Grand.Domain/Customers/CustomerHistoryPassword.cs @@ -8,12 +8,12 @@ public class CustomerHistoryPassword : BaseEntity /// /// Gets or sets the customer identifier /// - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the password /// - public string Password { get; set; } + public string? Password { get; set; } /// /// Gets or sets the password format identifier @@ -23,5 +23,5 @@ public class CustomerHistoryPassword : BaseEntity /// /// Gets or sets the password salt /// - public string PasswordSalt { get; set; } + public string? PasswordSalt { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Customers/CustomerNote.cs b/src/Core/Grand.Domain/Customers/CustomerNote.cs index 262ea1fb1..cb976aafb 100644 --- a/src/Core/Grand.Domain/Customers/CustomerNote.cs +++ b/src/Core/Grand.Domain/Customers/CustomerNote.cs @@ -12,23 +12,23 @@ public class CustomerNote : BaseEntity /// [AuditReference(typeof(Customer))] [AuditOwner] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the title /// [AuditName] - public string Title { get; set; } + public string? Title { get; set; } /// /// Gets or sets the note /// - public string Note { get; set; } + public string? Note { get; set; } /// /// Gets or sets the attached file (download) identifier /// - public string DownloadId { get; set; } + public string? DownloadId { get; set; } /// /// Gets or sets a value indicating whether a customer can see a note diff --git a/src/Core/Grand.Domain/Customers/CustomerProduct.cs b/src/Core/Grand.Domain/Customers/CustomerProduct.cs index b6e472061..2949b03bb 100644 --- a/src/Core/Grand.Domain/Customers/CustomerProduct.cs +++ b/src/Core/Grand.Domain/Customers/CustomerProduct.cs @@ -5,7 +5,7 @@ namespace Grand.Domain.Customers; public class CustomerProduct : BaseEntity { [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } - public string ProductId { get; set; } + public string? CustomerId { get; set; } + public string? ProductId { get; set; } public int DisplayOrder { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Customers/CustomerProductPrice.cs b/src/Core/Grand.Domain/Customers/CustomerProductPrice.cs index eade38d40..fb15e6eff 100644 --- a/src/Core/Grand.Domain/Customers/CustomerProductPrice.cs +++ b/src/Core/Grand.Domain/Customers/CustomerProductPrice.cs @@ -5,7 +5,7 @@ namespace Grand.Domain.Customers; public class CustomerProductPrice : BaseEntity { [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } - public string ProductId { get; set; } + public string? CustomerId { get; set; } + public string? ProductId { get; set; } public double Price { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Customers/CustomerSettings.cs b/src/Core/Grand.Domain/Customers/CustomerSettings.cs index b074e001c..6b935bb6b 100644 --- a/src/Core/Grand.Domain/Customers/CustomerSettings.cs +++ b/src/Core/Grand.Domain/Customers/CustomerSettings.cs @@ -43,7 +43,7 @@ public class CustomerSettings : ISettings /// /// Gets or sets a regular expression for password validation /// - public string PasswordRegularExpression { get; set; } + public string? PasswordRegularExpression { get; set; } /// /// Gets or sets a number of passwords that should not be the same as the previous one; 0 if the customer can use the diff --git a/src/Core/Grand.Domain/Customers/CustomerTag.cs b/src/Core/Grand.Domain/Customers/CustomerTag.cs index f04e48605..ad7b5aa66 100644 --- a/src/Core/Grand.Domain/Customers/CustomerTag.cs +++ b/src/Core/Grand.Domain/Customers/CustomerTag.cs @@ -8,5 +8,5 @@ public class CustomerTag : BaseEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Customers/CustomerTagProduct.cs b/src/Core/Grand.Domain/Customers/CustomerTagProduct.cs index cbd17647a..bccf70b37 100644 --- a/src/Core/Grand.Domain/Customers/CustomerTagProduct.cs +++ b/src/Core/Grand.Domain/Customers/CustomerTagProduct.cs @@ -12,13 +12,13 @@ public class CustomerTagProduct : BaseEntity /// Gets or sets the customer tag id /// [AuditReference(typeof(CustomerTag))] - public string CustomerTagId { get; set; } + public string? CustomerTagId { get; set; } /// /// Gets or sets the product Id /// [AuditReference(typeof(Product))] - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Customers/ExternalAuthentication.cs b/src/Core/Grand.Domain/Customers/ExternalAuthentication.cs index 924c41ba1..3e1953d2c 100644 --- a/src/Core/Grand.Domain/Customers/ExternalAuthentication.cs +++ b/src/Core/Grand.Domain/Customers/ExternalAuthentication.cs @@ -12,39 +12,39 @@ public class ExternalAuthentication : BaseEntity /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the external email /// [AuditName] - public string Email { get; set; } + public string? Email { get; set; } /// /// Gets or sets the external identifier /// - public string ExternalIdentifier { get; set; } + public string? ExternalIdentifier { get; set; } /// /// Gets or sets the external display identifier /// - public string ExternalDisplayIdentifier { get; set; } + public string? ExternalDisplayIdentifier { get; set; } /// /// Gets or sets the OAuthAccessToken /// - public string OAuthAccessToken { get; set; } + public string? OAuthAccessToken { get; set; } /// /// Gets or sets the provider /// - public string ProviderSystemName { get; set; } + public string? ProviderSystemName { get; set; } /// /// Gets or sets the store of the linked customer when customers are registered per store; empty otherwise /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets a value indicating whether the link was made by the e-mail address alone, without the account's password diff --git a/src/Core/Grand.Domain/Customers/OidcLinkSettings.cs b/src/Core/Grand.Domain/Customers/OidcLinkSettings.cs index a5f07b648..9e7eadb17 100644 --- a/src/Core/Grand.Domain/Customers/OidcLinkSettings.cs +++ b/src/Core/Grand.Domain/Customers/OidcLinkSettings.cs @@ -9,5 +9,5 @@ namespace Grand.Domain.Customers; public class OidcLinkSettings : ISettings { /// Authority the links were made with; empty until the first use, which adopts the configured one - public string Authority { get; set; } + public string? Authority { get; set; } } diff --git a/src/Core/Grand.Domain/Customers/OidcSession.cs b/src/Core/Grand.Domain/Customers/OidcSession.cs index 5a2d631e4..427a9e575 100644 --- a/src/Core/Grand.Domain/Customers/OidcSession.cs +++ b/src/Core/Grand.Domain/Customers/OidcSession.cs @@ -6,16 +6,16 @@ namespace Grand.Domain.Customers; /// public class OidcSession : BaseEntity { - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// The store of the sign-in - public string StoreId { get; set; } + public string? StoreId { get; set; } /// Provider subject (sub) - public string Subject { get; set; } + public string? Subject { get; set; } /// Provider session id (sid) from the ID token; empty when the provider sends none - public string Sid { get; set; } + public string? Sid { get; set; } public DateTime CreatedUtc { get; set; } public DateTime LastActivityUtc { get; set; } @@ -24,10 +24,10 @@ public class OidcSession : BaseEntity public DateTime LastValidatedUtc { get; set; } /// Refresh token protected with Data Protection; cleared when the session ends - public string ProtectedRefreshToken { get; set; } + public string? ProtectedRefreshToken { get; set; } /// Holder of the refresh in progress (one at a time on every instance); empty when none - public string RefreshLeaseId { get; set; } + public string? RefreshLeaseId { get; set; } /// The lease lapses at this time, so a holder that died does not block the next refresh public DateTime? RefreshLeaseUntilUtc { get; set; } diff --git a/src/Core/Grand.Domain/Customers/OidcTokenRevocation.cs b/src/Core/Grand.Domain/Customers/OidcTokenRevocation.cs index 7956a1846..3e30f2df9 100644 --- a/src/Core/Grand.Domain/Customers/OidcTokenRevocation.cs +++ b/src/Core/Grand.Domain/Customers/OidcTokenRevocation.cs @@ -10,7 +10,7 @@ public class OidcTokenRevocation : BaseEntity /// /// Gets or sets the subject (sub claim) at the identity provider /// - public string Subject { get; set; } + public string? Subject { get; set; } /// /// Gets or sets the time before which the subject's access tokens are refused diff --git a/src/Core/Grand.Domain/Customers/SalesEmployee.cs b/src/Core/Grand.Domain/Customers/SalesEmployee.cs index 1dd2a1aa9..27e68a8b9 100644 --- a/src/Core/Grand.Domain/Customers/SalesEmployee.cs +++ b/src/Core/Grand.Domain/Customers/SalesEmployee.cs @@ -5,17 +5,17 @@ public class SalesEmployee : BaseEntity /// /// Gets or sets the sales employee name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the sales employee email /// - public string Email { get; set; } + public string? Email { get; set; } /// /// Gets or sets the sales employee phone /// - public string Phone { get; set; } + public string? Phone { get; set; } /// /// Gets or sets the sales employee active diff --git a/src/Core/Grand.Domain/Customers/ScimGroup.cs b/src/Core/Grand.Domain/Customers/ScimGroup.cs index 585c21a5f..92b6d2769 100644 --- a/src/Core/Grand.Domain/Customers/ScimGroup.cs +++ b/src/Core/Grand.Domain/Customers/ScimGroup.cs @@ -10,23 +10,23 @@ namespace Grand.Domain.Customers; /// public class ScimGroup : BaseEntity { - public string DisplayName { get; set; } + public string? DisplayName { get; set; } /// The identity provider's id of the group - public string ExternalId { get; set; } + public string? ExternalId { get; set; } /// Ids of the SCIM-managed customers in the group public List Members { get; set; } = []; /// Customer group the members get; empty while the group is not mapped [AuditReference(typeof(CustomerGroup))] - public string CustomerGroupId { get; set; } + public string? CustomerGroupId { get; set; } /// Staff store of the members, with the StoreManager group [AuditReference(typeof(Store))] - public string StaffStoreId { get; set; } + public string? StaffStoreId { get; set; } /// Vendor of the members, with the Vendors group [AuditReference(typeof(Vendor))] - public string VendorId { get; set; } + public string? VendorId { get; set; } } diff --git a/src/Core/Grand.Domain/Customers/ScimUser.cs b/src/Core/Grand.Domain/Customers/ScimUser.cs index f3e87e403..802dfb635 100644 --- a/src/Core/Grand.Domain/Customers/ScimUser.cs +++ b/src/Core/Grand.Domain/Customers/ScimUser.cs @@ -11,18 +11,18 @@ namespace Grand.Domain.Customers; public class ScimUser : BaseEntity { /// The identity provider's id of the user (with Scim:ExternalIdIsSubject also its OpenID Connect subject) - public string ExternalId { get; set; } + public string? ExternalId { get; set; } /// Customer groups SCIM gave the account public List GrantedGroupIds { get; set; } = []; /// Staff store SCIM set on the account; empty when SCIM set none [AuditReference(typeof(Store))] - public string GrantedStaffStoreId { get; set; } + public string? GrantedStaffStoreId { get; set; } /// Vendor SCIM set on the account; empty when SCIM set none [AuditReference(typeof(Vendor))] - public string GrantedVendorId { get; set; } + public string? GrantedVendorId { get; set; } /// The account was deactivated by SCIM, so SCIM may activate it again (never an account disabled by hand) public bool DeactivatedByScim { get; set; } diff --git a/src/Core/Grand.Domain/Customers/UserApi.cs b/src/Core/Grand.Domain/Customers/UserApi.cs index d64e5d6c1..4e4c7c67d 100644 --- a/src/Core/Grand.Domain/Customers/UserApi.cs +++ b/src/Core/Grand.Domain/Customers/UserApi.cs @@ -6,9 +6,9 @@ namespace Grand.Domain.Customers; public class UserApi : BaseEntity { [AuditName] - public string Email { get; set; } - public string Password { get; set; } - public string PrivateKey { get; set; } + public string? Email { get; set; } + public string? Password { get; set; } + public string? PrivateKey { get; set; } public bool IsActive { get; set; } - public string Token { get; set; } + public string? Token { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Directory/Country.cs b/src/Core/Grand.Domain/Directory/Country.cs index 33dd6ba0b..d39546e1c 100644 --- a/src/Core/Grand.Domain/Directory/Country.cs +++ b/src/Core/Grand.Domain/Directory/Country.cs @@ -9,12 +9,12 @@ namespace Grand.Domain.Directory; /// public class Country : BaseEntity, ITranslationEntity, IStoreLinkEntity { - private ICollection _stateProvinces; + private ICollection? _stateProvinces; /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets a value indicating whether billing is allowed to this country @@ -29,12 +29,12 @@ public class Country : BaseEntity, ITranslationEntity, IStoreLinkEntity /// /// Gets or sets the two letter ISO code /// - public string TwoLetterIsoCode { get; set; } + public string? TwoLetterIsoCode { get; set; } /// /// Gets or sets the three letter ISO code /// - public string ThreeLetterIsoCode { get; set; } + public string? ThreeLetterIsoCode { get; set; } /// /// Gets or sets the numeric ISO code diff --git a/src/Core/Grand.Domain/Directory/Currency.cs b/src/Core/Grand.Domain/Directory/Currency.cs index 0e047f749..6553d6bdc 100644 --- a/src/Core/Grand.Domain/Directory/Currency.cs +++ b/src/Core/Grand.Domain/Directory/Currency.cs @@ -12,12 +12,12 @@ public class Currency : BaseEntity, ITranslationEntity, IStoreLinkEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the currency code /// - public string CurrencyCode { get; set; } + public string? CurrencyCode { get; set; } /// /// Gets or sets the rate @@ -27,12 +27,12 @@ public class Currency : BaseEntity, ITranslationEntity, IStoreLinkEntity /// /// Gets or sets the display locale /// - public string DisplayLocale { get; set; } + public string? DisplayLocale { get; set; } /// /// Gets or sets the custom formatting /// - public string CustomFormatting { get; set; } + public string? CustomFormatting { get; set; } /// /// Gets or sets a value indicating whether the entity is published diff --git a/src/Core/Grand.Domain/Directory/CurrencySettings.cs b/src/Core/Grand.Domain/Directory/CurrencySettings.cs index 1fb7a205b..c5766abe2 100644 --- a/src/Core/Grand.Domain/Directory/CurrencySettings.cs +++ b/src/Core/Grand.Domain/Directory/CurrencySettings.cs @@ -4,8 +4,8 @@ namespace Grand.Domain.Directory; public class CurrencySettings : ISettings { - public string PrimaryStoreCurrencyId { get; set; } - public string PrimaryExchangeRateCurrencyId { get; set; } - public string ActiveExchangeRateProviderSystemName { get; set; } + public string? PrimaryStoreCurrencyId { get; set; } + public string? PrimaryExchangeRateCurrencyId { get; set; } + public string? ActiveExchangeRateProviderSystemName { get; set; } public bool AutoUpdateEnabled { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Directory/DateTimeSettings.cs b/src/Core/Grand.Domain/Directory/DateTimeSettings.cs index 526065cce..4f9975754 100644 --- a/src/Core/Grand.Domain/Directory/DateTimeSettings.cs +++ b/src/Core/Grand.Domain/Directory/DateTimeSettings.cs @@ -7,5 +7,5 @@ public class DateTimeSettings : ISettings /// /// Gets or sets a default store time zone ident /// - public string DefaultStoreTimeZoneId { get; set; } + public string? DefaultStoreTimeZoneId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Directory/MeasureDimension.cs b/src/Core/Grand.Domain/Directory/MeasureDimension.cs index 5e4530c68..9f6505bb8 100644 --- a/src/Core/Grand.Domain/Directory/MeasureDimension.cs +++ b/src/Core/Grand.Domain/Directory/MeasureDimension.cs @@ -8,12 +8,12 @@ public class MeasureDimension : BaseEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the system keyword /// - public string SystemKeyword { get; set; } + public string? SystemKeyword { get; set; } /// /// Gets or sets the ratio diff --git a/src/Core/Grand.Domain/Directory/MeasureSettings.cs b/src/Core/Grand.Domain/Directory/MeasureSettings.cs index 1e2553dd6..ca6bc2e34 100644 --- a/src/Core/Grand.Domain/Directory/MeasureSettings.cs +++ b/src/Core/Grand.Domain/Directory/MeasureSettings.cs @@ -4,6 +4,6 @@ namespace Grand.Domain.Directory; public class MeasureSettings : ISettings { - public string BaseDimensionId { get; set; } - public string BaseWeightId { get; set; } + public string? BaseDimensionId { get; set; } + public string? BaseWeightId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Directory/MeasureUnit.cs b/src/Core/Grand.Domain/Directory/MeasureUnit.cs index f0a4fb1cd..28364afdb 100644 --- a/src/Core/Grand.Domain/Directory/MeasureUnit.cs +++ b/src/Core/Grand.Domain/Directory/MeasureUnit.cs @@ -8,7 +8,7 @@ public class MeasureUnit : BaseEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Directory/MeasureWeight.cs b/src/Core/Grand.Domain/Directory/MeasureWeight.cs index 4473490d3..1415169ae 100644 --- a/src/Core/Grand.Domain/Directory/MeasureWeight.cs +++ b/src/Core/Grand.Domain/Directory/MeasureWeight.cs @@ -8,12 +8,12 @@ public class MeasureWeight : BaseEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the system keyword /// - public string SystemKeyword { get; set; } + public string? SystemKeyword { get; set; } /// /// Gets or sets the ratio diff --git a/src/Core/Grand.Domain/Directory/StateProvince.cs b/src/Core/Grand.Domain/Directory/StateProvince.cs index 952d580f3..520bf9067 100644 --- a/src/Core/Grand.Domain/Directory/StateProvince.cs +++ b/src/Core/Grand.Domain/Directory/StateProvince.cs @@ -10,12 +10,12 @@ public class StateProvince : SubBaseEntity, ITranslationEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the abbreviation /// - public string Abbreviation { get; set; } + public string? Abbreviation { get; set; } /// /// Gets or sets a value indicating whether the entity is published diff --git a/src/Core/Grand.Domain/Discounts/Discount.cs b/src/Core/Grand.Domain/Discounts/Discount.cs index caba77228..4585a6113 100644 --- a/src/Core/Grand.Domain/Discounts/Discount.cs +++ b/src/Core/Grand.Domain/Discounts/Discount.cs @@ -8,12 +8,12 @@ namespace Grand.Domain.Discounts; /// public class Discount : BaseEntity, IStoreLinkEntity { - private ICollection _discountRules; + private ICollection? _discountRules; /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the discount type identifier @@ -38,7 +38,7 @@ public class Discount : BaseEntity, IStoreLinkEntity /// /// Gets or sets the discount currency /// - public string CurrencyCode { get; set; } + public string? CurrencyCode { get; set; } /// /// Gets or sets a value indicating whether to calculate by plugin @@ -48,7 +48,7 @@ public class Discount : BaseEntity, IStoreLinkEntity /// /// Gets or sets a value indicating whether to calculate by plugin /// - public string DiscountPluginName { get; set; } + public string? DiscountPluginName { get; set; } /// /// Gets or sets the maximum discount amount (used with "UsePercentage") diff --git a/src/Core/Grand.Domain/Discounts/DiscountCoupon.cs b/src/Core/Grand.Domain/Discounts/DiscountCoupon.cs index fa69a6acf..7c5575a19 100644 --- a/src/Core/Grand.Domain/Discounts/DiscountCoupon.cs +++ b/src/Core/Grand.Domain/Discounts/DiscountCoupon.cs @@ -8,13 +8,13 @@ public class DiscountCoupon : BaseEntity /// Gets or sets the coupon code /// [AuditName] - public string CouponCode { get; set; } + public string? CouponCode { get; set; } /// /// Gets or sets the discount id /// [AuditReference(typeof(Discount))] - public string DiscountId { get; set; } + public string? DiscountId { get; set; } /// /// Gets or sets discount used diff --git a/src/Core/Grand.Domain/Discounts/DiscountRule.cs b/src/Core/Grand.Domain/Discounts/DiscountRule.cs index bef94ba80..e9655fb8c 100644 --- a/src/Core/Grand.Domain/Discounts/DiscountRule.cs +++ b/src/Core/Grand.Domain/Discounts/DiscountRule.cs @@ -11,10 +11,10 @@ public class DiscountRule : SubBaseEntity /// Gets or sets the discount requirement rule system name /// [AuditName] - public string DiscountRequirementRuleSystemName { get; set; } + public string? DiscountRequirementRuleSystemName { get; set; } /// /// Gets or sets the metadata /// - public string Metadata { get; set; } + public string? Metadata { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Discounts/DiscountUsageHistory.cs b/src/Core/Grand.Domain/Discounts/DiscountUsageHistory.cs index 40a2c7911..99c6e96b7 100644 --- a/src/Core/Grand.Domain/Discounts/DiscountUsageHistory.cs +++ b/src/Core/Grand.Domain/Discounts/DiscountUsageHistory.cs @@ -13,24 +13,24 @@ public class DiscountUsageHistory : BaseEntity /// Gets or sets the discount identifier /// [AuditReference(typeof(Discount))] - public string DiscountId { get; set; } + public string? DiscountId { get; set; } /// /// Gets or sets the discount coupon code /// - public string CouponCode { get; set; } + public string? CouponCode { get; set; } /// /// Gets or sets the order identifier /// [AuditReference(typeof(Order))] - public string OrderId { get; set; } + public string? OrderId { get; set; } /// /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the canceled identifier diff --git a/src/Core/Grand.Domain/Documents/Document.cs b/src/Core/Grand.Domain/Documents/Document.cs index 3dab3fb88..064c2d1c8 100644 --- a/src/Core/Grand.Domain/Documents/Document.cs +++ b/src/Core/Grand.Domain/Documents/Document.cs @@ -14,38 +14,38 @@ public class Document : BaseEntity, IGroupLinkEntity, IStoreLinkEntity /// /// Gets or sets the document number /// - public string Number { get; set; } + public string? Number { get; set; } /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the sales employee identifier /// - public string SeId { get; set; } + public string? SeId { get; set; } /// /// Gets or sets the description /// - public string Description { get; set; } + public string? Description { get; set; } /// /// Gets or sets the parent document identifier /// [AuditReference(typeof(Document))] - public string ParentDocumentId { get; set; } + public string? ParentDocumentId { get; set; } /// /// Gets or sets the picture identifier /// - public string PictureId { get; set; } + public string? PictureId { get; set; } /// /// Gets or sets the download identifier /// - public string DownloadId { get; set; } + public string? DownloadId { get; set; } /// /// Gets or sets a value indicating whether the entity is published @@ -60,18 +60,18 @@ public class Document : BaseEntity, IGroupLinkEntity, IStoreLinkEntity /// /// Gets or sets the flag /// - public string Flag { get; set; } + public string? Flag { get; set; } /// /// Gets or sets the lik /// - public string Link { get; set; } + public string? Link { get; set; } /// /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets an document status identifier @@ -86,28 +86,28 @@ public class Document : BaseEntity, IGroupLinkEntity, IStoreLinkEntity /// /// Gets or sets an object reference identifier /// - public string ObjectId { get; set; } + public string? ObjectId { get; set; } /// /// Gets or sets an document type identifier (DocumentType) /// [AuditReference(typeof(DocumentType))] - public string DocumentTypeId { get; set; } + public string? DocumentTypeId { get; set; } /// /// Gets or sets the customer email /// - public string CustomerEmail { get; set; } + public string? CustomerEmail { get; set; } /// /// Gets or sets the user name /// - public string Username { get; set; } + public string? Username { get; set; } /// /// Gets or sets the currency code /// - public string CurrencyCode { get; set; } + public string? CurrencyCode { get; set; } /// /// Gets or sets the total amount diff --git a/src/Core/Grand.Domain/Documents/DocumentType.cs b/src/Core/Grand.Domain/Documents/DocumentType.cs index 4b716bb17..877501e73 100644 --- a/src/Core/Grand.Domain/Documents/DocumentType.cs +++ b/src/Core/Grand.Domain/Documents/DocumentType.cs @@ -5,7 +5,7 @@ /// public class DocumentType : BaseEntity { - public string Name { get; set; } - public string Description { get; set; } + public string? Name { get; set; } + public string? Description { get; set; } public int DisplayOrder { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Grand.Domain.csproj b/src/Core/Grand.Domain/Grand.Domain.csproj index 7693fd893..114ebd33f 100644 --- a/src/Core/Grand.Domain/Grand.Domain.csproj +++ b/src/Core/Grand.Domain/Grand.Domain.csproj @@ -9,4 +9,7 @@ + + enable + diff --git a/src/Core/Grand.Domain/History/HistoryObject.cs b/src/Core/Grand.Domain/History/HistoryObject.cs index 1bf5d17b5..6efeb6adf 100644 --- a/src/Core/Grand.Domain/History/HistoryObject.cs +++ b/src/Core/Grand.Domain/History/HistoryObject.cs @@ -2,5 +2,5 @@ public class HistoryObject : BaseEntity { - public BaseEntity Object { get; set; } + public BaseEntity? Object { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Knowledgebase/ITreeNode.cs b/src/Core/Grand.Domain/Knowledgebase/ITreeNode.cs index 65da912a1..9702aff3e 100644 --- a/src/Core/Grand.Domain/Knowledgebase/ITreeNode.cs +++ b/src/Core/Grand.Domain/Knowledgebase/ITreeNode.cs @@ -4,7 +4,7 @@ public interface ITreeNode { string Id { get; set; } - string Name { get; set; } + string? Name { get; set; } - string ParentCategoryId { get; set; } + string? ParentCategoryId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseArticle.cs b/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseArticle.cs index f8d140a27..bf4ebb3f8 100644 --- a/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseArticle.cs +++ b/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseArticle.cs @@ -13,7 +13,7 @@ public class KnowledgebaseArticle : BaseEntity, ITreeNode, ITranslationEntity, I /// /// Gets or sets content of the article /// - public string Content { get; set; } + public string? Content { get; set; } /// /// Gets or sets display order @@ -28,17 +28,17 @@ public class KnowledgebaseArticle : BaseEntity, ITreeNode, ITranslationEntity, I /// /// Gets or sets meta keywords /// - public string MetaKeywords { get; set; } + public string? MetaKeywords { get; set; } /// /// Gets or sets meta description /// - public string MetaDescription { get; set; } + public string? MetaDescription { get; set; } /// /// Gets or sets meta title /// - public string MetaTitle { get; set; } + public string? MetaTitle { get; set; } /// /// Gets or sets value indicating whether to show article on knowledgebase homepage @@ -66,7 +66,7 @@ public class KnowledgebaseArticle : BaseEntity, ITreeNode, ITranslationEntity, I /// /// Gets or sets the name /// - public string SeName { get; set; } + public string? SeName { get; set; } /// /// Gets or sets a value indicating whether the entity is limited/restricted to certain stores @@ -84,11 +84,11 @@ public class KnowledgebaseArticle : BaseEntity, ITreeNode, ITranslationEntity, I /// /// Gets or sets title of the article /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets parent category Id /// [AuditReference(typeof(KnowledgebaseCategory))] - public string ParentCategoryId { get; set; } + public string? ParentCategoryId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseArticleComment.cs b/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseArticleComment.cs index 5b376b887..50fc82577 100644 --- a/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseArticleComment.cs +++ b/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseArticleComment.cs @@ -9,23 +9,23 @@ public class KnowledgebaseArticleComment : BaseEntity /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the comment text /// [AuditName] - public string CommentText { get; set; } + public string? CommentText { get; set; } /// /// Gets or sets the blog post title /// - public string ArticleTitle { get; set; } + public string? ArticleTitle { get; set; } /// /// Gets or sets the blog post identifier /// [AuditReference(typeof(KnowledgebaseArticle))] [AuditOwner] - public string ArticleId { get; set; } + public string? ArticleId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseCategory.cs b/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseCategory.cs index 83773d68e..e63d30e58 100644 --- a/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseCategory.cs +++ b/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseCategory.cs @@ -18,7 +18,7 @@ public class KnowledgebaseCategory : BaseEntity, ITreeNode, ITranslationEntity, /// /// Gets or sets description /// - public string Description { get; set; } + public string? Description { get; set; } /// /// Gets or sets published @@ -28,17 +28,17 @@ public class KnowledgebaseCategory : BaseEntity, ITreeNode, ITranslationEntity, /// /// Gets or sets meta keywords /// - public string MetaKeywords { get; set; } + public string? MetaKeywords { get; set; } /// /// Gets or sets meta description /// - public string MetaDescription { get; set; } + public string? MetaDescription { get; set; } /// /// Gets or sets meta title /// - public string MetaTitle { get; set; } + public string? MetaTitle { get; set; } /// /// Gets or sets a value indicating whether the entity is subject to ACL @@ -51,7 +51,7 @@ public class KnowledgebaseCategory : BaseEntity, ITreeNode, ITranslationEntity, /// /// Gets or sets the name /// - public string SeName { get; set; } + public string? SeName { get; set; } /// /// Gets or sets a value indicating whether the entity is limited/restricted to certain stores @@ -69,11 +69,11 @@ public class KnowledgebaseCategory : BaseEntity, ITreeNode, ITranslationEntity, /// /// Gets or sets name of the category /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets parent category Id /// [AuditReference(typeof(KnowledgebaseCategory))] - public string ParentCategoryId { get; set; } + public string? ParentCategoryId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Localization/Language.cs b/src/Core/Grand.Domain/Localization/Language.cs index e55af1b0b..822ab921c 100644 --- a/src/Core/Grand.Domain/Localization/Language.cs +++ b/src/Core/Grand.Domain/Localization/Language.cs @@ -12,22 +12,22 @@ public class Language : BaseEntity, IStoreLinkEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the language culture /// - public string LanguageCulture { get; set; } + public string? LanguageCulture { get; set; } /// /// Gets or sets the unique SEO code /// - public string UniqueSeoCode { get; set; } + public string? UniqueSeoCode { get; set; } /// /// Gets or sets the flag image file name /// - public string FlagImageFileName { get; set; } + public string? FlagImageFileName { get; set; } /// /// Gets or sets a value indicating whether the language supports "Right-to-left" @@ -39,7 +39,7 @@ public class Language : BaseEntity, IStoreLinkEntity /// display order /// [AuditReference(typeof(Currency))] - public string DefaultCurrencyId { get; set; } + public string? DefaultCurrencyId { get; set; } /// /// Gets or sets a value indicating whether the language is published diff --git a/src/Core/Grand.Domain/Localization/LanguageSettings.cs b/src/Core/Grand.Domain/Localization/LanguageSettings.cs index 781f43dec..425e97969 100644 --- a/src/Core/Grand.Domain/Localization/LanguageSettings.cs +++ b/src/Core/Grand.Domain/Localization/LanguageSettings.cs @@ -7,7 +7,7 @@ public class LanguageSettings : ISettings /// /// Default admin area language identifier /// - public string DefaultAdminLanguageId { get; set; } + public string? DefaultAdminLanguageId { get; set; } /// /// A value indicating whether we should detect the current language by a customer region (browser settings) diff --git a/src/Core/Grand.Domain/Localization/TranslationEntity.cs b/src/Core/Grand.Domain/Localization/TranslationEntity.cs index 12cd555bf..12ae575da 100644 --- a/src/Core/Grand.Domain/Localization/TranslationEntity.cs +++ b/src/Core/Grand.Domain/Localization/TranslationEntity.cs @@ -8,15 +8,15 @@ public class TranslationEntity : SubBaseEntity /// /// Gets or sets the language identifier /// - public string LanguageId { get; set; } + public string? LanguageId { get; set; } /// /// Gets or sets the locale key /// - public string LocaleKey { get; set; } + public string? LocaleKey { get; set; } /// /// Gets or sets the locale value /// - public string LocaleValue { get; set; } + public string? LocaleValue { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Localization/TranslationResource.cs b/src/Core/Grand.Domain/Localization/TranslationResource.cs index 51014a2b6..5c827342d 100644 --- a/src/Core/Grand.Domain/Localization/TranslationResource.cs +++ b/src/Core/Grand.Domain/Localization/TranslationResource.cs @@ -12,17 +12,17 @@ public class TranslationResource : BaseEntity /// [AuditReference(typeof(Language))] [AuditOwner] - public string LanguageId { get; set; } + public string? LanguageId { get; set; } /// /// Gets or sets the translation name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the translation value /// - public string Value { get; set; } + public string? Value { get; set; } /// /// Gets or sets the translation area diff --git a/src/Core/Grand.Domain/Media/Download.cs b/src/Core/Grand.Domain/Media/Download.cs index 9f4b54e16..ead176c30 100644 --- a/src/Core/Grand.Domain/Media/Download.cs +++ b/src/Core/Grand.Domain/Media/Download.cs @@ -8,7 +8,7 @@ public class Download : BaseEntity /// /// Gets or sets a customer identifier /// - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets a GUID @@ -23,32 +23,32 @@ public class Download : BaseEntity /// /// Gets or sets a download URL /// - public string DownloadUrl { get; set; } + public string? DownloadUrl { get; set; } /// /// Gets or sets the download binary /// - public byte[] DownloadBinary { get; set; } + public byte[]? DownloadBinary { get; set; } /// /// Gets or sets the download binary /// - public string DownloadObjectId { get; set; } + public string? DownloadObjectId { get; set; } /// /// The mime-type of the download /// - public string ContentType { get; set; } + public string? ContentType { get; set; } /// /// The filename of the download /// - public string Filename { get; set; } + public string? Filename { get; set; } /// /// Gets or sets the extension /// - public string Extension { get; set; } + public string? Extension { get; set; } /// /// Gets or sets an download type @@ -58,5 +58,5 @@ public class Download : BaseEntity /// /// Gets or sets an object reference identifier /// - public string ReferenceId { get; set; } + public string? ReferenceId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Media/MediaSettings.cs b/src/Core/Grand.Domain/Media/MediaSettings.cs index 722989292..72ccb2806 100644 --- a/src/Core/Grand.Domain/Media/MediaSettings.cs +++ b/src/Core/Grand.Domain/Media/MediaSettings.cs @@ -35,5 +35,5 @@ public class MediaSettings : ISettings /// public int ImageQuality { get; set; } = 80; - public string AllowedFileTypes { get; set; } + public string? AllowedFileTypes { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Media/Picture.cs b/src/Core/Grand.Domain/Media/Picture.cs index fc0654a9a..c0045f890 100644 --- a/src/Core/Grand.Domain/Media/Picture.cs +++ b/src/Core/Grand.Domain/Media/Picture.cs @@ -11,7 +11,7 @@ public class Picture : BaseEntity, ITranslationEntity /// /// Gets or sets the picture binary /// - public byte[] PictureBinary { get; set; } + public byte[]? PictureBinary { get; set; } /// /// Gets or sets an reference identifier @@ -21,39 +21,39 @@ public class Picture : BaseEntity, ITranslationEntity /// /// Gets or sets an object reference identifier /// - public string ObjectId { get; set; } + public string? ObjectId { get; set; } /// /// Gets or sets the picture mime type /// - public string MimeType { get; set; } + public string? MimeType { get; set; } /// /// Gets or sets the SEO friednly filename of the picture /// - public string SeoFilename { get; set; } + public string? SeoFilename { get; set; } /// /// Gets or sets the "alt" attribute for "img" HTML element. If empty, then a default rule will be used (e.g. product /// name) /// - public string AltAttribute { get; set; } + public string? AltAttribute { get; set; } /// /// Gets or sets the "title" attribute for "img" HTML element. If empty, then a default rule will be used (e.g. product /// name) /// - public string TitleAttribute { get; set; } + public string? TitleAttribute { get; set; } /// /// Gets or sets the "Style" attribute for "img" HTML element. /// - public string Style { get; set; } + public string? Style { get; set; } /// /// Gets or sets the "extra field" /// - public string ExtraField { get; set; } + public string? ExtraField { get; set; } /// /// Gets or sets a value indicating whether the picture is new diff --git a/src/Core/Grand.Domain/Messages/Campaign.cs b/src/Core/Grand.Domain/Messages/Campaign.cs index 64d100d68..222e0b604 100644 --- a/src/Core/Grand.Domain/Messages/Campaign.cs +++ b/src/Core/Grand.Domain/Messages/Campaign.cs @@ -10,36 +10,36 @@ namespace Grand.Domain.Messages; /// public class Campaign : BaseEntity { - private ICollection _customerGroups; - private ICollection _customerTags; - private ICollection _newsletterCategories; + private ICollection? _customerGroups; + private ICollection? _customerTags; + private ICollection? _newsletterCategories; /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the subject /// - public string Subject { get; set; } + public string? Subject { get; set; } /// /// Gets or sets the body /// - public string Body { get; set; } + public string? Body { get; set; } /// /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the lang identifier /// [AuditReference(typeof(Language))] - public string LanguageId { get; set; } + public string? LanguageId { get; set; } public DateTime? CustomerCreatedDateFrom { get; set; } public DateTime? CustomerCreatedDateTo { get; set; } @@ -56,7 +56,7 @@ public class Campaign : BaseEntity /// Gets or sets the used email account identifier /// [AuditReference(typeof(EmailAccount))] - public string EmailAccountId { get; set; } + public string? EmailAccountId { get; set; } /// /// Gets or sets the customer tags diff --git a/src/Core/Grand.Domain/Messages/CampaignCustomerSubscription.cs b/src/Core/Grand.Domain/Messages/CampaignCustomerSubscription.cs index a339d7c2a..1b2123c36 100644 --- a/src/Core/Grand.Domain/Messages/CampaignCustomerSubscription.cs +++ b/src/Core/Grand.Domain/Messages/CampaignCustomerSubscription.cs @@ -2,6 +2,6 @@ public class CampaignCustomerSubscription { - public string CustomerId { get; set; } - public string Email { get; set; } + public string? CustomerId { get; set; } + public string? Email { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Messages/CampaignHistory.cs b/src/Core/Grand.Domain/Messages/CampaignHistory.cs index 684e41116..02699aded 100644 --- a/src/Core/Grand.Domain/Messages/CampaignHistory.cs +++ b/src/Core/Grand.Domain/Messages/CampaignHistory.cs @@ -7,14 +7,14 @@ namespace Grand.Domain.Messages; /// public class CampaignHistory : BaseEntity { - public string CampaignId { get; set; } + public string? CampaignId { get; set; } [AuditName] - public string Email { get; set; } + public string? Email { get; set; } - public string CustomerId { get; set; } + public string? CustomerId { get; set; } - public string StoreId { get; set; } + public string? StoreId { get; set; } public DateTime CreatedDateUtc { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Messages/ContactAttribute.cs b/src/Core/Grand.Domain/Messages/ContactAttribute.cs index 2c5c24767..32c8c7233 100644 --- a/src/Core/Grand.Domain/Messages/ContactAttribute.cs +++ b/src/Core/Grand.Domain/Messages/ContactAttribute.cs @@ -13,17 +13,17 @@ namespace Grand.Domain.Messages; /// public class ContactAttribute : BaseEntity, ITranslationEntity, IStoreLinkEntity, IGroupLinkEntity { - private ICollection _contactAttributeValues; + private ICollection? _contactAttributeValues; /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the text prompt /// - public string TextPrompt { get; set; } + public string? TextPrompt { get; set; } /// /// Gets or sets a value indicating whether the entity is required @@ -56,7 +56,7 @@ public class ContactAttribute : BaseEntity, ITranslationEntity, IStoreLinkEntity /// /// Gets or sets the validation rule for file allowed extensions (for file upload) /// - public string ValidationFileAllowedExtensions { get; set; } + public string? ValidationFileAllowedExtensions { get; set; } /// /// Gets or sets the validation rule for file maximum size in kilobytes (for file upload) @@ -66,7 +66,7 @@ public class ContactAttribute : BaseEntity, ITranslationEntity, IStoreLinkEntity /// /// Gets or sets the default value (for textbox and multiline textbox) /// - public string DefaultValue { get; set; } + public string? DefaultValue { get; set; } public IList ConditionAttribute { get; set; } = new List(); diff --git a/src/Core/Grand.Domain/Messages/ContactAttributeValue.cs b/src/Core/Grand.Domain/Messages/ContactAttributeValue.cs index a09c30100..7fd0679a7 100644 --- a/src/Core/Grand.Domain/Messages/ContactAttributeValue.cs +++ b/src/Core/Grand.Domain/Messages/ContactAttributeValue.cs @@ -12,17 +12,17 @@ public class ContactAttributeValue : SubBaseEntity, ITranslationEntity /// Gets or sets the checkout attribute mapping identifier /// [AuditReference(typeof(ContactAttribute))] - public string ContactAttributeId { get; set; } + public string? ContactAttributeId { get; set; } /// /// Gets or sets the checkout attribute name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the color RGB value (used with "Color squares" attribute type) /// - public string ColorSquaresRgb { get; set; } + public string? ColorSquaresRgb { get; set; } /// /// Gets or sets a value indicating whether the value is pre-selected diff --git a/src/Core/Grand.Domain/Messages/ContactUs.cs b/src/Core/Grand.Domain/Messages/ContactUs.cs index 2ebf632e0..eee25379b 100644 --- a/src/Core/Grand.Domain/Messages/ContactUs.cs +++ b/src/Core/Grand.Domain/Messages/ContactUs.cs @@ -15,56 +15,56 @@ public class ContactUs : BaseEntity /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the IP address /// - public string IpAddress { get; set; } + public string? IpAddress { get; set; } /// /// Gets or sets the email /// [AuditName] - public string Email { get; set; } + public string? Email { get; set; } /// /// Gets or sets full name /// - public string FullName { get; set; } + public string? FullName { get; set; } /// /// Gets or sets the subject /// - public string Subject { get; set; } + public string? Subject { get; set; } /// /// Gets or sets enquiry /// - public string Enquiry { get; set; } + public string? Enquiry { get; set; } /// /// Gets or sets the email account identifier /// [AuditReference(typeof(EmailAccount))] - public string EmailAccountId { get; set; } + public string? EmailAccountId { get; set; } /// /// Gets or sets the vendor identifier /// [AuditReference(typeof(Vendor))] - public string VendorId { get; set; } + public string? VendorId { get; set; } /// /// Gets or sets the contact attribute description /// - public string ContactAttributeDescription { get; set; } + public string? ContactAttributeDescription { get; set; } /// /// Gets or sets the custom attributes (see "AddressAttribute" entity for more info) diff --git a/src/Core/Grand.Domain/Messages/EmailAccount.cs b/src/Core/Grand.Domain/Messages/EmailAccount.cs index a6ff52398..aa0eb5d4b 100644 --- a/src/Core/Grand.Domain/Messages/EmailAccount.cs +++ b/src/Core/Grand.Domain/Messages/EmailAccount.cs @@ -12,17 +12,17 @@ public class EmailAccount : BaseEntity /// Gets or sets an email address /// [AuditName] - public string Email { get; set; } + public string? Email { get; set; } /// /// Gets or sets an email display name /// - public string DisplayName { get; set; } + public string? DisplayName { get; set; } /// /// Gets or sets an email host /// - public string Host { get; set; } + public string? Host { get; set; } /// /// Gets or sets an email port @@ -32,12 +32,12 @@ public class EmailAccount : BaseEntity /// /// Gets or sets an email user name /// - public string Username { get; set; } + public string? Username { get; set; } /// /// Gets or sets an email password /// - public string Password { get; set; } + public string? Password { get; set; } /// /// Gets or sets a value that the remote certificate is invalid according to the validation procedure. @@ -55,5 +55,5 @@ public class EmailAccount : BaseEntity /// An empty string means this is a global/shared email account. /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Messages/EmailAccountSettings.cs b/src/Core/Grand.Domain/Messages/EmailAccountSettings.cs index 586153efe..950761bd6 100644 --- a/src/Core/Grand.Domain/Messages/EmailAccountSettings.cs +++ b/src/Core/Grand.Domain/Messages/EmailAccountSettings.cs @@ -7,5 +7,5 @@ public class EmailAccountSettings : ISettings /// /// Gets or sets a store default email account identifier /// - public string DefaultEmailAccountId { get; set; } + public string? DefaultEmailAccountId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Messages/LiquidObject.cs b/src/Core/Grand.Domain/Messages/LiquidObject.cs index 2d7e1654a..71eb61cbe 100644 --- a/src/Core/Grand.Domain/Messages/LiquidObject.cs +++ b/src/Core/Grand.Domain/Messages/LiquidObject.cs @@ -7,58 +7,58 @@ namespace Grand.Domain.Messages; /// public class LiquidObject { - public Drop AttributeCombination { get; set; } + public Drop? AttributeCombination { get; set; } - public Drop Auctions { get; set; } + public Drop? Auctions { get; set; } - public Drop OutOfStockSubscription { get; set; } + public Drop? OutOfStockSubscription { get; set; } - public Drop BlogComment { get; set; } + public Drop? BlogComment { get; set; } - public Drop Customer { get; set; } + public Drop? Customer { get; set; } - public Drop GiftVoucher { get; set; } - public Drop Inventory { get; set; } + public Drop? GiftVoucher { get; set; } + public Drop? Inventory { get; set; } - public Drop Knowledgebase { get; set; } + public Drop? Knowledgebase { get; set; } - public Drop NewsComment { get; set; } + public Drop? NewsComment { get; set; } - public Drop NewsLetterSubscription { get; set; } + public Drop? NewsLetterSubscription { get; set; } - public Drop Order { get; set; } + public Drop? Order { get; set; } - public Drop OrderApproval { get; set; } + public Drop? OrderApproval { get; set; } - public Drop Product { get; set; } + public Drop? Product { get; set; } - public Drop ProductReview { get; set; } + public Drop? ProductReview { get; set; } - public Drop RecurringPayment { get; set; } + public Drop? RecurringPayment { get; set; } - public Drop MerchandiseReturn { get; set; } + public Drop? MerchandiseReturn { get; set; } - public Drop Shipment { get; set; } + public Drop? Shipment { get; set; } - public Drop ShoppingCart { get; set; } + public Drop? ShoppingCart { get; set; } - public Drop Store { get; set; } + public Drop? Store { get; set; } - public Drop Vendor { get; set; } + public Drop? Vendor { get; set; } - public Drop VendorReview { get; set; } + public Drop? VendorReview { get; set; } - public Drop EmailAFriend { get; set; } + public Drop? EmailAFriend { get; set; } - public Drop GuestOrderLink { get; set; } + public Drop? GuestOrderLink { get; set; } - public Drop AskQuestion { get; set; } + public Drop? AskQuestion { get; set; } - public Drop VatValidationResult { get; set; } + public Drop? VatValidationResult { get; set; } - public Drop ContactUs { get; set; } + public Drop? ContactUs { get; set; } - public Drop Email { get; set; } + public Drop? Email { get; set; } public IDictionary AdditionalTokens { get; set; } = new Dictionary(); } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Messages/MessageTemplate.cs b/src/Core/Grand.Domain/Messages/MessageTemplate.cs index 0864b110f..1ac425aaa 100644 --- a/src/Core/Grand.Domain/Messages/MessageTemplate.cs +++ b/src/Core/Grand.Domain/Messages/MessageTemplate.cs @@ -12,22 +12,22 @@ public class MessageTemplate : BaseEntity, ITranslationEntity, IStoreLinkEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the BCC Email addresses /// - public string BccEmailAddresses { get; set; } + public string? BccEmailAddresses { get; set; } /// /// Gets or sets the subject /// - public string Subject { get; set; } + public string? Subject { get; set; } /// /// Gets or sets the body /// - public string Body { get; set; } + public string? Body { get; set; } /// /// Gets or sets a value indicating whether the template is active @@ -47,13 +47,13 @@ public class MessageTemplate : BaseEntity, ITranslationEntity, IStoreLinkEntity /// /// Gets or sets the download identifier of attached file /// - public string AttachedDownloadId { get; set; } + public string? AttachedDownloadId { get; set; } /// /// Gets or sets the used email account identifier /// [AuditReference(typeof(EmailAccount))] - public string EmailAccountId { get; set; } + public string? EmailAccountId { get; set; } /// /// Gets or sets a value indicating whether the entity is limited/restricted to certain stores diff --git a/src/Core/Grand.Domain/Messages/NewsLetterSubscription.cs b/src/Core/Grand.Domain/Messages/NewsLetterSubscription.cs index 73b56df45..89897cbf4 100644 --- a/src/Core/Grand.Domain/Messages/NewsLetterSubscription.cs +++ b/src/Core/Grand.Domain/Messages/NewsLetterSubscription.cs @@ -10,7 +10,7 @@ namespace Grand.Domain.Messages; /// public class NewsLetterSubscription : BaseEntity, IHistory { - private ICollection _categories; + private ICollection? _categories; /// /// Gets or sets the newsletter subscription GUID @@ -21,13 +21,13 @@ public class NewsLetterSubscription : BaseEntity, IHistory /// Gets or sets the Customer identifier /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the subcriber email /// [AuditName] - public string Email { get; set; } + public string? Email { get; set; } /// /// Gets or sets a value indicating whether subscription is active @@ -38,7 +38,7 @@ public class NewsLetterSubscription : BaseEntity, IHistory /// Gets or sets the store identifier in which a customer has subscribed to newsletter /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the categories diff --git a/src/Core/Grand.Domain/Messages/NewsletterCategory.cs b/src/Core/Grand.Domain/Messages/NewsletterCategory.cs index ba1be5db6..f743290fd 100644 --- a/src/Core/Grand.Domain/Messages/NewsletterCategory.cs +++ b/src/Core/Grand.Domain/Messages/NewsletterCategory.cs @@ -9,12 +9,12 @@ public class NewsletterCategory : BaseEntity, ITranslationEntity, IStoreLinkEnti /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the description /// - public string Description { get; set; } + public string? Description { get; set; } /// /// Gets or sets the selected diff --git a/src/Core/Grand.Domain/Messages/QueuedEmail.cs b/src/Core/Grand.Domain/Messages/QueuedEmail.cs index 3f8600136..7d7cc1407 100644 --- a/src/Core/Grand.Domain/Messages/QueuedEmail.cs +++ b/src/Core/Grand.Domain/Messages/QueuedEmail.cs @@ -15,63 +15,63 @@ public class QueuedEmail : BaseEntity /// /// Gets or sets the From property /// - public string From { get; set; } + public string? From { get; set; } /// /// Gets or sets the FromName property /// - public string FromName { get; set; } + public string? FromName { get; set; } /// /// Gets or sets the To property /// - public string To { get; set; } + public string? To { get; set; } /// /// Gets or sets the ToName property /// - public string ToName { get; set; } + public string? ToName { get; set; } /// /// Gets or sets the ReplyTo property /// - public string ReplyTo { get; set; } + public string? ReplyTo { get; set; } /// /// Gets or sets the ReplyToName property /// - public string ReplyToName { get; set; } + public string? ReplyToName { get; set; } /// /// Gets or sets the CC /// - public string CC { get; set; } + public string? CC { get; set; } /// /// Gets or sets the Bcc /// - public string Bcc { get; set; } + public string? Bcc { get; set; } /// /// Gets or sets the subject /// - public string Subject { get; set; } + public string? Subject { get; set; } /// /// Gets or sets the body /// - public string Body { get; set; } + public string? Body { get; set; } /// /// Gets or sets the attachment file path (full file path) /// - public string AttachmentFilePath { get; set; } + public string? AttachmentFilePath { get; set; } /// /// Gets or sets the attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, /// "AttachmentFilePath" name will be used. /// - public string AttachmentFileName { get; set; } + public string? AttachmentFileName { get; set; } /// /// Gets or sets the download identifiers of attached file @@ -82,7 +82,7 @@ public class QueuedEmail : BaseEntity /// Gets or sets the download identifier of the order invoice generated for this email. /// Unlike AttachedDownloads, the email owns this download and it is deleted together with the email /// - public string InvoiceDownloadId { get; set; } + public string? InvoiceDownloadId { get; set; } /// /// Gets or sets the date and time in UTC before which this email should not be sent @@ -107,7 +107,7 @@ public class QueuedEmail : BaseEntity /// /// Gets or sets the used email account identifier /// - public string EmailAccountId { get; set; } + public string? EmailAccountId { get; set; } /// /// Gets or sets an reference identifier @@ -117,5 +117,5 @@ public class QueuedEmail : BaseEntity /// /// Gets or sets an object reference identifier /// - public string ObjectId { get; set; } + public string? ObjectId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/MigrationDb.cs b/src/Core/Grand.Domain/MigrationDb.cs index d83cfdda6..c487bfa04 100644 --- a/src/Core/Grand.Domain/MigrationDb.cs +++ b/src/Core/Grand.Domain/MigrationDb.cs @@ -10,10 +10,10 @@ public class MigrationDb : BaseEntity /// /// Name of migration. /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Db Version /// - public string Version { get; set; } + public string? Version { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/News/NewsComment.cs b/src/Core/Grand.Domain/News/NewsComment.cs index 0428c2c59..94c38579f 100644 --- a/src/Core/Grand.Domain/News/NewsComment.cs +++ b/src/Core/Grand.Domain/News/NewsComment.cs @@ -13,30 +13,30 @@ public class NewsComment : SubBaseEntity /// Gets or sets the comment title /// [AuditName] - public string CommentTitle { get; set; } + public string? CommentTitle { get; set; } /// /// Gets or sets the comment text /// - public string CommentText { get; set; } + public string? CommentText { get; set; } /// /// Gets or sets the news item identifier /// [AuditReference(typeof(NewsItem))] - public string NewsItemId { get; set; } + public string? NewsItemId { get; set; } /// /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the date and time of instance creation diff --git a/src/Core/Grand.Domain/News/NewsItem.cs b/src/Core/Grand.Domain/News/NewsItem.cs index d7b0a96a1..3c57854ce 100644 --- a/src/Core/Grand.Domain/News/NewsItem.cs +++ b/src/Core/Grand.Domain/News/NewsItem.cs @@ -12,28 +12,28 @@ namespace Grand.Domain.News; /// public class NewsItem : BaseEntity, ISlugEntity, IStoreLinkEntity, ITranslationEntity, IGroupLinkEntity { - private ICollection _newsComments; + private ICollection? _newsComments; /// /// Gets or sets the news title /// [AuditName] - public string Title { get; set; } + public string? Title { get; set; } /// /// Gets or sets the picture identifier /// - public string PictureId { get; set; } + public string? PictureId { get; set; } /// /// Gets or sets the short text /// - public string Short { get; set; } + public string? Short { get; set; } /// /// Gets or sets the full text /// - public string Full { get; set; } + public string? Full { get; set; } /// /// Gets or sets a value indicating whether the news item is published @@ -66,17 +66,17 @@ public class NewsItem : BaseEntity, ISlugEntity, IStoreLinkEntity, ITranslationE /// /// Gets or sets the meta keywords /// - public string MetaKeywords { get; set; } + public string? MetaKeywords { get; set; } /// /// Gets or sets the meta description /// - public string MetaDescription { get; set; } + public string? MetaDescription { get; set; } /// /// Gets or sets the meta title /// - public string MetaTitle { get; set; } + public string? MetaTitle { get; set; } /// /// Gets or sets the news comments @@ -97,7 +97,7 @@ public virtual ICollection NewsComments { /// /// Gets or sets the sename /// - public string SeName { get; set; } + public string? SeName { get; set; } /// /// Gets or sets a value indicating whether the entity is limited/restricted to certain stores diff --git a/src/Core/Grand.Domain/Orders/CheckoutAttribute.cs b/src/Core/Grand.Domain/Orders/CheckoutAttribute.cs index 6e38cbeb6..229fc8638 100644 --- a/src/Core/Grand.Domain/Orders/CheckoutAttribute.cs +++ b/src/Core/Grand.Domain/Orders/CheckoutAttribute.cs @@ -14,17 +14,17 @@ namespace Grand.Domain.Orders; /// public class CheckoutAttribute : BaseEntity, ITranslationEntity, IStoreLinkEntity, IGroupLinkEntity { - private ICollection _checkoutAttributeValues; + private ICollection? _checkoutAttributeValues; /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the text prompt /// - public string TextPrompt { get; set; } + public string? TextPrompt { get; set; } /// /// Gets or sets a value indicating whether the entity is required @@ -45,7 +45,7 @@ public class CheckoutAttribute : BaseEntity, ITranslationEntity, IStoreLinkEntit /// Gets or sets the tax category identifier /// [AuditReference(typeof(TaxCategory))] - public string TaxCategoryId { get; set; } + public string? TaxCategoryId { get; set; } /// /// Gets or sets the attribute control type identifier @@ -72,7 +72,7 @@ public class CheckoutAttribute : BaseEntity, ITranslationEntity, IStoreLinkEntit /// /// Gets or sets the validation rule for file allowed extensions (for file upload) /// - public string ValidationFileAllowedExtensions { get; set; } + public string? ValidationFileAllowedExtensions { get; set; } /// /// Gets or sets the validation rule for file maximum size in kilobytes (for file upload) @@ -82,7 +82,7 @@ public class CheckoutAttribute : BaseEntity, ITranslationEntity, IStoreLinkEntit /// /// Gets or sets the default value (for textbox and multiline textbox) /// - public string DefaultValue { get; set; } + public string? DefaultValue { get; set; } /// /// Gets or sets a condition (depending on other attribute) when this attribute should be enabled (visible). diff --git a/src/Core/Grand.Domain/Orders/CheckoutAttributeValue.cs b/src/Core/Grand.Domain/Orders/CheckoutAttributeValue.cs index c28903c23..251d6ab2b 100644 --- a/src/Core/Grand.Domain/Orders/CheckoutAttributeValue.cs +++ b/src/Core/Grand.Domain/Orders/CheckoutAttributeValue.cs @@ -12,17 +12,17 @@ public class CheckoutAttributeValue : SubBaseEntity, ITranslationEntity /// Gets or sets the checkout attribute mapping identifier /// [AuditReference(typeof(CheckoutAttribute))] - public string CheckoutAttributeId { get; set; } + public string? CheckoutAttributeId { get; set; } /// /// Gets or sets the checkout attribute name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the color RGB value (used with "Color squares" attribute type) /// - public string ColorSquaresRgb { get; set; } + public string? ColorSquaresRgb { get; set; } /// /// Gets or sets the price adjustment diff --git a/src/Core/Grand.Domain/Orders/GiftVoucher.cs b/src/Core/Grand.Domain/Orders/GiftVoucher.cs index cdee9f1ea..81bd0cb8f 100644 --- a/src/Core/Grand.Domain/Orders/GiftVoucher.cs +++ b/src/Core/Grand.Domain/Orders/GiftVoucher.cs @@ -9,7 +9,7 @@ namespace Grand.Domain.Orders; /// public class GiftVoucher : BaseEntity { - private ICollection _giftVoucherUsageHistory; + private ICollection? _giftVoucherUsageHistory; /// /// Gets or sets the gift voucher type identifier @@ -24,7 +24,7 @@ public class GiftVoucher : BaseEntity /// /// Gets or sets the currency code /// - public string CurrencyCode { get; set; } + public string? CurrencyCode { get; set; } /// /// Gets or sets a value indicating whether gift voucher is activated @@ -35,32 +35,32 @@ public class GiftVoucher : BaseEntity /// Gets or sets a gift voucher coupon code /// [AuditName] - public string Code { get; set; } + public string? Code { get; set; } /// /// Gets or sets a recipient name /// - public string RecipientName { get; set; } + public string? RecipientName { get; set; } /// /// Gets or sets a recipient email /// - public string RecipientEmail { get; set; } + public string? RecipientEmail { get; set; } /// /// Gets or sets a sender name /// - public string SenderName { get; set; } + public string? SenderName { get; set; } /// /// Gets or sets a sender email /// - public string SenderEmail { get; set; } + public string? SenderEmail { get; set; } /// /// Gets or sets a message /// - public string Message { get; set; } + public string? Message { get; set; } /// /// Gets or sets a value indicating whether recipient is notified @@ -71,7 +71,7 @@ public class GiftVoucher : BaseEntity /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the date and time of instance creation @@ -89,5 +89,5 @@ public virtual ICollection GiftVoucherUsageHistory { /// /// Gets or sets the associated order item /// - public virtual OrderItem PurchasedWithOrderItem { get; set; } + public virtual OrderItem? PurchasedWithOrderItem { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Orders/GiftVoucherExtensions.cs b/src/Core/Grand.Domain/Orders/GiftVoucherExtensions.cs index e7cd4ec9c..b6c97fb26 100644 --- a/src/Core/Grand.Domain/Orders/GiftVoucherExtensions.cs +++ b/src/Core/Grand.Domain/Orders/GiftVoucherExtensions.cs @@ -43,9 +43,9 @@ public static IList AddGiftVoucherAttribute(IListSender name /// Sender email /// Message - public static void GetGiftVoucherAttribute(IList customAttributes, out string recipientName, - out string recipientEmail, out string senderName, - out string senderEmail, out string giftVoucherMessage) + public static void GetGiftVoucherAttribute(IList customAttributes, out string? recipientName, + out string? recipientEmail, out string? senderName, + out string? senderEmail, out string? giftVoucherMessage) { customAttributes ??= new List(); diff --git a/src/Core/Grand.Domain/Orders/GiftVoucherUsageHistory.cs b/src/Core/Grand.Domain/Orders/GiftVoucherUsageHistory.cs index c85056466..cd96e15d3 100644 --- a/src/Core/Grand.Domain/Orders/GiftVoucherUsageHistory.cs +++ b/src/Core/Grand.Domain/Orders/GiftVoucherUsageHistory.cs @@ -11,14 +11,14 @@ public class GiftVoucherUsageHistory : SubBaseEntity /// Gets or sets the gift voucher identifier /// [AuditReference(typeof(GiftVoucher))] - public string GiftVoucherId { get; set; } + public string? GiftVoucherId { get; set; } /// /// Gets or sets the order identifier /// [AuditReference(typeof(Order))] [AuditName] - public string UsedWithOrderId { get; set; } + public string? UsedWithOrderId { get; set; } /// /// Gets or sets the used value (amount) diff --git a/src/Core/Grand.Domain/Orders/LoyaltyPointsHistory.cs b/src/Core/Grand.Domain/Orders/LoyaltyPointsHistory.cs index de39a032b..132bbb13f 100644 --- a/src/Core/Grand.Domain/Orders/LoyaltyPointsHistory.cs +++ b/src/Core/Grand.Domain/Orders/LoyaltyPointsHistory.cs @@ -13,13 +13,13 @@ public class LoyaltyPointsHistory : BaseEntity /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the store identifier in which these loyalty points were awarded or redeemed /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the points redeemed/added @@ -39,8 +39,8 @@ public class LoyaltyPointsHistory : BaseEntity /// /// Gets or sets the message /// - public string Message { get; set; } + public string? Message { get; set; } [AuditReference(typeof(Order))] - public string UsedWithOrderId { get; set; } + public string? UsedWithOrderId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Orders/MerchandiseReturn.cs b/src/Core/Grand.Domain/Orders/MerchandiseReturn.cs index 717a91be1..4fb921fae 100644 --- a/src/Core/Grand.Domain/Orders/MerchandiseReturn.cs +++ b/src/Core/Grand.Domain/Orders/MerchandiseReturn.cs @@ -17,30 +17,30 @@ public class MerchandiseReturn : BaseEntity /// /// Gets or sets the ExternalId /// - public string ExternalId { get; set; } + public string? ExternalId { get; set; } /// /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the order item identifier /// [AuditReference(typeof(Order))] - public string OrderId { get; set; } + public string? OrderId { get; set; } /// /// Gets or sets the owner item identifier /// [AuditReference(typeof(Customer))] - public string OwnerId { get; set; } + public string? OwnerId { get; set; } /// /// Gets or sets the sales employee identifier /// - public string SeId { get; set; } + public string? SeId { get; set; } /// /// Gets or sets the merchandise return items @@ -51,23 +51,23 @@ public class MerchandiseReturn : BaseEntity /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the vendor item identifier /// [AuditReference(typeof(Vendor))] - public string VendorId { get; set; } + public string? VendorId { get; set; } /// /// Gets or sets the customer comments /// - public string CustomerComments { get; set; } + public string? CustomerComments { get; set; } /// /// Gets or sets the staff notes /// - public string StaffNotes { get; set; } + public string? StaffNotes { get; set; } /// /// Gets or sets the return status identifier @@ -90,17 +90,17 @@ public MerchandiseReturnStatus MerchandiseReturnStatus { /// /// Gets or sets the pickup address /// - public Address PickupAddress { get; set; } + public Address? PickupAddress { get; set; } /// /// Gets or sets how the items are sent back; null when no return shipping was chosen /// - public MerchandiseReturnShipping ReturnShipping { get; set; } + public MerchandiseReturnShipping? ReturnShipping { get; set; } /// /// Gets or sets the money given back for the return; null until a refund is started /// - public MerchandiseReturnRefund Refund { get; set; } + public MerchandiseReturnRefund? Refund { get; set; } /// /// Gets or sets the statuses the return reached after it was submitted, oldest first; empty for a return diff --git a/src/Core/Grand.Domain/Orders/MerchandiseReturnAction.cs b/src/Core/Grand.Domain/Orders/MerchandiseReturnAction.cs index f65f4d65d..9ccb655eb 100644 --- a/src/Core/Grand.Domain/Orders/MerchandiseReturnAction.cs +++ b/src/Core/Grand.Domain/Orders/MerchandiseReturnAction.cs @@ -12,7 +12,7 @@ public class MerchandiseReturnAction : BaseEntity, ITranslationEntity, IStoreLin /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Orders/MerchandiseReturnItem.cs b/src/Core/Grand.Domain/Orders/MerchandiseReturnItem.cs index ce52b3661..3f72655db 100644 --- a/src/Core/Grand.Domain/Orders/MerchandiseReturnItem.cs +++ b/src/Core/Grand.Domain/Orders/MerchandiseReturnItem.cs @@ -5,17 +5,17 @@ public class MerchandiseReturnItem : BaseEntity /// /// Gets or sets the order item identifier /// - public string OrderItemId { get; set; } + public string? OrderItemId { get; set; } /// /// Gets or sets the merchandise return reason identifier; null when it is not known /// - public string ReasonId { get; set; } + public string? ReasonId { get; set; } /// /// Gets or sets the reason for return: its name in the customer's language when submitted /// - public string ReasonForReturn { get; set; } + public string? ReasonForReturn { get; set; } /// /// Gets or sets the quantity @@ -25,10 +25,10 @@ public class MerchandiseReturnItem : BaseEntity /// /// Gets or sets the merchandise return action identifier; null when it is not known /// - public string ActionId { get; set; } + public string? ActionId { get; set; } /// /// Gets or sets the requested action: its name in the customer's language when submitted /// - public string RequestedAction { get; set; } + public string? RequestedAction { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Orders/MerchandiseReturnNote.cs b/src/Core/Grand.Domain/Orders/MerchandiseReturnNote.cs index 4f0fab053..e40f08d18 100644 --- a/src/Core/Grand.Domain/Orders/MerchandiseReturnNote.cs +++ b/src/Core/Grand.Domain/Orders/MerchandiseReturnNote.cs @@ -12,23 +12,23 @@ public class MerchandiseReturnNote : BaseEntity /// [AuditReference(typeof(MerchandiseReturn))] [AuditOwner] - public string MerchandiseReturnId { get; set; } + public string? MerchandiseReturnId { get; set; } /// /// Gets or sets the title /// [AuditName] - public string Title { get; set; } + public string? Title { get; set; } /// /// Gets or sets the note /// - public string Note { get; set; } + public string? Note { get; set; } /// /// Gets or sets the attached file (download) identifier /// - public string DownloadId { get; set; } + public string? DownloadId { get; set; } /// /// Gets or sets a value indicating whether a customer can see a note diff --git a/src/Core/Grand.Domain/Orders/MerchandiseReturnReason.cs b/src/Core/Grand.Domain/Orders/MerchandiseReturnReason.cs index 1642ae63f..2ed3210c5 100644 --- a/src/Core/Grand.Domain/Orders/MerchandiseReturnReason.cs +++ b/src/Core/Grand.Domain/Orders/MerchandiseReturnReason.cs @@ -12,7 +12,7 @@ public class MerchandiseReturnReason : BaseEntity, ITranslationEntity, IStoreLin /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Orders/MerchandiseReturnRefund.cs b/src/Core/Grand.Domain/Orders/MerchandiseReturnRefund.cs index ab1af7032..57d402442 100644 --- a/src/Core/Grand.Domain/Orders/MerchandiseReturnRefund.cs +++ b/src/Core/Grand.Domain/Orders/MerchandiseReturnRefund.cs @@ -33,7 +33,7 @@ public class MerchandiseReturnRefund /// Gets or sets the payment transaction refunded /// [AuditReference(typeof(PaymentTransaction))] - public string PaymentTransactionId { get; set; } + public string? PaymentTransactionId { get; set; } /// /// Gets or sets whether the payment answered the refund with errors: it may have given the money back before it @@ -44,7 +44,7 @@ public class MerchandiseReturnRefund /// /// Gets or sets who refunded, as the staff note names them /// - public string RefundedBy { get; set; } + public string? RefundedBy { get; set; } /// /// Gets or sets when the refund was started diff --git a/src/Core/Grand.Domain/Orders/MerchandiseReturnShipping.cs b/src/Core/Grand.Domain/Orders/MerchandiseReturnShipping.cs index 842f323b7..78d6c640d 100644 --- a/src/Core/Grand.Domain/Orders/MerchandiseReturnShipping.cs +++ b/src/Core/Grand.Domain/Orders/MerchandiseReturnShipping.cs @@ -10,17 +10,17 @@ public class MerchandiseReturnShipping /// /// Gets or sets the system name of the return shipping provider /// - public string ProviderSystemName { get; set; } + public string? ProviderSystemName { get; set; } /// /// Gets or sets the code of the chosen option of the provider /// - public string OptionCode { get; set; } + public string? OptionCode { get; set; } /// /// Gets or sets the name of the chosen option of the provider /// - public string OptionName { get; set; } + public string? OptionName { get; set; } /// /// Gets or sets the cost the customer pays, in the primary store currency @@ -35,32 +35,32 @@ public class MerchandiseReturnShipping /// /// Gets or sets the drop-off point the customer leaves the parcel at /// - public ReturnDropOffPoint DropOffPoint { get; set; } + public ReturnDropOffPoint? DropOffPoint { get; set; } /// /// Gets or sets the address the parcel is sent to /// - public Address ReturnAddress { get; set; } + public Address? ReturnAddress { get; set; } /// /// Gets or sets the tracking number /// - public string TrackingNumber { get; set; } + public string? TrackingNumber { get; set; } /// /// Gets or sets the code the customer shows at the drop-off point /// - public string ReturnCode { get; set; } + public string? ReturnCode { get; set; } /// /// Gets or sets the identifier of the download holding the label /// - public string LabelDownloadId { get; set; } + public string? LabelDownloadId { get; set; } /// /// Gets or sets the instructions shown to the customer /// - public string Instructions { get; set; } + public string? Instructions { get; set; } /// /// Gets or sets the label status identifier @@ -78,7 +78,7 @@ public ReturnLabelStatus LabelStatus { /// /// Gets or sets the error of the last failed label request /// - public string LabelError { get; set; } + public string? LabelError { get; set; } /// /// Gets or sets the data only the provider understands @@ -94,25 +94,25 @@ public class ReturnDropOffPoint /// /// Gets or sets the provider's identifier of the point /// - public string Id { get; set; } + public string? Id { get; set; } /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the address /// - public Address Address { get; set; } + public Address? Address { get; set; } /// /// Gets or sets the opening hours /// - public string OpeningHours { get; set; } + public string? OpeningHours { get; set; } /// /// Gets or sets the warehouse identifier when the point is a warehouse of the store /// - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } } diff --git a/src/Core/Grand.Domain/Orders/Order.cs b/src/Core/Grand.Domain/Orders/Order.cs index 22f82cdd9..88e24ccdb 100644 --- a/src/Core/Grand.Domain/Orders/Order.cs +++ b/src/Core/Grand.Domain/Orders/Order.cs @@ -16,9 +16,9 @@ namespace Grand.Domain.Orders; /// public class Order : BaseEntity { - private ICollection _orderItems; - private ICollection _orderTags; - private ICollection _orderTaxes; + private ICollection? _orderItems; + private ICollection? _orderTags; + private ICollection? _orderTaxes; #region Properties @@ -36,35 +36,35 @@ public class Order : BaseEntity /// /// Gets or sets the order code /// - public string Code { get; set; } + public string? Code { get; set; } /// /// Gets or sets the buyer's own purchase order number /// - public string PurchaseOrderNumber { get; set; } + public string? PurchaseOrderNumber { get; set; } /// /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the owner identifier /// [AuditReference(typeof(Customer))] - public string OwnerId { get; set; } + public string? OwnerId { get; set; } /// /// Gets or sets the sales employee identifier /// - public string SeId { get; set; } + public string? SeId { get; set; } /// /// Gets or sets a value indicating whether a customer chose "pick up in store" shipping option @@ -90,19 +90,19 @@ public class Order : BaseEntity /// /// Gets or sets the payment method system name /// - public string PaymentMethodSystemName { get; set; } + public string? PaymentMethodSystemName { get; set; } - public string PaymentOptionAttribute { get; set; } + public string? PaymentOptionAttribute { get; set; } /// /// Gets or sets the customer currency code (at the moment of order placing) /// - public string CustomerCurrencyCode { get; set; } + public string? CustomerCurrencyCode { get; set; } /// /// Gets or sets the primary currency code (at the moment of order placing) /// - public string PrimaryCurrencyCode { get; set; } + public string? PrimaryCurrencyCode { get; set; } /// /// Gets or sets the currency rate @@ -122,7 +122,7 @@ public class Order : BaseEntity /// /// Gets or sets the VAT number /// - public string VatNumber { get; set; } + public string? VatNumber { get; set; } /// /// Gets or sets the VAT number status id @@ -132,22 +132,22 @@ public class Order : BaseEntity /// /// Gets or sets the Company name /// - public string CompanyName { get; set; } + public string? CompanyName { get; set; } /// /// Gets or sets the CustomerEmail /// - public string CustomerEmail { get; set; } + public string? CustomerEmail { get; set; } /// /// Gets or sets the FirstName /// - public string FirstName { get; set; } + public string? FirstName { get; set; } /// /// Gets or sets the LastName /// - public string LastName { get; set; } + public string? LastName { get; set; } /// /// Gets or sets the order subtotal (incl tax) @@ -249,7 +249,7 @@ public class Order : BaseEntity /// /// Gets or sets the checkout attribute description /// - public string CheckoutAttributeDescription { get; set; } + public string? CheckoutAttributeDescription { get; set; } public IList CheckoutAttributes { get; set; } = new List(); @@ -257,28 +257,28 @@ public class Order : BaseEntity /// Gets or sets the customer language identifier /// [AuditReference(typeof(Language))] - public string CustomerLanguageId { get; set; } + public string? CustomerLanguageId { get; set; } /// /// Gets or sets the affiliate identifier /// [AuditReference(typeof(Affiliate))] - public string AffiliateId { get; set; } + public string? AffiliateId { get; set; } /// /// Gets or sets the customer IP address /// - public string CustomerIp { get; set; } + public string? CustomerIp { get; set; } /// /// Gets or sets the shipping method /// - public string ShippingMethod { get; set; } + public string? ShippingMethod { get; set; } /// /// Gets or sets the Shipping rate method identifier /// - public string ShippingRateProviderSystemName { get; set; } + public string? ShippingRateProviderSystemName { get; set; } /// /// Gets or sets a value indicating whether the entity has been deleted @@ -318,7 +318,7 @@ public class Order : BaseEntity /// /// Gets or sets the order the customer placed, on an order paying a later cycle of its recurring payment /// - public string InitialOrderId { get; set; } + public string? InitialOrderId { get; set; } /// /// Gets or sets the recurring payment cycle the order pays: 1 on the initial order, 0 when not recurring @@ -328,12 +328,12 @@ public class Order : BaseEntity /// /// Gets or sets the Shipping Option description (customer friendly string) /// - public string ShippingOptionAttributeDescription { get; set; } + public string? ShippingOptionAttributeDescription { get; set; } /// /// Gets or sets the Shipping Option (developer friendly string) /// - public string ShippingOptionAttribute { get; set; } + public string? ShippingOptionAttribute { get; set; } #endregion @@ -342,17 +342,17 @@ public class Order : BaseEntity /// /// Gets or sets the billing address /// - public virtual Address BillingAddress { get; set; } + public virtual Address? BillingAddress { get; set; } /// /// Gets or sets the shipping address /// - public virtual Address ShippingAddress { get; set; } + public virtual Address? ShippingAddress { get; set; } /// /// Gets or sets the pickup point /// - public virtual PickupPoint PickupPoint { get; set; } + public virtual PickupPoint? PickupPoint { get; set; } /// /// Gets or sets order items diff --git a/src/Core/Grand.Domain/Orders/OrderApproval.cs b/src/Core/Grand.Domain/Orders/OrderApproval.cs index 2c9b002cf..5716ba72c 100644 --- a/src/Core/Grand.Domain/Orders/OrderApproval.cs +++ b/src/Core/Grand.Domain/Orders/OrderApproval.cs @@ -13,7 +13,7 @@ public class OrderApproval : BaseEntity /// Gets or sets the store identifier the order belongs to /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets who decides the request @@ -24,7 +24,7 @@ public class OrderApproval : BaseEntity /// Gets or sets the identifier of the company owner; every company read is scoped by it. Null when the store decides. /// [AuditReference(typeof(Customer))] - public string CompanyOwnerId { get; set; } + public string? CompanyOwnerId { get; set; } /// /// Gets or sets why the order needs an approval, in the buyer's language @@ -35,7 +35,7 @@ public class OrderApproval : BaseEntity /// Gets or sets the buyer identifier /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the status @@ -60,7 +60,7 @@ public class OrderApproval : BaseEntity /// /// Gets or sets the buyer's currency code, for display /// - public string CurrencyCode { get; set; } + public string? CurrencyCode { get; set; } /// /// Gets or sets the date and time of the decision @@ -71,21 +71,21 @@ public class OrderApproval : BaseEntity /// Gets or sets the identifier of the customer who decided /// [AuditReference(typeof(Customer))] - public string DecidedByCustomerId { get; set; } + public string? DecidedByCustomerId { get; set; } /// /// Gets or sets the approver's comment /// - public string DecisionComment { get; set; } + public string? DecisionComment { get; set; } /// /// Gets or sets the identifier of the write that closed the request; tells concurrent callers which one won /// - public string CloseId { get; set; } + public string? CloseId { get; set; } /// /// Gets or sets the identifier of the order awaiting the decision; set at creation /// [AuditReference(typeof(Order))] - public string OrderId { get; set; } + public string? OrderId { get; set; } } diff --git a/src/Core/Grand.Domain/Orders/OrderApprovalItem.cs b/src/Core/Grand.Domain/Orders/OrderApprovalItem.cs index f23653376..d5fa9d4b7 100644 --- a/src/Core/Grand.Domain/Orders/OrderApprovalItem.cs +++ b/src/Core/Grand.Domain/Orders/OrderApprovalItem.cs @@ -13,17 +13,17 @@ public class OrderApprovalItem : SubBaseEntity /// [AuditReference(typeof(Product))] [AuditName] - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// Gets or sets the product name /// - public string ProductName { get; set; } + public string? ProductName { get; set; } /// /// Gets or sets the product SKU /// - public string Sku { get; set; } + public string? Sku { get; set; } /// /// Gets or sets the quantity @@ -33,15 +33,15 @@ public class OrderApprovalItem : SubBaseEntity /// /// Gets or sets the formatted attributes /// - public string AttributeDescription { get; set; } + public string? AttributeDescription { get; set; } /// /// Gets or sets the formatted unit price, in the buyer's currency /// - public string UnitPrice { get; set; } + public string? UnitPrice { get; set; } /// /// Gets or sets the formatted line total, in the buyer's currency /// - public string LineTotal { get; set; } + public string? LineTotal { get; set; } } diff --git a/src/Core/Grand.Domain/Orders/OrderApprovalSummary.cs b/src/Core/Grand.Domain/Orders/OrderApprovalSummary.cs index bf1b0bac6..6a698d7a2 100644 --- a/src/Core/Grand.Domain/Orders/OrderApprovalSummary.cs +++ b/src/Core/Grand.Domain/Orders/OrderApprovalSummary.cs @@ -9,30 +9,30 @@ public class OrderApprovalSummary /// /// Gets or sets the sub total /// - public string SubTotal { get; set; } + public string? SubTotal { get; set; } /// /// Gets or sets the discount /// - public string Discount { get; set; } + public string? Discount { get; set; } /// /// Gets or sets the shipping method name /// - public string ShippingMethod { get; set; } + public string? ShippingMethod { get; set; } /// /// Gets or sets the shipping cost /// - public string Shipping { get; set; } + public string? Shipping { get; set; } /// /// Gets or sets the tax /// - public string Tax { get; set; } + public string? Tax { get; set; } /// /// Gets or sets the order total /// - public string Total { get; set; } + public string? Total { get; set; } } diff --git a/src/Core/Grand.Domain/Orders/OrderItem.cs b/src/Core/Grand.Domain/Orders/OrderItem.cs index 8d049604e..7b16f67dd 100644 --- a/src/Core/Grand.Domain/Orders/OrderItem.cs +++ b/src/Core/Grand.Domain/Orders/OrderItem.cs @@ -21,29 +21,29 @@ public class OrderItem : SubBaseEntity /// [AuditReference(typeof(Product))] [AuditName] - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// Gets or sets the sku product identifier /// - public string Sku { get; set; } + public string? Sku { get; set; } /// /// Gets or sets the vendor identifier /// [AuditReference(typeof(Vendor))] - public string VendorId { get; set; } + public string? VendorId { get; set; } /// /// Gets or sets the warehouse identifier /// [AuditReference(typeof(Warehouse))] - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } /// /// Gets or sets the sales employee identifier /// - public string SeId { get; set; } + public string? SeId { get; set; } /// /// Gets or sets the quantity @@ -138,7 +138,7 @@ public class OrderItem : SubBaseEntity /// /// Gets or sets the attribute description /// - public string AttributeDescription { get; set; } + public string? AttributeDescription { get; set; } public IList Attributes { get; set; } = new List(); @@ -155,7 +155,7 @@ public class OrderItem : SubBaseEntity /// /// Gets or sets a license download identifier (in case this is a downloadable product) /// - public string LicenseDownloadId { get; set; } + public string? LicenseDownloadId { get; set; } /// /// Gets or sets the total weight of one item @@ -185,5 +185,5 @@ public class OrderItem : SubBaseEntity /// /// Gets or sets owner cid /// - public string cId { get; set; } + public string? cId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Orders/OrderNote.cs b/src/Core/Grand.Domain/Orders/OrderNote.cs index d1577e584..509d22e20 100644 --- a/src/Core/Grand.Domain/Orders/OrderNote.cs +++ b/src/Core/Grand.Domain/Orders/OrderNote.cs @@ -12,18 +12,18 @@ public class OrderNote : BaseEntity /// [AuditReference(typeof(Order))] [AuditOwner] - public string OrderId { get; set; } + public string? OrderId { get; set; } /// /// Gets or sets the note /// [AuditName] - public string Note { get; set; } + public string? Note { get; set; } /// /// Gets or sets the attached file (download) identifier /// - public string DownloadId { get; set; } + public string? DownloadId { get; set; } /// /// Gets or sets a value indicating whether a customer can see a note diff --git a/src/Core/Grand.Domain/Orders/OrderStatus.cs b/src/Core/Grand.Domain/Orders/OrderStatus.cs index 6d081012f..59387f09b 100644 --- a/src/Core/Grand.Domain/Orders/OrderStatus.cs +++ b/src/Core/Grand.Domain/Orders/OrderStatus.cs @@ -3,7 +3,7 @@ public class OrderStatus : BaseEntity { public int StatusId { get; set; } - public string Name { get; set; } + public string? Name { get; set; } public int DisplayOrder { get; set; } public bool IsSystem { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Orders/OrderTag.cs b/src/Core/Grand.Domain/Orders/OrderTag.cs index b79caaf1a..1a28f3335 100644 --- a/src/Core/Grand.Domain/Orders/OrderTag.cs +++ b/src/Core/Grand.Domain/Orders/OrderTag.cs @@ -5,7 +5,7 @@ public class OrderTag : BaseEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the count diff --git a/src/Core/Grand.Domain/Orders/RecurringPayment.cs b/src/Core/Grand.Domain/Orders/RecurringPayment.cs index 532aae91c..b6b91dae5 100644 --- a/src/Core/Grand.Domain/Orders/RecurringPayment.cs +++ b/src/Core/Grand.Domain/Orders/RecurringPayment.cs @@ -15,24 +15,24 @@ public class RecurringPayment : BaseEntity /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the order the customer placed /// [AuditReference(typeof(Order))] - public string InitialOrderId { get; set; } + public string? InitialOrderId { get; set; } /// /// Gets or sets the system name of the payment method that runs the schedule /// - public string PaymentMethodSystemName { get; set; } + public string? PaymentMethodSystemName { get; set; } /// /// Gets or sets the cycle length @@ -63,7 +63,7 @@ public class RecurringPayment : BaseEntity /// /// Gets or sets the gateway's subscription identifier /// - public string ProviderReference { get; set; } + public string? ProviderReference { get; set; } /// /// Gets or sets the next payment date as reported by the provider; informational only @@ -73,7 +73,7 @@ public class RecurringPayment : BaseEntity /// /// Gets or sets the reason the last cycle failed /// - public string LastError { get; set; } + public string? LastError { get; set; } /// /// Gets or sets the date and time the last cycle failed @@ -88,7 +88,7 @@ public class RecurringPayment : BaseEntity /// /// Gets or sets who cancelled: the customer, a staff name or the provider /// - public string CancelledBy { get; set; } + public string? CancelledBy { get; set; } /// /// Gets or sets the paid cycles diff --git a/src/Core/Grand.Domain/Orders/RecurringPaymentCycle.cs b/src/Core/Grand.Domain/Orders/RecurringPaymentCycle.cs index 26c02ee93..c2cf6c6dc 100644 --- a/src/Core/Grand.Domain/Orders/RecurringPaymentCycle.cs +++ b/src/Core/Grand.Domain/Orders/RecurringPaymentCycle.cs @@ -13,12 +13,12 @@ public class RecurringPaymentCycle : SubBaseEntity /// /// Gets or sets the order the cycle was paid with /// - public string OrderId { get; set; } + public string? OrderId { get; set; } /// /// Gets or sets the gateway's invoice or charge identifier /// - public string ProviderReference { get; set; } + public string? ProviderReference { get; set; } /// /// Gets or sets the amount the gateway charged diff --git a/src/Core/Grand.Domain/Orders/ShoppingCartItem.cs b/src/Core/Grand.Domain/Orders/ShoppingCartItem.cs index b9a25a0ef..5bf0dfb9f 100644 --- a/src/Core/Grand.Domain/Orders/ShoppingCartItem.cs +++ b/src/Core/Grand.Domain/Orders/ShoppingCartItem.cs @@ -12,12 +12,12 @@ public class ShoppingCartItem : SubBaseEntity /// /// Gets or sets the store identifier /// - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the warehouse identifier /// - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } /// /// Gets or sets the shopping cart type identifier @@ -29,7 +29,7 @@ public class ShoppingCartItem : SubBaseEntity /// [AuditReference(typeof(Product))] [AuditName] - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// Gets or sets the custom attributes (see "ProductAttribute" entity for more info) @@ -94,20 +94,20 @@ public class ShoppingCartItem : SubBaseEntity /// /// Gets or sets the reservation identifier /// - public string ReservationId { get; set; } + public string? ReservationId { get; set; } /// /// Gets or sets parameter of reservation /// - public string Parameter { get; set; } + public string? Parameter { get; set; } /// /// Gets or sets Duration of reservation /// - public string Duration { get; set; } + public string? Duration { get; set; } /// /// Gets or sets owner cid /// - public string cId { get; set; } + public string? cId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Orders/ShoppingCartSettings.cs b/src/Core/Grand.Domain/Orders/ShoppingCartSettings.cs index 0f279f32d..30e891ef7 100644 --- a/src/Core/Grand.Domain/Orders/ShoppingCartSettings.cs +++ b/src/Core/Grand.Domain/Orders/ShoppingCartSettings.cs @@ -123,5 +123,5 @@ public class ShoppingCartSettings : ISettings /// /// Gets or sets a value reservation format date /// - public string ReservationDateFormat { get; set; } + public string? ReservationDateFormat { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Pages/Page.cs b/src/Core/Grand.Domain/Pages/Page.cs index e27f6c8d4..89173e5e4 100644 --- a/src/Core/Grand.Domain/Pages/Page.cs +++ b/src/Core/Grand.Domain/Pages/Page.cs @@ -15,7 +15,7 @@ public class Page : BaseEntity, ITranslationEntity, ISlugEntity, IStoreLinkEntit /// /// Gets or sets the name /// - public string SystemName { get; set; } + public string? SystemName { get; set; } /// /// Gets or sets the value indicating whether this page should be included in sitemap @@ -60,39 +60,39 @@ public class Page : BaseEntity, ITranslationEntity, ISlugEntity, IStoreLinkEntit /// /// Gets or sets the password /// - public string Password { get; set; } + public string? Password { get; set; } /// /// Gets or sets the title /// [AuditName] - public string Title { get; set; } + public string? Title { get; set; } /// /// Gets or sets the body /// - public string Body { get; set; } + public string? Body { get; set; } /// /// Gets or sets a value of used page layout identifier /// [AuditReference(typeof(PageLayout))] - public string PageLayoutId { get; set; } + public string? PageLayoutId { get; set; } /// /// Gets or sets the meta keywords /// - public string MetaKeywords { get; set; } + public string? MetaKeywords { get; set; } /// /// Gets or sets the meta description /// - public string MetaDescription { get; set; } + public string? MetaDescription { get; set; } /// /// Gets or sets the meta title /// - public string MetaTitle { get; set; } + public string? MetaTitle { get; set; } /// /// Gets or sets a value indicating whether the entity is published @@ -121,7 +121,7 @@ public class Page : BaseEntity, ITranslationEntity, ISlugEntity, IStoreLinkEntit /// /// Gets or sets the sename /// - public string SeName { get; set; } + public string? SeName { get; set; } /// /// Gets or sets a value indicating whether the entity is limited/restricted to certain stores diff --git a/src/Core/Grand.Domain/Pages/PageLayout.cs b/src/Core/Grand.Domain/Pages/PageLayout.cs index 8d607216d..36234c031 100644 --- a/src/Core/Grand.Domain/Pages/PageLayout.cs +++ b/src/Core/Grand.Domain/Pages/PageLayout.cs @@ -8,12 +8,12 @@ public class PageLayout : BaseEntity /// /// Gets or sets the layout name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the view path /// - public string ViewPath { get; set; } + public string? ViewPath { get; set; } /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/ParentEntity.cs b/src/Core/Grand.Domain/ParentEntity.cs index 16edb93b8..504ac64a3 100644 --- a/src/Core/Grand.Domain/ParentEntity.cs +++ b/src/Core/Grand.Domain/ParentEntity.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using Grand.SharedKernel.Attributes; namespace Grand.Domain; @@ -12,6 +13,8 @@ protected ParentEntity() } [DBFieldName("_id")] + //the setter turns null into a new identifier, so the getter never returns null + [AllowNull] public string Id { get => _id; set => _id = string.IsNullOrEmpty(value) ? UniqueIdentifier.New : value; diff --git a/src/Core/Grand.Domain/Payments/PaymentTransaction.cs b/src/Core/Grand.Domain/Payments/PaymentTransaction.cs index 9732d0aa9..9b3866eb8 100644 --- a/src/Core/Grand.Domain/Payments/PaymentTransaction.cs +++ b/src/Core/Grand.Domain/Payments/PaymentTransaction.cs @@ -9,7 +9,7 @@ public class PaymentTransaction : BaseEntity /// /// Gets or sets payment method system name /// - public string PaymentMethodSystemName { get; set; } + public string? PaymentMethodSystemName { get; set; } /// /// Gets or sets transaction status @@ -20,7 +20,7 @@ public class PaymentTransaction : BaseEntity /// Gets or sets store ident /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets order guid @@ -31,23 +31,23 @@ public class PaymentTransaction : BaseEntity /// Gets or sets order code /// [AuditName] - public string OrderCode { get; set; } + public string? OrderCode { get; set; } /// /// Gets or sets customer ident /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets customer email /// - public string CustomerEmail { get; set; } + public string? CustomerEmail { get; set; } /// /// Gets or sets currency code /// - public string CurrencyCode { get; set; } + public string? CurrencyCode { get; set; } public double CurrencyRate { get; set; } @@ -66,42 +66,42 @@ public class PaymentTransaction : BaseEntity /// /// Gets or sets id transaction /// - public string IPAddress { get; set; } + public string? IPAddress { get; set; } /// /// Gets or sets authorization transaction id /// - public string AuthorizationTransactionId { get; set; } + public string? AuthorizationTransactionId { get; set; } /// /// Gets or sets authorization transaction code /// - public string AuthorizationTransactionCode { get; set; } + public string? AuthorizationTransactionCode { get; set; } /// /// Gets or sets authorization transaction result /// - public string AuthorizationTransactionResult { get; set; } + public string? AuthorizationTransactionResult { get; set; } /// /// Gets or sets capture transaction id /// - public string CaptureTransactionId { get; set; } + public string? CaptureTransactionId { get; set; } /// /// Gets or sets capture transaction result /// - public string CaptureTransactionResult { get; set; } + public string? CaptureTransactionResult { get; set; } /// /// Gets or sets description /// - public string Description { get; set; } + public string? Description { get; set; } /// /// Gets or sets additional info /// - public string AdditionalInfo { get; set; } + public string? AdditionalInfo { get; set; } /// /// Gets or sets custom values diff --git a/src/Core/Grand.Domain/Payments/PaymentTransactionEntry.cs b/src/Core/Grand.Domain/Payments/PaymentTransactionEntry.cs index f56bef5ff..10fd47b00 100644 --- a/src/Core/Grand.Domain/Payments/PaymentTransactionEntry.cs +++ b/src/Core/Grand.Domain/Payments/PaymentTransactionEntry.cs @@ -10,7 +10,7 @@ public class PaymentTransactionEntry : BaseEntity { [AuditReference(typeof(PaymentTransaction))] [AuditOwner] - public string PaymentTransactionId { get; set; } + public string? PaymentTransactionId { get; set; } public PaymentTransactionEntryType EntryType { get; set; } @@ -19,12 +19,12 @@ public class PaymentTransactionEntry : BaseEntity /// /// Gets or sets who recorded the operation: a staff e-mail or a payment method system name /// - public string RecordedBy { get; set; } + public string? RecordedBy { get; set; } /// /// Gets or sets the bank transfer title, receipt or gateway number the money can be matched with /// - public string Reference { get; set; } + public string? Reference { get; set; } - public string Note { get; set; } + public string? Note { get; set; } } diff --git a/src/Core/Grand.Domain/Permissions/DefaultPermission.cs b/src/Core/Grand.Domain/Permissions/DefaultPermission.cs index 2e35a14ca..d4acd0a63 100644 --- a/src/Core/Grand.Domain/Permissions/DefaultPermission.cs +++ b/src/Core/Grand.Domain/Permissions/DefaultPermission.cs @@ -8,7 +8,7 @@ public class DefaultPermission /// /// Gets or sets the customer group system name /// - public string CustomerGroupSystemName { get; set; } + public string? CustomerGroupSystemName { get; set; } /// /// Gets or sets the permissions diff --git a/src/Core/Grand.Domain/Permissions/Permission.cs b/src/Core/Grand.Domain/Permissions/Permission.cs index 0bb413c91..170185f7c 100644 --- a/src/Core/Grand.Domain/Permissions/Permission.cs +++ b/src/Core/Grand.Domain/Permissions/Permission.cs @@ -8,28 +8,28 @@ namespace Grand.Domain.Permissions; /// public class Permission : BaseEntity { - private ICollection _actions; - private ICollection _customerGroups; + private ICollection? _actions; + private ICollection? _customerGroups; /// /// Gets or sets the permission name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the permission system name /// - public string SystemName { get; set; } + public string? SystemName { get; set; } /// /// Gets or sets the area name /// - public string Area { get; set; } + public string? Area { get; set; } /// /// Gets or sets the permission category /// - public string Category { get; set; } + public string? Category { get; set; } /// /// Gets or sets customer groups diff --git a/src/Core/Grand.Domain/Permissions/PermissionAction.cs b/src/Core/Grand.Domain/Permissions/PermissionAction.cs index db34dc9ab..dd63647dc 100644 --- a/src/Core/Grand.Domain/Permissions/PermissionAction.cs +++ b/src/Core/Grand.Domain/Permissions/PermissionAction.cs @@ -12,16 +12,16 @@ public class PermissionAction : BaseEntity /// Gets or sets the permission system name /// [AuditName] - public string SystemName { get; set; } + public string? SystemName { get; set; } /// /// Gets or sets the customer group ident /// [AuditReference(typeof(CustomerGroup))] - public string CustomerGroupId { get; set; } + public string? CustomerGroupId { get; set; } /// /// Gets or sets the action name for denied access /// - public string Action { get; set; } + public string? Action { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/PushNotifications/PushMessage.cs b/src/Core/Grand.Domain/PushNotifications/PushMessage.cs index 64196b8ff..03585faa6 100644 --- a/src/Core/Grand.Domain/PushNotifications/PushMessage.cs +++ b/src/Core/Grand.Domain/PushNotifications/PushMessage.cs @@ -5,9 +5,9 @@ namespace Grand.Domain.PushNotifications; public class PushMessage : BaseEntity { [AuditName] - public string Title { get; set; } + public string? Title { get; set; } - public string Text { get; set; } + public string? Text { get; set; } public DateTime SentOn { get; set; } diff --git a/src/Core/Grand.Domain/PushNotifications/PushNotificationsSettings.cs b/src/Core/Grand.Domain/PushNotifications/PushNotificationsSettings.cs index cdbc6f6c7..0f58f303f 100644 --- a/src/Core/Grand.Domain/PushNotifications/PushNotificationsSettings.cs +++ b/src/Core/Grand.Domain/PushNotifications/PushNotificationsSettings.cs @@ -9,15 +9,15 @@ public class PushNotificationsSettings : ISettings /// public bool Enabled { get; set; } - public string PrivateApiKey { get; set; } - public string PublicApiKey { get; set; } - public string SenderId { get; set; } - public string AuthDomain { get; set; } - public string DatabaseUrl { get; set; } - public string ProjectId { get; set; } - public string StorageBucket { get; set; } - public string PictureId { get; set; } + public string? PrivateApiKey { get; set; } + public string? PublicApiKey { get; set; } + public string? SenderId { get; set; } + public string? AuthDomain { get; set; } + public string? DatabaseUrl { get; set; } + public string? ProjectId { get; set; } + public string? StorageBucket { get; set; } + public string? PictureId { get; set; } public bool AllowGuestNotifications { get; set; } - public string ClickUrl { get; set; } - public string AppId { get; set; } + public string? ClickUrl { get; set; } + public string? AppId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/PushNotifications/PushRegistration.cs b/src/Core/Grand.Domain/PushNotifications/PushRegistration.cs index bf765768b..258eb98f0 100644 --- a/src/Core/Grand.Domain/PushNotifications/PushRegistration.cs +++ b/src/Core/Grand.Domain/PushNotifications/PushRegistration.cs @@ -2,11 +2,11 @@ public class PushRegistration : BaseEntity { - public string CustomerId { get; set; } + public string? CustomerId { get; set; } public bool Allowed { get; set; } - public string Token { get; set; } + public string? Token { get; set; } public DateTime RegisteredOn { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Security/RefreshToken.cs b/src/Core/Grand.Domain/Security/RefreshToken.cs index d8d97682c..684686702 100644 --- a/src/Core/Grand.Domain/Security/RefreshToken.cs +++ b/src/Core/Grand.Domain/Security/RefreshToken.cs @@ -2,8 +2,8 @@ public class RefreshToken { - public string RefreshId { get; set; } - public string Token { get; set; } + public string? RefreshId { get; set; } + public string? Token { get; set; } public DateTime ValidTo { get; set; } public bool IsActive { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Security/SecuritySettings.cs b/src/Core/Grand.Domain/Security/SecuritySettings.cs index 756103679..0d540dbdb 100644 --- a/src/Core/Grand.Domain/Security/SecuritySettings.cs +++ b/src/Core/Grand.Domain/Security/SecuritySettings.cs @@ -7,5 +7,5 @@ public class SecuritySettings : ISettings /// /// Gets or sets a list of admin area allowed IP addresses /// - public List AdminAreaAllowedIpAddresses { get; set; } + public List? AdminAreaAllowedIpAddresses { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Seo/EntityUrl.cs b/src/Core/Grand.Domain/Seo/EntityUrl.cs index ce53d4595..76d9536e8 100644 --- a/src/Core/Grand.Domain/Seo/EntityUrl.cs +++ b/src/Core/Grand.Domain/Seo/EntityUrl.cs @@ -11,18 +11,18 @@ public class EntityUrl : BaseEntity /// /// Gets or sets the entity identifier /// - public string EntityId { get; set; } + public string? EntityId { get; set; } /// /// Gets or sets the entity name /// - public string EntityName { get; set; } + public string? EntityName { get; set; } /// /// Gets or sets the slug /// [AuditName] - public string Slug { get; set; } + public string? Slug { get; set; } /// /// Gets or sets the value indicating whether the item is active @@ -33,15 +33,15 @@ public class EntityUrl : BaseEntity /// Gets or sets the language identifier /// [AuditReference(typeof(Language))] - public string LanguageId { get; set; } + public string? LanguageId { get; set; } /// /// Gets or sets the controller name /// - public string Controller { get; set; } + public string? Controller { get; set; } /// /// Gets or sets the action name /// - public string Action { get; set; } + public string? Action { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Seo/ISlugEntity.cs b/src/Core/Grand.Domain/Seo/ISlugEntity.cs index c5cc33ad6..4b31c9f49 100644 --- a/src/Core/Grand.Domain/Seo/ISlugEntity.cs +++ b/src/Core/Grand.Domain/Seo/ISlugEntity.cs @@ -5,5 +5,5 @@ namespace Grand.Domain.Seo; /// public interface ISlugEntity { - string SeName { get; set; } + string? SeName { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Seo/SeoSettings.cs b/src/Core/Grand.Domain/Seo/SeoSettings.cs index a02cb9f75..dbe475831 100644 --- a/src/Core/Grand.Domain/Seo/SeoSettings.cs +++ b/src/Core/Grand.Domain/Seo/SeoSettings.cs @@ -10,7 +10,7 @@ public class SeoSettings : ISettings /// /// Page title separator /// - public string PageTitleSeparator { get; set; } + public string? PageTitleSeparator { get; set; } /// /// Page itle SEO adjustment @@ -20,17 +20,17 @@ public class SeoSettings : ISettings /// /// Default title /// - public string DefaultTitle { get; set; } + public string? DefaultTitle { get; set; } /// /// Default META keywords /// - public string DefaultMetaKeywords { get; set; } + public string? DefaultMetaKeywords { get; set; } /// /// Default META description /// - public string DefaultMetaDescription { get; set; } + public string? DefaultMetaDescription { get; set; } /// /// A value indicating whether product META descriptions will be generated automatically (if not entered) @@ -45,7 +45,7 @@ public class SeoSettings : ISettings /// /// A value indicating to conver non-wetern chars to western ones /// - public string SeoCharConversion { get; set; } + public string? SeoCharConversion { get; set; } /// /// A value indicating whether unicode chars are allowed @@ -75,7 +75,7 @@ public class SeoSettings : ISettings /// /// Gets or sets a picture identifier of the store picture. If 0, then the default one will be used /// - public string StorePictureId { get; set; } + public string? StorePictureId { get; set; } /// /// Slugs (sename) reserved for some other needs @@ -85,5 +85,5 @@ public class SeoSettings : ISettings /// /// Custom tags in the head section /// - public string CustomHeadTags { get; set; } + public string? CustomHeadTags { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Shipping/DeliveryDate.cs b/src/Core/Grand.Domain/Shipping/DeliveryDate.cs index 58ad77626..93e24d425 100644 --- a/src/Core/Grand.Domain/Shipping/DeliveryDate.cs +++ b/src/Core/Grand.Domain/Shipping/DeliveryDate.cs @@ -12,7 +12,7 @@ public class DeliveryDate : BaseEntity, ITranslationEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the display order @@ -22,7 +22,7 @@ public class DeliveryDate : BaseEntity, ITranslationEntity /// /// Gets or sets the color RGB value (used with "Color squares" attribute type) /// - public string ColorSquaresRgb { get; set; } + public string? ColorSquaresRgb { get; set; } /// /// Gets or sets the collection of locales @@ -33,5 +33,5 @@ public class DeliveryDate : BaseEntity, ITranslationEntity /// Gets or sets the store identifier. Empty means available to all stores. /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Shipping/PickupPoints.cs b/src/Core/Grand.Domain/Shipping/PickupPoints.cs index fb8758705..450c4e105 100644 --- a/src/Core/Grand.Domain/Shipping/PickupPoints.cs +++ b/src/Core/Grand.Domain/Shipping/PickupPoints.cs @@ -12,34 +12,34 @@ public class PickupPoint : BaseEntity /// /// Gets or sets the point name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the description /// - public string Description { get; set; } + public string? Description { get; set; } /// /// Gets or sets the admin comment /// - public string AdminComment { get; set; } + public string? AdminComment { get; set; } /// /// Gets or sets the address identifier /// - public Address Address { get; set; } + public Address? Address { get; set; } /// /// Gets or sets the warehouse identifier /// [AuditReference(typeof(Warehouse))] - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } /// /// Gets or sets a store identifier /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the pickup fee diff --git a/src/Core/Grand.Domain/Shipping/ReturnShippingProviderSettings.cs b/src/Core/Grand.Domain/Shipping/ReturnShippingProviderSettings.cs index eca65ca76..58577c9cd 100644 --- a/src/Core/Grand.Domain/Shipping/ReturnShippingProviderSettings.cs +++ b/src/Core/Grand.Domain/Shipping/ReturnShippingProviderSettings.cs @@ -13,7 +13,7 @@ public class ReturnShippingProviderSettings : ISettings /// /// Gets or sets the address the returned parcels are sent to /// - public Address ReturnAddress { get; set; } + public Address? ReturnAddress { get; set; } /// /// Gets or sets the cost of a return the customer sends back on their own diff --git a/src/Core/Grand.Domain/Shipping/Shipment.cs b/src/Core/Grand.Domain/Shipping/Shipment.cs index 5fa97a531..7d263c9d1 100644 --- a/src/Core/Grand.Domain/Shipping/Shipment.cs +++ b/src/Core/Grand.Domain/Shipping/Shipment.cs @@ -10,35 +10,35 @@ namespace Grand.Domain.Shipping; /// public class Shipment : BaseEntity { - private ICollection _shipmentItems; + private ICollection? _shipmentItems; /// /// Gets or sets the order identifier /// [AuditReference(typeof(Order))] - public string OrderId { get; set; } + public string? OrderId { get; set; } /// /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the vendor identifier /// [AuditReference(typeof(Vendor))] - public string VendorId { get; set; } + public string? VendorId { get; set; } /// /// Gets or sets the sales employee identifier /// - public string SeId { get; set; } + public string? SeId { get; set; } /// /// Gets or sets the tracking number of this shipment /// - public string TrackingNumber { get; set; } + public string? TrackingNumber { get; set; } /// /// Gets or sets the total weight of this shipment @@ -58,7 +58,7 @@ public class Shipment : BaseEntity /// /// Gets or sets the admin comment /// - public string AdminComment { get; set; } + public string? AdminComment { get; set; } /// /// Gets the shipment number diff --git a/src/Core/Grand.Domain/Shipping/ShipmentItem.cs b/src/Core/Grand.Domain/Shipping/ShipmentItem.cs index 68431dda7..9162efaec 100644 --- a/src/Core/Grand.Domain/Shipping/ShipmentItem.cs +++ b/src/Core/Grand.Domain/Shipping/ShipmentItem.cs @@ -12,14 +12,14 @@ public class ShipmentItem : SubBaseEntity /// /// Gets or sets the order item identifier /// - public string OrderItemId { get; set; } + public string? OrderItemId { get; set; } /// /// Gets or sets the product /// [AuditReference(typeof(Product))] [AuditName] - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// Gets or sets the product attribute xml @@ -35,7 +35,7 @@ public class ShipmentItem : SubBaseEntity /// Gets or sets the warehouse identifier /// [AuditReference(typeof(Warehouse))] - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } /// /// A batch-tracked product: the batches shipped; the rest of the quantity is stock without a batch diff --git a/src/Core/Grand.Domain/Shipping/ShipmentItemBatch.cs b/src/Core/Grand.Domain/Shipping/ShipmentItemBatch.cs index 9cbf58a48..74de122e3 100644 --- a/src/Core/Grand.Domain/Shipping/ShipmentItemBatch.cs +++ b/src/Core/Grand.Domain/Shipping/ShipmentItemBatch.cs @@ -5,7 +5,7 @@ namespace Grand.Domain.Shipping; /// public class ShipmentItemBatch { - public string Number { get; set; } + public string? Number { get; set; } public int Quantity { get; set; } } diff --git a/src/Core/Grand.Domain/Shipping/ShipmentNote.cs b/src/Core/Grand.Domain/Shipping/ShipmentNote.cs index 99ebc59d4..0f39f81f7 100644 --- a/src/Core/Grand.Domain/Shipping/ShipmentNote.cs +++ b/src/Core/Grand.Domain/Shipping/ShipmentNote.cs @@ -12,18 +12,18 @@ public class ShipmentNote : BaseEntity /// [AuditReference(typeof(Shipment))] [AuditOwner] - public string ShipmentId { get; set; } + public string? ShipmentId { get; set; } /// /// Gets or sets the note /// [AuditName] - public string Note { get; set; } + public string? Note { get; set; } /// /// Gets or sets the attached file (download) identifier /// - public string DownloadId { get; set; } + public string? DownloadId { get; set; } /// /// Gets or sets a value indicating whether a customer can see a note diff --git a/src/Core/Grand.Domain/Shipping/ShippingMethod.cs b/src/Core/Grand.Domain/Shipping/ShippingMethod.cs index a2446dc19..3b1bb05be 100644 --- a/src/Core/Grand.Domain/Shipping/ShippingMethod.cs +++ b/src/Core/Grand.Domain/Shipping/ShippingMethod.cs @@ -10,18 +10,18 @@ namespace Grand.Domain.Shipping; /// public class ShippingMethod : BaseEntity, ITranslationEntity { - private ICollection _restrictedCountries; - private ICollection _restrictedGroups; + private ICollection? _restrictedCountries; + private ICollection? _restrictedGroups; /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the description /// - public string Description { get; set; } + public string? Description { get; set; } /// /// Gets or sets the display order @@ -53,5 +53,5 @@ public virtual ICollection RestrictedGroups { /// Gets or sets the store identifier. Empty means available to all stores. /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Shipping/ShippingOption.cs b/src/Core/Grand.Domain/Shipping/ShippingOption.cs index d787e43b9..5659342a8 100644 --- a/src/Core/Grand.Domain/Shipping/ShippingOption.cs +++ b/src/Core/Grand.Domain/Shipping/ShippingOption.cs @@ -8,7 +8,7 @@ public class ShippingOption /// /// Gets or sets the system name of shipping rate provider /// - public string ShippingRateProviderSystemName { get; set; } + public string? ShippingRateProviderSystemName { get; set; } /// /// Gets or sets a shipping rate (without discounts, additional shipping charges, etc) @@ -18,10 +18,10 @@ public class ShippingOption /// /// Gets or sets a shipping option name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets a shipping option description /// - public string Description { get; set; } + public string? Description { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Shipping/ShippingSettings.cs b/src/Core/Grand.Domain/Shipping/ShippingSettings.cs index 31b913765..27f05ec00 100644 --- a/src/Core/Grand.Domain/Shipping/ShippingSettings.cs +++ b/src/Core/Grand.Domain/Shipping/ShippingSettings.cs @@ -44,7 +44,7 @@ public class ShippingSettings : ISettings /// /// Gets or sets shipping origin address /// - public Address ShippingOriginAddress { get; set; } + public Address? ShippingOriginAddress { get; set; } /// /// Gets or sets a value indicating whether we should skip 'select shipping method' page if we have only one shipping diff --git a/src/Core/Grand.Domain/Shipping/Warehouse.cs b/src/Core/Grand.Domain/Shipping/Warehouse.cs index 075abe382..262133639 100644 --- a/src/Core/Grand.Domain/Shipping/Warehouse.cs +++ b/src/Core/Grand.Domain/Shipping/Warehouse.cs @@ -12,17 +12,17 @@ public class Warehouse : BaseEntity /// /// Gets or sets the warehouse code /// - public string Code { get; set; } + public string? Code { get; set; } /// /// Gets or sets the warehouse name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the admin comment /// - public string AdminComment { get; set; } + public string? AdminComment { get; set; } /// /// Gets or sets the latitude of the GeoCoordinate. @@ -48,7 +48,7 @@ public class Warehouse : BaseEntity /// Gets or sets the store identifier. Empty means available to all stores. /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets a value indicating whether the stock of this warehouse belongs to an external system (ERP/WMS). diff --git a/src/Core/Grand.Domain/Shipping/WarehouseLocation.cs b/src/Core/Grand.Domain/Shipping/WarehouseLocation.cs index 7ab6bbe7d..c19601d2b 100644 --- a/src/Core/Grand.Domain/Shipping/WarehouseLocation.cs +++ b/src/Core/Grand.Domain/Shipping/WarehouseLocation.cs @@ -8,15 +8,15 @@ namespace Grand.Domain.Shipping; public class WarehouseLocation : BaseEntity { [AuditReference(typeof(Warehouse))] - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } /// /// The code written on the place, such as A-01-03 /// [AuditName] - public string Code { get; set; } + public string? Code { get; set; } - public string Name { get; set; } + public string? Name { get; set; } public int DisplayOrder { get; set; } } diff --git a/src/Core/Grand.Domain/Stores/BankAccount.cs b/src/Core/Grand.Domain/Stores/BankAccount.cs index 2dccb4c86..b8821360e 100644 --- a/src/Core/Grand.Domain/Stores/BankAccount.cs +++ b/src/Core/Grand.Domain/Stores/BankAccount.cs @@ -2,8 +2,8 @@ public class BankAccount : SubBaseEntity { - public string BankCode { get; set; } - public string BankName { get; set; } - public string SwiftCode { get; set; } - public string AccountNumber { get; set; } + public string? BankCode { get; set; } + public string? BankName { get; set; } + public string? SwiftCode { get; set; } + public string? AccountNumber { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Stores/DomainHost.cs b/src/Core/Grand.Domain/Stores/DomainHost.cs index 945523dcc..3643a7e91 100644 --- a/src/Core/Grand.Domain/Stores/DomainHost.cs +++ b/src/Core/Grand.Domain/Stores/DomainHost.cs @@ -5,7 +5,7 @@ namespace Grand.Domain.Stores; public class DomainHost : SubBaseEntity { [AuditName] - public string HostName { get; set; } - public string Url { get; set; } + public string? HostName { get; set; } + public string? Url { get; set; } public bool Primary { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Stores/Store.cs b/src/Core/Grand.Domain/Stores/Store.cs index 472a19e9d..2a664ced3 100644 --- a/src/Core/Grand.Domain/Stores/Store.cs +++ b/src/Core/Grand.Domain/Stores/Store.cs @@ -14,23 +14,23 @@ public class Store : BaseEntity, ITranslationEntity /// /// Gets or sets the store name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the store shortcut /// - public string Shortcut { get; set; } + public string? Shortcut { get; set; } /// /// Gets or sets the store URL, including the scheme /// - public string Url { get; set; } + public string? Url { get; set; } /// /// Gets or sets the account told about the store's order approvals; it does not limit who may decide them /// [AuditReference(typeof(Customer))] - public string OwnerCustomerId { get; set; } + public string? OwnerCustomerId { get; set; } /// /// Gets or sets the list of domains @@ -42,25 +42,25 @@ public class Store : BaseEntity, ITranslationEntity /// display order /// [AuditReference(typeof(Language))] - public string DefaultLanguageId { get; set; } + public string? DefaultLanguageId { get; set; } /// /// Gets or sets the identifier of the default waregouse for this store /// [AuditReference(typeof(Warehouse))] - public string DefaultWarehouseId { get; set; } + public string? DefaultWarehouseId { get; set; } /// /// Gets or sets the identifier of the default country for this store /// [AuditReference(typeof(Country))] - public string DefaultCountryId { get; set; } + public string? DefaultCountryId { get; set; } /// /// Gets or sets the identifier of the default currency for this store /// [AuditReference(typeof(Currency))] - public string DefaultCurrencyId { get; set; } + public string? DefaultCurrencyId { get; set; } /// /// Gets or sets the display order @@ -70,37 +70,37 @@ public class Store : BaseEntity, ITranslationEntity /// /// Gets or sets the company name /// - public string CompanyName { get; set; } + public string? CompanyName { get; set; } /// /// Gets or sets the company registration number /// - public string CompanyRegNo { get; set; } + public string? CompanyRegNo { get; set; } /// /// Gets or sets the company address /// - public string CompanyAddress { get; set; } + public string? CompanyAddress { get; set; } /// /// Gets or sets the store phone number /// - public string CompanyPhoneNumber { get; set; } + public string? CompanyPhoneNumber { get; set; } /// /// Gets or sets the company VAT (used in Europe Union countries) /// - public string CompanyVat { get; set; } + public string? CompanyVat { get; set; } /// /// Gets or sets the company email /// - public string CompanyEmail { get; set; } + public string? CompanyEmail { get; set; } /// /// Gets or sets the company opening hours /// - public string CompanyHours { get; set; } + public string? CompanyHours { get; set; } public BankAccount BankAccount { get; set; } = new(); diff --git a/src/Core/Grand.Domain/Stores/StoreExtensions.cs b/src/Core/Grand.Domain/Stores/StoreExtensions.cs index 61cf90363..d4ec39b5d 100644 --- a/src/Core/Grand.Domain/Stores/StoreExtensions.cs +++ b/src/Core/Grand.Domain/Stores/StoreExtensions.cs @@ -15,7 +15,7 @@ public static bool ContainsHostValue(this Store store, string host) if (string.IsNullOrEmpty(host)) return false; - var contains = store.Domains.FirstOrDefault(x => x.HostName.Equals(host, StringComparison.OrdinalIgnoreCase)) != + var contains = store.Domains.FirstOrDefault(x => string.Equals(x.HostName, host, StringComparison.OrdinalIgnoreCase)) != null; return contains; } @@ -26,12 +26,12 @@ public static bool ContainsHostValue(this Store store, string host) /// Store /// Host /// DomainHost - public static DomainHost HostValue(this Store store, string host) + public static DomainHost? HostValue(this Store store, string host) { ArgumentNullException.ThrowIfNull(store); return string.IsNullOrEmpty(host) ? null - : store.Domains.FirstOrDefault(x => x.HostName.Equals(host, StringComparison.OrdinalIgnoreCase)); + : store.Domains.FirstOrDefault(x => string.Equals(x.HostName, host, StringComparison.OrdinalIgnoreCase)); } /// @@ -56,12 +56,12 @@ public static DomainHost PrimaryHost(this Store store) /// Store /// Host the request was made to; null when there is no request /// DomainHost - public static DomainHost LinkHost(this Store store, DomainHost host) + public static DomainHost LinkHost(this Store store, DomainHost? host) { ArgumentNullException.ThrowIfNull(store); var domain = string.IsNullOrEmpty(host?.HostName) ? null - : store.Domains?.FirstOrDefault(x => x.HostName.Equals(host.HostName, StringComparison.OrdinalIgnoreCase)); + : store.Domains?.FirstOrDefault(x => string.Equals(x.HostName, host.HostName, StringComparison.OrdinalIgnoreCase)); return domain ?? store.PrimaryHost(); } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Stores/StoreInformationSettings.cs b/src/Core/Grand.Domain/Stores/StoreInformationSettings.cs index ea582a100..e9bec380e 100644 --- a/src/Core/Grand.Domain/Stores/StoreInformationSettings.cs +++ b/src/Core/Grand.Domain/Stores/StoreInformationSettings.cs @@ -12,7 +12,7 @@ public class StoreInformationSettings : ISettings /// /// Gets or sets a default store theme /// - public string DefaultStoreTheme { get; set; } + public string? DefaultStoreTheme { get; set; } /// /// Gets or sets a value indicating whether customers are allowed to select a theme @@ -27,7 +27,7 @@ public class StoreInformationSettings : ISettings /// /// Gets or sets a logo /// - public string LogoPictureId { get; set; } + public string? LogoPictureId { get; set; } /// /// Gets or sets a value indicating whether we should display info about the cookie @@ -42,32 +42,32 @@ public class StoreInformationSettings : ISettings /// /// Gets or sets a value of Facebook page URL of the site /// - public string FacebookLink { get; set; } + public string? FacebookLink { get; set; } /// /// Gets or sets a value of Twitter page URL of the site /// - public string TwitterLink { get; set; } + public string? TwitterLink { get; set; } /// /// Gets or sets a value of YouTube channel URL of the site /// - public string YoutubeLink { get; set; } + public string? YoutubeLink { get; set; } /// /// Gets or sets a value of Instagram page URL of the site /// - public string InstagramLink { get; set; } + public string? InstagramLink { get; set; } /// /// Gets or sets a value of LinkedIn page URL of the site /// - public string LinkedInLink { get; set; } + public string? LinkedInLink { get; set; } /// /// Gets or sets a value of Pinterest page URL of the site /// - public string PinterestLink { get; set; } + public string? PinterestLink { get; set; } /// /// Gets or sets a value indicating whether we enable voice navigation diff --git a/src/Core/Grand.Domain/Tasks/ScheduleTask.cs b/src/Core/Grand.Domain/Tasks/ScheduleTask.cs index f85bb8169..443b37bea 100644 --- a/src/Core/Grand.Domain/Tasks/ScheduleTask.cs +++ b/src/Core/Grand.Domain/Tasks/ScheduleTask.cs @@ -6,16 +6,16 @@ namespace Grand.Domain.Tasks; public class ScheduleTask : BaseEntity { [AuditName] - public string ScheduleTaskName { get; set; } + public string? ScheduleTaskName { get; set; } public bool Enabled { get; set; } public bool StopOnError { get; set; } public DateTime? LastStartUtc { get; set; } public DateTime? LastNonSuccessEndUtc { get; set; } public DateTime? LastSuccessUtc { get; set; } - public string LeasedByMachineName { get; set; } + public string? LeasedByMachineName { get; set; } public DateTime? LeasedUntilUtc { get; set; } - public string LeasedByInstance { get; set; } + public string? LeasedByInstance { get; set; } public int TimeInterval { get; set; } [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Tax/TaxCategory.cs b/src/Core/Grand.Domain/Tax/TaxCategory.cs index 33425c170..27bf99a9e 100644 --- a/src/Core/Grand.Domain/Tax/TaxCategory.cs +++ b/src/Core/Grand.Domain/Tax/TaxCategory.cs @@ -11,7 +11,7 @@ public class TaxCategory : BaseEntity /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the display order @@ -22,5 +22,5 @@ public class TaxCategory : BaseEntity /// Gets or sets the store identifier (empty = available to all stores) /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Tax/TaxProviderSettings.cs b/src/Core/Grand.Domain/Tax/TaxProviderSettings.cs index 88b11b867..ebb23670c 100644 --- a/src/Core/Grand.Domain/Tax/TaxProviderSettings.cs +++ b/src/Core/Grand.Domain/Tax/TaxProviderSettings.cs @@ -4,5 +4,5 @@ namespace Grand.Domain.Tax; public class TaxProviderSettings : ISettings { - public string ActiveTaxProviderSystemName { get; set; } + public string? ActiveTaxProviderSystemName { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Tax/TaxSettings.cs b/src/Core/Grand.Domain/Tax/TaxSettings.cs index 4fccbe4e8..295680e58 100644 --- a/src/Core/Grand.Domain/Tax/TaxSettings.cs +++ b/src/Core/Grand.Domain/Tax/TaxSettings.cs @@ -18,7 +18,7 @@ public class TaxSettings : ISettings /// /// Gets or sets default address used for tax calculation /// - public Address DefaultTaxAddress { get; set; } + public Address? DefaultTaxAddress { get; set; } /// /// Gets or sets a value indicating whether each tax rate should be displayed on separate line (shopping cart page) @@ -55,7 +55,7 @@ public class TaxSettings : ISettings /// /// Gets or sets a default tax category identifier for products /// - public string DefaultTaxCategoryId { get; set; } + public string? DefaultTaxCategoryId { get; set; } /// /// Gets or sets a value indicating whether shipping price is taxable @@ -70,7 +70,7 @@ public class TaxSettings : ISettings /// /// Gets or sets a value indicating the shipping tax category identifier /// - public string ShippingTaxCategoryId { get; set; } + public string? ShippingTaxCategoryId { get; set; } /// /// Gets or sets a value indicating whether payment method additional fee is taxable @@ -85,7 +85,7 @@ public class TaxSettings : ISettings /// /// Gets or sets a value indicating the payment method additional fee tax class identifier /// - public string PaymentMethodAdditionalFeeTaxCategoryId { get; set; } + public string? PaymentMethodAdditionalFeeTaxCategoryId { get; set; } /// /// Gets or sets a value indicating whether EU VAT (Eupore Union Value Added Tax) is enabled @@ -95,7 +95,7 @@ public class TaxSettings : ISettings /// /// Gets or sets a shop country identifier /// - public string EuVatShopCountryId { get; set; } + public string? EuVatShopCountryId { get; set; } /// /// Gets or sets a value indicating whether this store will exempt eligible VAT-registered customers from VAT diff --git a/src/Core/Grand.Domain/Vendors/Vendor.cs b/src/Core/Grand.Domain/Vendors/Vendor.cs index ce8a6f7c0..0a0133b7c 100644 --- a/src/Core/Grand.Domain/Vendors/Vendor.cs +++ b/src/Core/Grand.Domain/Vendors/Vendor.cs @@ -12,8 +12,8 @@ namespace Grand.Domain.Vendors; /// public class Vendor : BaseEntity, ITranslationEntity, ISlugEntity { - private ICollection _appliedDiscounts; - private ICollection _vendorNotes; + private ICollection? _appliedDiscounts; + private ICollection? _vendorNotes; public Vendor() { @@ -24,33 +24,33 @@ public Vendor() /// /// Gets or sets the name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the picture identifier /// - public string PictureId { get; set; } + public string? PictureId { get; set; } /// /// Gets or sets the email /// - public string Email { get; set; } + public string? Email { get; set; } /// /// Gets or sets the description /// - public string Description { get; set; } + public string? Description { get; set; } /// /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string StoreId { get; set; } + public string? StoreId { get; set; } /// /// Gets or sets the admin comment /// - public string AdminComment { get; set; } + public string? AdminComment { get; set; } /// /// Gets or sets a value indicating whether the entity is active @@ -71,17 +71,17 @@ public Vendor() /// /// Gets or sets the meta keywords /// - public string MetaKeywords { get; set; } + public string? MetaKeywords { get; set; } /// /// Gets or sets the meta description /// - public string MetaDescription { get; set; } + public string? MetaDescription { get; set; } /// /// Gets or sets the meta title /// - public string MetaTitle { get; set; } + public string? MetaTitle { get; set; } /// /// Gets or sets the page size @@ -96,7 +96,7 @@ public Vendor() /// /// Gets or sets the available customer selectable page size options /// - public string PageSizeOptions { get; set; } + public string? PageSizeOptions { get; set; } /// /// Gets or sets a value indicating whether the vendor allows customer reviews @@ -136,7 +136,7 @@ public Vendor() /// /// Gets or sets the coordinates /// - public GeoCoordinates Coordinates { get; set; } + public GeoCoordinates? Coordinates { get; set; } /// /// Gets or sets vendor notes @@ -158,7 +158,7 @@ public virtual ICollection AppliedDiscounts { /// /// Gets or sets the sename /// - public string SeName { get; set; } + public string? SeName { get; set; } /// /// Gets or sets the collection of locales diff --git a/src/Core/Grand.Domain/Vendors/VendorNote.cs b/src/Core/Grand.Domain/Vendors/VendorNote.cs index 0cf805da2..18b72627f 100644 --- a/src/Core/Grand.Domain/Vendors/VendorNote.cs +++ b/src/Core/Grand.Domain/Vendors/VendorNote.cs @@ -8,7 +8,7 @@ public class VendorNote : SubBaseEntity /// /// Gets or sets the note /// - public string Note { get; set; } + public string? Note { get; set; } /// /// Gets or sets the date and time of vendor note creation diff --git a/src/Core/Grand.Domain/Vendors/VendorReview.cs b/src/Core/Grand.Domain/Vendors/VendorReview.cs index 351dbb5cb..b8e613bca 100644 --- a/src/Core/Grand.Domain/Vendors/VendorReview.cs +++ b/src/Core/Grand.Domain/Vendors/VendorReview.cs @@ -8,19 +8,19 @@ namespace Grand.Domain.Vendors; /// public class VendorReview : BaseEntity { - private ICollection _vendorReviewHelpfulnessEntries; + private ICollection? _vendorReviewHelpfulnessEntries; /// /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the vendor identifier /// [AuditReference(typeof(Vendor))] - public string VendorId { get; set; } + public string? VendorId { get; set; } /// /// Gets or sets a value indicating whether the content is approved @@ -31,12 +31,12 @@ public class VendorReview : BaseEntity /// Gets or sets the title /// [AuditName] - public string Title { get; set; } + public string? Title { get; set; } /// /// Gets or sets the review text /// - public string ReviewText { get; set; } + public string? ReviewText { get; set; } /// /// Review rating diff --git a/src/Core/Grand.Domain/Vendors/VendorReviewHelpfulness.cs b/src/Core/Grand.Domain/Vendors/VendorReviewHelpfulness.cs index d3c6f1d8d..30188100e 100644 --- a/src/Core/Grand.Domain/Vendors/VendorReviewHelpfulness.cs +++ b/src/Core/Grand.Domain/Vendors/VendorReviewHelpfulness.cs @@ -8,7 +8,7 @@ public class VendorReviewHelpfulness : SubBaseEntity /// /// Gets or sets the vendor review identifier /// - public string VendorReviewId { get; set; } + public string? VendorReviewId { get; set; } /// /// A value indicating whether a review a helpful @@ -18,5 +18,5 @@ public class VendorReviewHelpfulness : SubBaseEntity /// /// Gets or sets the customer identifier /// - public string CustomerId { get; set; } + public string? CustomerId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Vendors/VendorSettings.cs b/src/Core/Grand.Domain/Vendors/VendorSettings.cs index dbe176ddd..fd564b696 100644 --- a/src/Core/Grand.Domain/Vendors/VendorSettings.cs +++ b/src/Core/Grand.Domain/Vendors/VendorSettings.cs @@ -11,7 +11,7 @@ public class VendorSettings : ISettings /// /// Gets or sets the default value to use for Vendor page size options (for new vendors) /// - public string DefaultVendorPageSizeOptions { get; set; } + public string? DefaultVendorPageSizeOptions { get; set; } /// /// Gets or sets the value indicating how many vendors to display in vendors block From 7536bf810f559365d1480724ffaa02e8d5be3b2f Mon Sep 17 00:00:00 2001 From: support Date: Wed, 25 Nov 2026 07:58:27 +0100 Subject: [PATCH 04/30] Enable nullable in Grand.Data IRepository.GetById, GetByIdAsync, GetOneAsync and FirstOrDefaultAsync return T? - each answers null when nothing matches. A repository created without a connection string (before installation) has no collection. Collection and Database now throw an InvalidOperationException naming the repository instead of a NullReferenceException at the first call. DataSettingsManager.LoadSettings never returns null: a settings file holding the literal "null" reads as empty settings, as a missing file already did. --- src/Core/Grand.Data/Audit/AuditFilterId.cs | 18 +++++----- src/Core/Grand.Data/Audit/AuditSnapshot.cs | 9 +++-- .../Grand.Data/Audit/IAuditRecordReader.cs | 4 +-- src/Core/Grand.Data/Audit/IAuditTracker.cs | 4 +-- src/Core/Grand.Data/Audit/RepositoryAudit.cs | 4 +-- src/Core/Grand.Data/DataSettings.cs | 2 +- src/Core/Grand.Data/DataSettingsManager.cs | 7 ++-- src/Core/Grand.Data/Grand.Data.csproj | 3 ++ src/Core/Grand.Data/IRepository.cs | 8 ++--- .../LiteDb/LiteDBAuditRecordReader.cs | 6 ++-- .../LiteDb/LiteDBPluginStateStore.cs | 2 +- .../Grand.Data/LiteDb/LiteDBRepository.cs | 30 ++++++++++++---- .../Mongo/MongoAuditRecordReader.cs | 8 ++--- .../Grand.Data/Mongo/MongoPluginStateStore.cs | 8 ++--- src/Core/Grand.Data/Mongo/MongoRepository.cs | 34 ++++++++++++++----- src/Core/Grand.Data/OrderBuilder.cs | 8 ++--- src/Core/Grand.Data/UpdateBuilder.cs | 6 ++-- 17 files changed, 101 insertions(+), 60 deletions(-) diff --git a/src/Core/Grand.Data/Audit/AuditFilterId.cs b/src/Core/Grand.Data/Audit/AuditFilterId.cs index a1f7871a8..4f0447e98 100644 --- a/src/Core/Grand.Data/Audit/AuditFilterId.cs +++ b/src/Core/Grand.Data/Audit/AuditFilterId.cs @@ -1,4 +1,5 @@ using Grand.Domain; +using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using System.Reflection; @@ -12,7 +13,7 @@ public static class AuditFilterId /// /// Recognises x => x.Id == value (either operand order) and evaluates the value /// - public static bool TryGetId(Expression> filter, out string id) where T : BaseEntity + public static bool TryGetId(Expression> filter, [NotNullWhen(true)] out string? id) where T : BaseEntity { id = null; if (filter?.Body is not BinaryExpression { NodeType: ExpressionType.Equal } equal) @@ -29,12 +30,12 @@ public static bool TryGetId(Expression> filter, out string id) /// /// The dotted member path of x => x.A.B, or null when the expression is not a plain member chain /// - public static string MemberPath(Expression> expression) + public static string? MemberPath(Expression> expression) { return MemberPath((LambdaExpression)expression); } - public static string MemberPath(LambdaExpression expression) + public static string? MemberPath(LambdaExpression expression) { var names = new Stack(); var current = StripConvert(expression.Body); @@ -50,7 +51,7 @@ public static string MemberPath(LambdaExpression expression) /// /// The member paths an update builder sets /// - public static IList MemberPaths(UpdateBuilder builder) + public static IList MemberPaths(UpdateBuilder builder) { return builder.ExpressionFields.Select(f => MemberPath(f.Expression)).ToList(); } @@ -61,14 +62,15 @@ private static bool IsIdOf(Expression expression, ParameterExpression parameter) && StripConvert(member.Expression) == parameter; } - private static Expression StripConvert(Expression expression) + [return: NotNullIfNotNull(nameof(expression))] + private static Expression? StripConvert(Expression? expression) { while (expression is UnaryExpression { NodeType: ExpressionType.Convert or ExpressionType.ConvertChecked } unary) expression = unary.Operand; return expression; } - private static bool TryEvaluate(Expression expression, out string value) + private static bool TryEvaluate(Expression expression, [NotNullWhen(true)] out string? value) { value = null; if (!TryEvaluateObject(StripConvert(expression), out var result)) @@ -79,7 +81,7 @@ private static bool TryEvaluate(Expression expression, out string value) } //constants and captured variables only, without compiling the expression - private static bool TryEvaluateObject(Expression expression, out object value) + private static bool TryEvaluateObject(Expression expression, out object? value) { value = null; switch (expression) @@ -88,7 +90,7 @@ private static bool TryEvaluateObject(Expression expression, out object value) value = constant.Value; return true; case MemberExpression member: - object target = null; + object? target = null; if (member.Expression != null && !TryEvaluateObject(StripConvert(member.Expression), out target)) return false; if (member.Expression != null && target == null) diff --git a/src/Core/Grand.Data/Audit/AuditSnapshot.cs b/src/Core/Grand.Data/Audit/AuditSnapshot.cs index ace63c2ee..8ac527679 100644 --- a/src/Core/Grand.Data/Audit/AuditSnapshot.cs +++ b/src/Core/Grand.Data/Audit/AuditSnapshot.cs @@ -1,6 +1,7 @@ using Grand.Domain; using Grand.Domain.Configuration; using MongoDB.Bson; +using System.Diagnostics.CodeAnalysis; namespace Grand.Data.Audit; @@ -30,7 +31,8 @@ public static IDictionary Take(object entity, Type entityType) return Flatten(entity.ToBsonDocument(entityType), entityType == typeof(Setting)); } - public static IDictionary Flatten(BsonDocument document, bool isSetting) + [return: NotNullIfNotNull(nameof(document))] + public static IDictionary? Flatten(BsonDocument? document, bool isSetting) { if (document == null) return null; @@ -101,7 +103,7 @@ private static bool IsKeyed(BsonDocument document) return !HasId(document, out _) && document.TryGetValue("Key", out var key) && key.IsString && key.AsString != ""; } - private static BsonDocument TryParse(string json) + private static BsonDocument? TryParse(string json) { try { @@ -129,6 +131,7 @@ private static string Format(BsonValue value) return value.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'"); if (value.IsBsonArray) return value.ToJson(); - return value.ToString(); + //object.ToString may return null by contract; no BsonValue does + return value.ToString() ?? string.Empty; } } diff --git a/src/Core/Grand.Data/Audit/IAuditRecordReader.cs b/src/Core/Grand.Data/Audit/IAuditRecordReader.cs index 47edbee91..5da1883da 100644 --- a/src/Core/Grand.Data/Audit/IAuditRecordReader.cs +++ b/src/Core/Grand.Data/Audit/IAuditRecordReader.cs @@ -10,12 +10,12 @@ public interface IAuditRecordReader /// , as "path → value", or null when there is none. With , /// the snapshot may hold only that top-level field. /// - Task> Read(Type entityType, string value, string key = null, string field = null); + Task?> Read(Type entityType, string value, string? key = null, string? field = null); /// /// The records whose is one of , in one read, by that value; a /// value without a record is left out. Otherwise as . /// Task>> ReadMany(Type entityType, IReadOnlyCollection values, - string key = null, string field = null); + string? key = null, string? field = null); } diff --git a/src/Core/Grand.Data/Audit/IAuditTracker.cs b/src/Core/Grand.Data/Audit/IAuditTracker.cs index a2f161cfc..e966a9d42 100644 --- a/src/Core/Grand.Data/Audit/IAuditTracker.cs +++ b/src/Core/Grand.Data/Audit/IAuditTracker.cs @@ -20,7 +20,7 @@ public interface IAuditTracker /// flush; null means every field. /// Task BeforeWriteAsync(string id, bool isInsert, Func, Task>> loadMany, - IReadOnlyCollection writtenPaths = null) where T : BaseEntity; + IReadOnlyCollection? writtenPaths = null) where T : BaseEntity; /// /// Keeps the entity of a full update as its "after" state, so a later change by someone else before the flush @@ -35,7 +35,7 @@ Task BeforeWriteAsync(string id, bool isInsert, Func, the entry shows in that record's change history. /// - IDisposable CountInserts(string operation, string details, BaseEntity owner = null) where T : BaseEntity; + IDisposable CountInserts(string operation, string details, BaseEntity? owner = null) where T : BaseEntity; Task FlushAsync(); diff --git a/src/Core/Grand.Data/Audit/RepositoryAudit.cs b/src/Core/Grand.Data/Audit/RepositoryAudit.cs index c6fbc58cb..900b8524e 100644 --- a/src/Core/Grand.Data/Audit/RepositoryAudit.cs +++ b/src/Core/Grand.Data/Audit/RepositoryAudit.cs @@ -73,8 +73,8 @@ public void Bulk(string operation, string filter) } //an unreadable expression means "any field may have changed" - private static IReadOnlyCollection Paths(IList paths) + private static IReadOnlyCollection? Paths(IList paths) { - return paths.Count == 0 || paths.Any(p => p == null) ? null : paths.ToList(); + return paths.Count == 0 || paths.Any(p => p == null) ? null : paths.OfType().ToList(); } } diff --git a/src/Core/Grand.Data/DataSettings.cs b/src/Core/Grand.Data/DataSettings.cs index 5ab46d64f..b666db689 100644 --- a/src/Core/Grand.Data/DataSettings.cs +++ b/src/Core/Grand.Data/DataSettings.cs @@ -8,7 +8,7 @@ public class DataSettings /// /// Connection string /// - public string ConnectionString { get; set; } + public string? ConnectionString { get; set; } /// /// Database type diff --git a/src/Core/Grand.Data/DataSettingsManager.cs b/src/Core/Grand.Data/DataSettingsManager.cs index 8c998c912..9b639e231 100644 --- a/src/Core/Grand.Data/DataSettingsManager.cs +++ b/src/Core/Grand.Data/DataSettingsManager.cs @@ -7,14 +7,14 @@ namespace Grand.Data; /// public sealed class DataSettingsManager { - private static DataSettingsManager _instance; + private static DataSettingsManager? _instance; private static readonly Lock _lock = new(); public static DataSettingsManager Instance => _instance ?? throw new InvalidOperationException("DataSettingsManager has not been initialized. Call Initialize first."); private readonly string _settingsPath; - private DataSettings _dataSettings; + private DataSettings? _dataSettings; private bool? _databaseIsInstalled; @@ -48,7 +48,8 @@ public DataSettings LoadSettings(bool reloadSettings = false) try { var text = File.ReadAllText(_settingsPath); - _dataSettings = JsonSerializer.Deserialize(text); + //a file holding the literal "null" reads as no settings, the same as a missing file + _dataSettings = JsonSerializer.Deserialize(text) ?? new DataSettings(); } catch { diff --git a/src/Core/Grand.Data/Grand.Data.csproj b/src/Core/Grand.Data/Grand.Data.csproj index 6af3a32cf..d5fc21f23 100644 --- a/src/Core/Grand.Data/Grand.Data.csproj +++ b/src/Core/Grand.Data/Grand.Data.csproj @@ -12,4 +12,7 @@ + + enable + diff --git a/src/Core/Grand.Data/IRepository.cs b/src/Core/Grand.Data/IRepository.cs index 5cc68c746..c6eb9d5f8 100644 --- a/src/Core/Grand.Data/IRepository.cs +++ b/src/Core/Grand.Data/IRepository.cs @@ -19,21 +19,21 @@ public interface IRepository where T : BaseEntity /// /// Identifier /// Entity - T GetById(string id); + T? GetById(string id); /// /// Get async entity by identifier /// /// Identifier /// Entity - Task GetByIdAsync(string id); + Task GetByIdAsync(string id); /// /// Get entity by identifier /// /// /// Entity - Task GetOneAsync(Expression> predicate); + Task GetOneAsync(Expression> predicate); /// /// Insert entity @@ -183,7 +183,7 @@ Task> ToListAsync(IQueryable query, /// Type of the query result - the entity itself or a projection /// Query built on top of or /// Cancellation token - Task FirstOrDefaultAsync(IQueryable query, + Task FirstOrDefaultAsync(IQueryable query, CancellationToken cancellationToken = default); /// diff --git a/src/Core/Grand.Data/LiteDb/LiteDBAuditRecordReader.cs b/src/Core/Grand.Data/LiteDb/LiteDBAuditRecordReader.cs index 0cab29dce..58709c64c 100644 --- a/src/Core/Grand.Data/LiteDb/LiteDBAuditRecordReader.cs +++ b/src/Core/Grand.Data/LiteDb/LiteDBAuditRecordReader.cs @@ -9,8 +9,8 @@ namespace Grand.Data.LiteDb; public class LiteDBAuditRecordReader(Func database) : IAuditRecordReader { //the embedded database reads the whole document either way, so the field is not projected - public Task> Read(Type entityType, string value, string key = null, - string field = null) + public Task?> Read(Type entityType, string value, string? key = null, + string? field = null) { var db = database(); var collection = db.GetCollection(entityType.Name); @@ -25,7 +25,7 @@ public Task> Read(Type entityType, string value, str //an embedded database has no round trip to save, so each record is read on its own public async Task>> ReadMany(Type entityType, - IReadOnlyCollection values, string key = null, string field = null) + IReadOnlyCollection values, string? key = null, string? field = null) { var records = new Dictionary>(); foreach (var value in values.Distinct()) diff --git a/src/Core/Grand.Data/LiteDb/LiteDBPluginStateStore.cs b/src/Core/Grand.Data/LiteDb/LiteDBPluginStateStore.cs index 327877670..5fdb30424 100644 --- a/src/Core/Grand.Data/LiteDb/LiteDBPluginStateStore.cs +++ b/src/Core/Grand.Data/LiteDb/LiteDBPluginStateStore.cs @@ -11,7 +11,7 @@ public sealed class LiteDBPluginStateStore : IPluginStateStore { private readonly Func _connectionString; private readonly Lock _lock = new(); - private Func _shared; + private Func? _shared; /// Read on every call: the installation sets it while the application runs public LiteDBPluginStateStore(Func connectionString) diff --git a/src/Core/Grand.Data/LiteDb/LiteDBRepository.cs b/src/Core/Grand.Data/LiteDb/LiteDBRepository.cs index eda3be3ea..56d03dce7 100644 --- a/src/Core/Grand.Data/LiteDb/LiteDBRepository.cs +++ b/src/Core/Grand.Data/LiteDb/LiteDBRepository.cs @@ -18,16 +18,24 @@ public class LiteDBRepository : IRepository where T : BaseEntity private const string UpdatedByField = "UpdatedBy"; private readonly IAuditInfoProvider _auditInfoProvider; + private readonly ILiteCollection? _collection; + private readonly LiteDatabase? _database; /// /// Gets the collection /// - protected ILiteCollection Collection { get; init; } + protected ILiteCollection Collection { + get => _collection ?? throw NotConfigured(); + init => _collection = value; + } /// /// Mongo Database /// - protected LiteDatabase Database { get; init; } + protected LiteDatabase Database { + get => _database ?? throw NotConfigured(); + init => _database = value; + } #endregion @@ -67,12 +75,20 @@ public LiteDBRepository(LiteDatabase database, IAuditInfoProvider auditInfoProvi #region Methods + /// + /// A repository created before the database was configured has no collection to work on + /// + private static InvalidOperationException NotConfigured() + { + return new InvalidOperationException($"The {typeof(T).Name} repository has no database - the connection string is not configured"); + } + /// /// Get entity by identifier /// /// Identifier /// Entity - public virtual T GetById(string id) + public virtual T? GetById(string id) { return Collection.Find(e => e.Id == id).FirstOrDefault(); } @@ -82,7 +98,7 @@ public virtual T GetById(string id) /// /// Identifier /// Entity - public virtual async Task GetByIdAsync(string id) + public virtual async Task GetByIdAsync(string id) { return await Task.FromResult(GetById(id)); } @@ -92,7 +108,7 @@ public virtual async Task GetByIdAsync(string id) /// /// /// Entity - public virtual Task GetOneAsync(Expression> predicate) + public virtual Task GetOneAsync(Expression> predicate) { var visitor = new ToLowerInvariantVisitor(); //WORKAROUND Issue #479 - Method ToLowerInvariant() in String are not supported when convert to BsonExpression @@ -462,7 +478,7 @@ public virtual Task CountAsync(IQueryable query, /// /// Executes the query and returns its first result, or the default value when nothing matches /// - public virtual Task FirstOrDefaultAsync(IQueryable query, + public virtual Task FirstOrDefaultAsync(IQueryable query, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(query); @@ -517,7 +533,7 @@ private static string GetName(Expression> { if (Equals(Field, null)) throw new NullReferenceException("Field is required"); - MemberExpression expr = null; + MemberExpression? expr = null; switch (Field.Body) { diff --git a/src/Core/Grand.Data/Mongo/MongoAuditRecordReader.cs b/src/Core/Grand.Data/Mongo/MongoAuditRecordReader.cs index 59aa20bce..36ae93321 100644 --- a/src/Core/Grand.Data/Mongo/MongoAuditRecordReader.cs +++ b/src/Core/Grand.Data/Mongo/MongoAuditRecordReader.cs @@ -10,8 +10,8 @@ namespace Grand.Data.Mongo; /// public class MongoAuditRecordReader(Func database) : IAuditRecordReader { - public async Task> Read(Type entityType, string value, string key = null, - string field = null) + public async Task?> Read(Type entityType, string value, string? key = null, + string? field = null) { var find = database().GetCollection(entityType.Name) .Find(new BsonDocument(key ?? "_id", Match(value, key))); @@ -22,7 +22,7 @@ public async Task> Read(Type entityType, string valu } public async Task>> ReadMany(Type entityType, - IReadOnlyCollection values, string key = null, string field = null) + IReadOnlyCollection values, string? key = null, string? field = null) { var name = key ?? "_id"; var find = database().GetCollection(entityType.Name) @@ -41,7 +41,7 @@ public async Task>> ReadMany(Typ } //a key other than the id may hold a number, stored as one - private static BsonValue Match(string value, string key) + private static BsonValue Match(string value, string? key) { return key != null && int.TryParse(value, out var number) ? number : value; } diff --git a/src/Core/Grand.Data/Mongo/MongoPluginStateStore.cs b/src/Core/Grand.Data/Mongo/MongoPluginStateStore.cs index 3fd36c1b2..a7663228b 100644 --- a/src/Core/Grand.Data/Mongo/MongoPluginStateStore.cs +++ b/src/Core/Grand.Data/Mongo/MongoPluginStateStore.cs @@ -15,10 +15,10 @@ public sealed class MongoPluginStateStore : IPluginStateStore private readonly Func _connectionString; private readonly Lock _lock = new(); - private Func _shared; - private MongoClient _ownClient; - private string _currentConnectionString; - private IMongoCollection _collection; + private Func? _shared; + private MongoClient? _ownClient; + private string? _currentConnectionString; + private IMongoCollection? _collection; /// Read on every call: the installation sets it while the application runs public MongoPluginStateStore(Func connectionString) diff --git a/src/Core/Grand.Data/Mongo/MongoRepository.cs b/src/Core/Grand.Data/Mongo/MongoRepository.cs index 2d426a55a..45093725d 100644 --- a/src/Core/Grand.Data/Mongo/MongoRepository.cs +++ b/src/Core/Grand.Data/Mongo/MongoRepository.cs @@ -14,16 +14,24 @@ public class MongoRepository : IRepository where T : BaseEntity #region Fields private readonly IAuditInfoProvider _auditInfoProvider; + private readonly IMongoCollection? _collection; + private readonly IMongoDatabase? _database; /// /// Gets the collection /// - public IMongoCollection Collection { get; protected init; } + public IMongoCollection Collection { + get => _collection ?? throw NotConfigured(); + protected init => _collection = value; + } /// /// Mongo Database /// - protected IMongoDatabase Database { get; init; } + protected IMongoDatabase Database { + get => _database ?? throw NotConfigured(); + init => _database = value; + } #endregion @@ -37,7 +45,7 @@ public MongoRepository(IAuditInfoProvider auditInfoProvider) : this( { } - public MongoRepository(string connectionString, IAuditInfoProvider auditInfoProvider) + public MongoRepository(string? connectionString, IAuditInfoProvider auditInfoProvider) { _auditInfoProvider = auditInfoProvider; @@ -61,12 +69,20 @@ public MongoRepository(IMongoDatabase database, IAuditInfoProvider auditInfoProv #region Methods + /// + /// A repository created before the database was configured has no collection to work on + /// + private static InvalidOperationException NotConfigured() + { + return new InvalidOperationException($"The {typeof(T).Name} repository has no database - the connection string is not configured"); + } + /// /// Get entity by identifier /// /// Identifier /// Entity - public virtual T GetById(string id) + public virtual T? GetById(string id) { return Collection.Find(e => e.Id == id).FirstOrDefault(); } @@ -76,9 +92,9 @@ public virtual T GetById(string id) /// /// Identifier /// Entity - public virtual Task GetByIdAsync(string id) + public virtual async Task GetByIdAsync(string id) { - return Collection.Find(e => e.Id == id).FirstOrDefaultAsync(); + return await Collection.Find(e => e.Id == id).FirstOrDefaultAsync(); } /// @@ -86,9 +102,9 @@ public virtual Task GetByIdAsync(string id) /// /// /// Entity - public virtual Task GetOneAsync(Expression> predicate) + public virtual async Task GetOneAsync(Expression> predicate) { - return Collection.Find(predicate).FirstOrDefaultAsync(); + return await Collection.Find(predicate).FirstOrDefaultAsync(); } /// @@ -404,7 +420,7 @@ public virtual async Task CountAsync(IQueryable query, /// /// Executes the query and returns its first result, or the default value when nothing matches /// - public virtual async Task FirstOrDefaultAsync(IQueryable query, + public virtual async Task FirstOrDefaultAsync(IQueryable query, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(query); diff --git a/src/Core/Grand.Data/OrderBuilder.cs b/src/Core/Grand.Data/OrderBuilder.cs index 2f2542533..488e8d126 100644 --- a/src/Core/Grand.Data/OrderBuilder.cs +++ b/src/Core/Grand.Data/OrderBuilder.cs @@ -4,18 +4,18 @@ namespace Grand.Data; public class OrderBuilder { - private readonly List<(Expression> selector, bool value, string fieldName)> _list = new(); + private readonly List<(Expression>? selector, bool value, string fieldName)> _list = new(); protected OrderBuilder() { } - public IEnumerable<(Expression> selector, bool value, string fieldName)> Fields => _list; + public IEnumerable<(Expression>? selector, bool value, string fieldName)> Fields => _list; public static OrderBuilder Create() { return new OrderBuilder(); } - public OrderBuilder Ascending(Expression> selector) + public OrderBuilder Ascending(Expression> selector) { _list.Add((selector, true, "")); @@ -29,7 +29,7 @@ public OrderBuilder Ascending(string fieldName) return this; } - public OrderBuilder Descending(Expression> selector) + public OrderBuilder Descending(Expression> selector) { _list.Add((selector, false, "")); diff --git a/src/Core/Grand.Data/UpdateBuilder.cs b/src/Core/Grand.Data/UpdateBuilder.cs index f2fe3d1e2..019a9d986 100644 --- a/src/Core/Grand.Data/UpdateBuilder.cs +++ b/src/Core/Grand.Data/UpdateBuilder.cs @@ -5,14 +5,14 @@ namespace Grand.Data; public class UpdateBuilder { - private readonly List> _expressionFieldDefinitions = new(); + private readonly List> _expressionFieldDefinitions = new(); private readonly List> _list = new(); protected UpdateBuilder() { } public IEnumerable> Fields => _list; - public IEnumerable> ExpressionFields => _expressionFieldDefinitions; + public IEnumerable> ExpressionFields => _expressionFieldDefinitions; public static UpdateBuilder Create() { @@ -25,7 +25,7 @@ public UpdateBuilder Set(Expression> selector, _list.Add(Builders.Update.Set(selector, value)); //for other Db - _expressionFieldDefinitions.Add(new ExpressionFieldDefinition(selector, value)); + _expressionFieldDefinitions.Add(new ExpressionFieldDefinition(selector, value)); return this; } From cb6f3dd8fbf5d5ed8138ce28c7e1e738111edd3d Mon Sep 17 00:00:00 2001 From: support Date: Wed, 25 Nov 2026 08:13:38 +0100 Subject: [PATCH 05/30] Enable nullable in Grand.Infrastructure Configuration classes are nullable where appsettings may leave a value out. Members that are set by an initialization step (AutoMapperConfig, PluginManager.StateStore, the repository collection) throw an InvalidOperationException naming what was not set instead of a NullReferenceException. ICacheBase.GetAsync returns the T its acquire returns: a hit is always a value this class stored from that acquire, the one invariant marked with ! in MemoryCacheBase. The audit snapshots before and after are nullable throughout - null is an insert or a delete - and a change without a path is skipped where it used to throw inside the catch-all. --- src/Core/Grand.Data/IAuditInfoProvider.cs | 2 +- src/Core/Grand.Data/IPluginStateStore.cs | 8 +- .../LiteDb/LiteDBPluginStateStore.cs | 4 +- .../Grand.Data/Mongo/MongoPluginStateStore.cs | 6 +- .../Grand.Infrastructure/Audit/AuditDiff.cs | 14 ++- .../Audit/AuditReferences.cs | 56 ++++----- .../Audit/AuditTracker.cs | 46 ++++---- .../Caching/ICacheBase.cs | 4 +- .../Caching/MemoryCacheBase.cs | 12 +- .../Caching/Message/CacheMessageEvent.cs | 4 +- .../Caching/Message/IMessageEvent.cs | 2 +- .../Caching/Message/IMessageEventClient.cs | 2 +- .../Caching/Message/MessageEvent.cs | 2 +- .../Caching/Message/MessageEventClient.cs | 4 +- .../Caching/Redis/RedisMessageBus.cs | 18 +-- .../Configuration/AmazonConfig.cs | 10 +- .../Configuration/AppConfig.cs | 8 +- .../Configuration/AppConfigExtensions.cs | 2 +- .../Configuration/AzureConfig.cs | 14 +-- .../Configuration/BackendAPIConfig.cs | 6 +- .../Configuration/DatabaseConfig.cs | 2 +- .../Configuration/ExtensionsConfig.cs | 4 +- .../Configuration/FrontendAPIConfig.cs | 6 +- .../Configuration/OidcLoginConfig.cs | 4 +- .../Configuration/OidcProtectedResource.cs | 6 +- .../Configuration/OidcResourceServerConfig.cs | 2 +- .../Configuration/RedisConfig.cs | 6 +- .../Configuration/ScimConfig.cs | 11 +- .../Configuration/SecurityConfig.cs | 16 +-- .../Extensions/CommonExtensions.cs | 2 +- .../Grand.Infrastructure.csproj | 3 + src/Core/Grand.Infrastructure/GrandVersion.cs | 16 +-- .../Grand.Infrastructure/IStoreContext.cs | 2 +- src/Core/Grand.Infrastructure/IWorkContext.cs | 2 +- .../Mapper/AutoMapperConfig.cs | 6 +- .../Migrations/DbVersion.cs | 6 +- .../Migrations/MigrationManager.cs | 5 +- .../Migrations/MigrationResult.cs | 2 +- .../JsonBodyModelBinderProvider.cs | 2 +- .../Models/BaseEntityModel.cs | 2 +- .../Models/CaptchaModel.cs | 8 +- .../Models/ICaptchaValidModel.cs | 8 +- .../Modules/ModuleLoader.cs | 8 +- .../Plugins/BasePlugin.cs | 11 +- .../Grand.Infrastructure/Plugins/IPlugin.cs | 4 +- .../Plugins/IsolatedLoadContext.cs | 5 +- .../Plugins/PluginArchiveInstaller.cs | 6 +- .../Plugins/PluginExtensions.cs | 2 +- .../Plugins/PluginFolderScanner.cs | 20 ++-- .../Plugins/PluginInfo.cs | 34 +++--- .../Plugins/PluginInfoAttribute.cs | 4 +- .../Plugins/PluginLoadSnapshot.cs | 18 +-- .../Plugins/PluginLoader.cs | 2 +- .../Plugins/PluginManager.cs | 106 ++++++++++-------- .../Plugins/PluginManifest.cs | 10 +- .../Plugins/PluginManifestReader.cs | 9 +- .../Plugins/PluginVersionResolver.cs | 4 +- .../Roslyn/ResultCompiler.cs | 6 +- .../Roslyn/RoslynCompiler.cs | 4 +- .../Security/HtmlSanitizationService.cs | 12 +- .../Startup/AuditInfoProvider.cs | 2 +- src/Core/Grand.Infrastructure/StartupBase.cs | 27 +++-- .../Converter/BoolTypeConverter.cs | 2 +- .../CustomAttributeListTypeConverter.cs | 8 +- .../GenericDictionaryTypeConverter.cs | 8 +- .../Converter/GenericListTypeConverter.cs | 6 +- .../Converter/RefreshTokenTypeConverter.cs | 8 +- .../ShippingOptionListTypeConverter.cs | 8 +- .../Converter/ShippingOptionTypeConverter.cs | 8 +- .../JsonConverters/InterfaceConverter.cs | 4 +- .../JsonConverters/StringConverter.cs | 2 +- .../TypeSearch/TypeSearcher.cs | 15 +-- .../Validators/NoHtmlAttribute.cs | 4 +- .../Validators/SanitizeHtmlAttribute.cs | 4 +- .../Validators/ValidationFilter.cs | 2 +- .../Extensions/CommonHelper.cs | 2 +- 76 files changed, 392 insertions(+), 328 deletions(-) diff --git a/src/Core/Grand.Data/IAuditInfoProvider.cs b/src/Core/Grand.Data/IAuditInfoProvider.cs index 068197f1a..58e35dc1d 100644 --- a/src/Core/Grand.Data/IAuditInfoProvider.cs +++ b/src/Core/Grand.Data/IAuditInfoProvider.cs @@ -2,6 +2,6 @@ public interface IAuditInfoProvider { - string GetCurrentUser(); + string? GetCurrentUser(); DateTime GetCurrentDateTime(); } \ No newline at end of file diff --git a/src/Core/Grand.Data/IPluginStateStore.cs b/src/Core/Grand.Data/IPluginStateStore.cs index a7a087a2a..f7ba13d38 100644 --- a/src/Core/Grand.Data/IPluginStateStore.cs +++ b/src/Core/Grand.Data/IPluginStateStore.cs @@ -55,10 +55,10 @@ public interface IPluginStateStore /// Why the plugin was rejected; null when it was not public sealed record PluginState( string SystemName, - string FriendlyName, - string Version, - string FolderName, - string LoadError, + string? FriendlyName, + string? Version, + string? FolderName, + string? LoadError, DateTime LoadedOnUtc); /// diff --git a/src/Core/Grand.Data/LiteDb/LiteDBPluginStateStore.cs b/src/Core/Grand.Data/LiteDb/LiteDBPluginStateStore.cs index 5fdb30424..4d7600be6 100644 --- a/src/Core/Grand.Data/LiteDb/LiteDBPluginStateStore.cs +++ b/src/Core/Grand.Data/LiteDb/LiteDBPluginStateStore.cs @@ -9,12 +9,12 @@ namespace Grand.Data.LiteDb; /// public sealed class LiteDBPluginStateStore : IPluginStateStore { - private readonly Func _connectionString; + private readonly Func _connectionString; private readonly Lock _lock = new(); private Func? _shared; /// Read on every call: the installation sets it while the application runs - public LiteDBPluginStateStore(Func connectionString) + public LiteDBPluginStateStore(Func connectionString) { ArgumentNullException.ThrowIfNull(connectionString); _connectionString = connectionString; diff --git a/src/Core/Grand.Data/Mongo/MongoPluginStateStore.cs b/src/Core/Grand.Data/Mongo/MongoPluginStateStore.cs index a7663228b..372629050 100644 --- a/src/Core/Grand.Data/Mongo/MongoPluginStateStore.cs +++ b/src/Core/Grand.Data/Mongo/MongoPluginStateStore.cs @@ -13,7 +13,7 @@ public sealed class MongoPluginStateStore : IPluginStateStore { private static readonly UpdateOptions Upsert = new() { IsUpsert = true }; - private readonly Func _connectionString; + private readonly Func _connectionString; private readonly Lock _lock = new(); private Func? _shared; private MongoClient? _ownClient; @@ -21,7 +21,7 @@ public sealed class MongoPluginStateStore : IPluginStateStore private IMongoCollection? _collection; /// Read on every call: the installation sets it while the application runs - public MongoPluginStateStore(Func connectionString) + public MongoPluginStateStore(Func connectionString) { ArgumentNullException.ThrowIfNull(connectionString); _connectionString = connectionString; @@ -111,7 +111,7 @@ public void SaveLoadResults(IEnumerable plugins) Collection().BulkWrite(writes); } - private static BsonValue ValueOf(string value) + private static BsonValue ValueOf(string? value) { return value == null ? BsonNull.Value : new BsonString(value); } diff --git a/src/Core/Grand.Infrastructure/Audit/AuditDiff.cs b/src/Core/Grand.Infrastructure/Audit/AuditDiff.cs index dd87f6a21..e870bed3c 100644 --- a/src/Core/Grand.Infrastructure/Audit/AuditDiff.cs +++ b/src/Core/Grand.Infrastructure/Audit/AuditDiff.cs @@ -1,5 +1,6 @@ using Grand.Data.Audit; using Grand.Domain.Audit; +using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; namespace Grand.Infrastructure.Audit; @@ -26,8 +27,8 @@ public static bool IsSensitive(string name) /// Lists the changed fields. is null for an insert, /// is null for a delete (which lists nothing). /// - public static IList Compare(string entityType, IDictionary before, - IDictionary after, ISet ignoredPaths) + public static IList Compare(string entityType, IDictionary? before, + IDictionary? after, ISet ignoredPaths) { var changes = new List(); if (after == null) @@ -52,7 +53,7 @@ public static IList Compare(string entityType, IDictionary snapshot, string path) + private static string? ValueOf(IDictionary snapshot, string path) { return snapshot.TryGetValue(path, out var value) && !string.IsNullOrEmpty(value) ? value : null; } @@ -67,7 +68,7 @@ private static bool IsUnder(string path, string parent) /// /// A change of one path, its values cut to and marked when they were /// - public static AuditChange Change(string path, string oldValue, string newValue) + public static AuditChange Change(string path, string? oldValue, string? newValue) { var change = new AuditChange { Path = path, @@ -78,9 +79,10 @@ public static AuditChange Change(string path, string oldValue, string newValue) return change; } - private static string Truncate(string value, out bool truncated) + [return: NotNullIfNotNull(nameof(value))] + private static string? Truncate(string? value, out bool truncated) { truncated = value is { Length: > MaxValueLength }; - return truncated ? value[..MaxValueLength] : value; + return value is { Length: > MaxValueLength } ? value[..MaxValueLength] : value; } } diff --git a/src/Core/Grand.Infrastructure/Audit/AuditReferences.cs b/src/Core/Grand.Infrastructure/Audit/AuditReferences.cs index 35f505b68..a310ff14b 100644 --- a/src/Core/Grand.Infrastructure/Audit/AuditReferences.cs +++ b/src/Core/Grand.Infrastructure/Audit/AuditReferences.cs @@ -14,14 +14,14 @@ namespace Grand.Infrastructure.Audit; public partial class AuditReferences(IAuditRecordReader reader) { private static readonly ConcurrentDictionary NameProperties = new(); - private static readonly ConcurrentDictionary<(Type, string), PropertyInfo> Properties = new(); - private static readonly ConcurrentDictionary Owners = new(); + private static readonly ConcurrentDictionary<(Type, string), PropertyInfo?> Properties = new(); + private static readonly ConcurrentDictionary Owners = new(); //the records read for these entries, null when there is none - private readonly Dictionary> _records = new(); + private readonly Dictionary?> _records = new(); //set while Prefetch walks the entries: the records they need are noted instead of read - private HashSet _wanted; + private HashSet? _wanted; [GeneratedRegex(@"\[[^\]]*\]")] private static partial Regex ElementKeys(); @@ -40,7 +40,7 @@ public static string NameProperty(Type type) /// describing them afterwards reads nothing. A record that could not be read this way is read when needed. /// public async Task Prefetch( - IEnumerable<(Type Type, AuditEntry Entry, IDictionary Before, IDictionary After)> entries) + IEnumerable<(Type Type, AuditEntry Entry, IDictionary? Before, IDictionary? After)> entries) { var wanted = _wanted = []; try @@ -77,20 +77,23 @@ public async Task Prefetch( /// /// Names the list elements, the references and the owner of one entry /// - public async Task DescribeEntry(Type entityType, AuditEntry entry, IDictionary before, - IDictionary after) + public async Task DescribeEntry(Type entityType, AuditEntry entry, IDictionary? before, + IDictionary? after) { await NameElements(entityType, entry.Changes, before, after); await Describe(entityType, entry.Changes, before, after); await LinkOwner(entityType, entry, after ?? before); } - public async Task Describe(Type entityType, IEnumerable changes, IDictionary before, - IDictionary after) + public async Task Describe(Type entityType, IEnumerable changes, IDictionary? before, + IDictionary? after) { //a cut value is no longer a whole id list; it stays as stored foreach (var change in changes.Where(c => !c.Masked && !c.Truncated)) { + if (change.Path == null) + continue; + var property = PropertyAt(entityType, change.Path); if (property == null) continue; @@ -120,11 +123,14 @@ public async Task Describe(Type entityType, IEnumerable changes, ID /// change reads "Color family" instead of an element id /// public async Task NameElements(Type entityType, IEnumerable changes, - IDictionary before, IDictionary after) + IDictionary? before, IDictionary? after) { - var named = new Dictionary(); + var named = new Dictionary(); foreach (var change in changes) { + if (change.Path == null) + continue; + //a name that cannot be found leaves the element ids, never the change out try { @@ -160,8 +166,8 @@ public async Task NameElements(Type entityType, IEnumerable changes } //the element's [AuditName] or Name value; a reference names it by the referenced record - private async Task ElementName(Type elementType, string path, IDictionary before, - IDictionary after) + private async Task ElementName(Type elementType, string path, IDictionary? before, + IDictionary? after) { var property = elementType.GetProperty(NameProperty(elementType)); if (property == null) @@ -184,7 +190,7 @@ private async Task ElementName(Type elementType, string path, IDictionar /// Links the entry of a record that belongs to another (see ) to that record, /// so it shows in the owner's change history, and to the owner's store when it has none of its own /// - public async Task LinkOwner(Type entityType, AuditEntry entry, IDictionary snapshot) + public async Task LinkOwner(Type entityType, AuditEntry entry, IDictionary? snapshot) { var owner = Owners.GetOrAdd(entityType, t => t.GetProperties().FirstOrDefault(p => p.IsDefined(typeof(AuditOwnerAttribute)) && p.IsDefined(typeof(AuditReferenceAttribute)))); @@ -226,15 +232,15 @@ public static bool HasNamedValues(Type entityType, string path) /// The property a changed path ends at, e.g. "ProductSpecificationAttributes[id=1].SpecificationAttributeOptionId" /// is SpecificationAttributeOptionId of the element type; null when the path is not a property /// - public static PropertyInfo PropertyAt(Type type, string path) + public static PropertyInfo? PropertyAt(Type type, string path) { //cached by the path without its element keys, so the cache grows with the model, not with the data return Properties.GetOrAdd((type, ElementKeys().Replace(path, "")), key => FindProperty(key.Item1, key.Item2)); } - private static PropertyInfo FindProperty(Type type, string path) + private static PropertyInfo? FindProperty(Type type, string path) { - PropertyInfo property = null; + PropertyInfo? property = null; foreach (var segment in path.Split('.')) { property = type?.GetProperty(segment.Split('[')[0]); @@ -247,7 +253,7 @@ private static PropertyInfo FindProperty(Type type, string path) return property; } - private static Type ElementType(Type type) + private static Type? ElementType(Type type) { return type == typeof(string) ? null @@ -256,8 +262,8 @@ private static Type ElementType(Type type) ?.GetGenericArguments()[0]; } - private async Task Describe(PropertyInfo property, string path, string value, - IDictionary snapshot) + private async Task Describe(PropertyInfo property, string path, string? value, + IDictionary? snapshot) { if (string.IsNullOrEmpty(value)) return value; @@ -285,20 +291,20 @@ private async Task Describe(PropertyInfo property, string path, string v return string.Join(", ", described); } - private static string SiblingValue(IDictionary snapshot, string path, string sibling) + private static string? SiblingValue(IDictionary? snapshot, string path, string sibling) { var parent = path.Contains('.') ? path[..(path.LastIndexOf('.') + 1)] : ""; return snapshot != null && snapshot.TryGetValue(parent + sibling, out var value) ? value : null; } - private async Task Label(AuditReferenceAttribute reference, string owner, string id) + private async Task Label(AuditReferenceAttribute reference, string? owner, string id) { var name = await NameOf(reference, owner, id); return name == null ? id : $"{name} ({id})"; } //the name in the snapshot of the referenced record, or of the element of its list; null when there is none - private async Task NameOf(AuditReferenceAttribute reference, string owner, string id) + private async Task NameOf(AuditReferenceAttribute reference, string? owner, string id) { var recordId = reference.List == null ? id : owner; if (string.IsNullOrEmpty(recordId)) @@ -315,7 +321,7 @@ private async Task NameOf(AuditReferenceAttribute reference, string owne } //each record is read once for all the entries; while Prefetch collects, it is only noted - private async Task> Record(Type target, string value, string key, string field) + private async Task?> Record(Type target, string value, string? key, string field) { var recordKey = new RecordKey(target, key, field, value); if (_wanted != null) @@ -329,5 +335,5 @@ private async Task> Record(Type target, string value return record; } - private readonly record struct RecordKey(Type Target, string Key, string Field, string Value); + private readonly record struct RecordKey(Type Target, string? Key, string Field, string Value); } diff --git a/src/Core/Grand.Infrastructure/Audit/AuditTracker.cs b/src/Core/Grand.Infrastructure/Audit/AuditTracker.cs index 4cedceb6a..ae8c4bf7b 100644 --- a/src/Core/Grand.Infrastructure/Audit/AuditTracker.cs +++ b/src/Core/Grand.Infrastructure/Audit/AuditTracker.cs @@ -42,7 +42,7 @@ private readonly Dictionary, Task _publishing = new(); - private AuditActor _actor; + private AuditActor? _actor; public bool IsActive => _actor != null && !_publishing.Value; @@ -57,7 +57,7 @@ public bool IsAudited(Type entityType) } public async Task BeforeWriteAsync(string id, bool isInsert, - Func, Task>> loadMany, IReadOnlyCollection writtenPaths = null) + Func, Task>> loadMany, IReadOnlyCollection? writtenPaths = null) where T : BaseEntity { if (!IsActive || string.IsNullOrEmpty(id)) @@ -90,7 +90,7 @@ public async Task BeforeWriteAsync(string id, bool isInsert, if (flush) await FlushAsync(); - IDictionary before = null; + IDictionary? before = null; if (!isInsert) try { @@ -100,7 +100,7 @@ public async Task BeforeWriteAsync(string id, bool isInsert, catch (Exception ex) { logger.LogError(ex, "Audit could not read {EntityType} {EntityId} before operation {OperationId}", - typeof(T).Name, id, _actor.OperationId); + typeof(T).Name, id, _actor?.OperationId); return; } @@ -141,7 +141,7 @@ public void AfterFullUpdate(T entity) where T : BaseEntity catch (Exception ex) { logger.LogError(ex, "Audit could not keep {EntityType} {EntityId} after operation {OperationId}", - typeof(T).Name, entity.Id, _actor.OperationId); + typeof(T).Name, entity.Id, _actor?.OperationId); } } @@ -160,7 +160,7 @@ public void RecordBulk(string operation, string filter) where T : BaseEntity } } - public IDisposable CountInserts(string operation, string details, BaseEntity owner = null) + public IDisposable CountInserts(string operation, string details, BaseEntity? owner = null) where T : BaseEntity { if (!IsActive) @@ -194,7 +194,7 @@ public IDisposable CountInserts(string operation, string details, BaseEntity }); } - private sealed class Scope(Action end) : IDisposable + private sealed class Scope(Action? end) : IDisposable { public void Dispose() { @@ -271,8 +271,8 @@ private static async Task> BuildEntries( AuditReferences references) { //an entry of null: its changes could not be computed - var built = new List<(Type Type, string Id, AuditEntry Entry, IDictionary Before, - IDictionary After)>(); + var built = new List<(Type Type, string Id, AuditEntry? Entry, IDictionary? Before, + IDictionary? After)>(); foreach (var group in pending.GroupBy(p => p.Key.Type)) { var toRead = group.Where(p => p.Value.AfterHint == null).Select(p => p.Key.Id).ToList(); @@ -297,7 +297,11 @@ private static async Task> BuildEntries( } //the names of all entries in a few reads, instead of one read per referenced record - await references.Prefetch(built.Where(b => b.Entry != null).Select(b => (b.Type, b.Entry, b.Before, b.After))); + var described = new List<(Type, AuditEntry, IDictionary?, IDictionary?)>(); + foreach (var b in built) + if (b.Entry != null) + described.Add((b.Type, b.Entry, b.Before, b.After)); + await references.Prefetch(described); var entries = new List(); foreach (var item in built) @@ -324,8 +328,8 @@ private static async Task> BuildEntries( return entries; } - private static AuditEntry Build(Type type, string entityId, Pending pending, - IDictionary after) + private static AuditEntry? Build(Type type, string entityId, Pending pending, + IDictionary? after) { var entityType = type.Name; var before = pending.Before; @@ -352,8 +356,8 @@ private static AuditEntry Build(Type type, string entityId, Pending pending, return entry; } - if (pending.Paths != null) - changes = changes.Where(c => pending.Paths.Any(p => Touches(c.Path, p))).ToList(); + if (pending.Paths is { } paths) + changes = changes.Where(c => c.Path != null && paths.Any(p => Touches(c.Path, p))).ToList(); if (changes.Count == 0) return null; @@ -362,7 +366,7 @@ private static AuditEntry Build(Type type, string entityId, Pending pending, return entry; } - private static string NameOf(Type type, IDictionary snapshot) + private static string? NameOf(Type type, IDictionary? snapshot) { //a name can be a note or a comment: kept to the length of a stored value var property = AuditReferences.NameProperty(type); @@ -372,7 +376,7 @@ private static string NameOf(Type type, IDictionary snapshot) } //"" is a record of all stores, null one without a store - private static string StoreIdOf(IDictionary snapshot) + private static string? StoreIdOf(IDictionary? snapshot) { return snapshot != null && snapshot.TryGetValue("StoreId", out var storeId) ? storeId : null; } @@ -384,21 +388,21 @@ private static bool Touches(string changePath, string writtenPath) || changePath.StartsWith(writtenPath + "[", StringComparison.Ordinal); } - private sealed class Pending(IDictionary before, IReadOnlyCollection paths) + private sealed class Pending(IDictionary? before, IReadOnlyCollection? paths) { - public IDictionary Before { get; } = before; + public IDictionary? Before { get; } = before; /// /// The paths written in this scope; null means every field /// - public HashSet Paths { get; private set; } = paths == null ? null : [..paths]; + public HashSet? Paths { get; private set; } = paths == null ? null : [..paths]; /// /// The state a full update wrote, so the flush does not re-read it /// - public IDictionary AfterHint { get; set; } + public IDictionary? AfterHint { get; set; } - public void Merge(IReadOnlyCollection writtenPaths) + public void Merge(IReadOnlyCollection? writtenPaths) { //any later write changes the stored document again, so the kept "after" is stale; a full update //sets it again right after its write diff --git a/src/Core/Grand.Infrastructure/Caching/ICacheBase.cs b/src/Core/Grand.Infrastructure/Caching/ICacheBase.cs index b5f29846c..5370ffb11 100644 --- a/src/Core/Grand.Infrastructure/Caching/ICacheBase.cs +++ b/src/Core/Grand.Infrastructure/Caching/ICacheBase.cs @@ -1,3 +1,5 @@ +using System.Diagnostics.CodeAnalysis; + namespace Grand.Infrastructure.Caching; /// @@ -8,7 +10,7 @@ public interface ICacheBase /// /// Gets a cached value without loading it on a miss /// - bool TryGet(string key, out T value); + bool TryGet(string key, [MaybeNullWhen(false)] out T value); Task GetAsync(string key, Func> acquire); Task GetAsync(string key, Func> acquire, int cacheTime); diff --git a/src/Core/Grand.Infrastructure/Caching/MemoryCacheBase.cs b/src/Core/Grand.Infrastructure/Caching/MemoryCacheBase.cs index 6f00d0d3c..7c7e67dfc 100644 --- a/src/Core/Grand.Infrastructure/Caching/MemoryCacheBase.cs +++ b/src/Core/Grand.Infrastructure/Caching/MemoryCacheBase.cs @@ -4,6 +4,7 @@ using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Primitives; using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; namespace Grand.Infrastructure.Caching; @@ -37,7 +38,7 @@ public MemoryCacheBase(IMemoryCache cache, IMediator mediator, CacheConfig cache #region Methods - public virtual bool TryGet(string key, out T value) + public virtual bool TryGet(string key, [MaybeNullWhen(false)] out T value) { return _cache.TryGetValue(key, out value); } @@ -49,7 +50,8 @@ public virtual Task GetAsync(string key, Func> acquire) public virtual async Task GetAsync(string key, Func> acquire, int cacheTime) { - if (_cache.TryGetValue(key, out T cacheEntry)) return cacheEntry; + //an entry is only ever stored under its key by this class, from the acquire of the same T, so a hit is a T + if (_cache.TryGetValue(key, out T? cacheEntry)) return cacheEntry!; var semaphore = CacheEntries.GetOrAdd(key, _ => new SemaphoreSlim(1, 1)); await semaphore.WaitAsync(); try @@ -66,7 +68,7 @@ public virtual async Task GetAsync(string key, Func> acquire, int semaphore.Release(); } - return cacheEntry; + return cacheEntry!; } public virtual Task SetAsync(string key, Func> acquire) @@ -179,13 +181,13 @@ private MemoryCacheEntryOptions GetMemoryCacheEntryOptions(int cacheTime, Cancel return options; } - private void PostEvictionCallback(object key, object value, EvictionReason reason, object state) + private void PostEvictionCallback(object key, object? value, EvictionReason reason, object? state) { if (reason == EvictionReason.Replaced) return; //MemoryCache runs this callback on the thread pool, often after the same key has been stored //again; the newer entry must stay tracked, or RemoveByPrefix would never remove it - var cacheKey = key.ToString(); + if (key.ToString() is not { } cacheKey) return; CacheEntries.TryRemove(cacheKey, out _); if (_cache.TryGetValue(cacheKey, out _)) CacheEntries.GetOrAdd(cacheKey, _ => new SemaphoreSlim(1, 1)); diff --git a/src/Core/Grand.Infrastructure/Caching/Message/CacheMessageEvent.cs b/src/Core/Grand.Infrastructure/Caching/Message/CacheMessageEvent.cs index d9df22496..2c0c04a61 100644 --- a/src/Core/Grand.Infrastructure/Caching/Message/CacheMessageEvent.cs +++ b/src/Core/Grand.Infrastructure/Caching/Message/CacheMessageEvent.cs @@ -2,7 +2,7 @@ public class CacheMessageEvent { - public string ClientId { get; set; } - public string Key { get; set; } + public string? ClientId { get; set; } + public string? Key { get; set; } public int MessageType { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Caching/Message/IMessageEvent.cs b/src/Core/Grand.Infrastructure/Caching/Message/IMessageEvent.cs index ef84139fe..0a75624bc 100644 --- a/src/Core/Grand.Infrastructure/Caching/Message/IMessageEvent.cs +++ b/src/Core/Grand.Infrastructure/Caching/Message/IMessageEvent.cs @@ -2,6 +2,6 @@ public interface IMessageEvent { - string Key { get; set; } + string? Key { get; set; } int MessageType { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Caching/Message/IMessageEventClient.cs b/src/Core/Grand.Infrastructure/Caching/Message/IMessageEventClient.cs index afdd7a6e0..dff57bcf3 100644 --- a/src/Core/Grand.Infrastructure/Caching/Message/IMessageEventClient.cs +++ b/src/Core/Grand.Infrastructure/Caching/Message/IMessageEventClient.cs @@ -2,5 +2,5 @@ public interface IMessageEventClient : IMessageEvent { - string ClientId { get; set; } + string? ClientId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Caching/Message/MessageEvent.cs b/src/Core/Grand.Infrastructure/Caching/Message/MessageEvent.cs index 3ec90d711..7084f42ab 100644 --- a/src/Core/Grand.Infrastructure/Caching/Message/MessageEvent.cs +++ b/src/Core/Grand.Infrastructure/Caching/Message/MessageEvent.cs @@ -2,6 +2,6 @@ public class MessageEvent : IMessageEvent { - public string Key { get; set; } + public string? Key { get; set; } public int MessageType { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Caching/Message/MessageEventClient.cs b/src/Core/Grand.Infrastructure/Caching/Message/MessageEventClient.cs index 6313281ff..e799d1137 100644 --- a/src/Core/Grand.Infrastructure/Caching/Message/MessageEventClient.cs +++ b/src/Core/Grand.Infrastructure/Caching/Message/MessageEventClient.cs @@ -2,7 +2,7 @@ public class MessageEventClient : IMessageEventClient { - public string ClientId { get; set; } - public string Key { get; set; } + public string? ClientId { get; set; } + public string? Key { get; set; } public int MessageType { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageBus.cs b/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageBus.cs index 4e7a613c9..26987fb9c 100644 --- a/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageBus.cs +++ b/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageBus.cs @@ -21,7 +21,7 @@ public sealed class RedisMessageBus : IMessageBus, IHostedService, IDisposable private readonly ISubscriber _subscriber; private readonly ILogger _logger; private readonly CancellationTokenSource _cts = new(); - private Task _subscribeLoop; + private Task? _subscribeLoop; public RedisMessageBus(IConnectionMultiplexer connection, IServiceProvider serviceProvider, RedisConfig redisConfig, ILogger logger) @@ -63,7 +63,7 @@ public async Task PublishAsync(TMessage msg) where TMessage : IMessage try { var receivers = - await _subscriber.PublishAsync(RedisChannel.Literal(_redisConfig.RedisPubSubChannel), message); + await _subscriber.PublishAsync(Channel, message); if (_logger.IsEnabled(LogLevel.Debug)) _logger.LogDebug( "Published cache invalidation message (type: {MessageType}, key: {Key}), delivered to {Receivers} subscriber(s)", @@ -79,19 +79,23 @@ public async Task PublishAsync(TMessage msg) where TMessage : IMessage public Task SubscribeAsync() { - return _subscriber.SubscribeAsync(RedisChannel.Literal(_redisConfig.RedisPubSubChannel), OnMessage); + return _subscriber.SubscribeAsync(Channel, OnMessage); } + private RedisChannel Channel => RedisChannel.Literal(_redisConfig.RedisPubSubChannel ?? + throw new InvalidOperationException("Redis:RedisPubSubChannel is not configured")); + public void OnSubscriptionChanged(IMessageEvent message) { using var scope = _serviceProvider.CreateScope(); var cache = scope.ServiceProvider.GetRequiredService(); switch (message.MessageType) { - case (int)MessageEventType.RemoveKey: + //a message without a key names nothing to remove + case (int)MessageEventType.RemoveKey when message.Key != null: _ = cache.RemoveAsync(message.Key, false); break; - case (int)MessageEventType.RemoveByPrefix: + case (int)MessageEventType.RemoveByPrefix when message.Key != null: _ = cache.RemoveByPrefix(message.Key, false); break; case (int)MessageEventType.ClearCache: @@ -163,14 +167,14 @@ private void OnMessage(RedisChannel channel, RedisValue redisValue) } } - private void OnConnectionFailed(object sender, ConnectionFailedEventArgs e) + private void OnConnectionFailed(object? sender, ConnectionFailedEventArgs e) { _logger.LogWarning(e.Exception, "Redis connection failed ({ConnectionType}, {FailureType}) - cache invalidation messages may be lost while disconnected", e.ConnectionType, e.FailureType); } - private void OnConnectionRestored(object sender, ConnectionFailedEventArgs e) + private void OnConnectionRestored(object? sender, ConnectionFailedEventArgs e) { //invalidation messages published while this instance was disconnected are lost //(Redis pub/sub has no replay), so the local cache can no longer be trusted diff --git a/src/Core/Grand.Infrastructure/Configuration/AmazonConfig.cs b/src/Core/Grand.Infrastructure/Configuration/AmazonConfig.cs index 4f1846a14..c4fec4e72 100644 --- a/src/Core/Grand.Infrastructure/Configuration/AmazonConfig.cs +++ b/src/Core/Grand.Infrastructure/Configuration/AmazonConfig.cs @@ -5,26 +5,26 @@ public class AmazonConfig /// /// Amazon Access Key /// - public string AmazonAwsAccessKeyId { get; set; } + public string? AmazonAwsAccessKeyId { get; set; } /// /// Amazon Secret Access Key /// - public string AmazonAwsSecretAccessKey { get; set; } + public string? AmazonAwsSecretAccessKey { get; set; } /// /// Amazon Bucket Name using for identifying resources /// - public string AmazonBucketName { get; set; } + public string? AmazonBucketName { get; set; } /// /// Amazon Domain name for cloudfront distribution /// - public string AmazonDistributionDomainName { get; set; } + public string? AmazonDistributionDomainName { get; set; } /// /// Amazon Region /// http://docs.amazonwebservices.com/AmazonS3/latest/BucketConfiguration.html#LocationSelection /// - public string AmazonRegion { get; set; } + public string? AmazonRegion { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs b/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs index e67d26b34..5b08aa275 100644 --- a/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs +++ b/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs @@ -15,14 +15,14 @@ public class AppConfig /// /// Gets or sets a value of "Cache-Control" header value for static content /// - public string StaticFilesCacheControl { get; set; } + public string? StaticFilesCacheControl { get; set; } /// /// Gets or sets the file extensions served from the Plugins folder on top of the built-in css, js, images, /// fonts and pdf (e.g. ".mp4"). The folder also holds the plugin assemblies and their build files - add only /// extensions that are safe to publish; .dll, .pdb, .exe and .config are never served. /// - public string[] PluginStaticFileExtensions { get; set; } + public string[]? PluginStaticFileExtensions { get; set; } /// /// Gets or sets a value indicating whether to display the full error in production environment. @@ -52,7 +52,7 @@ public class AppConfig /// thumbnails, sitemap xml files). Empty keeps them in wwwroot. With more than one instance, point every /// instance at the same shared volume. A relative path is resolved against the content root. /// - public string MediaPath { get; set; } + public string? MediaPath { get; set; } /// /// Gets or sets the name this instance answers to when a scheduled task is pinned to a machine @@ -60,5 +60,5 @@ public class AppConfig /// hostname and changes on every deployment. Several instances may share the name - one of them /// runs each due task. /// - public string InstanceName { get; set; } + public string? InstanceName { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Configuration/AppConfigExtensions.cs b/src/Core/Grand.Infrastructure/Configuration/AppConfigExtensions.cs index 3d61e26f7..4fa6bb999 100644 --- a/src/Core/Grand.Infrastructure/Configuration/AppConfigExtensions.cs +++ b/src/Core/Grand.Infrastructure/Configuration/AppConfigExtensions.cs @@ -14,7 +14,7 @@ public static class AppConfigExtensions /// The media path is the content root, one of its parents, or App_Data: the media root is served /// at "/", so it would publish appsettings.json and Settings.cfg /// - public static string GetMediaRootPath(this AppConfig appConfig, string contentRootPath) + public static string? GetMediaRootPath(this AppConfig appConfig, string contentRootPath) { ArgumentNullException.ThrowIfNull(appConfig); diff --git a/src/Core/Grand.Infrastructure/Configuration/AzureConfig.cs b/src/Core/Grand.Infrastructure/Configuration/AzureConfig.cs index fa8780e69..e24083d58 100644 --- a/src/Core/Grand.Infrastructure/Configuration/AzureConfig.cs +++ b/src/Core/Grand.Infrastructure/Configuration/AzureConfig.cs @@ -5,23 +5,23 @@ public class AzureConfig /// /// Connection string for Azure BLOB storage /// - public string AzureBlobStorageConnectionString { get; set; } + public string? AzureBlobStorageConnectionString { get; set; } /// /// Container name for Azure BLOB storage /// - public string AzureBlobStorageContainerName { get; set; } + public string? AzureBlobStorageContainerName { get; set; } /// /// End point for Azure BLOB storage /// - public string AzureBlobStorageEndPoint { get; set; } + public string? AzureBlobStorageEndPoint { get; set; } /// /// Connection string for PersistKeys Azure BLOB storage /// - public string PersistKeysAzureBlobStorageConnectionString { get; set; } + public string? PersistKeysAzureBlobStorageConnectionString { get; set; } /// /// Indicates whether we should use Azure Key Vault to store data protection keys @@ -36,15 +36,15 @@ public class AzureConfig /// /// Azure blob storage container name /// - public string DataProtectionContainerName { get; set; } + public string? DataProtectionContainerName { get; set; } /// /// Azure blob storage blob name /// - public string DataProtectionBlobName { get; set; } + public string? DataProtectionBlobName { get; set; } /// /// The keyIdentifier is the key vault key identifier used for key encryption. /// - public string KeyIdentifier { get; set; } + public string? KeyIdentifier { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Configuration/BackendAPIConfig.cs b/src/Core/Grand.Infrastructure/Configuration/BackendAPIConfig.cs index ef6ff8a53..66e8eee47 100644 --- a/src/Core/Grand.Infrastructure/Configuration/BackendAPIConfig.cs +++ b/src/Core/Grand.Infrastructure/Configuration/BackendAPIConfig.cs @@ -3,10 +3,10 @@ public class BackendAPIConfig { public bool Enabled { get; set; } - public string SecretKey { get; set; } + public string? SecretKey { get; set; } public bool ValidateIssuer { get; set; } - public string ValidIssuer { get; set; } + public string? ValidIssuer { get; set; } public bool ValidateAudience { get; set; } - public string ValidAudience { get; set; } + public string? ValidAudience { get; set; } public int ExpiryInMinutes { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Configuration/DatabaseConfig.cs b/src/Core/Grand.Infrastructure/Configuration/DatabaseConfig.cs index 273ab7a4a..6d72f481d 100644 --- a/src/Core/Grand.Infrastructure/Configuration/DatabaseConfig.cs +++ b/src/Core/Grand.Infrastructure/Configuration/DatabaseConfig.cs @@ -10,7 +10,7 @@ public class DatabaseConfig /// /// Gets or sets a value indicating whether use LiteDB database (only for installation process) /// - public string LiteDbConnectionString { get; set; } + public string? LiteDbConnectionString { get; set; } /// /// Gets or sets a value indicating whether storefront product keyword search uses a text index (whole diff --git a/src/Core/Grand.Infrastructure/Configuration/ExtensionsConfig.cs b/src/Core/Grand.Infrastructure/Configuration/ExtensionsConfig.cs index 3ff932601..9816de2e1 100644 --- a/src/Core/Grand.Infrastructure/Configuration/ExtensionsConfig.cs +++ b/src/Core/Grand.Infrastructure/Configuration/ExtensionsConfig.cs @@ -19,7 +19,7 @@ public class ExtensionsConfig /// /// A list of plugins to be ignored during start application - pattern /// - public string PluginSkipLoadingPattern { get; set; } + public string? PluginSkipLoadingPattern { get; set; } /// /// Enable scripting C# applications to execute code. @@ -29,7 +29,7 @@ public class ExtensionsConfig /// /// List of installed plugins (comma separated) /// - public string InstalledPlugins { get; set; } + public string? InstalledPlugins { get; set; } /// /// Stop the application when an installed plugin, or a module enabled under FeatureManagement, fails to diff --git a/src/Core/Grand.Infrastructure/Configuration/FrontendAPIConfig.cs b/src/Core/Grand.Infrastructure/Configuration/FrontendAPIConfig.cs index dc51d77b5..d3d3b0010 100644 --- a/src/Core/Grand.Infrastructure/Configuration/FrontendAPIConfig.cs +++ b/src/Core/Grand.Infrastructure/Configuration/FrontendAPIConfig.cs @@ -5,11 +5,11 @@ public class FrontendAPIConfig public static string AuthenticationScheme => "FrontAuthentication"; public bool Enabled { get; set; } public bool JsonContentType { get; set; } - public string SecretKey { get; set; } + public string? SecretKey { get; set; } public bool ValidateIssuer { get; set; } - public string ValidIssuer { get; set; } + public string? ValidIssuer { get; set; } public bool ValidateAudience { get; set; } - public string ValidAudience { get; set; } + public string? ValidAudience { get; set; } public bool ValidateLifetime { get; set; } public bool ValidateIssuerSigningKey { get; set; } public int ExpiryInMinutes { get; set; } diff --git a/src/Core/Grand.Infrastructure/Configuration/OidcLoginConfig.cs b/src/Core/Grand.Infrastructure/Configuration/OidcLoginConfig.cs index 3191f96b1..f5ddd28c4 100644 --- a/src/Core/Grand.Infrastructure/Configuration/OidcLoginConfig.cs +++ b/src/Core/Grand.Infrastructure/Configuration/OidcLoginConfig.cs @@ -17,8 +17,8 @@ public class OidcLoginConfig private const int DefaultStaffMaxSessionHours = 10; private const int DefaultRevalidationMinutes = 10; - public string ClientId { get; set; } - public string ClientSecret { get; set; } + public string? ClientId { get; set; } + public string? ClientSecret { get; set; } public string Scopes { get; set; } = "openid profile email offline_access"; /// Order of the sign-in button among the external authentication methods diff --git a/src/Core/Grand.Infrastructure/Configuration/OidcProtectedResource.cs b/src/Core/Grand.Infrastructure/Configuration/OidcProtectedResource.cs index 3332500fa..6e2a5df07 100644 --- a/src/Core/Grand.Infrastructure/Configuration/OidcProtectedResource.cs +++ b/src/Core/Grand.Infrastructure/Configuration/OidcProtectedResource.cs @@ -6,13 +6,13 @@ namespace Grand.Infrastructure.Configuration; public class OidcProtectedResource { /// Unique name, also published as resource_name - public string Name { get; set; } + public string? Name { get; set; } /// Path prefix, matched case-insensitively on a segment boundary ("/api" covers "/api/x", not "/apix") - public string PathPrefix { get; set; } + public string? PathPrefix { get; set; } /// Canonical resource URI (RFC 8707); empty = the Store URL of the request's store + PathPrefix - public string Resource { get; set; } + public string? Resource { get; set; } /// Additional accepted "aud" values, for providers that do not put the resource URI there public List Audiences { get; set; } = []; diff --git a/src/Core/Grand.Infrastructure/Configuration/OidcResourceServerConfig.cs b/src/Core/Grand.Infrastructure/Configuration/OidcResourceServerConfig.cs index 6269a0dae..f42266c91 100644 --- a/src/Core/Grand.Infrastructure/Configuration/OidcResourceServerConfig.cs +++ b/src/Core/Grand.Infrastructure/Configuration/OidcResourceServerConfig.cs @@ -11,7 +11,7 @@ public class OidcResourceServerConfig /// /// Issuer of the identity provider; discovery document at {Authority}/.well-known/openid-configuration /// - public string Authority { get; set; } + public string? Authority { get; set; } public bool RequireHttpsMetadata { get; set; } = true; public int ClockSkewSeconds { get; set; } = 60; diff --git a/src/Core/Grand.Infrastructure/Configuration/RedisConfig.cs b/src/Core/Grand.Infrastructure/Configuration/RedisConfig.cs index 9e87ca40d..79541dfd3 100644 --- a/src/Core/Grand.Infrastructure/Configuration/RedisConfig.cs +++ b/src/Core/Grand.Infrastructure/Configuration/RedisConfig.cs @@ -10,13 +10,13 @@ public class RedisConfig /// /// Redis connection string. Used when Redis Publish/Subscribe is enabled /// - public string RedisPubSubConnectionString { get; set; } + public string? RedisPubSubConnectionString { get; set; } /// /// Messages sent by other clients to these channels will be pushed by Redis to all the subscribed clients. It must me /// the same value on every server /// - public string RedisPubSubChannel { get; set; } + public string? RedisPubSubChannel { get; set; } /// /// Indicates whether we should use Redis server for persist keys - required in farm scenario @@ -26,5 +26,5 @@ public class RedisConfig /// /// Redis connection string. Used when PersistKeysToRedis is enabled /// - public string PersistKeysToRedisUrl { get; set; } + public string? PersistKeysToRedisUrl { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Configuration/ScimConfig.cs b/src/Core/Grand.Infrastructure/Configuration/ScimConfig.cs index a0541bee1..d6d2ad23f 100644 --- a/src/Core/Grand.Infrastructure/Configuration/ScimConfig.cs +++ b/src/Core/Grand.Infrastructure/Configuration/ScimConfig.cs @@ -10,7 +10,7 @@ public class ScimConfig private const int DefaultMaxResults = 100; /// Bearer token the identity provider sends; keep it out of source control (env var Scim__Token or a secret store) - public string Token { get; set; } + public string? Token { get; set; } /// /// True: the SCIM externalId of a user is its OpenID Connect subject, and every SCIM write links the account to it, @@ -32,12 +32,13 @@ public class ScimConfig public bool TokenUsable => !string.IsNullOrEmpty(Token) && Token.Length >= MinTokenLength; /// The e-mail is in one of (case-insensitive, exact domain) - public bool IsTakeOverDomain(string email) + public bool IsTakeOverDomain(string? email) { - var at = email?.Trim().LastIndexOf('@') ?? -1; - if (at < 1 || TakeOverDomains == null) + var trimmed = email?.Trim(); + var at = trimmed?.LastIndexOf('@') ?? -1; + if (trimmed == null || at < 1 || TakeOverDomains == null) return false; - var domain = email.Trim()[(at + 1)..]; + var domain = trimmed[(at + 1)..]; return TakeOverDomains.Any(x => !string.IsNullOrWhiteSpace(x) && string.Equals(x.Trim().TrimStart('@'), domain, StringComparison.OrdinalIgnoreCase)); diff --git a/src/Core/Grand.Infrastructure/Configuration/SecurityConfig.cs b/src/Core/Grand.Infrastructure/Configuration/SecurityConfig.cs index 5dc66eda5..6bf11f60e 100644 --- a/src/Core/Grand.Infrastructure/Configuration/SecurityConfig.cs +++ b/src/Core/Grand.Infrastructure/Configuration/SecurityConfig.cs @@ -17,12 +17,12 @@ public class SecurityConfig /// /// Gets or sets a value for allowedHosts, is used for host filtering to bind your app to specific hostnames /// - public string AllowedHosts { get; set; } + public string? AllowedHosts { get; set; } /// /// Gets or sets a value for Key persistence location /// - public string KeyPersistenceLocation { get; set; } + public string? KeyPersistenceLocation { get; set; } /// /// Gets or sets a value indicating for cookie expires in hours - default 24 * 365 = 8760 @@ -32,7 +32,7 @@ public class SecurityConfig /// /// Gets or sets a value for Cookie prefix /// - public string CookiePrefix { get; set; } + public string? CookiePrefix { get; set; } /// /// Gets or sets a value for Cookie SameSite @@ -47,7 +47,7 @@ public class SecurityConfig /// /// Gets or sets a value for Cookie claim issuer /// - public string CookieClaimsIssuer { get; set; } + public string? CookieClaimsIssuer { get; set; } /// /// Gets or sets a value of "Cookie SecurePolicy Always" @@ -86,7 +86,7 @@ public class SecurityConfig /// IMPORTANT: changing this value invalidates all existing PBKDF2 hashes (affected customers must reset their /// password); legacy SHA hashes are unaffected. Set it once, before going live. /// - public string PasswordHashKey { get; set; } + public string? PasswordHashKey { get; set; } /// /// PBKDF2 (HMAC-SHA256) iteration count for newly created/upgraded password hashes. Default 210000 (OWASP 2023). @@ -100,7 +100,7 @@ public class SecurityConfig /// Matching is case-insensitive on the host only; a leading "*." matches any subdomain. /// Leave empty to fall back to the built-in video-embed defaults; set to a single empty entry to block every iframe. /// - public string[] SanitizerAllowedIframeHosts { get; set; } + public string[]? SanitizerAllowedIframeHosts { get; set; } /// /// Attributes allowed in rich-text content on top of the HtmlSanitizer defaults (href, src, alt, title, style @@ -110,7 +110,7 @@ public class SecurityConfig /// none of them. "id" is not a default: the storefront scripts look elements and globals up by id, and content /// can take those names over. /// - public string[] SanitizerAllowedAttributes { get; set; } + public string[]? SanitizerAllowedAttributes { get; set; } /// /// Hosts on the internal network that picture URLs in Excel imports may point to. Any other host must resolve to @@ -118,7 +118,7 @@ public class SecurityConfig /// reach services only the server can see. A listed host may also use a port other than 80/443. /// Matching is case-insensitive on the host only; a leading "*." matches any subdomain. Empty by default. /// - public string[] PictureImportAllowedPrivateHosts { get; set; } + public string[]? PictureImportAllowedPrivateHosts { get; set; } /// /// Gets or sets a value indicating whether [SanitizeHtml] and [NoHtml] reject markup on save. Default true. diff --git a/src/Core/Grand.Infrastructure/Extensions/CommonExtensions.cs b/src/Core/Grand.Infrastructure/Extensions/CommonExtensions.cs index 40e4f3b81..3253dae78 100644 --- a/src/Core/Grand.Infrastructure/Extensions/CommonExtensions.cs +++ b/src/Core/Grand.Infrastructure/Extensions/CommonExtensions.cs @@ -38,7 +38,7 @@ public static string ModifyQueryString(string url, string key, string value) var query = QueryHelpers.ParseQuery(queryString); - var items = query.SelectMany(x => x.Value, (col, val) => new KeyValuePair(col.Key, val)) + var items = query.SelectMany(x => x.Value, (col, val) => new KeyValuePair(col.Key, val ?? string.Empty)) .ToList(); items.RemoveAll(x => x.Key == key); diff --git a/src/Core/Grand.Infrastructure/Grand.Infrastructure.csproj b/src/Core/Grand.Infrastructure/Grand.Infrastructure.csproj index 545bdd1b0..58b661803 100644 --- a/src/Core/Grand.Infrastructure/Grand.Infrastructure.csproj +++ b/src/Core/Grand.Infrastructure/Grand.Infrastructure.csproj @@ -27,4 +27,7 @@ + + enable + \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/GrandVersion.cs b/src/Core/Grand.Infrastructure/GrandVersion.cs index deef8dd2c..0a27da5e2 100644 --- a/src/Core/Grand.Infrastructure/GrandVersion.cs +++ b/src/Core/Grand.Infrastructure/GrandVersion.cs @@ -8,12 +8,14 @@ public static class GrandVersion /// /// Gets the major version /// - public static readonly string MajorVersion = Assembly.GetExecutingAssembly().GetName().Version?.Major.ToString(); + public static readonly string MajorVersion = + Assembly.GetExecutingAssembly().GetName().Version?.Major.ToString() ?? string.Empty; /// /// Gets the minor version /// - public static readonly string MinorVersion = Assembly.GetExecutingAssembly().GetName().Version?.Minor.ToString(); + public static readonly string MinorVersion = + Assembly.GetExecutingAssembly().GetName().Version?.Minor.ToString() ?? string.Empty; /// /// Gets the full version @@ -33,7 +35,7 @@ public static class GrandVersion /// /// Gets the git branch /// - public static readonly string GitBranch = GetGitBranch(); + public static readonly string? GitBranch = GetGitBranch(); /// /// Gets the git commit @@ -57,9 +59,9 @@ public static string PatchVersion { } } - private static string _gitHash { get; set; } + private static string? _gitHash { get; set; } - private static string _gitBranch { get; set; } + private static string? _gitBranch { get; set; } private static string GetGitHash() { @@ -67,14 +69,14 @@ private static string GetGitHash() var version = "1.0.0+LOCALBUILD"; var appAssembly = typeof(GrandVersion).Assembly; - var infoVerAttr = (AssemblyInformationalVersionAttribute)appAssembly + var infoVerAttr = (AssemblyInformationalVersionAttribute?)appAssembly .GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute)).FirstOrDefault(); if (infoVerAttr is { InformationalVersion.Length: > 6 }) version = infoVerAttr.InformationalVersion; _gitHash = version[(version.IndexOf('+') + 1)..]; return _gitHash; } - private static string GetGitBranch() + private static string? GetGitBranch() { if (!string.IsNullOrEmpty(_gitBranch)) return _gitBranch; diff --git a/src/Core/Grand.Infrastructure/IStoreContext.cs b/src/Core/Grand.Infrastructure/IStoreContext.cs index a09df7981..e808c7c87 100644 --- a/src/Core/Grand.Infrastructure/IStoreContext.cs +++ b/src/Core/Grand.Infrastructure/IStoreContext.cs @@ -21,5 +21,5 @@ public interface IStoreContextSetter /// Initialize the store context /// /// - Task InitializeStoreContext(string storeId = null); + Task InitializeStoreContext(string? storeId = null); } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/IWorkContext.cs b/src/Core/Grand.Infrastructure/IWorkContext.cs index 37d8bf7f8..b0571c19f 100644 --- a/src/Core/Grand.Infrastructure/IWorkContext.cs +++ b/src/Core/Grand.Infrastructure/IWorkContext.cs @@ -54,5 +54,5 @@ public interface IWorkContextSetter /// Initialize the work context /// /// - Task InitializeWorkContext(string storeId = null); + Task InitializeWorkContext(string? storeId = null); } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Mapper/AutoMapperConfig.cs b/src/Core/Grand.Infrastructure/Mapper/AutoMapperConfig.cs index 48d56acef..54706dd8a 100644 --- a/src/Core/Grand.Infrastructure/Mapper/AutoMapperConfig.cs +++ b/src/Core/Grand.Infrastructure/Mapper/AutoMapperConfig.cs @@ -4,10 +4,12 @@ namespace Grand.Infrastructure.Mapper; public static class AutoMapperConfig { + private static IMapper? _mapper; + /// /// Mapper /// - public static IMapper Mapper { get; private set; } + public static IMapper Mapper => _mapper ?? throw new InvalidOperationException("AutoMapperConfig.Init has not been called"); /// /// Initialize mapper @@ -15,6 +17,6 @@ public static class AutoMapperConfig /// Mapper configuration public static void Init(MapperConfiguration config) { - Mapper = config.CreateMapper(); + _mapper = config.CreateMapper(); } } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Migrations/DbVersion.cs b/src/Core/Grand.Infrastructure/Migrations/DbVersion.cs index bc4ab64e4..c7f2b5fdc 100644 --- a/src/Core/Grand.Infrastructure/Migrations/DbVersion.cs +++ b/src/Core/Grand.Infrastructure/Migrations/DbVersion.cs @@ -24,8 +24,12 @@ public DbVersion(int major, int minor) /// /// /// - public int CompareTo(DbVersion otherVersion) + public int CompareTo(DbVersion? otherVersion) { + //by the IComparable convention every version follows null + if (otherVersion is null) + return 1; + if (Major != otherVersion.Major) if (Major > otherVersion.Major) return 1; diff --git a/src/Core/Grand.Infrastructure/Migrations/MigrationManager.cs b/src/Core/Grand.Infrastructure/Migrations/MigrationManager.cs index 03b29024e..33082dbb8 100644 --- a/src/Core/Grand.Infrastructure/Migrations/MigrationManager.cs +++ b/src/Core/Grand.Infrastructure/Migrations/MigrationManager.cs @@ -21,8 +21,9 @@ public IEnumerable GetAllMigrations() { return _migrationConfigurations .Where(PluginExtensions.OnlyInstalledPlugins) - .Select(mg => (IMigration)Activator.CreateInstance(mg)) - .OrderBy(mg => mg!.Priority); + .Select(mg => Activator.CreateInstance(mg)) + .OfType() + .OrderBy(mg => mg.Priority); } /// diff --git a/src/Core/Grand.Infrastructure/Migrations/MigrationResult.cs b/src/Core/Grand.Infrastructure/Migrations/MigrationResult.cs index f75122362..cb46f0633 100644 --- a/src/Core/Grand.Infrastructure/Migrations/MigrationResult.cs +++ b/src/Core/Grand.Infrastructure/Migrations/MigrationResult.cs @@ -2,6 +2,6 @@ public class MigrationResult { - public IBaseMigration Migration; + public IBaseMigration? Migration; public bool Success; } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinderProvider.cs b/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinderProvider.cs index ede85b50f..2319d78e0 100644 --- a/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinderProvider.cs +++ b/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinderProvider.cs @@ -11,7 +11,7 @@ public JsonBodyModelBinderProvider(IModelBinderProvider overriddenModelBinderPro _overriddenModelBinderProvider = overriddenModelBinderProvider; } - public IModelBinder GetBinder(ModelBinderProviderContext context) + public IModelBinder? GetBinder(ModelBinderProviderContext context) { var modelBinder = _overriddenModelBinderProvider.GetBinder(context); return modelBinder == null ? null : new JsonBodyModelBinder(modelBinder); diff --git a/src/Core/Grand.Infrastructure/Models/BaseEntityModel.cs b/src/Core/Grand.Infrastructure/Models/BaseEntityModel.cs index 4d0058f97..85f8b1f73 100644 --- a/src/Core/Grand.Infrastructure/Models/BaseEntityModel.cs +++ b/src/Core/Grand.Infrastructure/Models/BaseEntityModel.cs @@ -8,5 +8,5 @@ public class BaseEntityModel : BaseModel /// /// Gets or sets model identifier /// - public virtual string Id { get; set; } + public virtual string? Id { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Models/CaptchaModel.cs b/src/Core/Grand.Infrastructure/Models/CaptchaModel.cs index 8733b22d9..64cfbb3f1 100644 --- a/src/Core/Grand.Infrastructure/Models/CaptchaModel.cs +++ b/src/Core/Grand.Infrastructure/Models/CaptchaModel.cs @@ -2,8 +2,8 @@ public record CaptchaModel : ICaptchaValidModel { - public string ReCaptchaChallengeField { get; set; } - public string ReCaptchaResponseField { get; set; } - public string ReCaptchaResponseValue { get; set; } - public string ReCaptchaResponse { get; set; } + public string? ReCaptchaChallengeField { get; set; } + public string? ReCaptchaResponseField { get; set; } + public string? ReCaptchaResponseValue { get; set; } + public string? ReCaptchaResponse { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Models/ICaptchaValidModel.cs b/src/Core/Grand.Infrastructure/Models/ICaptchaValidModel.cs index ec7ce9cc8..e4f0b9aa4 100644 --- a/src/Core/Grand.Infrastructure/Models/ICaptchaValidModel.cs +++ b/src/Core/Grand.Infrastructure/Models/ICaptchaValidModel.cs @@ -6,8 +6,8 @@ namespace Grand.Infrastructure.Models; [InterfaceConverter(typeof(InterfaceConverter))] public interface ICaptchaValidModel { - public string ReCaptchaChallengeField { get; set; } - public string ReCaptchaResponseField { get; set; } - public string ReCaptchaResponseValue { get; set; } - public string ReCaptchaResponse { get; set; } + public string? ReCaptchaChallengeField { get; set; } + public string? ReCaptchaResponseField { get; set; } + public string? ReCaptchaResponseValue { get; set; } + public string? ReCaptchaResponse { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Modules/ModuleLoader.cs b/src/Core/Grand.Infrastructure/Modules/ModuleLoader.cs index bfdcf1f5f..15d5d8068 100644 --- a/src/Core/Grand.Infrastructure/Modules/ModuleLoader.cs +++ b/src/Core/Grand.Infrastructure/Modules/ModuleLoader.cs @@ -23,7 +23,7 @@ public static class ModuleLoader private const string LOGGER_NAME = "ModuleManager"; //the contexts of modules that failed to load; their assemblies stay loaded, so scans must skip them - private static readonly ConditionalWeakTable FailedContexts = new(); + private static readonly ConditionalWeakTable FailedContexts = new(); private static List<(string FeatureName, bool IsEnabled)> GetFeatureList(IConfiguration configuration) { @@ -105,7 +105,7 @@ internal static bool IsFailedModule(Assembly assembly) } /// The reason the module could not be loaded; null when it is loaded, or has no files to load - private static string LoadModule(string moduleName, IWebHostEnvironment hostingEnvironment, + private static string? LoadModule(string moduleName, IWebHostEnvironment hostingEnvironment, IMvcCoreBuilder mvcCoreBuilder, ILogger logger, Func createContext) { var modulePath = GetModulePath(hostingEnvironment, moduleName); @@ -118,7 +118,7 @@ private static string LoadModule(string moduleName, IWebHostEnvironment hostingE return null; } - AssemblyLoadContext context = null; + AssemblyLoadContext? context = null; try { context = createContext(moduleFile); @@ -155,7 +155,7 @@ private static string LoadModule(string moduleName, IWebHostEnvironment hostingE /// is reported here: it would fail only once a request reached the member it lacks. /// /// The reason the module cannot use its references; null when it can - private static string ResolveReferences(Assembly assembly, AssemblyLoadContext context) + private static string? ResolveReferences(Assembly assembly, AssemblyLoadContext context) { foreach (var reference in assembly.GetReferencedAssemblies()) { diff --git a/src/Core/Grand.Infrastructure/Plugins/BasePlugin.cs b/src/Core/Grand.Infrastructure/Plugins/BasePlugin.cs index 17276e550..5b8d360b2 100644 --- a/src/Core/Grand.Infrastructure/Plugins/BasePlugin.cs +++ b/src/Core/Grand.Infrastructure/Plugins/BasePlugin.cs @@ -6,7 +6,7 @@ public abstract class BasePlugin : IPlugin /// Gets a configuration page URL /// /// - public virtual string ConfigurationUrl() + public virtual string? ConfigurationUrl() { return null; } @@ -14,14 +14,14 @@ public virtual string ConfigurationUrl() /// /// Gets or sets the plugin info /// - public virtual PluginInfo PluginInfo { get; set; } + public virtual PluginInfo? PluginInfo { get; set; } /// /// Install plugin /// public virtual async Task Install() { - await PluginExtensions.MarkPluginAsInstalled(PluginInfo.SystemName); + await PluginExtensions.MarkPluginAsInstalled(SystemName); } /// @@ -29,6 +29,9 @@ public virtual async Task Install() /// public virtual async Task Uninstall() { - await PluginExtensions.MarkPluginAsUninstalled(PluginInfo.SystemName); + await PluginExtensions.MarkPluginAsUninstalled(SystemName); } + + private string SystemName => PluginInfo?.SystemName ?? + throw new InvalidOperationException($"{GetType().Name} has no plugin info"); } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Plugins/IPlugin.cs b/src/Core/Grand.Infrastructure/Plugins/IPlugin.cs index bd1ac5469..e77ae4fbe 100644 --- a/src/Core/Grand.Infrastructure/Plugins/IPlugin.cs +++ b/src/Core/Grand.Infrastructure/Plugins/IPlugin.cs @@ -9,12 +9,12 @@ public interface IPlugin /// /// Gets or sets the plugin info /// - PluginInfo PluginInfo { get; set; } + PluginInfo? PluginInfo { get; set; } /// /// Gets a configuration URL /// - string ConfigurationUrl(); + string? ConfigurationUrl(); /// /// Install plugin diff --git a/src/Core/Grand.Infrastructure/Plugins/IsolatedLoadContext.cs b/src/Core/Grand.Infrastructure/Plugins/IsolatedLoadContext.cs index 29465594c..575cfa3f9 100644 --- a/src/Core/Grand.Infrastructure/Plugins/IsolatedLoadContext.cs +++ b/src/Core/Grand.Infrastructure/Plugins/IsolatedLoadContext.cs @@ -33,7 +33,8 @@ internal IsolatedLoadContext(string name, string mainAssemblyPath, ISet ArgumentNullException.ThrowIfNull(hostAssemblyNames); _resolver = new AssemblyDependencyResolver(mainAssemblyPath); - _folder = Path.GetDirectoryName(Path.GetFullPath(mainAssemblyPath)); + _folder = Path.GetDirectoryName(Path.GetFullPath(mainAssemblyPath)) ?? + throw new ArgumentException("The main assembly path names no folder", nameof(mainAssemblyPath)); _hostAssemblyNames = hostAssemblyNames; } @@ -41,7 +42,7 @@ internal IsolatedLoadContext(string name, string mainAssemblyPath, ISet /// Null hands the name to the default context: an assembly the application provides, or one it has /// already loaded, is never loaded a second time. /// - protected override Assembly Load(AssemblyName assemblyName) + protected override Assembly? Load(AssemblyName assemblyName) { var name = assemblyName.Name; if (string.IsNullOrEmpty(name) || _hostAssemblyNames.Contains(name) || IsLoadedInDefault(name)) diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginArchiveInstaller.cs b/src/Core/Grand.Infrastructure/Plugins/PluginArchiveInstaller.cs index bf99a86f6..1816cd235 100644 --- a/src/Core/Grand.Infrastructure/Plugins/PluginArchiveInstaller.cs +++ b/src/Core/Grand.Infrastructure/Plugins/PluginArchiveInstaller.cs @@ -229,7 +229,7 @@ private static PluginManifest ReadSingleManifest(string folder) var manifests = new List(); foreach (var dll in Directory.GetFiles(folder, "*.dll", SearchOption.TopDirectoryOnly)) { - PluginManifest manifest; + PluginManifest? manifest; try { manifest = PluginManifestReader.Read(dll); @@ -257,12 +257,12 @@ private static PluginManifest ReadSingleManifest(string folder) /// The exact name of the plugin folder that names, compared case-insensitively /// on every platform; the folder with exactly that name wins when several match. Null when there is none. /// - private string ExistingFolderName(string folderName) + private string? ExistingFolderName(string folderName) { if (!Directory.Exists(pluginsPath)) return null; - var matches = Directory.GetDirectories(pluginsPath).Select(Path.GetFileName) + var matches = Directory.GetDirectories(pluginsPath).Select(x => Path.GetFileName(x)) .Where(x => !IsReservedFolder(x) && string.Equals(x, folderName, StringComparison.OrdinalIgnoreCase)) .Order(StringComparer.Ordinal) .ToList(); diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginExtensions.cs b/src/Core/Grand.Infrastructure/Plugins/PluginExtensions.cs index 06d200fff..c98556873 100644 --- a/src/Core/Grand.Infrastructure/Plugins/PluginExtensions.cs +++ b/src/Core/Grand.Infrastructure/Plugins/PluginExtensions.cs @@ -8,7 +8,7 @@ namespace Grand.Infrastructure.Plugins; public sealed class PluginPaths { - private static PluginPaths _instance; + private static PluginPaths? _instance; private static readonly Lock _lock = new(); public static PluginPaths Instance => _instance ?? throw new InvalidOperationException("PluginPaths has not been initialized. Call Initialize first."); private readonly string _pluginPath; diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginFolderScanner.cs b/src/Core/Grand.Infrastructure/Plugins/PluginFolderScanner.cs index 8d82d9cfc..35c082b72 100644 --- a/src/Core/Grand.Infrastructure/Plugins/PluginFolderScanner.cs +++ b/src/Core/Grand.Infrastructure/Plugins/PluginFolderScanner.cs @@ -46,12 +46,12 @@ public static class PluginFolderScanner { private static readonly string[] IgnoredFolders = ["bin", "TempUploads"]; - private sealed record ScannedFile(string Path, string Name, PluginManifest Manifest); + private sealed record ScannedFile(string Path, string Name, PluginManifest? Manifest); /// /// Never throws because of one folder or file: what cannot be read becomes a problem of its folder. /// - public static PluginScanResult Scan(DirectoryInfo pluginsFolder, string skipPattern, ISet hostAssemblyNames) + public static PluginScanResult Scan(DirectoryInfo pluginsFolder, string? skipPattern, ISet hostAssemblyNames) { var problems = new List(); var warnings = new List(); @@ -81,7 +81,10 @@ public static PluginScanResult Scan(DirectoryInfo pluginsFolder, string skipPatt if (files == null) continue; - var manifests = files.Where(x => x.Manifest != null).ToList(); + var manifests = new List<(ScannedFile File, PluginManifest Manifest)>(); + foreach (var file in files) + if (file.Manifest != null) + manifests.Add((file, file.Manifest)); if (manifests.Count == 0) continue; @@ -89,13 +92,12 @@ public static PluginScanResult Scan(DirectoryInfo pluginsFolder, string skipPatt if (manifests.Count > 1) { problems.Add(new PluginLoadProblem(folder.Name, - $"The folder contains {manifests.Count} plugin assemblies ({string.Join(", ", manifests.Select(x => x.Name))}); only one is allowed.", + $"The folder contains {manifests.Count} plugin assemblies ({string.Join(", ", manifests.Select(x => x.File.Name))}); only one is allowed.", manifests.Select(x => x.Manifest.SystemName).Where(x => !string.IsNullOrWhiteSpace(x)).ToList())); continue; } - var main = manifests[0]; - var manifest = main.Manifest; + var (main, manifest) = manifests[0]; if (string.IsNullOrWhiteSpace(manifest.SystemName)) { problems.Add(new PluginLoadProblem(folder.Name, "has no SystemName")); @@ -122,7 +124,7 @@ public static PluginScanResult Scan(DirectoryInfo pluginsFolder, string skipPatt /// Returns the folder's assemblies, or null when the folder or one of its files cannot be read; the /// folder is then a problem, since the unread file may be the plugin itself or one it needs. /// - private static List ScanFolder(DirectoryInfo folder, string skipPattern, + private static List? ScanFolder(DirectoryInfo folder, string? skipPattern, ISet hostAssemblyNames, List warnings, List problems) { FileInfo[] dlls; @@ -165,7 +167,7 @@ private static List ScanFolder(DirectoryInfo folder, string skipPat return result; } - private static ScannedFile ScanFile(DirectoryInfo folder, FileInfo file, ISet hostAssemblyNames, + private static ScannedFile? ScanFile(DirectoryInfo folder, FileInfo file, ISet hostAssemblyNames, List warnings) { if (!PluginManifestReader.IsManagedAssembly(file.FullName)) @@ -201,7 +203,7 @@ internal static bool IsIgnoredFolder(string name) => internal static bool IsReadFailure(Exception ex) => ex is IOException or UnauthorizedAccessException or BadImageFormatException; - internal static bool IsSkipped(string fileName, string skipPattern) => + internal static bool IsSkipped(string fileName, string? skipPattern) => !string.IsNullOrEmpty(skipPattern) && Matches(fileName, skipPattern); private static bool Matches(string fileName, string pattern) diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginInfo.cs b/src/Core/Grand.Infrastructure/Plugins/PluginInfo.cs index 0540cebc6..e1b8f0598 100644 --- a/src/Core/Grand.Infrastructure/Plugins/PluginInfo.cs +++ b/src/Core/Grand.Infrastructure/Plugins/PluginInfo.cs @@ -7,7 +7,7 @@ namespace Grand.Infrastructure.Plugins; public sealed class PluginInfo { - private Assembly _referencedAssembly; + private Assembly? _referencedAssembly; public PluginInfo( FileInfo originalAssemblyFile, @@ -31,12 +31,12 @@ public PluginInfo() /// /// Plugin type /// - public string PluginFileName { get; set; } + public string? PluginFileName { get; set; } /// /// Plugin type /// - public Type PluginType { get; set; } + public Type? PluginType { get; set; } /// /// The plugin's main assembly once it is loaded: at startup for an installed plugin, on demand @@ -45,7 +45,7 @@ public PluginInfo() /// /// Set last when a plugin loads on demand, so a request that sees it also sees /// - public Assembly ReferencedAssembly + public Assembly? ReferencedAssembly { get => Volatile.Read(ref _referencedAssembly); internal set => Volatile.Write(ref _referencedAssembly, value); @@ -55,54 +55,54 @@ public Assembly ReferencedAssembly /// The scanned folder loads; null when there is nothing to load /// on demand (the plugin loaded at startup, is built for another version, or was not found by a scan) /// - internal PluginCandidate Candidate { get; set; } + internal PluginCandidate? Candidate { get; set; } /// /// The plugin's own load context, once loading it began; it holds the plugin's assemblies, also those of /// a plugin that failed to load. Null for a plugin that was not loaded. /// - internal AssemblyLoadContext LoadContext { get; set; } + internal AssemblyLoadContext? LoadContext { get; set; } /// /// The original assembly file that a shadow copy was made from it /// - public FileInfo OriginalAssemblyFile { get; internal set; } + public FileInfo? OriginalAssemblyFile { get; internal set; } /// /// The plugin's folder in Plugins; together with it tells apart two folders /// declaring the same system name, and it is known also for a folder whose plugin could not be identified /// - public string FolderName { get; internal set; } + public string? FolderName { get; internal set; } /// /// Gets or sets the plugin group /// - public string Group { get; set; } + public string? Group { get; set; } /// /// Gets or sets the friendly name /// - public string FriendlyName { get; set; } + public string? FriendlyName { get; set; } /// /// Gets or sets the system name /// - public string SystemName { get; set; } + public string? SystemName { get; set; } /// /// Gets or sets the version /// - public string Version { get; set; } + public string? Version { get; set; } /// /// Gets or sets the supported version /// - public string SupportedVersion { get; set; } + public string? SupportedVersion { get; set; } /// /// Gets or sets the author /// - public string Author { get; set; } + public string? Author { get; set; } /// /// Gets or sets the display order @@ -117,7 +117,7 @@ public Assembly ReferencedAssembly /// /// Why the plugin could not be loaded; null when it loaded /// - public string LoadError { get; internal set; } + public string? LoadError { get; internal set; } /// /// Simple names of the plugin's assemblies, compared case-insensitively. Taken from the plugin @@ -137,7 +137,7 @@ public Assembly ReferencedAssembly /// so it is created with its constructor dependencies taken from . /// /// The plugin cannot be loaded or created - public T Instance(IServiceProvider serviceProvider) where T : class, IPlugin + public T? Instance(IServiceProvider serviceProvider) where T : class, IPlugin { if (ReferencedAssembly == null && LoadError == null) PluginManager.LoadForInstall(this); @@ -168,7 +168,7 @@ public T Instance(IServiceProvider serviceProvider) where T : class, IPlugin return typedInstance; } - public IPlugin Instance(IServiceProvider serviceProvider) + public IPlugin? Instance(IServiceProvider serviceProvider) { return Instance(serviceProvider); } diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginInfoAttribute.cs b/src/Core/Grand.Infrastructure/Plugins/PluginInfoAttribute.cs index aba23d772..b00905475 100644 --- a/src/Core/Grand.Infrastructure/Plugins/PluginInfoAttribute.cs +++ b/src/Core/Grand.Infrastructure/Plugins/PluginInfoAttribute.cs @@ -13,7 +13,7 @@ public class PluginInfoAttribute : Attribute /// it is then resolved from the assembly's Grand.Infrastructure reference by /// . /// - public string SupportedVersion { get; set; } + public string? SupportedVersion { get; set; } - public string Version { get; set; } + public string? Version { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginLoadSnapshot.cs b/src/Core/Grand.Infrastructure/Plugins/PluginLoadSnapshot.cs index c7b935067..df69b6da5 100644 --- a/src/Core/Grand.Infrastructure/Plugins/PluginLoadSnapshot.cs +++ b/src/Core/Grand.Infrastructure/Plugins/PluginLoadSnapshot.cs @@ -20,16 +20,16 @@ private sealed record LoadedFolder(string SystemName, FileStamp Stamp); private sealed record FileStamp(long Length, DateTime LastWriteTimeUtc, int Count); private readonly string _pluginsFolder; - private readonly IPluginStateStore _stateStore; - private readonly string _skipPattern; + private readonly IPluginStateStore? _stateStore; + private readonly string? _skipPattern; private readonly HashSet _installed; private readonly Dictionary _otherFolders; private readonly Dictionary _plugins; - private readonly ILogger _logger; + private readonly ILogger? _logger; - private PluginLoadSnapshot(string pluginsFolder, IPluginStateStore stateStore, string skipPattern, + private PluginLoadSnapshot(string pluginsFolder, IPluginStateStore? stateStore, string? skipPattern, HashSet installed, Dictionary otherFolders, Dictionary plugins, - ILogger logger) + ILogger? logger) { _pluginsFolder = pluginsFolder; _stateStore = stateStore; @@ -49,8 +49,8 @@ private PluginLoadSnapshot(string pluginsFolder, IPluginStateStore stateStore, s /// /// Told when the database cannot be read while comparing internal static PluginLoadSnapshot Capture(DirectoryInfo pluginsFolder, PluginScanResult scan, - IEnumerable installedSystemNames, IPluginStateStore stateStore, string skipPattern, - ILogger logger = null) + IEnumerable installedSystemNames, IPluginStateStore? stateStore, string? skipPattern, + ILogger? logger = null) { var plugins = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var candidate in scan.Plugins) @@ -145,7 +145,7 @@ private string FolderOf(string systemName) /// /// The first plugin manifest among the folder's top-level assemblies, read from metadata /// - private PluginManifest ReadManifest(string folder) + private PluginManifest? ReadManifest(string folder) { foreach (var file in Files(folder)) { @@ -192,7 +192,7 @@ private static List Files(string folder) /// /// The plugin folder names; null when the Plugins folder cannot be listed /// - private static List Folders(string pluginsFolder) + private static List? Folders(string pluginsFolder) { try { diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginLoader.cs b/src/Core/Grand.Infrastructure/Plugins/PluginLoader.cs index 0b98c34a0..97252f9e5 100644 --- a/src/Core/Grand.Infrastructure/Plugins/PluginLoader.cs +++ b/src/Core/Grand.Infrastructure/Plugins/PluginLoader.cs @@ -54,7 +54,7 @@ string Prepared(string path) => //assemblies it never ships, and it would fail here although it works at runtime. //Every assembly is loaded before any type is resolved, so the order of the files does not matter var pluginCode = assemblies.Where(x => x == main || IsPluginCode(x)).ToList(); - Type pluginType = null; + Type? pluginType = null; foreach (var assembly in pluginCode) { var types = assembly.GetTypes(); diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs b/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs index 4a907bb72..06fb422df 100644 --- a/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs +++ b/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs @@ -42,15 +42,15 @@ public static class PluginManager #region Fields - private static DirectoryInfo _copyFolder; - private static DirectoryInfo _pluginFolder; - private static ExtensionsConfig _config; - private static ILogger _logger; + private static DirectoryInfo? _copyFolder; + private static DirectoryInfo? _pluginFolder; + private static ExtensionsConfig? _config; + private static ILogger? _logger; //what LoadForInstall needs to load a plugin as Load would have - private static Func, AssemblyLoadContext> _createContext; - private static ISet _hostAssemblyNames; - private static Func _prepareFolder; + private static Func, AssemblyLoadContext>? _createContext; + private static ISet? _hostAssemblyNames; + private static Func? _prepareFolder; private static bool _useLiteDb; #endregion @@ -60,17 +60,20 @@ public static class PluginManager /// /// Returns a collection of all referenced plugin assemblies that have been shadow copied /// - public static IEnumerable ReferencedPlugins { get; set; } + public static IEnumerable? ReferencedPlugins { get; set; } /// /// Where the plugins are recorded as installed; set before /// - public static IPluginStateStore StateStore { get; internal set; } + public static IPluginStateStore? StateStore { get; internal set; } + + private static IPluginStateStore RequiredStateStore => + StateStore ?? throw new InvalidOperationException("PluginManager.StateStore is not set"); /// /// What saw on disk; null until plugins are loaded /// - internal static PluginLoadSnapshot LoadSnapshot { get; set; } + internal static PluginLoadSnapshot? LoadSnapshot { get; set; } /// /// Whether this application records the plugins in the database: only the storefront does. The admin, store @@ -114,7 +117,7 @@ internal static void Load(IMvcCoreBuilder mvcCoreBuilder, IConfiguration configu { ArgumentNullException.ThrowIfNull(mvcCoreBuilder); - _logger = mvcCoreBuilder.Services.BuildServiceProvider().GetService() + _logger = mvcCoreBuilder.Services.BuildServiceProvider().GetRequiredService() .CreateLogger("PluginManager"); _pluginFolder = new DirectoryInfo(Path.Combine(hostEnvironment.ContentRootPath, CommonPath.Plugins)); @@ -124,9 +127,9 @@ internal static void Load(IMvcCoreBuilder mvcCoreBuilder, IConfiguration configu //storefront takes its file over: the admin, store and vendor applications kept files of their own RecordsPluginState = hostEnvironment.ApplicationName == StorefrontApplicationName; var installedByConfiguration = !string.IsNullOrEmpty(_config.InstalledPlugins); - var installedPluginSystemNames = installedByConfiguration + var installedPluginSystemNames = !string.IsNullOrEmpty(_config.InstalledPlugins) ? _config.InstalledPlugins.Split(",").Select(x => x.Trim()).ToList() - : ReadInstalledPlugins(StateStore, + : ReadInstalledPlugins(RequiredStateStore, RecordsPluginState ? PluginPaths.Instance.InstalledPluginsFile : null, _logger); _logger.LogInformation("Creating shadow copy folder and querying for dlls"); @@ -185,7 +188,10 @@ internal static void Load(IMvcCoreBuilder mvcCoreBuilder, IConfiguration configu _createContext = createContext; _hostAssemblyNames = hostAssemblyNames; - _prepareFolder = _config.PluginShadowCopy ? ShadowCopyFolder : candidate => candidate.Folder; + var copyFolder = _copyFolder; + _prepareFolder = _config.PluginShadowCopy + ? candidate => ShadowCopyFolder(candidate, copyFolder) + : candidate => candidate.Folder; _useLiteDb = dbConfig.UseLiteDb; foreach (var candidate in scan.Plugins) @@ -209,7 +215,8 @@ internal static void Load(IMvcCoreBuilder mvcCoreBuilder, IConfiguration configu continue; } - var plugin = PluginLoader.Load(candidate, true, ContextFactory(candidate), _prepareFolder); + var plugin = PluginLoader.Load(candidate, true, ContextFactory(candidate, createContext, hostAssemblyNames), + _prepareFolder); referencedPlugins.Add(plugin); //controllers and views only for an installed plugin - an uninstalled one must not be routable @@ -224,7 +231,8 @@ internal static void Load(IMvcCoreBuilder mvcCoreBuilder, IConfiguration configu } } - if (plugin.LoadError != null) + //a plugin without a load error has its type; checked so the registration below cannot get null + if (plugin.LoadError != null || plugin.PluginType == null) { _logger.LogError("Plugin folder {PluginFolder} could not be loaded: {LoadError}", candidate.Folder.Name, plugin.LoadError); @@ -268,11 +276,12 @@ public static PluginInfo LoadForInstall(PluginInfo plugin) { var candidate = plugin.Candidate; if (plugin.ReferencedAssembly != null || plugin.LoadError != null || candidate == null || - _createContext == null) + _createContext == null || _hostAssemblyNames == null || _prepareFolder == null) return plugin; _logger?.LogInformation("Loading plugin {PluginSystemName} to install it", plugin.SystemName); - var loaded = PluginLoader.Load(candidate, plugin.Installed, ContextFactory(candidate), _prepareFolder); + var loaded = PluginLoader.Load(candidate, plugin.Installed, + ContextFactory(candidate, _createContext, _hostAssemblyNames), _prepareFolder); //warming here races with concurrent LiteDB reads: every entity mapper lives in one shared //BsonMapper.Global dictionary, read without a lock, so a request reading any type while these few //inserts run can fail. Accepted: the window is a few inserts during an admin-initiated install, and @@ -304,7 +313,7 @@ public static PluginInfo LoadForInstall(PluginInfo plugin) /// /// Type /// Plugin descriptor if exists; otherwise null - public static PluginInfo FindPlugin(Type typeAssembly) + public static PluginInfo? FindPlugin(Type typeAssembly) { ArgumentNullException.ThrowIfNull(typeAssembly); @@ -317,7 +326,7 @@ public static PluginInfo FindPlugin(Type typeAssembly) /// /// Assembly /// Plugin descriptor if exists; otherwise null - public static PluginInfo FindPlugin(Assembly assembly) + public static PluginInfo? FindPlugin(Assembly assembly) { ArgumentNullException.ThrowIfNull(assembly); @@ -338,7 +347,7 @@ public static PluginInfo FindPlugin(Assembly assembly) /// The plugin whose own load context holds the assembly; null for an assembly of the default context or /// of a context no plugin owns /// - internal static PluginInfo OwnerOf(Assembly assembly, IEnumerable plugins) + internal static PluginInfo? OwnerOf(Assembly assembly, IEnumerable? plugins) { var context = AssemblyLoadContext.GetLoadContext(assembly); if (context == null || context == AssemblyLoadContext.Default || plugins == null) @@ -353,7 +362,7 @@ internal static PluginInfo OwnerOf(Assembly assembly, IEnumerable pl /// public static async Task ClearPlugins() { - await StateStore.Clear(); + await RequiredStateStore.Clear(); var filePath = PluginPaths.Instance.InstalledPluginsFile; if (File.Exists(filePath)) @@ -377,9 +386,12 @@ public static void SaveLoadResults() var loadedOnUtc = DateTime.UtcNow; try { - StateStore.SaveLoadResults(plugins.Where(x => !string.IsNullOrEmpty(x.SystemName)) - .Select(x => new PluginState(x.SystemName, x.FriendlyName, x.Version, - x.FolderName ?? x.OriginalAssemblyFile?.Directory?.Name, RejectionOf(x), loadedOnUtc))); + var states = new List(); + foreach (var x in plugins) + if (!string.IsNullOrEmpty(x.SystemName)) + states.Add(new PluginState(x.SystemName, x.FriendlyName, x.Version, + x.FolderName ?? x.OriginalAssemblyFile?.Directory?.Name, RejectionOf(x), loadedOnUtc)); + StateStore.SaveLoadResults(states); } catch (Exception ex) { @@ -402,8 +414,8 @@ public static void SaveLoadResults() /// The database could not be read, or the file to take over is not valid: an empty list would deactivate /// every plugin /// - internal static List ReadInstalledPlugins(IPluginStateStore store, string installedPluginsFile, - ILogger logger) + internal static List ReadInstalledPlugins(IPluginStateStore store, string? installedPluginsFile, + ILogger? logger) { ArgumentNullException.ThrowIfNull(store); @@ -423,16 +435,16 @@ internal static List ReadInstalledPlugins(IPluginStateStore store, strin } } - private static void TakeFileOver(IPluginStateStore store, string installedPluginsFile, ILogger logger) + private static void TakeFileOver(IPluginStateStore store, string installedPluginsFile, ILogger? logger) { try { - IList fromFile = null; + IList? fromFile = null; //a blank entry named no plugin in the file either if (store.ImportInstalled(() => fromFile = PluginExtensions.ParseInstalledPluginsFile(installedPluginsFile) .Where(x => !string.IsNullOrWhiteSpace(x)).ToList())) logger?.LogInformation("Installed plugins taken over from {InstalledPluginsFile}: {SystemNames}", - installedPluginsFile, string.Join(", ", fromFile)); + installedPluginsFile, string.Join(", ", fromFile ?? [])); else logger?.LogWarning( "{InstalledPluginsFile} ignored: the database lists the installed plugins already", @@ -451,7 +463,7 @@ private static void TakeFileOver(IPluginStateStore store, string installedPlugin /// The database has the list now; the file is kept under another name, never read again. A file that cannot /// be renamed (a read-only App_Data) is ignored on every start that follows, so it must not stop this one. /// - private static void RenameTakenOverFile(string installedPluginsFile, ILogger logger) + private static void RenameTakenOverFile(string installedPluginsFile, ILogger? logger) { try { @@ -471,7 +483,7 @@ private static void RenameTakenOverFile(string installedPluginsFile, ILogger log /// /// Why the plugin is not running: its load error, or a version it was not built for /// - private static string RejectionOf(PluginInfo plugin) + private static string? RejectionOf(PluginInfo plugin) { if (plugin.LoadError != null) return plugin.LoadError; @@ -489,21 +501,21 @@ internal static HashSet HostAssemblyNames() { var trusted = AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") as string ?? string.Empty; var names = trusted.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries) - .Select(Path.GetFileNameWithoutExtension) + .Select(x => Path.GetFileNameWithoutExtension(x)) .ToHashSet(StringComparer.OrdinalIgnoreCase); names.UnionWith(AssemblyLoadContext.Default.Assemblies .Select(x => x.GetName().Name) - .Where(x => !string.IsNullOrEmpty(x))); + .OfType() + .Where(x => x.Length > 0)); return names; } /// /// Creates the candidate's own context once its folder is prepared and its main assembly path is known /// - private static Func ContextFactory(PluginCandidate candidate) + private static Func ContextFactory(PluginCandidate candidate, + Func, AssemblyLoadContext> createContext, ISet hostAssemblyNames) { - var createContext = _createContext; - var hostAssemblyNames = _hostAssemblyNames; return mainAssemblyPath => createContext(candidate.Manifest.SystemName, mainAssemblyPath, hostAssemblyNames); } @@ -512,10 +524,13 @@ private static Func ContextFactory(PluginCandidate /// build while requests read them (see ), and requests are running here: /// see the accepted race at the call site. Returns the error, if any. /// - private static string WarmLiteDbMappers(PluginInfo plugin) + private static string? WarmLiteDbMappers(PluginInfo plugin) { try { + if (plugin.LoadContext == null) + return $"Plugin {plugin.SystemName} has no load context"; + var assemblies = plugin.LoadContext.Assemblies .Where(x => plugin.AssemblyNames.Contains(x.GetName().Name, StringComparer.OrdinalIgnoreCase)) .ToList(); @@ -534,10 +549,10 @@ private static string WarmLiteDbMappers(PluginInfo plugin) /// size or last write time differs from the copy's. Only this plugin's copy is touched. /// /// The folder to load the plugin from - private static DirectoryInfo ShadowCopyFolder(PluginCandidate candidate) + private static DirectoryInfo ShadowCopyFolder(PluginCandidate candidate, DirectoryInfo copyFolder) { var source = candidate.Folder; - var target = new DirectoryInfo(Path.Combine(_copyFolder.FullName, source.Name)); + var target = new DirectoryInfo(Path.Combine(copyFolder.FullName, source.Name)); var copies = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (var file in source.GetFiles("*", SearchOption.AllDirectories)) @@ -559,7 +574,7 @@ private static DirectoryInfo ShadowCopyFolder(PluginCandidate candidate) } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { - _logger.LogWarning(ex, "Stale shadow copy {FullName} could not be deleted", stale.FullName); + _logger?.LogWarning(ex, "Stale shadow copy {FullName} could not be deleted", stale.FullName); } return target; @@ -575,7 +590,7 @@ private static void CopyFile(FileInfo source, FileInfo copy) { //a copy in use (another process still running from it, or a debugger) cannot be overwritten, but it //can be renamed, which frees its name; the renamed file is removed as stale by a later start - _logger.LogInformation("{FullName} is locked, attempting to rename", copy.FullName); + _logger?.LogInformation("{FullName} is locked, attempting to rename", copy.FullName); File.Move(copy.FullName, copy.FullName + "." + Guid.NewGuid().ToString("N") + ".old"); File.Copy(source.FullName, copy.FullName, true); } @@ -587,12 +602,15 @@ private static void CopyFile(FileInfo source, FileInfo copy) /// /// Adds the plugin's controllers and views; returns the error when its parts cannot be read /// - private static string AddApplicationPart(IMvcCoreBuilder mvcCoreBuilder, PluginInfo plugin) + private static string? AddApplicationPart(IMvcCoreBuilder mvcCoreBuilder, PluginInfo plugin) { try { //we can now register the plugin definition - _logger.LogInformation("Adding to ApplicationParts: '{0}'", plugin.SystemName); + if (plugin.ReferencedAssembly == null) + return $"Plugin {plugin.SystemName} has no assembly"; + + _logger?.LogInformation("Adding to ApplicationParts: '{0}'", plugin.SystemName); //related parts are read first, so a failure adds nothing var relatedParts = RelatedAssemblyAttribute.GetRelatedAssemblies(plugin.ReferencedAssembly, false) diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginManifest.cs b/src/Core/Grand.Infrastructure/Plugins/PluginManifest.cs index 432c41fa8..71ae82d48 100644 --- a/src/Core/Grand.Infrastructure/Plugins/PluginManifest.cs +++ b/src/Core/Grand.Infrastructure/Plugins/PluginManifest.cs @@ -8,8 +8,8 @@ namespace Grand.Infrastructure.Plugins; /// public sealed record PluginManifest( string SystemName, - string FriendlyName, - string Group, - string Author, - string Version, - string SupportedVersion); + string? FriendlyName, + string? Group, + string? Author, + string? Version, + string? SupportedVersion); diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginManifestReader.cs b/src/Core/Grand.Infrastructure/Plugins/PluginManifestReader.cs index dfa9ecd1b..2e936b449 100644 --- a/src/Core/Grand.Infrastructure/Plugins/PluginManifestReader.cs +++ b/src/Core/Grand.Infrastructure/Plugins/PluginManifestReader.cs @@ -33,7 +33,7 @@ public static bool IsManagedAssembly(string path) /// The file cannot be opened or read /// The file cannot be opened /// The attribute cannot be decoded - public static PluginManifest Read(string assemblyPath) + public static PluginManifest? Read(string assemblyPath) { using var stream = File.OpenRead(assemblyPath); using var peReader = new PEReader(stream); @@ -48,14 +48,15 @@ public static PluginManifest Read(string assemblyPath) if (!IsPluginInfoAttribute(reader, attribute.Constructor)) continue; - var named = new Dictionary(StringComparer.Ordinal); + var named = new Dictionary(StringComparer.Ordinal); foreach (var argument in attribute.DecodeValue(provider).NamedArguments) if (!named.TryAdd(argument.Name!, argument.Value as string)) throw new BadImageFormatException( $"The PluginInfo attribute of '{Path.GetFileName(assemblyPath)}' sets {argument.Name} more than once."); + //a manifest without a system name is rejected by the scanner, as one with an empty name is return new PluginManifest( - named.GetValueOrDefault(nameof(PluginInfoAttribute.SystemName)), + named.GetValueOrDefault(nameof(PluginInfoAttribute.SystemName)) ?? string.Empty, named.GetValueOrDefault(nameof(PluginInfoAttribute.FriendlyName)), named.GetValueOrDefault(nameof(PluginInfoAttribute.Group)), named.GetValueOrDefault(nameof(PluginInfoAttribute.Author)), @@ -82,7 +83,7 @@ private static bool HasMetadata(PEReader peReader) } } - private static Version GetCoreReference(MetadataReader reader) + private static Version? GetCoreReference(MetadataReader reader) { foreach (var handle in reader.AssemblyReferences) { diff --git a/src/Core/Grand.Infrastructure/Plugins/PluginVersionResolver.cs b/src/Core/Grand.Infrastructure/Plugins/PluginVersionResolver.cs index 60b56e599..a9c1fe6a8 100644 --- a/src/Core/Grand.Infrastructure/Plugins/PluginVersionResolver.cs +++ b/src/Core/Grand.Infrastructure/Plugins/PluginVersionResolver.cs @@ -20,7 +20,7 @@ public static class PluginVersionResolver /// such a plugin cannot be matched against and is /// therefore treated as incompatible. /// - public static string ResolveSupportedVersion(Assembly pluginAssembly, string declaredVersion) + public static string? ResolveSupportedVersion(Assembly pluginAssembly, string declaredVersion) { var coreReference = pluginAssembly?.GetReferencedAssemblies() .FirstOrDefault(x => string.Equals(x.Name, CoreAssemblyName, StringComparison.OrdinalIgnoreCase)); @@ -33,7 +33,7 @@ public static string ResolveSupportedVersion(Assembly pluginAssembly, string dec /// /// The version of the plugin's Grand.Infrastructure reference, if it has one /// The version declared on , if any - public static string ResolveSupportedVersion(Version coreReference, string declaredVersion) + public static string? ResolveSupportedVersion(Version? coreReference, string? declaredVersion) { if (!string.IsNullOrWhiteSpace(declaredVersion)) return declaredVersion.Trim(); diff --git a/src/Core/Grand.Infrastructure/Roslyn/ResultCompiler.cs b/src/Core/Grand.Infrastructure/Roslyn/ResultCompiler.cs index 1e48db417..aa39b5843 100644 --- a/src/Core/Grand.Infrastructure/Roslyn/ResultCompiler.cs +++ b/src/Core/Grand.Infrastructure/Roslyn/ResultCompiler.cs @@ -4,9 +4,9 @@ namespace Grand.Infrastructure.Roslyn; public class ResultCompiler { - public Assembly ReferencedAssembly { get; internal set; } - public string OriginalFile { get; internal set; } - public virtual string DLLAssemblyFile { get; internal set; } + public Assembly? ReferencedAssembly { get; internal set; } + public string? OriginalFile { get; internal set; } + public virtual string? DLLAssemblyFile { get; internal set; } public bool IsCompiled { get; internal set; } public IList ErrorInfo { get; internal set; } = new List(); } \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/Roslyn/RoslynCompiler.cs b/src/Core/Grand.Infrastructure/Roslyn/RoslynCompiler.cs index 48d546fdc..57939b90a 100644 --- a/src/Core/Grand.Infrastructure/Roslyn/RoslynCompiler.cs +++ b/src/Core/Grand.Infrastructure/Roslyn/RoslynCompiler.cs @@ -15,14 +15,14 @@ public static class RoslynCompiler { #region Fields - private static DirectoryInfo _shadowCopyScriptPath; + private static DirectoryInfo? _shadowCopyScriptPath; #endregion /// /// Returns a collection of all referenced assemblies /// - public static IEnumerable ReferencedScripts { get; set; } + public static IEnumerable? ReferencedScripts { get; set; } public static void Load(ApplicationPartManager applicationPartManager, IConfiguration configuration, IWebHostEnvironment webHostEnvironment) { diff --git a/src/Core/Grand.Infrastructure/Security/HtmlSanitizationService.cs b/src/Core/Grand.Infrastructure/Security/HtmlSanitizationService.cs index 5642fd99e..af71fd949 100644 --- a/src/Core/Grand.Infrastructure/Security/HtmlSanitizationService.cs +++ b/src/Core/Grand.Infrastructure/Security/HtmlSanitizationService.cs @@ -111,12 +111,12 @@ public bool ContainsDisallowedRichText(string html) var disallowedContentSeen = false; - void MarkDisallowed(object sender, EventArgs e) + void MarkDisallowed(object? sender, EventArgs e) { disallowedContentSeen = true; } - void OnFilterUrl(object sender, FilterUrlEventArgs e) + void OnFilterUrl(object? sender, FilterUrlEventArgs e) { var url = e.SanitizedUrl ?? e.OriginalUrl; if (string.IsNullOrWhiteSpace(url)) return; @@ -175,7 +175,7 @@ public bool ContainsMarkup(string text) var disallowedContentSeen = false; - void MarkDisallowed(object sender, EventArgs e) + void MarkDisallowed(object? sender, EventArgs e) { disallowedContentSeen = true; } @@ -201,12 +201,12 @@ void MarkDisallowed(object sender, EventArgs e) return disallowedContentSeen; } - private static bool HasOwnAttributes(AngleSharp.Dom.IElement element) + private static bool HasOwnAttributes(AngleSharp.Dom.IElement? element) { return element is not null && element.Attributes.Length > 0; } - private static string[] ResolveAllowedIframeHosts(SecurityConfig securityConfig) + private static string[] ResolveAllowedIframeHosts(SecurityConfig? securityConfig) { //absent configuration means "use the defaults"; a configured but empty list means "frame nothing" if (securityConfig?.SanitizerAllowedIframeHosts is null) return DefaultAllowedIframeHosts; @@ -217,7 +217,7 @@ private static string[] ResolveAllowedIframeHosts(SecurityConfig securityConfig) .ToArray(); } - private static string[] ResolveAllowedAttributes(SecurityConfig securityConfig) + private static string[] ResolveAllowedAttributes(SecurityConfig? securityConfig) { //absent configuration means "use the defaults"; a configured but empty list means "none on top of the library's" if (securityConfig?.SanitizerAllowedAttributes is null) return DefaultAllowedAttributes; diff --git a/src/Core/Grand.Infrastructure/Startup/AuditInfoProvider.cs b/src/Core/Grand.Infrastructure/Startup/AuditInfoProvider.cs index 1b8c8bb0e..09df35518 100644 --- a/src/Core/Grand.Infrastructure/Startup/AuditInfoProvider.cs +++ b/src/Core/Grand.Infrastructure/Startup/AuditInfoProvider.cs @@ -13,7 +13,7 @@ public AuditInfoProvider(IHttpContextAccessor contextAccessor) _contextAccessor = contextAccessor; } - public string GetCurrentUser() + public string? GetCurrentUser() { return _contextAccessor.HttpContext?.User.FindFirst(ClaimTypes.Name)?.Value; } diff --git a/src/Core/Grand.Infrastructure/StartupBase.cs b/src/Core/Grand.Infrastructure/StartupBase.cs index d84ea2e73..fa53ecd53 100644 --- a/src/Core/Grand.Infrastructure/StartupBase.cs +++ b/src/Core/Grand.Infrastructure/StartupBase.cs @@ -64,7 +64,7 @@ private static IPluginStateStore CreatePluginStateStore(IConfiguration configura var dbConfig = new DatabaseConfig(); configuration.GetSection("Database").Bind(dbConfig); - static string ConnectionString() => DataSettingsManager.Instance.LoadSettings().ConnectionString; + static string? ConnectionString() => DataSettingsManager.Instance.LoadSettings().ConnectionString; return dbConfig.UseLiteDb ? new LiteDBPluginStateStore(ConnectionString) @@ -83,8 +83,9 @@ private static void InitAutoMapper(ITypeSearcher typeSearcher) //create and sort instances of mapper configurations var instances = mapperConfigurations .Where(PluginExtensions.OnlyInstalledPlugins) - .Select(mapperConfiguration => (IAutoMapperProfile)Activator.CreateInstance(mapperConfiguration)) - .OrderBy(mapperConfiguration => mapperConfiguration!.Order); + .Select(mapperConfiguration => Activator.CreateInstance(mapperConfiguration)) + .OfType() + .OrderBy(mapperConfiguration => mapperConfiguration.Order); //create AutoMapper configuration var config = new MapperConfiguration(cfg => @@ -107,8 +108,9 @@ private static void RegisterTypeConverter(ITypeSearcher typeSearcher) //create and sort instances of typeConverter var instances = converters - .Select(converter => (ITypeConverter)Activator.CreateInstance(converter)) - .OrderBy(converter => converter!.Order); + .Select(converter => Activator.CreateInstance(converter)) + .OfType() + .OrderBy(converter => converter.Order); foreach (var item in instances) item.Register(); @@ -282,8 +284,9 @@ public static void ConfigureServices(IServiceCollection services, IConfiguration //instantiate once - the same instances serve both configuration passes var startupInstances = typeSearcher.ClassesOfType() .Where(PluginExtensions.OnlyInstalledPlugins) - .Select(startup => (IStartupApplication)Activator.CreateInstance(startup)) - .OrderBy(startup => startup!.Priority) + .Select(startup => Activator.CreateInstance(startup)) + .OfType() + .OrderBy(startup => startup.Priority) .ToList(); //configure services @@ -338,8 +341,9 @@ public static void ConfigureRequestPipeline(WebApplication application, //create and sort instances of startup configurations var instances = startupConfigurations .Where(PluginExtensions.OnlyInstalledPlugins) - .Select(startup => (IStartupApplication)Activator.CreateInstance(startup)) - .OrderBy(startup => startup!.Priority); + .Select(startup => Activator.CreateInstance(startup)) + .OfType() + .OrderBy(startup => startup.Priority); //configure request pipeline foreach (var instance in instances) @@ -352,8 +356,9 @@ private static void ExecuteStartupBase(ITypeSearcher typeSearcher) //create and sort instances of startup configurations var instances = startupBaseConfigurations - .Select(startup => (IStartupBase)Activator.CreateInstance(startup)) - .OrderBy(startup => startup!.Priority); + .Select(startup => Activator.CreateInstance(startup)) + .OfType() + .OrderBy(startup => startup.Priority); //execute foreach (var instance in instances) diff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/BoolTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/BoolTypeConverter.cs index 53ffa1313..877a60945 100644 --- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/BoolTypeConverter.cs +++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/BoolTypeConverter.cs @@ -5,7 +5,7 @@ namespace Grand.Infrastructure.TypeConverters.Converter; public class BoolTypeConverter : BooleanConverter { - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) { try { diff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/CustomAttributeListTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/CustomAttributeListTypeConverter.cs index d8d1a91a0..b5db9f867 100644 --- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/CustomAttributeListTypeConverter.cs +++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/CustomAttributeListTypeConverter.cs @@ -7,15 +7,15 @@ namespace Grand.Infrastructure.TypeConverters.Converter; public class CustomAttributeListTypeConverter : TypeConverter { - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) { if (value is not string valueStr) return base.ConvertFrom(context, culture, value); - List customAttributes = null; + List? customAttributes = null; if (string.IsNullOrEmpty(valueStr)) return null; try { @@ -29,7 +29,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c return customAttributes; } - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { if (destinationType == typeof(string)) diff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericDictionaryTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericDictionaryTypeConverter.cs index ba33ab971..a65793fd9 100644 --- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericDictionaryTypeConverter.cs +++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericDictionaryTypeConverter.cs @@ -8,7 +8,7 @@ namespace Grand.Infrastructure.TypeConverters.Converter; /// /// Key type (simple) /// Value type (simple) -public class GenericDictionaryTypeConverter : TypeConverter +public class GenericDictionaryTypeConverter : TypeConverter where K : notnull { private readonly TypeConverter _typeConverterKey; private readonly TypeConverter _typeConverterValue; @@ -34,7 +34,7 @@ public GenericDictionaryTypeConverter() /// Context /// Source type /// Result - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } @@ -46,7 +46,7 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT /// Culture /// Value /// Result - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) { if (value is not string input) return base.ConvertFrom(context, culture, value); var items = string.IsNullOrEmpty(input) @@ -79,7 +79,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// Value /// Destination type /// Result - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType); diff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericListTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericListTypeConverter.cs index 71f02d0e9..ca2452a3a 100644 --- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericListTypeConverter.cs +++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericListTypeConverter.cs @@ -42,7 +42,7 @@ protected virtual string[] GetStringArray(string input) /// Context /// Source type /// Result - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) { if (sourceType != typeof(string)) return base.CanConvertFrom(context, sourceType); var items = GetStringArray(sourceType.ToString()); @@ -56,7 +56,7 @@ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceT /// Culture /// Value /// Result - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) { if (value is not string strValue) return base.ConvertFrom(context, culture, value); var items = GetStringArray(strValue); @@ -78,7 +78,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c /// Value /// Destination type /// Result - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType); diff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/RefreshTokenTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/RefreshTokenTypeConverter.cs index f3cb301ae..da73c023f 100644 --- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/RefreshTokenTypeConverter.cs +++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/RefreshTokenTypeConverter.cs @@ -7,15 +7,15 @@ namespace Grand.Infrastructure.TypeConverters.Converter; public class RefreshTokenTypeConverter : TypeConverter { - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) { if (value is not string valueStr) return base.ConvertFrom(context, culture, value); - RefreshToken refreshToken = null; + RefreshToken? refreshToken = null; if (string.IsNullOrEmpty(valueStr)) return null; try { @@ -29,7 +29,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c return refreshToken; } - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType); diff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionListTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionListTypeConverter.cs index c6cc59197..7df001e5f 100644 --- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionListTypeConverter.cs +++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionListTypeConverter.cs @@ -7,15 +7,15 @@ namespace Grand.Infrastructure.TypeConverters.Converter; public class ShippingOptionListTypeConverter : TypeConverter { - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) { if (value is not string valueStr) return base.ConvertFrom(context, culture, value); - List shippingOptions = null; + List? shippingOptions = null; if (string.IsNullOrEmpty(valueStr)) return null; try { @@ -29,7 +29,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c return shippingOptions; } - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { if (destinationType == typeof(string)) diff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionTypeConverter.cs index 0cd0a02fd..9873e4632 100644 --- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionTypeConverter.cs +++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionTypeConverter.cs @@ -7,15 +7,15 @@ namespace Grand.Infrastructure.TypeConverters.Converter; public class ShippingOptionTypeConverter : TypeConverter { - public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) + public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) { return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType); } - public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) + public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) { if (value is not string valueStr) return base.ConvertFrom(context, culture, value); - ShippingOption shippingOption = null; + ShippingOption? shippingOption = null; if (string.IsNullOrEmpty(valueStr)) return null; try { @@ -29,7 +29,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c return shippingOption; } - public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) { if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType); diff --git a/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/InterfaceConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/InterfaceConverter.cs index 597722266..87116f1ce 100644 --- a/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/InterfaceConverter.cs +++ b/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/InterfaceConverter.cs @@ -5,7 +5,7 @@ namespace Grand.Infrastructure.TypeConverters.JsonConverters; public class InterfaceConverter : JsonConverter where TConcrete : TInterface, new() { - public override TInterface Read( + public override TInterface? Read( ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) @@ -21,7 +21,7 @@ public override void Write( switch (value) { case null: - JsonSerializer.Serialize(writer, null, options); + writer.WriteNullValue(); break; default: { diff --git a/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/StringConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/StringConverter.cs index 8b9023b50..f6bd5397f 100644 --- a/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/StringConverter.cs +++ b/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/StringConverter.cs @@ -5,7 +5,7 @@ namespace Grand.Infrastructure.TypeConverters.JsonConverters; public class StringConverter : JsonConverter { - public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { switch (reader.TokenType) { diff --git a/src/Core/Grand.Infrastructure/TypeSearch/TypeSearcher.cs b/src/Core/Grand.Infrastructure/TypeSearch/TypeSearcher.cs index ec0ba8544..1854db2b0 100644 --- a/src/Core/Grand.Infrastructure/TypeSearch/TypeSearcher.cs +++ b/src/Core/Grand.Infrastructure/TypeSearch/TypeSearcher.cs @@ -23,12 +23,12 @@ public class TypeSearcher : ITypeSearcher private sealed record AssemblySnapshot( int AppDomainAssemblyCount, - IEnumerable ReferencedPlugins, - IEnumerable ReferencedScripts, + IEnumerable? ReferencedPlugins, + IEnumerable? ReferencedScripts, IList Assemblies); //Replaced as a whole, never mutated. A race only costs one redundant recomputation. - private static volatile AssemblySnapshot _snapshot; + private static volatile AssemblySnapshot? _snapshot; private static IList CachedAssemblies() { @@ -51,7 +51,7 @@ private static IList AssembliesInAppDomain() { //one assembly per load context: plugins shipping the same library each load their own copy, and each //plugin's code uses the types of its own - var addedAssemblies = new HashSet<(AssemblyLoadContext, string)>(); + var addedAssemblies = new HashSet<(AssemblyLoadContext?, string?)>(); var assemblies = new List(); var currentAssem = Assembly.GetExecutingAssembly(); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) @@ -74,10 +74,11 @@ private static IList AssembliesInAppDomain() if (RoslynCompiler.ReferencedScripts == null) return assemblies; foreach (var scripts in RoslynCompiler.ReferencedScripts) { - if (string.IsNullOrEmpty(scripts.ReferencedAssembly.FullName)) continue; - var key = (AssemblyLoadContext.GetLoadContext(scripts.ReferencedAssembly), scripts.ReferencedAssembly.FullName); + var scriptAssembly = scripts.ReferencedAssembly; + if (scriptAssembly == null || string.IsNullOrEmpty(scriptAssembly.FullName)) continue; + var key = (AssemblyLoadContext.GetLoadContext(scriptAssembly), scriptAssembly.FullName); if (addedAssemblies.Contains(key)) continue; - assemblies.Add(scripts.ReferencedAssembly); + assemblies.Add(scriptAssembly); addedAssemblies.Add(key); } diff --git a/src/Core/Grand.Infrastructure/Validators/NoHtmlAttribute.cs b/src/Core/Grand.Infrastructure/Validators/NoHtmlAttribute.cs index d72503031..ff8c98e17 100644 --- a/src/Core/Grand.Infrastructure/Validators/NoHtmlAttribute.cs +++ b/src/Core/Grand.Infrastructure/Validators/NoHtmlAttribute.cs @@ -11,11 +11,11 @@ namespace Grand.Infrastructure.Validators; [AttributeUsage(AttributeTargets.Property)] public class NoHtmlAttribute() : ValidationAttribute("{0} must be plain text and cannot contain HTML markup.") { - protected override ValidationResult IsValid(object value, ValidationContext validationContext) + protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) { if (value is not string text || string.IsNullOrWhiteSpace(text)) return ValidationResult.Success; - var sanitizationService = (IHtmlSanitizationService)validationContext + var sanitizationService = (IHtmlSanitizationService?)validationContext .GetService(typeof(IHtmlSanitizationService)); if (sanitizationService is null) diff --git a/src/Core/Grand.Infrastructure/Validators/SanitizeHtmlAttribute.cs b/src/Core/Grand.Infrastructure/Validators/SanitizeHtmlAttribute.cs index 42360c83c..092601e2c 100644 --- a/src/Core/Grand.Infrastructure/Validators/SanitizeHtmlAttribute.cs +++ b/src/Core/Grand.Infrastructure/Validators/SanitizeHtmlAttribute.cs @@ -17,11 +17,11 @@ namespace Grand.Infrastructure.Validators; [AttributeUsage(AttributeTargets.Property)] public class SanitizeHtmlAttribute() : ValidationAttribute("{0} contains HTML markup that is not allowed.") { - protected override ValidationResult IsValid(object value, ValidationContext validationContext) + protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) { if (value is not string html || string.IsNullOrWhiteSpace(html)) return ValidationResult.Success; - var sanitizationService = (IHtmlSanitizationService)validationContext + var sanitizationService = (IHtmlSanitizationService?)validationContext .GetService(typeof(IHtmlSanitizationService)); if (sanitizationService is null) diff --git a/src/Core/Grand.Infrastructure/Validators/ValidationFilter.cs b/src/Core/Grand.Infrastructure/Validators/ValidationFilter.cs index c9b92622b..0463b05e8 100644 --- a/src/Core/Grand.Infrastructure/Validators/ValidationFilter.cs +++ b/src/Core/Grand.Infrastructure/Validators/ValidationFilter.cs @@ -46,7 +46,7 @@ public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionE foreach (var interfaceType in implementedInterfaces) { var genericType = typeof(IValidator<>).MakeGenericType(interfaceType); - var validator = (IValidator)_serviceProvider.GetService(genericType); + var validator = (IValidator?)_serviceProvider.GetService(genericType); if (validator is null) continue; var contextValidator = new ValidationContext(argument.Value); diff --git a/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs b/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs index eb418c231..e3764e299 100644 --- a/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs +++ b/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs @@ -142,7 +142,7 @@ public static bool ArraysEqual(T[] a1, T[] a2) /// /// /// - public static bool IsSimpleType(Type type) + public static bool IsSimpleType(Type? type) { if (type == null) return true; From 02b5e541b12604cbf1b047d1912a1df84ba40d97 Mon Sep 17 00:00:00 2001 From: support Date: Wed, 25 Nov 2026 08:32:34 +0100 Subject: [PATCH 06/30] Enable nullable in Grand.Business.Core The service contracts plugins build against. Result types created with a null member (ExternalAuthResult, OidcLoginResult, CatalogAccess, ...) say so in their constructors; CatalogAccess.ShowHidden tells the compiler that a catalog access limited to a customer has one. ISettingService.GetSettingByKey returns T? - the default value when the setting is missing. GenerateSlug and EnsureMaximumLength return null only for null input. --- .../SendNotificationsToSubscribersCommand.cs | 6 +- .../Catalog/SendOutBidCustomerCommand.cs | 6 +- .../SendQuantityBelowStoreOwnerCommand.cs | 4 +- .../UpdateProductReviewTotalsCommand.cs | 2 +- ...tivatedValueForPurchasedVouchersCommand.cs | 2 +- .../Orders/AddCustomerReservationCommand.cs | 8 +-- .../Orders/AddRequiredProductsCommand.cs | 8 +-- .../ApplyOrderApprovalDecisionCommand.cs | 10 +-- .../Orders/AwardLoyaltyPointsCommand.cs | 2 +- .../Orders/CalculateLoyaltyPointsCommand.cs | 2 +- .../Checkout/Orders/CancelOrderCommand.cs | 2 +- .../Checkout/Orders/CancelOrderItemCommand.cs | 4 +- .../Orders/CancelRecurringPaymentCommand.cs | 4 +- .../Checkout/Orders/CaptureCommand.cs | 4 +- .../Orders/CheckOrderStatusCommand.cs | 2 +- .../Orders/DecideStoreOrderApprovalCommand.cs | 8 +-- .../Checkout/Orders/DeleteOrderCommand.cs | 2 +- .../Checkout/Orders/DeleteOrderItemCommand.cs | 4 +- .../Checkout/Orders/InsertOrderItemCommand.cs | 6 +- .../Orders/MarkAsAuthorizedCommand.cs | 4 +- .../Checkout/Orders/MarkAsPaidCommand.cs | 8 +-- .../Orders/PartiallyPaidOfflineCommand.cs | 8 +-- .../Checkout/Orders/PartiallyRefundCommand.cs | 8 +-- .../Orders/PartiallyRefundOfflineCommand.cs | 8 +-- .../Checkout/Orders/PlaceOrderCommand.cs | 10 +-- .../Orders/PlaceRecurringCycleOrderCommand.cs | 4 +- .../Orders/ProcessOrderPaidCommand.cs | 2 +- .../Checkout/Orders/ReOrderCommand.cs | 4 +- .../RecordRecurringPaymentCycleCommand.cs | 6 +- .../RecordRecurringPaymentEndedCommand.cs | 4 +- .../RecordRecurringPaymentFailureCommand.cs | 8 +-- .../RecordRecurringPaymentReferenceCommand.cs | 4 +- .../Orders/ReduceLoyaltyPointsCommand.cs | 2 +- .../Commands/Checkout/Orders/RefundCommand.cs | 4 +- .../Checkout/Orders/RefundOfflineCommand.cs | 8 +-- .../ReturnBackRedeemedLoyaltyPointsCommand.cs | 2 +- .../Checkout/Orders/SetOrderStatusCommand.cs | 2 +- .../Checkout/Orders/UpdateOrderItemCommand.cs | 4 +- ...ateMinShoppingCartSubtotalAmountCommand.cs | 4 +- .../Commands/Checkout/Orders/VoidCommand.cs | 4 +- .../Checkout/Orders/VoidOfflineCommand.cs | 4 +- .../Checkout/Shipping/DeliveryCommand.cs | 2 +- .../Commands/Checkout/Shipping/ShipCommand.cs | 2 +- .../Commands/Customers/ActiveVendorCommand.cs | 2 +- .../Messages/Common/InsertContactUsCommand.cs | 22 +++--- .../Common/OrderNotificationCommand.cs | 8 +-- .../System/Common/GetSitemapXmlCommand.cs | 4 +- .../Grand.Business.Core/Dto/BrandDto.cs | 26 +++---- .../Grand.Business.Core/Dto/CategoryDto.cs | 32 ++++----- .../Grand.Business.Core/Dto/CollectionDto.cs | 26 +++---- .../Dto/CountryStatesDto.cs | 6 +- .../Dto/ProductAttributeDto.cs | 12 ++-- .../Grand.Business.Core/Dto/ProductDto.cs | 68 +++++++++---------- .../Dto/ProductVariantsDto.cs | 24 +++---- .../Dto/SpecificationAttributeDto.cs | 12 ++-- .../Enums/Checkout/ShipmentStatusEvent.cs | 6 +- .../Customers/CustomerLoginFailedEvent.cs | 2 +- .../Events/Marketing/EmailSubscribedEvent.cs | 2 +- .../Marketing/EmailUnsubscribedEvent.cs | 2 +- .../Extensions/AffiliateExtensions.cs | 4 +- .../Extensions/LanguageServiceExtensions.cs | 2 +- .../Extensions/MerchandiseReturnExtensions.cs | 2 +- .../MerchandiseReturnShippingExtensions.cs | 9 +-- .../Extensions/PaymentExtensions.cs | 2 +- .../ProductReservationExtensions.cs | 2 +- .../Extensions/SeoExtensions.cs | 29 ++++---- .../Extensions/TranslateExtensions.cs | 8 +-- .../Grand.Business.Core.csproj | 3 + .../Inventory/IInventoryDocumentService.cs | 10 +-- .../Catalog/Inventory/IProductUnitService.cs | 12 ++-- .../Products/IInventoryManageService.cs | 2 +- .../Catalog/Products/IProductReviewService.cs | 2 +- .../Catalog/Products/IProductService.cs | 10 +-- .../Interfaces/Catalog/Tax/ITaxService.cs | 2 +- .../GiftVouchers/IGiftVoucherService.cs | 4 +- .../Orders/IMerchandiseReturnLabelService.cs | 2 +- .../Orders/IMerchandiseReturnRefundService.cs | 4 +- .../IMerchandiseReturnWorkflowService.cs | 6 +- .../Checkout/Orders/IOrderApprovalService.cs | 4 +- .../Checkout/Orders/IOrderService.cs | 8 +-- .../Checkout/Orders/IShoppingCartService.cs | 12 ++-- .../Checkout/Payments/IPaymentService.cs | 4 +- .../IPaymentTransactionHistoryService.cs | 4 +- .../Shipping/IReturnShippingService.cs | 2 +- .../Checkout/Shipping/IShipmentService.cs | 4 +- .../Shipping/IShippingMethodService.cs | 2 +- .../Checkout/Shipping/IShippingService.cs | 8 +-- .../Shipping/IWarehouseLocationService.cs | 2 +- .../Interfaces/Cms/IBlogService.cs | 2 +- .../Interfaces/Cms/IWidgetService.cs | 6 +- .../Common/Audit/AuditEntrySearch.cs | 12 ++-- .../Common/Configuration/ISettingService.cs | 2 +- .../Localization/IPluginTranslateResource.cs | 2 +- .../Interfaces/Customers/IAffiliateService.cs | 4 +- .../Interfaces/Customers/ICustomerService.cs | 12 ++-- .../Interfaces/Customers/IVendorService.cs | 4 +- .../INewsLetterSubscriptionService.cs | 4 +- .../IPushNotificationsService.cs | 2 +- .../ICatalogMessageProviderService.cs | 8 +-- .../Messages/ICmsMessageProviderService.cs | 6 +- .../ICustomerMessageProviderService.cs | 18 ++--- .../Interfaces/Messages/IEmailSender.cs | 8 +-- ...MerchandiseReturnMessageProviderService.cs | 8 +-- .../Messages/IMessageProviderService.cs | 10 +-- .../INewsletterMessageProviderService.cs | 4 +- .../Messages/IOrderMessageProviderService.cs | 14 ++-- .../Messages/IVendorMessageProviderService.cs | 6 +- .../Interfaces/Storage/IFileStore.cs | 6 +- .../Interfaces/Storage/IPictureService.cs | 12 ++-- .../System/Reports/IOrderReportService.cs | 6 +- .../Catalog/GetDiscountUsageHistoryQuery.cs | 6 +- .../Catalog/GetPersonalizedProductsQuery.cs | 4 +- .../Catalog/GetPriceByCustomerProductQuery.cs | 4 +- .../Catalog/GetProductArchByIdQuery.cs | 2 +- .../Catalog/GetRecommendedProductsQuery.cs | 4 +- .../Queries/Catalog/GetSearchProductsQuery.cs | 12 ++-- .../GetShoppingCartItemsSubTotalQuery.cs | 4 +- .../Catalog/GetSitemapProductsQuery.cs | 6 +- .../Catalog/GetSuggestedProductsQuery.cs | 4 +- .../Queries/Catalog/GetVendorByIdQuery.cs | 2 +- .../Checkout/Orders/CanCancelOrderQuery.cs | 2 +- .../Checkout/Orders/CanCaptureQuery.cs | 2 +- .../CanDeletePaymentTransactionQuery.cs | 2 +- ...MarkPaymentTransactionAsAuthorizedQuery.cs | 2 +- .../CanMarkPaymentTransactionAsPaidQuery.cs | 2 +- .../Orders/CanPartiallyPaidOfflineQuery.cs | 2 +- .../Orders/CanPartiallyRefundOfflineQuery.cs | 2 +- .../Orders/CanPartiallyRefundQuery.cs | 2 +- .../Checkout/Orders/CanRefundOfflineQuery.cs | 2 +- .../Queries/Checkout/Orders/CanRefundQuery.cs | 2 +- .../Checkout/Orders/CanVoidOfflineQuery.cs | 2 +- .../Queries/Checkout/Orders/CanVoidQuery.cs | 2 +- .../Checkout/Orders/GetGiftVoucherQuery.cs | 2 +- .../Orders/GetMerchandiseReturnCountQuery.cs | 2 +- .../Queries/Checkout/Orders/GetOrderQuery.cs | 10 +-- .../Orders/GetPaymentTransactionQuery.cs | 6 +- .../Checkout/Orders/GetPickupPointById.cs | 2 +- .../Orders/GetRecurringPaymentsQuery.cs | 6 +- .../Orders/GetReturnableQuantitiesQuery.cs | 2 +- .../Checkout/Orders/GetVendorsInOrderQuery.cs | 2 +- .../Orders/IsMerchandiseReturnAllowedQuery.cs | 2 +- .../Queries/Customers/GetCustomerQuery.cs | 22 +++--- .../Customers/GetPasswordIsExpiredQuery.cs | 2 +- .../Messages/GetBidsByProductIdQuery.cs | 2 +- .../Queries/Messages/GetCustomerByIdQuery.cs | 2 +- .../Queries/Messages/GetProductByIdQuery.cs | 2 +- .../Queries/Messages/GetVendorByIdQuery.cs | 2 +- .../Authentication/ExternalAuthParam.cs | 10 +-- .../Authentication/ExternalAuthResult.cs | 4 +- .../Authentication/OidcCustomerResult.cs | 6 +- .../Authentication/OidcLoginResult.cs | 4 +- .../Authentication/OidcRefreshResult.cs | 2 +- .../Authentication/PasswordSignInDecision.cs | 2 +- .../Utilities/Authentication/ScimResults.cs | 4 +- .../Utilities/Catalog/ApplyDiscount.cs | 4 +- .../Utilities/Catalog/CatalogAccess.cs | 6 +- .../Catalog/DiscountRuleValidationRequest.cs | 8 +-- .../Catalog/DiscountRuleValidationResult.cs | 2 +- .../Catalog/DiscountValidationResult.cs | 4 +- .../Utilities/Catalog/InventoryTracking.cs | 4 +- .../Utilities/Catalog/ProductsCategory.cs | 2 +- .../Utilities/Catalog/ProductsCollection.cs | 2 +- .../Utilities/Catalog/SearchTermReportLine.cs | 2 +- .../Utilities/Catalog/StockBuckets.cs | 5 +- .../Utilities/Catalog/StockChange.cs | 6 +- .../Utilities/Catalog/TaxRequest.cs | 10 +-- .../Utilities/Catalog/VatRequest.cs | 4 +- .../Utilities/Catalog/VatResponse.cs | 8 +-- .../Utilities/Checkout/AppliedGiftVoucher.cs | 2 +- .../Checkout/CapturePaymentResult.cs | 4 +- .../Utilities/Checkout/CheckoutClaim.cs | 8 +-- .../Checkout/GetShippingOptionRequest.cs | 16 ++--- .../Checkout/MerchandiseReturnRefundQuote.cs | 4 +- .../MerchandiseReturnSubmitRequest.cs | 18 ++--- .../Checkout/OrderPlacementContext.cs | 2 +- .../Checkout/OrderPlacementRuleResult.cs | 2 +- .../Utilities/Checkout/PlaceOrderContainer.cs | 36 +++++----- .../Utilities/Checkout/PlaceOrderResult.cs | 4 +- .../Checkout/PurchaseOrderNumberRules.cs | 4 +- .../Utilities/Checkout/RecurringCycleClaim.cs | 2 +- .../Checkout/RecurringReportResult.cs | 2 +- .../Checkout/RefundPaymentRequest.cs | 2 +- .../Utilities/Checkout/ReturnShipping.cs | 46 ++++++------- .../Utilities/ExportImport/PropertyByName.cs | 6 +- .../Utilities/Messages/CampaignRecipient.cs | 8 +-- .../System/BestCustomerReportLine.cs | 2 +- .../Utilities/System/BestsellersReportLine.cs | 2 +- .../System/CustomerByTimeReportLine.cs | 2 +- .../System/MerchandiseReturnReportLine.cs | 4 +- .../System/OrderByCountryReportLine.cs | 2 +- .../Utilities/System/OrderByTimeReportLine.cs | 2 +- .../System/ProductsAttributeCombination.cs | 2 +- .../Extensions/CommonHelper.cs | 4 +- 193 files changed, 607 insertions(+), 593 deletions(-) diff --git a/src/Business/Grand.Business.Core/Commands/Catalog/SendNotificationsToSubscribersCommand.cs b/src/Business/Grand.Business.Core/Commands/Catalog/SendNotificationsToSubscribersCommand.cs index 325943bb8..8c5100f82 100644 --- a/src/Business/Grand.Business.Core/Commands/Catalog/SendNotificationsToSubscribersCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Catalog/SendNotificationsToSubscribersCommand.cs @@ -6,7 +6,7 @@ namespace Grand.Business.Core.Commands.Catalog; public class SendNotificationsToSubscribersCommand : IRequest> { - public Product Product { get; set; } - public IList Attributes { get; set; } - public string Warehouse { get; set; } + public Product? Product { get; set; } + public IList? Attributes { get; set; } + public string? Warehouse { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Catalog/SendOutBidCustomerCommand.cs b/src/Business/Grand.Business.Core/Commands/Catalog/SendOutBidCustomerCommand.cs index 719307abf..7374121d7 100644 --- a/src/Business/Grand.Business.Core/Commands/Catalog/SendOutBidCustomerCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Catalog/SendOutBidCustomerCommand.cs @@ -6,7 +6,7 @@ namespace Grand.Business.Core.Commands.Catalog; public class SendOutBidCustomerCommand : IRequest { - public Product Product { get; set; } - public Bid Bid { get; set; } - public Language Language { get; set; } + public Product? Product { get; set; } + public Bid? Bid { get; set; } + public Language? Language { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Catalog/SendQuantityBelowStoreOwnerCommand.cs b/src/Business/Grand.Business.Core/Commands/Catalog/SendQuantityBelowStoreOwnerCommand.cs index 082ba0053..8d6c349fc 100644 --- a/src/Business/Grand.Business.Core/Commands/Catalog/SendQuantityBelowStoreOwnerCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Catalog/SendQuantityBelowStoreOwnerCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Catalog; public class SendQuantityBelowStoreOwnerCommand : IRequest { - public Product Product { get; set; } - public ProductAttributeCombination ProductAttributeCombination { get; set; } + public Product? Product { get; set; } + public ProductAttributeCombination? ProductAttributeCombination { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Catalog/UpdateProductReviewTotalsCommand.cs b/src/Business/Grand.Business.Core/Commands/Catalog/UpdateProductReviewTotalsCommand.cs index b90fb9861..6588dff0c 100644 --- a/src/Business/Grand.Business.Core/Commands/Catalog/UpdateProductReviewTotalsCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Catalog/UpdateProductReviewTotalsCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Commands.Catalog; public class UpdateProductReviewTotalsCommand : IRequest { - public Product Product { get; set; } + public Product? Product { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ActivatedValueForPurchasedVouchersCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ActivatedValueForPurchasedVouchersCommand.cs index 988e3c1b4..89a5f390c 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ActivatedValueForPurchasedVouchersCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ActivatedValueForPurchasedVouchersCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class ActivatedValueForPurchasedGiftVouchersCommand : IRequest { - public Order Order { get; set; } + public Order? Order { get; set; } public bool Activate { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddCustomerReservationCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddCustomerReservationCommand.cs index bfec495a5..8c9c8ace9 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddCustomerReservationCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddCustomerReservationCommand.cs @@ -7,10 +7,10 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class AddCustomerReservationCommand : IRequest { - public Customer Customer { get; set; } - public Product Product { get; set; } + public Customer? Customer { get; set; } + public Product? Product { get; set; } public DateTime? RentalStartDate { get; set; } public DateTime? RentalEndDate { get; set; } - public ShoppingCartItem ShoppingCartItem { get; set; } - public string ReservationId { get; set; } + public ShoppingCartItem? ShoppingCartItem { get; set; } + public string? ReservationId { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddRequiredProductsCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddRequiredProductsCommand.cs index c630f70c1..d3b09e3f0 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddRequiredProductsCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddRequiredProductsCommand.cs @@ -8,13 +8,13 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class AddRequiredProductsCommand : IRequest { - public Customer Customer { get; set; } + public Customer? Customer { get; set; } public ShoppingCartType ShoppingCartType { get; set; } - public Product Product { get; set; } - public string StoreId { get; set; } + public Product? Product { get; set; } + public string? StoreId { get; set; } /// /// Language the cart warnings are written in /// - public Language Language { get; set; } + public Language? Language { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ApplyOrderApprovalDecisionCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ApplyOrderApprovalDecisionCommand.cs index 6216d6e5f..1cd2e6b13 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ApplyOrderApprovalDecisionCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ApplyOrderApprovalDecisionCommand.cs @@ -12,14 +12,14 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; /// public class ApplyOrderApprovalDecisionCommand : IRequest { - public OrderApproval Approval { get; set; } - public Customer DecidedBy { get; set; } + public OrderApproval? Approval { get; set; } + public Customer? DecidedBy { get; set; } public bool Approve { get; set; } - public string Comment { get; set; } - public Language Language { get; set; } + public string? Comment { get; set; } + public Language? Language { get; set; } /// /// Host of the storefront request; empty in a back office panel, links then use the store's primary domain /// - public DomainHost Host { get; set; } + public DomainHost? Host { get; set; } } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AwardLoyaltyPointsCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AwardLoyaltyPointsCommand.cs index 1ae197db8..a6236df27 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AwardLoyaltyPointsCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AwardLoyaltyPointsCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class AwardLoyaltyPointsCommand : IRequest { - public Order Order { get; set; } + public Order? Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CalculateLoyaltyPointsCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CalculateLoyaltyPointsCommand.cs index b300ac68d..7bec44c30 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CalculateLoyaltyPointsCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CalculateLoyaltyPointsCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class CalculateLoyaltyPointsCommand : IRequest { - public Customer Customer { get; set; } + public Customer? Customer { get; set; } public double Amount { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelOrderCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelOrderCommand.cs index d10cb1db9..347949ed9 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelOrderCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelOrderCommand.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class CancelOrderCommand : IRequest { - public Order Order { get; set; } + public Order? Order { get; set; } public bool NotifyCustomer { get; set; } public bool NotifyStoreOwner { get; set; } = false; } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelOrderItemCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelOrderItemCommand.cs index 8f16ad25a..36ab44398 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelOrderItemCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelOrderItemCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class CancelOrderItemCommand : IRequest<(bool error, string message)> { - public Order Order { get; set; } - public OrderItem OrderItem { get; set; } + public Order? Order { get; set; } + public OrderItem? OrderItem { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelRecurringPaymentCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelRecurringPaymentCommand.cs index 7d4690a44..8e6ab889b 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelRecurringPaymentCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelRecurringPaymentCommand.cs @@ -10,10 +10,10 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; /// public class CancelRecurringPaymentCommand : IRequest { - public RecurringPayment RecurringPayment { get; set; } + public RecurringPayment? RecurringPayment { get; set; } /// /// Who cancelled it: the customer's e-mail, the staff name, or the reason /// - public string CancelledBy { get; set; } + public string? CancelledBy { get; set; } } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CaptureCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CaptureCommand.cs index e66e0bf7e..860385a57 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CaptureCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CaptureCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class CaptureCommand : IRequest> { - public PaymentTransaction PaymentTransaction { get; set; } - public string CreatedBy { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } + public string? CreatedBy { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CheckOrderStatusCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CheckOrderStatusCommand.cs index b4ffd4d99..20ed1ae03 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CheckOrderStatusCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CheckOrderStatusCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class CheckOrderStatusCommand : IRequest { - public Order Order { get; set; } + public Order? Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DecideStoreOrderApprovalCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DecideStoreOrderApprovalCommand.cs index 6bd0924b2..a986646ae 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DecideStoreOrderApprovalCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DecideStoreOrderApprovalCommand.cs @@ -11,9 +11,9 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; /// public class DecideStoreOrderApprovalCommand : IRequest { - public Order Order { get; set; } - public Customer DecidedBy { get; set; } + public Order? Order { get; set; } + public Customer? DecidedBy { get; set; } public bool Approve { get; set; } - public string Comment { get; set; } - public Language Language { get; set; } + public string? Comment { get; set; } + public Language? Language { get; set; } } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DeleteOrderCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DeleteOrderCommand.cs index f46ca3017..d4e9fd939 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DeleteOrderCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DeleteOrderCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class DeleteOrderCommand : IRequest { - public Order Order { get; set; } + public Order? Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DeleteOrderItemCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DeleteOrderItemCommand.cs index 6a3f8d121..d18a89c11 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DeleteOrderItemCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DeleteOrderItemCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class DeleteOrderItemCommand : IRequest<(bool error, string message)> { - public Order Order { get; set; } - public OrderItem OrderItem { get; set; } + public Order? Order { get; set; } + public OrderItem? OrderItem { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/InsertOrderItemCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/InsertOrderItemCommand.cs index e8fafd6cd..278299b48 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/InsertOrderItemCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/InsertOrderItemCommand.cs @@ -6,7 +6,7 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class InsertOrderItemCommand : IRequest { - public Order Order { get; set; } - public OrderItem OrderItem { get; set; } - public Product Product { get; set; } + public Order? Order { get; set; } + public OrderItem? OrderItem { get; set; } + public Product? Product { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/MarkAsAuthorizedCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/MarkAsAuthorizedCommand.cs index c61308723..6af859ccb 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/MarkAsAuthorizedCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/MarkAsAuthorizedCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class MarkAsAuthorizedCommand : IRequest { - public PaymentTransaction PaymentTransaction { get; set; } - public string CreatedBy { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } + public string? CreatedBy { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/MarkAsPaidCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/MarkAsPaidCommand.cs index 6bb76ff13..37f123024 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/MarkAsPaidCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/MarkAsPaidCommand.cs @@ -5,14 +5,14 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class MarkAsPaidCommand : IRequest { - public PaymentTransaction PaymentTransaction { get; set; } - public string CreatedBy { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } + public string? CreatedBy { get; set; } /// /// The amount the payment method reports it took; the history records what was still to pay when not given /// public double? Amount { get; set; } - public string Reference { get; set; } - public string Note { get; set; } + public string? Reference { get; set; } + public string? Note { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyPaidOfflineCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyPaidOfflineCommand.cs index 7f9a358e4..34cf91a9b 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyPaidOfflineCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyPaidOfflineCommand.cs @@ -5,9 +5,9 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class PartiallyPaidOfflineCommand : IRequest { - public PaymentTransaction PaymentTransaction { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } public double AmountToPaid { get; set; } - public string CreatedBy { get; set; } - public string Reference { get; set; } - public string Note { get; set; } + public string? CreatedBy { get; set; } + public string? Reference { get; set; } + public string? Note { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyRefundCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyRefundCommand.cs index 315ed365a..dc05d3ec2 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyRefundCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyRefundCommand.cs @@ -5,9 +5,9 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class PartiallyRefundCommand : IRequest> { - public PaymentTransaction PaymentTransaction { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } public double AmountToRefund { get; set; } - public string CreatedBy { get; set; } - public string Reference { get; set; } - public string Note { get; set; } + public string? CreatedBy { get; set; } + public string? Reference { get; set; } + public string? Note { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyRefundOfflineCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyRefundOfflineCommand.cs index a6097db5a..5ede0f12c 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyRefundOfflineCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyRefundOfflineCommand.cs @@ -5,9 +5,9 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class PartiallyRefundOfflineCommand : IRequest { - public PaymentTransaction PaymentTransaction { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } public double AmountToRefund { get; set; } - public string CreatedBy { get; set; } - public string Reference { get; set; } - public string Note { get; set; } + public string? CreatedBy { get; set; } + public string? Reference { get; set; } + public string? Note { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceOrderCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceOrderCommand.cs index be0181851..90d0ac717 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceOrderCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceOrderCommand.cs @@ -11,25 +11,25 @@ public class PlaceOrderCommand : IRequest /// /// Customer, store, working currency and tax display the order is calculated for (required) /// - public CalculationContext Context { get; set; } + public CalculationContext? Context { get; set; } /// /// Language used when the customer has no published language of their own (required) /// - public Language Language { get; set; } + public Language? Language { get; set; } /// /// Store address used for file download links in the checkout attribute description (required) /// - public DomainHost Host { get; set; } + public DomainHost? Host { get; set; } /// /// Staff member who places the order while impersonating the customer, if any /// - public Customer OriginalCustomerIfImpersonated { get; set; } + public Customer? OriginalCustomerIfImpersonated { get; set; } /// /// Buyer's own purchase order number, if any /// - public string PurchaseOrderNumber { get; set; } + public string? PurchaseOrderNumber { get; set; } } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceRecurringCycleOrderCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceRecurringCycleOrderCommand.cs index 34c07ab28..2b1bdda59 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceRecurringCycleOrderCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceRecurringCycleOrderCommand.cs @@ -12,10 +12,10 @@ public class PlaceRecurringCycleOrderCommand : IRequest /// /// The recurring payment the cycle belongs to /// - public RecurringPayment RecurringPayment { get; set; } + public RecurringPayment? RecurringPayment { get; set; } /// /// The cycle the gateway reported, already claimed: its order identifier is the one the order is inserted with /// - public RecurringPaymentCycle Cycle { get; set; } + public RecurringPaymentCycle? Cycle { get; set; } } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ProcessOrderPaidCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ProcessOrderPaidCommand.cs index e0890a5c0..d7cdaaae5 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ProcessOrderPaidCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ProcessOrderPaidCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class ProcessOrderPaidCommand : IRequest { - public Order Order { get; set; } + public Order? Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReOrderCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReOrderCommand.cs index e61701ebb..8894c456b 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReOrderCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReOrderCommand.cs @@ -6,10 +6,10 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class ReOrderCommand : IRequest> { - public Order Order { get; set; } + public Order? Order { get; set; } /// /// Language the returned warnings are written in /// - public Language Language { get; set; } + public Language? Language { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs index 299d0f3bb..2f6838dbd 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs @@ -12,17 +12,17 @@ public class RecordRecurringPaymentCycleCommand : IRequest /// /// The recurring payment the provider was given as gateway metadata /// - public string RecurringPaymentId { get; set; } + public string? RecurringPaymentId { get; set; } /// /// The provider's reference of the subscription /// - public string ProviderReference { get; set; } + public string? ProviderReference { get; set; } /// /// The provider's reference of the cycle (the invoice or charge), so a resent report is recorded once /// - public string CycleReference { get; set; } + public string? CycleReference { get; set; } /// /// The amount paid, in the units of diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs index 32c207c15..83c8bb1e0 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs @@ -8,11 +8,11 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; /// public class RecordRecurringPaymentEndedCommand : IRequest { - public string RecurringPaymentId { get; set; } + public string? RecurringPaymentId { get; set; } /// /// The provider's reference of what ended (for example the subscription id), so the end of another /// subscription started for the same order does not cancel the one the recurring payment runs on /// - public string ProviderReference { get; set; } + public string? ProviderReference { get; set; } } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs index 891b22a72..fb8813882 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs @@ -8,18 +8,18 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; /// public class RecordRecurringPaymentFailureCommand : IRequest { - public string RecurringPaymentId { get; set; } + public string? RecurringPaymentId { get; set; } /// /// The provider's reference of the recurring payment (for example the subscription id), used to stop the /// gateway when the failure arrives for a payment the shop cancelled before learning it /// - public string ProviderReference { get; set; } + public string? ProviderReference { get; set; } /// /// The provider's reference of the cycle that failed /// - public string CycleReference { get; set; } + public string? CycleReference { get; set; } - public string Reason { get; set; } + public string? Reason { get; set; } } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentReferenceCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentReferenceCommand.cs index dfcdfe083..6f53bb811 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentReferenceCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentReferenceCommand.cs @@ -12,10 +12,10 @@ public class RecordRecurringPaymentReferenceCommand : IRequest /// /// The recurring payment the provider was given as gateway metadata /// - public string RecurringPaymentId { get; set; } + public string? RecurringPaymentId { get; set; } /// /// The provider's reference of the recurring payment (for example the subscription id) /// - public string ProviderReference { get; set; } + public string? ProviderReference { get; set; } } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReduceLoyaltyPointsCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReduceLoyaltyPointsCommand.cs index fe160e9d2..faa88dbbe 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReduceLoyaltyPointsCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReduceLoyaltyPointsCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class ReduceLoyaltyPointsCommand : IRequest { - public Order Order { get; set; } + public Order? Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RefundCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RefundCommand.cs index a3f395052..0bebb1c38 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RefundCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RefundCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class RefundCommand : IRequest> { - public PaymentTransaction PaymentTransaction { get; set; } - public string CreatedBy { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } + public string? CreatedBy { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RefundOfflineCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RefundOfflineCommand.cs index 83b72a5c0..2b7dd5688 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RefundOfflineCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RefundOfflineCommand.cs @@ -5,8 +5,8 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class RefundOfflineCommand : IRequest { - public PaymentTransaction PaymentTransaction { get; set; } - public string CreatedBy { get; set; } - public string Reference { get; set; } - public string Note { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } + public string? CreatedBy { get; set; } + public string? Reference { get; set; } + public string? Note { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReturnBackRedeemedLoyaltyPointsCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReturnBackRedeemedLoyaltyPointsCommand.cs index 61c1b263d..987eba2e0 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReturnBackRedeemedLoyaltyPointsCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReturnBackRedeemedLoyaltyPointsCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class ReturnBackRedeemedLoyaltyPointsCommand : IRequest { - public Order Order { get; set; } + public Order? Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/SetOrderStatusCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/SetOrderStatusCommand.cs index c76dc2c47..5bacce5a3 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/SetOrderStatusCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/SetOrderStatusCommand.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class SetOrderStatusCommand : IRequest { - public Order Order { get; set; } + public Order? Order { get; set; } public OrderStatusSystem Os { get; set; } public bool NotifyCustomer { get; set; } public bool NotifyStoreOwner { get; set; } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/UpdateOrderItemCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/UpdateOrderItemCommand.cs index 2c6450815..acdb5fe00 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/UpdateOrderItemCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/UpdateOrderItemCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class UpdateOrderItemCommand : IRequest { - public Order Order { get; set; } - public OrderItem OrderItem { get; set; } + public Order? Order { get; set; } + public OrderItem? OrderItem { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ValidateMinShoppingCartSubtotalAmountCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ValidateMinShoppingCartSubtotalAmountCommand.cs index 1f69ec782..fe2d361d2 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ValidateMinShoppingCartSubtotalAmountCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ValidateMinShoppingCartSubtotalAmountCommand.cs @@ -6,6 +6,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class ValidateMinShoppingCartSubtotalAmountCommand : IRequest { - public IList Cart { get; set; } - public CalculationContext Context { get; set; } + public IList? Cart { get; set; } + public CalculationContext? Context { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/VoidCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/VoidCommand.cs index e0f122013..c01c3a6f8 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/VoidCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/VoidCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class VoidCommand : IRequest> { - public PaymentTransaction PaymentTransaction { get; set; } - public string CreatedBy { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } + public string? CreatedBy { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/VoidOfflineCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/VoidOfflineCommand.cs index b0480abff..f869532d2 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/VoidOfflineCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/VoidOfflineCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class VoidOfflineCommand : IRequest { - public PaymentTransaction PaymentTransaction { get; set; } - public string CreatedBy { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } + public string? CreatedBy { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Shipping/DeliveryCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Shipping/DeliveryCommand.cs index 782e4ec0b..48a823b54 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Shipping/DeliveryCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Shipping/DeliveryCommand.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Commands.Checkout.Shipping; public class DeliveryCommand : IRequest { - public Shipment Shipment { get; set; } + public Shipment? Shipment { get; set; } public bool NotifyCustomer { get; set; } /// When a shipment is marked as delivered with a date of its own; null stamps now. diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Shipping/ShipCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Shipping/ShipCommand.cs index 71b1dc841..fde5fc274 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Shipping/ShipCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Shipping/ShipCommand.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Commands.Checkout.Shipping; public class ShipCommand : IRequest { - public Shipment Shipment { get; set; } + public Shipment? Shipment { get; set; } public bool NotifyCustomer { get; set; } /// When a shipment is marked as shipped with a date of its own; null stamps now. diff --git a/src/Business/Grand.Business.Core/Commands/Customers/ActiveVendorCommand.cs b/src/Business/Grand.Business.Core/Commands/Customers/ActiveVendorCommand.cs index 4705c3d86..e96d2a376 100644 --- a/src/Business/Grand.Business.Core/Commands/Customers/ActiveVendorCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Customers/ActiveVendorCommand.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Commands.Customers; public class ActiveVendorCommand : IRequest { - public Vendor Vendor { get; set; } + public Vendor? Vendor { get; set; } public bool Active { get; set; } public IList CustomerIds { get; set; } = new List(); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Messages/Common/InsertContactUsCommand.cs b/src/Business/Grand.Business.Core/Commands/Messages/Common/InsertContactUsCommand.cs index 25a613aac..95338eedc 100644 --- a/src/Business/Grand.Business.Core/Commands/Messages/Common/InsertContactUsCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Messages/Common/InsertContactUsCommand.cs @@ -5,15 +5,15 @@ namespace Grand.Business.Core.Commands.Messages.Common; public class InsertContactUsCommand : IRequest { - public string CustomerId { get; set; } - public string StoreId { get; set; } - public string VendorId { get; set; } - public string Email { get; set; } - public string FullName { get; set; } - public string Subject { get; set; } - public string Enquiry { get; set; } - public string RemoteIpAddress { get; set; } - public string ContactAttributeDescription { get; set; } - public IList ContactAttributes { get; set; } - public string EmailAccountId { get; set; } + public string? CustomerId { get; set; } + public string? StoreId { get; set; } + public string? VendorId { get; set; } + public string? Email { get; set; } + public string? FullName { get; set; } + public string? Subject { get; set; } + public string? Enquiry { get; set; } + public string? RemoteIpAddress { get; set; } + public string? ContactAttributeDescription { get; set; } + public IList? ContactAttributes { get; set; } + public string? EmailAccountId { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Messages/Common/OrderNotificationCommand.cs b/src/Business/Grand.Business.Core/Commands/Messages/Common/OrderNotificationCommand.cs index c6a0a5066..984ced3ce 100644 --- a/src/Business/Grand.Business.Core/Commands/Messages/Common/OrderNotificationCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Messages/Common/OrderNotificationCommand.cs @@ -7,22 +7,22 @@ namespace Grand.Business.Core.Commands.Messages.Common; public class OrderNotificationCommand : IRequest { - public Order Order { get; set; } + public Order? Order { get; set; } /// /// Customer the order was placed for /// - public Customer Customer { get; set; } + public Customer? Customer { get; set; } /// /// Staff member who placed the order while impersonating the customer, if any /// - public Customer OriginalCustomerIfImpersonated { get; set; } + public Customer? OriginalCustomerIfImpersonated { get; set; } /// /// Host of the storefront request that placed the order; the messages link to it /// - public DomainHost Host { get; set; } + public DomainHost? Host { get; set; } /// /// Gets or sets a value indicating whether the store owner and the vendors are told about the order; diff --git a/src/Business/Grand.Business.Core/Commands/System/Common/GetSitemapXmlCommand.cs b/src/Business/Grand.Business.Core/Commands/System/Common/GetSitemapXmlCommand.cs index f942f4a03..c81b2b729 100644 --- a/src/Business/Grand.Business.Core/Commands/System/Common/GetSitemapXmlCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/System/Common/GetSitemapXmlCommand.cs @@ -6,6 +6,6 @@ namespace Grand.Business.Core.Commands.System.Common; public class GetSitemapXmlCommand : IRequest { - public Store Store { get; set; } - public Language Language { get; set; } + public Store? Store { get; set; } + public Language? Language { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Dto/BrandDto.cs b/src/Business/Grand.Business.Core/Dto/BrandDto.cs index 2d5169c3a..def302f29 100644 --- a/src/Business/Grand.Business.Core/Dto/BrandDto.cs +++ b/src/Business/Grand.Business.Core/Dto/BrandDto.cs @@ -2,24 +2,24 @@ public class BrandDto { - public string Id { get; set; } - public string Name { get; set; } - public string SeName { get; set; } - public string Picture { get; set; } - public string Description { get; set; } - public string BottomDescription { get; set; } - public string BrandLayoutId { get; set; } - public string MetaKeywords { get; set; } - public string MetaDescription { get; set; } - public string MetaTitle { get; set; } + public string? Id { get; set; } + public string? Name { get; set; } + public string? SeName { get; set; } + public string? Picture { get; set; } + public string? Description { get; set; } + public string? BottomDescription { get; set; } + public string? BrandLayoutId { get; set; } + public string? MetaKeywords { get; set; } + public string? MetaDescription { get; set; } + public string? MetaTitle { get; set; } public int? PageSize { get; set; } public bool? AllowCustomersToSelectPageSize { get; set; } - public string PageSizeOptions { get; set; } + public string? PageSizeOptions { get; set; } public bool? ShowOnHomePage { get; set; } public bool? IncludeInMenu { get; set; } - public string Icon { get; set; } + public string? Icon { get; set; } public int? DefaultSort { get; set; } - public string ExternalId { get; set; } + public string? ExternalId { get; set; } public bool? Published { get; set; } public int? DisplayOrder { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Dto/CategoryDto.cs b/src/Business/Grand.Business.Core/Dto/CategoryDto.cs index d3de7c3ed..d770ec2fd 100644 --- a/src/Business/Grand.Business.Core/Dto/CategoryDto.cs +++ b/src/Business/Grand.Business.Core/Dto/CategoryDto.cs @@ -2,20 +2,20 @@ public class CategoryDto { - public string Id { get; set; } - public string Name { get; set; } - public string CategoryLayoutId { get; set; } - public string Picture { get; set; } - public string SeName { get; set; } - public string Description { get; set; } - public string BottomDescription { get; set; } - public string MetaKeywords { get; set; } - public string MetaDescription { get; set; } - public string MetaTitle { get; set; } - public string ParentCategoryId { get; set; } + public string? Id { get; set; } + public string? Name { get; set; } + public string? CategoryLayoutId { get; set; } + public string? Picture { get; set; } + public string? SeName { get; set; } + public string? Description { get; set; } + public string? BottomDescription { get; set; } + public string? MetaKeywords { get; set; } + public string? MetaDescription { get; set; } + public string? MetaTitle { get; set; } + public string? ParentCategoryId { get; set; } public int? PageSize { get; set; } public bool? AllowCustomersToSelectPageSize { get; set; } - public string PageSizeOptions { get; set; } + public string? PageSizeOptions { get; set; } public bool? ShowOnHomePage { get; set; } public bool? FeaturedProductsOnHomePage { get; set; } public bool? ShowOnSearchBox { get; set; } @@ -23,10 +23,10 @@ public class CategoryDto public bool? IncludeInMenu { get; set; } public bool? Published { get; set; } public int? DisplayOrder { get; set; } - public string ExternalId { get; set; } - public string Flag { get; set; } - public string FlagStyle { get; set; } - public string Icon { get; set; } + public string? ExternalId { get; set; } + public string? Flag { get; set; } + public string? FlagStyle { get; set; } + public string? Icon { get; set; } public int? DefaultSort { get; set; } public bool? HideOnCatalog { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Dto/CollectionDto.cs b/src/Business/Grand.Business.Core/Dto/CollectionDto.cs index 3058e45ff..5a459b2ee 100644 --- a/src/Business/Grand.Business.Core/Dto/CollectionDto.cs +++ b/src/Business/Grand.Business.Core/Dto/CollectionDto.cs @@ -2,25 +2,25 @@ public class CollectionDto { - public string Id { get; set; } - public string Name { get; set; } - public string Picture { get; set; } - public string SeName { get; set; } - public string Description { get; set; } - public string BottomDescription { get; set; } - public string CollectionLayoutId { get; set; } - public string MetaKeywords { get; set; } - public string MetaDescription { get; set; } - public string MetaTitle { get; set; } + public string? Id { get; set; } + public string? Name { get; set; } + public string? Picture { get; set; } + public string? SeName { get; set; } + public string? Description { get; set; } + public string? BottomDescription { get; set; } + public string? CollectionLayoutId { get; set; } + public string? MetaKeywords { get; set; } + public string? MetaDescription { get; set; } + public string? MetaTitle { get; set; } public int? PageSize { get; set; } public bool? AllowCustomersToSelectPageSize { get; set; } - public string PageSizeOptions { get; set; } + public string? PageSizeOptions { get; set; } public bool? ShowOnHomePage { get; set; } public bool? FeaturedProductsOnHomePage { get; set; } public bool? IncludeInMenu { get; set; } - public string Icon { get; set; } + public string? Icon { get; set; } public int? DefaultSort { get; set; } = -1; public bool? Published { get; set; } public int? DisplayOrder { get; set; } - public string ExternalId { get; set; } + public string? ExternalId { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Dto/CountryStatesDto.cs b/src/Business/Grand.Business.Core/Dto/CountryStatesDto.cs index f905c4ac0..3e923f623 100644 --- a/src/Business/Grand.Business.Core/Dto/CountryStatesDto.cs +++ b/src/Business/Grand.Business.Core/Dto/CountryStatesDto.cs @@ -2,9 +2,9 @@ public class CountryStatesDto { - public string Country { get; set; } - public string StateProvinceName { get; set; } - public string Abbreviation { get; set; } + public string? Country { get; set; } + public string? StateProvinceName { get; set; } + public string? Abbreviation { get; set; } public int DisplayOrder { get; set; } public bool Published { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Dto/ProductAttributeDto.cs b/src/Business/Grand.Business.Core/Dto/ProductAttributeDto.cs index 2927f886e..ab0510e55 100644 --- a/src/Business/Grand.Business.Core/Dto/ProductAttributeDto.cs +++ b/src/Business/Grand.Business.Core/Dto/ProductAttributeDto.cs @@ -2,18 +2,18 @@ namespace Grand.Business.Core.Dto; public class ProductAttributeDto { - public string Id { get; set; } - public string Name { get; set; } - public string SeName { get; set; } - public string Description { get; set; } + public string? Id { get; set; } + public string? Name { get; set; } + public string? SeName { get; set; } + public string? Description { get; set; } /// Predefined values, merged by name (case-insensitive): missing values are added, provided fields updated, none deleted - public IList Values { get; set; } + public IList? Values { get; set; } } public class ProductAttributeValueDto { - public string Name { get; set; } + public string? Name { get; set; } public double? PriceAdjustment { get; set; } public double? WeightAdjustment { get; set; } public double? Cost { get; set; } diff --git a/src/Business/Grand.Business.Core/Dto/ProductDto.cs b/src/Business/Grand.Business.Core/Dto/ProductDto.cs index e6f13ee3d..744569fcf 100644 --- a/src/Business/Grand.Business.Core/Dto/ProductDto.cs +++ b/src/Business/Grand.Business.Core/Dto/ProductDto.cs @@ -2,37 +2,37 @@ public class ProductDto { - public string Id { get; set; } + public string? Id { get; set; } public int? ProductTypeId { get; set; } - public string ParentGroupedProductId { get; set; } + public string? ParentGroupedProductId { get; set; } public bool? VisibleIndividually { get; set; } - public string Name { get; set; } - public string SeName { get; set; } - public string ShortDescription { get; set; } - public string FullDescription { get; set; } - public string AdminComment { get; set; } - public string ProductLayoutId { get; set; } - public string BrandId { get; set; } - public string VendorId { get; set; } + public string? Name { get; set; } + public string? SeName { get; set; } + public string? ShortDescription { get; set; } + public string? FullDescription { get; set; } + public string? AdminComment { get; set; } + public string? ProductLayoutId { get; set; } + public string? BrandId { get; set; } + public string? VendorId { get; set; } public bool? ShowOnHomePage { get; set; } public bool? BestSeller { get; set; } - public string MetaKeywords { get; set; } - public string MetaDescription { get; set; } - public string MetaTitle { get; set; } + public string? MetaKeywords { get; set; } + public string? MetaDescription { get; set; } + public string? MetaTitle { get; set; } public bool? AllowCustomerReviews { get; set; } public int? ApprovedRatingSum { get; set; } public int? NotApprovedRatingSum { get; set; } public int? ApprovedTotalReviews { get; set; } public int? NotApprovedTotalReviews { get; set; } - public string ExternalId { get; set; } - public string Sku { get; set; } - public string Mpn { get; set; } - public string Gtin { get; set; } + public string? ExternalId { get; set; } + public string? Sku { get; set; } + public string? Mpn { get; set; } + public string? Gtin { get; set; } public bool? IsGiftVoucher { get; set; } public int? GiftVoucherTypeId { get; set; } public double? OverGiftAmount { get; set; } public bool? RequireOtherProducts { get; set; } - public string RequiredProductIds { get; set; } + public string? RequiredProductIds { get; set; } public bool? AutoAddRequiredProducts { get; set; } public bool? IsDownload { get; set; } public bool? UnlimitedDownloads { get; set; } @@ -41,7 +41,7 @@ public class ProductDto public int? DownloadActivationTypeId { get; set; } public bool? HasSampleDownload { get; set; } public bool? HasUserAgreement { get; set; } - public string UserAgreementText { get; set; } + public string? UserAgreementText { get; set; } public bool? IsRecurring { get; set; } public int? RecurringCycleLength { get; set; } public int? RecurringCyclePeriodId { get; set; } @@ -53,13 +53,13 @@ public class ProductDto public bool? IsFreeShipping { get; set; } public bool? ShipSeparately { get; set; } public double? AdditionalShippingCharge { get; set; } - public string DeliveryDateId { get; set; } + public string? DeliveryDateId { get; set; } public bool? IsTaxExempt { get; set; } - public string TaxCategoryId { get; set; } + public string? TaxCategoryId { get; set; } public bool? IsTele { get; set; } public int? ManageInventoryMethodId { get; set; } public bool? UseMultipleWarehouses { get; set; } - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } public int? StockQuantity { get; set; } public int? ReservedQuantity { get; set; } public bool? StockAvailability { get; set; } @@ -72,7 +72,7 @@ public class ProductDto public bool? AllowOutOfStockSubscriptions { get; set; } public int? OrderMinimumQuantity { get; set; } public int? OrderMaximumQuantity { get; set; } - public string AllowedQuantities { get; set; } + public string? AllowedQuantities { get; set; } public bool? NotReturnable { get; set; } public bool? DisableBuyButton { get; set; } public bool? DisableWishlistButton { get; set; } @@ -88,11 +88,11 @@ public class ProductDto public double? MaxEnteredPrice { get; set; } public bool? BasePriceEnabled { get; set; } public double? BasePriceAmount { get; set; } - public string BasePriceUnitId { get; set; } + public string? BasePriceUnitId { get; set; } public double? BasePriceBaseAmount { get; set; } - public string BasePriceBaseUnitId { get; set; } - public string UnitId { get; set; } - public string CourseId { get; set; } + public string? BasePriceBaseUnitId { get; set; } + public string? UnitId { get; set; } + public string? CourseId { get; set; } public bool? MarkAsNew { get; set; } public DateTime? MarkAsNewStartDateTimeUtc { get; set; } public DateTime? MarkAsNewEndDateTimeUtc { get; set; } @@ -110,13 +110,13 @@ public class ProductDto public int? Sold { get; set; } public long? Viewed { get; set; } public int? OnSale { get; set; } - public string Flag { get; set; } - public string CategoryIds { get; set; } - public string CollectionIds { get; set; } - public string Picture1 { get; set; } - public string Picture2 { get; set; } - public string Picture3 { get; set; } + public string? Flag { get; set; } + public string? CategoryIds { get; set; } + public string? CollectionIds { get; set; } + public string? Picture1 { get; set; } + public string? Picture2 { get; set; } + public string? Picture3 { get; set; } /// Row import only: when present it replaces Picture1..3 - public IList PictureUrls { get; set; } + public IList? PictureUrls { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Dto/ProductVariantsDto.cs b/src/Business/Grand.Business.Core/Dto/ProductVariantsDto.cs index 136193028..a62ef1f0d 100644 --- a/src/Business/Grand.Business.Core/Dto/ProductVariantsDto.cs +++ b/src/Business/Grand.Business.Core/Dto/ProductVariantsDto.cs @@ -9,19 +9,19 @@ namespace Grand.Business.Core.Dto; public class ProductVariantsDto { /// Product to change; when set and not found the row is rejected - public string ProductId { get; set; } + public string? ProductId { get; set; } /// Used to find the product when ProductId is empty - public string ProductSku { get; set; } + public string? ProductSku { get; set; } - public IList Attributes { get; set; } - public IList Combinations { get; set; } + public IList? Attributes { get; set; } + public IList? Combinations { get; set; } } public class ProductVariantAttributeDto { /// Catalogue product attribute by id or SeName; it must exist - public string Attribute { get; set; } + public string? Attribute { get; set; } public AttributeControlType? ControlType { get; set; } public bool? IsRequired { get; set; } @@ -29,28 +29,28 @@ public class ProductVariantAttributeDto public int? DisplayOrder { get; set; } /// Values of the mapping, merged by name (case-insensitive): missing values are added, provided fields updated - public IList Values { get; set; } + public IList? Values { get; set; } } public class ProductVariantValueDto { - public string Name { get; set; } + public string? Name { get; set; } public double? PriceAdjustment { get; set; } public double? WeightAdjustment { get; set; } public double? Cost { get; set; } public bool? IsPreSelected { get; set; } - public string ColorSquaresRgb { get; set; } + public string? ColorSquaresRgb { get; set; } public int? DisplayOrder { get; set; } } public class ProductVariantCombinationDto { /// Attribute (id or SeName) to value name; the set identifies the combination, order does not matter - public IDictionary Values { get; set; } + public IDictionary? Values { get; set; } - public string Sku { get; set; } - public string Gtin { get; set; } - public string Mpn { get; set; } + public string? Sku { get; set; } + public string? Gtin { get; set; } + public string? Mpn { get; set; } /// Overridden price of the combination public double? Price { get; set; } diff --git a/src/Business/Grand.Business.Core/Dto/SpecificationAttributeDto.cs b/src/Business/Grand.Business.Core/Dto/SpecificationAttributeDto.cs index 98520e2e6..c6fc0ab68 100644 --- a/src/Business/Grand.Business.Core/Dto/SpecificationAttributeDto.cs +++ b/src/Business/Grand.Business.Core/Dto/SpecificationAttributeDto.cs @@ -2,18 +2,18 @@ namespace Grand.Business.Core.Dto; public class SpecificationAttributeDto { - public string Id { get; set; } - public string Name { get; set; } - public string SeName { get; set; } + public string? Id { get; set; } + public string? Name { get; set; } + public string? SeName { get; set; } public int? DisplayOrder { get; set; } /// Merged by name (case-insensitive): missing options are added, provided fields updated, none deleted - public IList Options { get; set; } + public IList? Options { get; set; } } public class SpecificationAttributeOptionDto { - public string Name { get; set; } - public string ColorSquaresRgb { get; set; } + public string? Name { get; set; } + public string? ColorSquaresRgb { get; set; } public int? DisplayOrder { get; set; } } diff --git a/src/Business/Grand.Business.Core/Enums/Checkout/ShipmentStatusEvent.cs b/src/Business/Grand.Business.Core/Enums/Checkout/ShipmentStatusEvent.cs index 31253c387..402571aad 100644 --- a/src/Business/Grand.Business.Core/Enums/Checkout/ShipmentStatusEvent.cs +++ b/src/Business/Grand.Business.Core/Enums/Checkout/ShipmentStatusEvent.cs @@ -8,17 +8,17 @@ public class ShipmentStatusEvent /// /// Event name /// - public string EventName { get; set; } + public string? EventName { get; set; } /// /// Location /// - public string Location { get; set; } + public string? Location { get; set; } /// /// two-letter country code /// - public string CountryCode { get; set; } + public string? CountryCode { get; set; } /// /// Date diff --git a/src/Business/Grand.Business.Core/Events/Customers/CustomerLoginFailedEvent.cs b/src/Business/Grand.Business.Core/Events/Customers/CustomerLoginFailedEvent.cs index 19177f1af..70873730f 100644 --- a/src/Business/Grand.Business.Core/Events/Customers/CustomerLoginFailedEvent.cs +++ b/src/Business/Grand.Business.Core/Events/Customers/CustomerLoginFailedEvent.cs @@ -29,5 +29,5 @@ public Customer Customer { /// /// Why the sign-in failed, e.g. wrong credentials or a wrong two-factor code /// - public string Reason { get; } + public string? Reason { get; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Events/Marketing/EmailSubscribedEvent.cs b/src/Business/Grand.Business.Core/Events/Marketing/EmailSubscribedEvent.cs index 72a7a0e3a..77b001fa2 100644 --- a/src/Business/Grand.Business.Core/Events/Marketing/EmailSubscribedEvent.cs +++ b/src/Business/Grand.Business.Core/Events/Marketing/EmailSubscribedEvent.cs @@ -18,7 +18,7 @@ public bool Equals(EmailSubscribedEvent other) return ReferenceEquals(this, other) || Equals(other.Email, Email); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; diff --git a/src/Business/Grand.Business.Core/Events/Marketing/EmailUnsubscribedEvent.cs b/src/Business/Grand.Business.Core/Events/Marketing/EmailUnsubscribedEvent.cs index 40917716b..2360a90da 100644 --- a/src/Business/Grand.Business.Core/Events/Marketing/EmailUnsubscribedEvent.cs +++ b/src/Business/Grand.Business.Core/Events/Marketing/EmailUnsubscribedEvent.cs @@ -18,7 +18,7 @@ public bool Equals(EmailUnsubscribedEvent other) return ReferenceEquals(this, other) || Equals(other.Email, Email); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; diff --git a/src/Business/Grand.Business.Core/Extensions/AffiliateExtensions.cs b/src/Business/Grand.Business.Core/Extensions/AffiliateExtensions.cs index 44f2f7e6b..404ecdc6e 100644 --- a/src/Business/Grand.Business.Core/Extensions/AffiliateExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/AffiliateExtensions.cs @@ -14,8 +14,8 @@ public static string GetFullName(this Affiliate affiliate) { ArgumentNullException.ThrowIfNull(affiliate); - var firstName = affiliate.Address.FirstName; - var lastName = affiliate.Address.LastName; + var firstName = affiliate.Address?.FirstName; + var lastName = affiliate.Address?.LastName; var fullName = ""; if (!string.IsNullOrWhiteSpace(firstName) && !string.IsNullOrWhiteSpace(lastName)) diff --git a/src/Business/Grand.Business.Core/Extensions/LanguageServiceExtensions.cs b/src/Business/Grand.Business.Core/Extensions/LanguageServiceExtensions.cs index d1cb4631f..cbcde2f0c 100644 --- a/src/Business/Grand.Business.Core/Extensions/LanguageServiceExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/LanguageServiceExtensions.cs @@ -15,7 +15,7 @@ public static class LanguageServiceExtensions /// Preferred language identifier; may be empty or point to a deleted language /// Store whose languages are the fallback; null for all stores /// The language, or null when no language exists at all - public static async Task GetLanguageOrStoreDefault(this ILanguageService languageService, + public static async Task GetLanguageOrStoreDefault(this ILanguageService languageService, string languageId, Store store) { if (!string.IsNullOrEmpty(languageId)) diff --git a/src/Business/Grand.Business.Core/Extensions/MerchandiseReturnExtensions.cs b/src/Business/Grand.Business.Core/Extensions/MerchandiseReturnExtensions.cs index 7cd226771..3d20897e2 100644 --- a/src/Business/Grand.Business.Core/Extensions/MerchandiseReturnExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/MerchandiseReturnExtensions.cs @@ -75,7 +75,7 @@ public static bool CanChangeTo(this MerchandiseReturnStatus from, MerchandiseRet /// How the staff note of a status change names the staff member who made it: the e-mail, else the full name, /// else the customer id; null when no one did, and the note says the system /// - public static string StatusChangedBy(this Customer staff) + public static string? StatusChangedBy(this Customer staff) { if (staff == null) return null; diff --git a/src/Business/Grand.Business.Core/Extensions/MerchandiseReturnShippingExtensions.cs b/src/Business/Grand.Business.Core/Extensions/MerchandiseReturnShippingExtensions.cs index b588ea4fd..a3519bd1b 100644 --- a/src/Business/Grand.Business.Core/Extensions/MerchandiseReturnShippingExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/MerchandiseReturnShippingExtensions.cs @@ -17,7 +17,8 @@ public static class MerchandiseReturnShippingExtensions /// public static bool CustomerEntersTrackingNumber(this MerchandiseReturn merchandiseReturn) { - return string.Equals(merchandiseReturn?.ReturnShipping?.ProviderSystemName, SendYourselfSystemName, + return merchandiseReturn != null + && string.Equals(merchandiseReturn.ReturnShipping?.ProviderSystemName, SendYourselfSystemName, StringComparison.OrdinalIgnoreCase) && merchandiseReturn.MerchandiseReturnStatus is MerchandiseReturnStatus.Pending or MerchandiseReturnStatus.Accepted; @@ -50,8 +51,8 @@ public static bool CustomerRetriesLabel(this MerchandiseReturn merchandiseReturn /// An address on one line, as every text and page of a merchandise return writes it: the leading parts (a /// name, a recipient), the street, the zip code with the city, the country; empty parts are left out /// - public static async Task AddressLine(ICountryService countryService, string address1, - string zipPostalCode, string city, string countryId, params string[] leading) + public static async Task AddressLine(ICountryService countryService, string? address1, + string? zipPostalCode, string? city, string? countryId, params string[] leading) { var country = string.IsNullOrEmpty(countryId) ? null : await countryService.GetCountryById(countryId); var zipAndCity = string.Join(" ", new[] { zipPostalCode, city }.Where(x => !string.IsNullOrEmpty(x))); @@ -63,7 +64,7 @@ public static async Task AddressLine(ICountryService countryService, str /// An address on one line, as every text and page of a merchandise return writes it; no address gives the /// leading parts alone /// - public static Task AddressLine(ICountryService countryService, Address address, params string[] leading) + public static Task AddressLine(ICountryService countryService, Address? address, params string[] leading) { return AddressLine(countryService, address?.Address1, address?.ZipPostalCode, address?.City, address?.CountryId, leading); diff --git a/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs b/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs index 4130f4950..b187b6128 100644 --- a/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs @@ -49,7 +49,7 @@ public static bool IsPaymentMethodActive(this IPaymentProvider paymentMethod, /// Payment method, or null when it is no longer installed /// Order /// Payment method name - public static string GetPaymentMethodName(this IPaymentProvider paymentMethod, Order order) + public static string? GetPaymentMethodName(this IPaymentProvider paymentMethod, Order order) { ArgumentNullException.ThrowIfNull(order); diff --git a/src/Business/Grand.Business.Core/Extensions/ProductReservationExtensions.cs b/src/Business/Grand.Business.Core/Extensions/ProductReservationExtensions.cs index cfe1f13c5..3693b28dd 100644 --- a/src/Business/Grand.Business.Core/Extensions/ProductReservationExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/ProductReservationExtensions.cs @@ -7,7 +7,7 @@ public static class ProductReservationExtensions /// /// Finds the first resource whose reservations cover the whole rental period, or null when none is free /// - public static IGrouping FindGroupToBook( + public static IGrouping? FindGroupToBook( this IEnumerable reservations, Product product, DateTime rentalStartDate, DateTime rentalEndDate) { diff --git a/src/Business/Grand.Business.Core/Extensions/SeoExtensions.cs b/src/Business/Grand.Business.Core/Extensions/SeoExtensions.cs index b349ccc7d..a80acd538 100644 --- a/src/Business/Grand.Business.Core/Extensions/SeoExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/SeoExtensions.cs @@ -5,6 +5,7 @@ using Grand.Domain.Localization; using Grand.Domain.Seo; using Grand.SharedKernel.Extensions; +using System.Diagnostics.CodeAnalysis; namespace Grand.Business.Core.Extensions; @@ -18,7 +19,7 @@ public static class SeoExtensions /// Product tag /// Language identifier /// Product tag SE (search engine) name - public static string GetSeName(this ProductTag productTag, string languageId) + public static string? GetSeName(this ProductTag productTag, string languageId) { ArgumentNullException.ThrowIfNull(productTag); var seName = GenerateSlug(productTag.GetTranslation(x => x.Name, languageId), false, false, false); @@ -29,7 +30,7 @@ public static string GetSeName(this ProductTag productTag, string languageId) #region Fields - private static Dictionary _seoCharacterTable; + private static Dictionary? _seoCharacterTable; private static readonly Lock SLock = new(); #endregion @@ -47,7 +48,7 @@ public static string GetSeName(this ProductTag productTag, string languageId) /// found) /// /// Search engine name (slug) - public static string GetSeName(this T entity, string languageId, bool returnDefaultValue = true) + public static string? GetSeName(this T entity, string languageId, bool returnDefaultValue = true) where T : BaseEntity, ISlugEntity, ITranslationEntity { ArgumentNullException.ThrowIfNull(entity); @@ -116,12 +117,12 @@ public static async Task ValidateSeName(this T entity, string seName, //check whether such slug already exists (and that is not the current entity) var entityUrl = await slugService.GetBySlug(tempSeName); var reserved1 = entityUrl != null && !(entityUrl.EntityId == entity.Id && - entityUrl.EntityName.Equals(entityName, + string.Equals(entityUrl.EntityName, entityName, StringComparison.OrdinalIgnoreCase)); //and it's not in the list of reserved slugs var reserved2 = seoSettings.ReservedEntityUrlSlugs.Contains(tempSeName, StringComparer.OrdinalIgnoreCase); var reserved3 = (await languageService.GetAllLanguages(true)).Any(language => - language.UniqueSeoCode.Equals(tempSeName, StringComparison.OrdinalIgnoreCase)); + string.Equals(language.UniqueSeoCode, tempSeName, StringComparison.OrdinalIgnoreCase)); if (!reserved1 && !reserved2 && !reserved3) break; @@ -137,7 +138,8 @@ public static async Task ValidateSeName(this T entity, string seName, return seName; } - private static string GetSeName(string name, SeoSettings seoSettings) + [return: NotNullIfNotNull(nameof(name))] + private static string? GetSeName(string? name, SeoSettings seoSettings) { return SeoExtensions.GenerateSlug(name, seoSettings.ConvertNonWesternChars, seoSettings.AllowUnicodeCharsInUrls, seoSettings.AllowSlashChar, seoSettings.SeoCharConversion); @@ -152,7 +154,7 @@ private static string GetSeName(string name, SeoSettings seoSettings) /// /// Result public static string GetSeName(string name, bool convertNonWesternChars, bool allowUnicodeCharsInUrls, - string charConversions = null) + string? charConversions = null) { return GenerateSlug(name, convertNonWesternChars, allowUnicodeCharsInUrls, false, charConversions); } @@ -166,8 +168,9 @@ public static string GetSeName(string name, bool convertNonWesternChars, bool al /// /// /// Result - public static string GenerateSlug(string name, bool convertNonWesternChars, bool allowUnicodeCharsInUrls, - bool allowSlashChar, string charConversions = null) + [return: NotNullIfNotNull(nameof(name))] + public static string? GenerateSlug(string? name, bool convertNonWesternChars, bool allowUnicodeCharsInUrls, + bool allowSlashChar, string? charConversions = null) { if (string.IsNullOrEmpty(name)) return name; @@ -219,10 +222,12 @@ private static void InitializeSeoCharacterTable(string charConversions) foreach (var conversion in charConversions.Split(";")) { - var strLeft = conversion.Split(":").FirstOrDefault(); - var strRight = conversion.Split(":").LastOrDefault(); + //Split always returns at least one part + var parts = conversion.Split(":"); + var strLeft = parts[0]; + var strRight = parts[^1]; if (!string.IsNullOrEmpty(strLeft) && !_seoCharacterTable.ContainsKey(strLeft)) - _seoCharacterTable.Add(strLeft.Trim(), strRight?.Trim()); + _seoCharacterTable.Add(strLeft.Trim(), strRight.Trim()); } } } diff --git a/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs b/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs index 31b2edead..6f1ee5abd 100644 --- a/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs @@ -19,8 +19,8 @@ public static class TranslateExtensions /// Language identifier /// A value indicating whether to return default value (if translation is not found) /// Translation property - public static string GetTranslation(this T entity, - Expression> keySelector, string languageId, + public static string? GetTranslation(this T entity, + Expression> keySelector, string languageId, bool returnDefaultValue = true) where T : ParentEntity, ITranslationEntity { @@ -33,7 +33,7 @@ public static string GetTranslation(this T entity, if (propInfo == null) throw new ArgumentException($"Expression '{keySelector}' refers to a field, not a property."); - string result = default; + string? result = default; var resultStr = string.Empty; var localeKey = propInfo.Name; @@ -51,7 +51,7 @@ public static string GetTranslation(this T entity, } //set default value if required - if (string.IsNullOrEmpty(resultStr) && returnDefaultValue) result = (string)propInfo.GetValue(entity); + if (string.IsNullOrEmpty(resultStr) && returnDefaultValue) result = (string?)propInfo.GetValue(entity); return result; } diff --git a/src/Business/Grand.Business.Core/Grand.Business.Core.csproj b/src/Business/Grand.Business.Core/Grand.Business.Core.csproj index 5d931b0d3..5ac658a58 100644 --- a/src/Business/Grand.Business.Core/Grand.Business.Core.csproj +++ b/src/Business/Grand.Business.Core/Grand.Business.Core.csproj @@ -5,4 +5,7 @@ + + enable + diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IInventoryDocumentService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IInventoryDocumentService.cs index 4e25629bd..d2f875e46 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IInventoryDocumentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IInventoryDocumentService.cs @@ -10,19 +10,19 @@ public sealed record InventoryDocumentSearch { public InventoryDocumentType? Type { get; init; } public InventoryDocumentStatus? Status { get; init; } - public string WarehouseId { get; init; } + public string? WarehouseId { get; init; } /// /// The store of the documents' warehouses; null for every store /// - public string StoreId { get; init; } + public string? StoreId { get; init; } - public string Number { get; init; } + public string? Number { get; init; } /// /// Only the return receipts of this merchandise return /// - public string MerchandiseReturnId { get; init; } + public string? MerchandiseReturnId { get; init; } public DateTime? FromUtc { get; init; } public DateTime? ToUtc { get; init; } } @@ -124,7 +124,7 @@ Task> Search(InventoryDocumentSearch search, int p /// receive, named twice, or scrapping less than none or more than is left refuses the whole receipt /// Task<(InventoryDocument Document, IList Errors)> CreateReturnReceipt(string merchandiseReturnId, - string customerId, IList inspection = null); + string customerId, IList? inspection = null); /// /// The return receipts of a merchandise return, and whether CreateReturnReceipt has anything left to put on a diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IProductUnitService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IProductUnitService.cs index 704470f4a..5a17bbc48 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IProductUnitService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IProductUnitService.cs @@ -48,21 +48,21 @@ public sealed record UnitSearch /// /// The number, compared without case /// - public string Number { get; init; } + public string? Number { get; init; } /// /// The number is the start of the numbers found /// public bool Prefix { get; init; } - public string ProductId { get; init; } + public string? ProductId { get; init; } public SerialNumberStatus? Status { get; init; } - public string WarehouseId { get; init; } + public string? WarehouseId { get; init; } /// /// The store of the units' warehouses; null for every store /// - public string StoreId { get; init; } + public string? StoreId { get; init; } public BatchExpiryStatus? ExpiryStatus { get; init; } @@ -99,7 +99,7 @@ public sealed record BatchRecipient( string CustomerEmail, int Quantity, DateTime ShippedOnUtc, - string StoreId = null); + string? StoreId = null); /// /// One stock bucket of a product tracking units: its stock and the part of it batches or serial numbers hold @@ -127,7 +127,7 @@ public interface IProductUnitService /// /// The product /// Only this combination; null for the whole product - Task AssignedQuantity(string productId, string combinationId = null); + Task AssignedQuantity(string productId, string? combinationId = null); /// /// The units assigned to stock kept in the warehouse, of every product diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IInventoryManageService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IInventoryManageService.cs index 757981685..e650d996e 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IInventoryManageService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IInventoryManageService.cs @@ -22,7 +22,7 @@ public interface IInventoryManageService /// Quantity to increase or decrease /// Attributes /// Warehouse ident - Task AdjustReserved(Product product, int quantityToChange, IList attributes = null, + Task AdjustReserved(Product product, int quantityToChange, IList? attributes = null, string warehouseId = ""); diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReviewService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReviewService.cs index 9e7ee9e6f..fc403db5d 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReviewService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReviewService.cs @@ -41,7 +41,7 @@ public interface IProductReviewService /// Reviews Task> GetAllProductReviews(string customerId, bool? approved = null, DateTime? fromUtc = null, DateTime? toUtc = null, - string message = null, string storeId = "", string productId = "", int pageIndex = 0, + string? message = null, string storeId = "", string productId = "", int pageIndex = 0, int pageSize = int.MaxValue); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductService.cs index 2235b54ec..ccc854d33 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductService.cs @@ -110,7 +110,7 @@ Task IncrementProductField(Product product, /// Ignore acl /// Ignore store /// Product number - int GetCategoryProductNumber(Customer customer, IList categoryIds = null, string storeId = "", + int GetCategoryProductNumber(Customer customer, IList? categoryIds = null, string storeId = "", bool ignoreAcl = true, bool ignoreStore = true); /// @@ -162,7 +162,7 @@ int GetCategoryProductNumber(Customer customer, IList categoryIds = null bool loadFilterableSpecificationAttributeOptionIds = false, int pageIndex = 0, int pageSize = int.MaxValue, - IList categoryIds = null, + IList? categoryIds = null, string brandId = "", string collectionId = "", string vendorId = "", @@ -175,13 +175,13 @@ int GetCategoryProductNumber(Customer customer, IList categoryIds = null double? priceMin = null, double? priceMax = null, string productTag = "", - string keywords = null, + string? keywords = null, bool searchDescriptions = false, bool searchSku = true, bool searchProductTags = false, string languageId = "", - IList filteredSpecs = null, - IList specificationOptions = null, + IList? filteredSpecs = null, + IList? specificationOptions = null, ProductSortingEnum orderBy = ProductSortingEnum.Position, bool? overridePublished = null); diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxService.cs index f95373069..d146017bd 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxService.cs @@ -33,7 +33,7 @@ public interface ITaxService /// Customer /// Store ident /// Tax providers - IList LoadAllTaxProviders(Customer customer = null, string storeId = ""); + IList LoadAllTaxProviders(Customer? customer = null, string storeId = ""); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/GiftVouchers/IGiftVoucherService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/GiftVouchers/IGiftVoucherService.cs index 70a652822..1effa4f0c 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/GiftVouchers/IGiftVoucherService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/GiftVouchers/IGiftVoucherService.cs @@ -30,8 +30,8 @@ public interface IGiftVoucherService /// Gift vouchers Task> GetAllGiftVouchers(string purchasedWithOrderItemId = "", DateTime? createdFromUtc = null, DateTime? createdToUtc = null, - bool? isGiftVoucherActivated = null, string giftVoucherCouponCode = null, - string recipientName = null, + bool? isGiftVoucherActivated = null, string? giftVoucherCouponCode = null, + string? recipientName = null, int pageIndex = 0, int pageSize = int.MaxValue, string storeId = ""); diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnLabelService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnLabelService.cs index e3a2af3ac..9629e636a 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnLabelService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnLabelService.cs @@ -35,5 +35,5 @@ public interface IMerchandiseReturnLabelService /// /// null when saved, else a key of MerchandiseReturnErrors (ShippingChangeNotAllowed when not allowed) Task UpdateShipping(string merchandiseReturnId, Action apply, - Func allowed = null); + Func? allowed = null); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnRefundService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnRefundService.cs index ecd966984..6cc9f6dc4 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnRefundService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnRefundService.cs @@ -39,7 +39,7 @@ public interface IMerchandiseReturnRefundService /// Whether the money was given back outside the payment provider /// Who refunded, as the staff notes name them; null for the system /// null when refunded, else a key of MerchandiseReturnErrors - Task Refund(string merchandiseReturnId, double amount, bool offline, string refundedBy = null); + Task Refund(string merchandiseReturnId, double amount, bool offline, string? refundedBy = null); /// /// Records what the staff found when they checked the payment of a refund that waits for it: the money went @@ -49,5 +49,5 @@ public interface IMerchandiseReturnRefundService /// Whether the money went back /// Who checked, as the staff notes name them; null for the system /// null when recorded, else a key of MerchandiseReturnErrors - Task ResolveRefund(string merchandiseReturnId, bool wentBack, string checkedBy = null); + Task ResolveRefund(string merchandiseReturnId, bool wentBack, string? checkedBy = null); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnWorkflowService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnWorkflowService.cs index 567c126a0..fdd28ecf6 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnWorkflowService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnWorkflowService.cs @@ -31,8 +31,8 @@ public interface IMerchandiseReturnWorkflowService /// The new status /// A note shown to the customer with the change, e.g. why the return was rejected /// Who changed it, as the staff note names them (e.g. the e-mail); null for the system - Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus status, string customerNote = null, - string changedBy = null); + Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus status, string? customerNote = null, + string? changedBy = null); /// /// Changes the status as the other overload does, when allowed says yes to the return as stored @@ -79,7 +79,7 @@ Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus st /// /// Merchandise return identifier /// Who posted the receipt, as the staff note names them; null for the system - Task MarkReceived(string merchandiseReturnId, string changedBy = null); + Task MarkReceived(string merchandiseReturnId, string? changedBy = null); /// /// Whether staff may mark the return received by hand: a posted return receipt took the goods in already (it diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderApprovalService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderApprovalService.cs index 30ab0dbbe..028db0cc9 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderApprovalService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderApprovalService.cs @@ -57,8 +57,8 @@ Task> GetForCustomer(string customerId, string storeId /// Who decided; null when nobody did /// The approver's comment /// Whether this call closed the request - Task Close(OrderApproval approval, OrderApprovalStatus status, string decidedByCustomerId = null, - string decisionComment = null); + Task Close(OrderApproval approval, OrderApprovalStatus status, string? decidedByCustomerId = null, + string? decisionComment = null); /// /// Makes a request closed by pending again, when what should follow the close has failed diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderService.cs index e2ad2836d..abacd735c 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderService.cs @@ -103,12 +103,12 @@ Task> SearchOrders(string storeId = "", string vendorId = "", string customerId = "", string productId = "", string affiliateId = "", string warehouseId = "", string billingCountryId = "", string ownerId = "", string salesEmployeeId = "", - string paymentMethodSystemName = null, + string? paymentMethodSystemName = null, DateTime? createdFromUtc = null, DateTime? createdToUtc = null, int? os = null, PaymentStatus? ps = null, ShippingStatus? ss = null, - string billingEmail = null, string billingLastName = "", string orderGuid = null, - string orderCode = null, int pageIndex = 0, int pageSize = int.MaxValue, string orderTagId = "", - string purchaseOrderNumber = null, bool overdueOnly = false); + string? billingEmail = null, string billingLastName = "", string? orderGuid = null, + string? orderCode = null, int pageIndex = 0, int pageSize = int.MaxValue, string orderTagId = "", + string? purchaseOrderNumber = null, bool overdueOnly = false); /// /// Inserts an order diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartService.cs index 79732af02..36d27a8d8 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartService.cs @@ -18,7 +18,7 @@ public interface IShoppingCartService /// Store identifier; pass null to load all records /// Shopping cart type; pass null to load all records /// Shopping Cart - Task> GetShoppingCart(Customer customer, string storeId = null, + Task> GetShoppingCart(Customer customer, string? storeId = null, params ShoppingCartType[] shoppingCartType); /// @@ -36,8 +36,8 @@ Task> GetShoppingCart(Customer customer, string storeId Task FindShoppingCartItem(IList shoppingCart, ShoppingCartType shoppingCartType, string productId, - string warehouseId = null, - IList attributes = null, + string? warehouseId = null, + IList? attributes = null, double? customerEnteredPrice = null, DateTime? rentalStartDate = null, DateTime? rentalEndDate = null); @@ -63,14 +63,14 @@ Task FindShoppingCartItem(IList shoppingCart /// ShoppingCartValidatorOptions /// (warnings, shoppingCartItem) Task<(IList warnings, ShoppingCartItem shoppingCartItem)> AddToCart(Customer customer, Language language, - string productId, ShoppingCartType shoppingCartType, string storeId, string warehouseId = null, - IList attributes = null, + string productId, ShoppingCartType shoppingCartType, string storeId, string? warehouseId = null, + IList? attributes = null, double? customerEnteredPrice = null, DateTime? rentalStartDate = null, DateTime? rentalEndDate = null, int quantity = 1, bool automaticallyAddRequiredProductsIfEnabled = true, string reservationId = "", string parameter = "", string duration = "", - ShoppingCartValidatorOptions validator = null); + ShoppingCartValidatorOptions? validator = null); /// /// Updates the shopping cart item diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs index 5c7b54391..dff03e661 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs @@ -18,7 +18,7 @@ public interface IPaymentService /// Store ident /// Specified country /// Payment methods - Task> LoadActivePaymentMethods(Customer customer = null, string storeId = "", + Task> LoadActivePaymentMethods(Customer? customer = null, string storeId = "", string filterByCountryId = ""); /// @@ -35,7 +35,7 @@ Task> LoadActivePaymentMethods(Customer customer = null, /// Customer /// Specified country /// Payment providers - Task> LoadAllPaymentMethods(Customer customer = null, string storeId = "", + Task> LoadAllPaymentMethods(Customer? customer = null, string storeId = "", string filterByCountryId = ""); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentTransactionHistoryService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentTransactionHistoryService.cs index 75ff3d18a..81f4b0d8b 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentTransactionHistoryService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentTransactionHistoryService.cs @@ -20,8 +20,8 @@ public interface IPaymentTransactionHistoryService /// The bank transfer title, receipt or gateway number the money can be matched with /// Anything else the staff want to keep with it Task Record(PaymentTransaction paymentTransaction, Order order, - PaymentTransactionEntryType entryType, double amount, string recordedBy, string reference = null, - string note = null); + PaymentTransactionEntryType entryType, double amount, string recordedBy, string? reference = null, + string? note = null); /// /// Gets the operations recorded on the transaction, oldest first diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IReturnShippingService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IReturnShippingService.cs index 356d00f5b..1ad8e794d 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IReturnShippingService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IReturnShippingService.cs @@ -22,7 +22,7 @@ public interface IReturnShippingService /// /// Loads the providers allowed in the store and for the customer, active or not, by priority /// - IList LoadAllProviders(Customer customer = null, string storeId = ""); + IList LoadAllProviders(Customer? customer = null, string storeId = ""); /// /// Gets the options offered for every vendor of the submitted items, with what the customer pays for all diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShipmentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShipmentService.cs index 10cd67a25..f04f341c0 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShipmentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShipmentService.cs @@ -30,8 +30,8 @@ public interface IShipmentService Task> GetAllShipments(string storeId = "", string vendorId = "", string warehouseId = "", string shippingCountryId = "", int shippingStateId = 0, - string shippingCity = null, - string trackingNumber = null, + string? shippingCity = null, + string? trackingNumber = null, bool loadNotShipped = false, DateTime? createdFromUtc = null, DateTime? createdToUtc = null, int pageIndex = 0, int pageSize = int.MaxValue); diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingMethodService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingMethodService.cs index bc2d7e11a..c571bb9ff 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingMethodService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingMethodService.cs @@ -20,7 +20,7 @@ public interface IShippingMethodService /// /// The store identifier to filter by /// Shipping methods - Task> GetAllShippingMethods(string filterByCountryId = "", Customer customer = null, string storeId = ""); + Task> GetAllShippingMethods(string filterByCountryId = "", Customer? customer = null, string storeId = ""); /// /// Inserts a shipping method diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingService.cs index a4a511df7..37e0c7d9d 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingService.cs @@ -18,8 +18,8 @@ public interface IShippingService /// Store ident /// Cart /// Shipping rate methods - Task> LoadActiveShippingRateCalculationProviders(Customer customer = null, - string storeId = "", IList cart = null); + Task> LoadActiveShippingRateCalculationProviders(Customer? customer = null, + string storeId = "", IList? cart = null); /// /// Load Shipping rate provider by system name @@ -34,7 +34,7 @@ Task> LoadActiveShippingRateCalculationP /// Customer /// Store ident /// Shipping rate providers - IList LoadAllShippingRateCalculationProviders(Customer customer = null, + IList LoadAllShippingRateCalculationProviders(Customer? customer = null, string storeId = ""); /// @@ -62,5 +62,5 @@ Task CreateShippingOptionRequests(Customer customer, /// Shipping options Task GetShippingOptions(Customer customer, IList cart, Address shippingAddress, - string allowedShippingRateMethodSystemName = "", Store store = null); + string allowedShippingRateMethodSystemName = "", Store? store = null); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IWarehouseLocationService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IWarehouseLocationService.cs index 913525432..eae81669a 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IWarehouseLocationService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IWarehouseLocationService.cs @@ -14,7 +14,7 @@ public interface IWarehouseLocationService /// The locations of the warehouses by display order and code /// /// The warehouses; null for all of them - Task> GetLocations(IList warehouseIds = null, int pageIndex = 0, + Task> GetLocations(IList? warehouseIds = null, int pageIndex = 0, int pageSize = int.MaxValue); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IBlogService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IBlogService.cs index 94cb4e8aa..e3853807d 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Cms/IBlogService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IBlogService.cs @@ -30,7 +30,7 @@ public interface IBlogService /// Blog posts Task> GetAllBlogPosts(string storeId, DateTime? dateFrom = null, DateTime? dateTo = null, - int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false, string tag = null, + int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false, string? tag = null, string blogPostName = "", string categoryId = ""); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IWidgetService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IWidgetService.cs index 995f3efcb..6b69ffc07 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Cms/IWidgetService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IWidgetService.cs @@ -13,7 +13,7 @@ public interface IWidgetService /// Store ident /// Customer /// Widgets - IList LoadActiveWidgets(string storeId = "", Customer customer = null); + IList LoadActiveWidgets(string storeId = "", Customer? customer = null); /// /// Load active widgets @@ -23,7 +23,7 @@ public interface IWidgetService /// Customer /// Widgets Task> LoadActiveWidgetsByWidgetZone(string widgetZone, string storeId = "", - Customer customer = null); + Customer? customer = null); /// /// Load widget by system name @@ -38,5 +38,5 @@ Task> LoadActiveWidgetsByWidgetZone(string widgetZone, st /// Store ident /// Customer /// Widgets - IList LoadAllWidgets(string storeId = "", Customer customer = null); + IList LoadAllWidgets(string storeId = "", Customer? customer = null); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Audit/AuditEntrySearch.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Audit/AuditEntrySearch.cs index 7b03df08e..9b6ca214c 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Audit/AuditEntrySearch.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Audit/AuditEntrySearch.cs @@ -12,24 +12,24 @@ public class AuditEntrySearch /// /// Part of the staff member's e-mail or of the record's name, any case /// - public string SearchText { get; set; } + public string? SearchText { get; set; } public AuditSource? Source { get; set; } public AuditKind? Kind { get; set; } /// /// One entity type, or several separated by commas (the records one screen edits, e.g. "Permission,PermissionAction") /// - public string EntityType { get; set; } + public string? EntityType { get; set; } - public string EntityId { get; set; } + public string? EntityId { get; set; } /// /// Any of these entity names, e.g. the setting classes one settings page saves /// - public IList EntityNames { get; set; } + public IList? EntityNames { get; set; } /// /// Entries made by that store's staff or changing a record of that store /// - public string StoreId { get; set; } - public string OperationId { get; set; } + public string? StoreId { get; set; } + public string? OperationId { get; set; } } diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Configuration/ISettingService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Configuration/ISettingService.cs index 250c03f52..e63c92ca5 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Configuration/ISettingService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Configuration/ISettingService.cs @@ -41,7 +41,7 @@ public interface ISettingService /// Store identifier /// Default value /// Setting value - Task GetSettingByKey(string key, T defaultValue = default, string storeId = ""); + Task GetSettingByKey(string key, T? defaultValue = default, string storeId = ""); /// /// Set setting value diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Localization/IPluginTranslateResource.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Localization/IPluginTranslateResource.cs index 251a6866f..113acbfb8 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Localization/IPluginTranslateResource.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Localization/IPluginTranslateResource.cs @@ -4,6 +4,6 @@ namespace Grand.Business.Core.Interfaces.Common.Localization; public interface IPluginTranslateResource { - Task AddOrUpdatePluginTranslateResource(string name, string value, TranslationResourceArea area = TranslationResourceArea.Common, string languageCulture = null); + Task AddOrUpdatePluginTranslateResource(string name, string value, TranslationResourceArea area = TranslationResourceArea.Common, string? languageCulture = null); Task DeletePluginTranslationResource(string name); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/IAffiliateService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/IAffiliateService.cs index 5aba67c8a..8642bec76 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Customers/IAffiliateService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Customers/IAffiliateService.cs @@ -26,8 +26,8 @@ public interface IAffiliateService /// Gets all affiliates /// /// Affiliates - Task> GetAllAffiliates(string friendlyUrlName = null, - string firstName = null, string lastName = null, + Task> GetAllAffiliates(string? friendlyUrlName = null, + string? firstName = null, string? lastName = null, bool loadOnlyWithOrders = false, DateTime? ordersCreatedFromUtc = null, DateTime? ordersCreatedToUtc = null, int pageIndex = 0, int pageSize = int.MaxValue, diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs index 8f90ca41f..319bad2c7 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs @@ -49,13 +49,13 @@ public interface ICustomerService Task> GetAllCustomers(DateTime? createdFromUtc = null, DateTime? createdToUtc = null, string affiliateId = "", string vendorId = "", string storeId = "", string ownerId = "", - string salesEmployeeId = "", string[] customerGroupIds = null, string[] customerTagIds = null, - string email = null, string username = null, - string firstName = null, string lastName = null, - string company = null, string phone = null, string zipPostalCode = null, + string salesEmployeeId = "", string[]? customerGroupIds = null, string[]? customerTagIds = null, + string? email = null, string? username = null, + string? firstName = null, string? lastName = null, + string? company = null, string? phone = null, string? zipPostalCode = null, bool loadOnlyWithShoppingCart = false, ShoppingCartType? sct = null, - int pageIndex = 0, int pageSize = int.MaxValue, Expression> orderBySelector = null, - string[] excludedCustomerGroupIds = null, bool excludeVendorAndStaffAccounts = false); + int pageIndex = 0, int pageSize = int.MaxValue, Expression>? orderBySelector = null, + string[]? excludedCustomerGroupIds = null, bool excludeVendorAndStaffAccounts = false); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/IVendorService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/IVendorService.cs index e2227c64c..dfca4ad35 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Customers/IVendorService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Customers/IVendorService.cs @@ -108,7 +108,7 @@ Task> GetAllVendors(string name = "", /// Reviews Task> GetAllVendorReviews(string customerId, bool? approved, DateTime? fromUtc = null, DateTime? toUtc = null, - string message = null, string vendorId = "", int pageIndex = 0, int pageSize = int.MaxValue); + string? message = null, string vendorId = "", int pageIndex = 0, int pageSize = int.MaxValue); /// /// Gets vendor review @@ -129,7 +129,7 @@ Task> GetAllVendorReviews(string customerId, bool? appr /// Vendor identifier; "" to load all records /// Keywords /// Vendors - Task> SearchVendors(string vendorId = "", string keywords = null); + Task> SearchVendors(string vendorId = "", string? keywords = null); #endregion } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.cs index 19861022a..73e890174 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.cs @@ -72,8 +72,8 @@ Task DeleteNewsLetterSubscription(NewsLetterSubscription newsLetterSubscription, /// Page index /// Page size /// NewsLetterSubscription entities - Task> GetAllNewsLetterSubscriptions(string email = null, - string storeId = "", bool? isActive = null, string[] categoryIds = null, int pageIndex = 0, + Task> GetAllNewsLetterSubscriptions(string? email = null, + string storeId = "", bool? isActive = null, string[]? categoryIds = null, int pageIndex = 0, int pageSize = int.MaxValue); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/PushNotifications/IPushNotificationsService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/PushNotifications/IPushNotificationsService.cs index a36b7c305..58c5f797a 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/PushNotifications/IPushNotificationsService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/PushNotifications/IPushNotificationsService.cs @@ -77,7 +77,7 @@ public interface IPushNotificationsService /// Cancels the request to the push service /// Bool indicating whether message was sent successfully and string result to display Task<(bool, string)> SendPushNotification(string title, string text, string pictureUrl, string clickUrl, - List registrationIds = null, CancellationToken cancellationToken = default); + List? registrationIds = null, CancellationToken cancellationToken = default); /// /// Sends push notification to all receivers diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/ICatalogMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/ICatalogMessageProviderService.cs index 6c17df3f5..ee8a12694 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/ICatalogMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/ICatalogMessageProviderService.cs @@ -22,7 +22,7 @@ public interface ICatalogMessageProviderService /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendProductEmailAFriendMessage(Customer customer, Store store, string languageId, - Product product, string customerEmail, string friendsEmail, string personalMessage, DomainHost host = null); + Product product, string customerEmail, string friendsEmail, string personalMessage, DomainHost? host = null); /// /// Sends wishlist "email a friend" message @@ -38,7 +38,7 @@ Task SendProductEmailAFriendMessage(Customer customer, Store store, string /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendWishlistEmailAFriendMessage(Customer customer, Store store, string languageId, - string customerEmail, string friendsEmail, string personalMessage, DomainHost host = null); + string customerEmail, string friendsEmail, string personalMessage, DomainHost? host = null); /// /// Sends "email a friend" message @@ -49,7 +49,7 @@ Task SendWishlistEmailAFriendMessage(Customer customer, Store store, string /// Task SendProductQuestionMessage(Customer customer, Store store, string languageId, Product product, string customerEmail, string fullName, string phone, string message, string ipaddress, - DomainHost host = null); + DomainHost? host = null); /// /// Sends a product review notification message to a store owner @@ -63,7 +63,7 @@ Task SendProductQuestionMessage(Customer customer, Store store, string lang /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendProductReviewMessage(Product product, ProductReview productReview, Store store, string languageId, - DomainHost host = null); + DomainHost? host = null); /// /// Sends a "quantity below" notification to a store owner diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/ICmsMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/ICmsMessageProviderService.cs index 4cb4539eb..9fb5f2054 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/ICmsMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/ICmsMessageProviderService.cs @@ -15,7 +15,7 @@ public interface ICmsMessageProviderService /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendBlogCommentMessage(BlogPost blogPost, BlogComment blogComment, string languageId, - DomainHost host = null); + DomainHost? host = null); /// /// Sends an article comment notification message to a store owner @@ -28,7 +28,7 @@ Task SendBlogCommentMessage(BlogPost blogPost, BlogComment blogComment, str /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendArticleCommentMessage(KnowledgebaseArticle article, KnowledgebaseArticleComment articleComment, - string languageId, DomainHost host = null); + string languageId, DomainHost? host = null); /// /// Sends a news comment notification message to a store owner @@ -41,5 +41,5 @@ Task SendArticleCommentMessage(KnowledgebaseArticle article, KnowledgebaseA /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendNewsCommentMessage(NewsItem newsItem, NewsComment newsComment, string languageId, - DomainHost host = null); + DomainHost? host = null); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/ICustomerMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/ICustomerMessageProviderService.cs index 24dbae0ea..57959b1bd 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/ICustomerMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/ICustomerMessageProviderService.cs @@ -17,7 +17,7 @@ public interface ICustomerMessageProviderService /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendCustomerRegisteredMessage(Customer customer, Store store, string languageId, DomainHost host = null); + Task SendCustomerRegisteredMessage(Customer customer, Store store, string languageId, DomainHost? host = null); /// /// Sends a welcome message to a customer @@ -29,7 +29,7 @@ public interface ICustomerMessageProviderService /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendCustomerWelcomeMessage(Customer customer, Store store, string languageId, DomainHost host = null); + Task SendCustomerWelcomeMessage(Customer customer, Store store, string languageId, DomainHost? host = null); /// /// Sends an email validation message to a customer @@ -42,7 +42,7 @@ public interface ICustomerMessageProviderService /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendCustomerEmailValidationMessage(Customer customer, Store store, string languageId, - DomainHost host = null); + DomainHost? host = null); /// /// Sends password recovery message to a customer @@ -55,7 +55,7 @@ Task SendCustomerEmailValidationMessage(Customer customer, Store store, str /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendCustomerPasswordRecoveryMessage(Customer customer, Store store, string languageId, - DomainHost host = null); + DomainHost? host = null); /// /// Sends a new customer note added notification to a customer @@ -78,7 +78,7 @@ Task SendCustomerPasswordRecoveryMessage(Customer customer, Store store, st /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendCustomerEmailTokenValidationMessage(Customer customer, Store store, string languageId, - DomainHost host = null); + DomainHost? host = null); /// /// Sends a "customer delete" notification to a store owner @@ -89,7 +89,7 @@ Task SendCustomerEmailTokenValidationMessage(Customer customer, Store store /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendCustomerDeleteStoreOwnerMessage(Customer customer, string languageId, DomainHost host = null); + Task SendCustomerDeleteStoreOwnerMessage(Customer customer, string languageId, DomainHost? host = null); /// /// Sends "contact us" message @@ -110,7 +110,7 @@ Task SendCustomerEmailTokenValidationMessage(Customer customer, Store store /// Task SendContactUsMessage(Customer customer, Store store, string languageId, string senderEmail, string senderName, string subject, string body, string attrInfo, IList customAttributes, - string ipaddress, DomainHost host = null); + string ipaddress, DomainHost? host = null); /// /// Sends an 'Order approval requested' message to the approver @@ -125,7 +125,7 @@ Task SendContactUsMessage(Customer customer, Store store, string languageId /// /// Queued email identifier Task SendOrderApprovalRequestedMessage(OrderApproval approval, Customer buyer, Customer approver, - Store store, string languageId, DomainHost host = null); + Store store, string languageId, DomainHost? host = null); /// /// Sends an 'Order approval decided' message to the buyer @@ -139,7 +139,7 @@ Task SendOrderApprovalRequestedMessage(OrderApproval approval, Customer buy /// /// Queued email identifier Task SendOrderApprovalDecidedMessage(OrderApproval approval, Customer buyer, Store store, - string languageId, DomainHost host = null); + string languageId, DomainHost? host = null); /// /// Sends an 'Order approval decided' message to the given address, for a buyer who has none of their own diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailSender.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailSender.cs index ba89c20fc..ca6d65c49 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailSender.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailSender.cs @@ -33,8 +33,8 @@ public interface IEmailSender /// Task SendEmail(EmailAccount emailAccount, string subject, string body, string fromAddress, string fromName, string toAddress, string toName, - string replyToAddress = null, string replyToName = null, - IEnumerable bcc = null, IEnumerable cc = null, - string attachmentFilePath = null, string attachmentFileName = null, - IEnumerable attachedDownloads = null, CancellationToken cancellationToken = default); + string? replyToAddress = null, string? replyToName = null, + IEnumerable? bcc = null, IEnumerable? cc = null, + string? attachmentFilePath = null, string? attachmentFileName = null, + IEnumerable? attachedDownloads = null, CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IMerchandiseReturnMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IMerchandiseReturnMessageProviderService.cs index 9ef57c97d..445eb1972 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/IMerchandiseReturnMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IMerchandiseReturnMessageProviderService.cs @@ -16,7 +16,7 @@ public interface IMerchandiseReturnMessageProviderService /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendNewMerchandiseReturnStoreOwnerMessage(MerchandiseReturn merchandiseReturn, Order order, - string languageId, DomainHost host = null); + string languageId, DomainHost? host = null); /// /// Sends the customer the message of the status the merchandise return reached (accepted, received, rejected, @@ -29,7 +29,7 @@ Task SendNewMerchandiseReturnStoreOwnerMessage(MerchandiseReturn merchandis /// The note shown to the customer with the change, e.g. why the return was rejected /// Queued email identifier Task SendMerchandiseReturnStatusChangedCustomerMessage(MerchandiseReturn merchandiseReturn, Order order, - string languageId, string statusNote = null); + string languageId, string? statusNote = null); /// /// Sends 'New Merchandise Return' message to a customer @@ -42,7 +42,7 @@ Task SendMerchandiseReturnStatusChangedCustomerMessage(MerchandiseReturn me /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendNewMerchandiseReturnCustomerMessage(MerchandiseReturn merchandiseReturn, Order order, - string languageId, DomainHost host = null); + string languageId, DomainHost? host = null); /// /// Sends a new merchandise return note added notification to a customer @@ -66,5 +66,5 @@ Task SendNewMerchandiseReturnNoteAddedCustomerMessage(MerchandiseReturn mer /// /// Queued email identifier Task SendNewMerchandiseReturnNoteAddedStoreOwnerMessage(MerchandiseReturn merchandiseReturn, - MerchandiseReturnNote merchandiseReturnNote, Order order, string languageId, DomainHost host = null); + MerchandiseReturnNote merchandiseReturnNote, Order order, string languageId, DomainHost? host = null); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageProviderService.cs index 815b12cf8..682e52af5 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageProviderService.cs @@ -29,9 +29,9 @@ public interface IMessageProviderService Task SendNotification(MessageTemplate messageTemplate, EmailAccount emailAccount, string languageId, LiquidObject liquidObject, string toEmailAddress, string toName, - string attachmentFilePath = null, string attachmentFileName = null, - IEnumerable attachedDownloads = null, - string replyToEmailAddress = null, string replyToName = null, - string fromEmail = null, string fromName = null, string subject = null, - Reference reference = Reference.None, string objectId = "", string invoiceDownloadId = null); + string? attachmentFilePath = null, string? attachmentFileName = null, + IEnumerable? attachedDownloads = null, + string? replyToEmailAddress = null, string? replyToName = null, + string? fromEmail = null, string? fromName = null, string? subject = null, + Reference reference = Reference.None, string objectId = "", string? invoiceDownloadId = null); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/INewsletterMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/INewsletterMessageProviderService.cs index 517fcaf3d..0ae2f5936 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/INewsletterMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/INewsletterMessageProviderService.cs @@ -15,7 +15,7 @@ public interface INewsletterMessageProviderService /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendNewsLetterSubscriptionActivationMessage(NewsLetterSubscription subscription, - string languageId, DomainHost host = null); + string languageId, DomainHost? host = null); /// /// Sends a newsletter subscription deactivation message @@ -27,5 +27,5 @@ Task SendNewsLetterSubscriptionActivationMessage(NewsLetterSubscription sub /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendNewsLetterSubscriptionDeactivationMessage(NewsLetterSubscription subscription, - string languageId, DomainHost host = null); + string languageId, DomainHost? host = null); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IOrderMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IOrderMessageProviderService.cs index cffb7484a..bc1ca26f7 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/IOrderMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IOrderMessageProviderService.cs @@ -20,7 +20,7 @@ public interface IOrderMessageProviderService /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendOrderPlacedVendorMessage(Order order, Customer customer, Vendor vendor, string languageId, - DomainHost host = null); + DomainHost? host = null); /// /// Sends an order placed notification to a store owner @@ -33,7 +33,7 @@ Task SendOrderPlacedVendorMessage(Order order, Customer customer, Vendor ve /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendOrderPlacedStoreOwnerMessage(Order order, Customer customer, string languageId, - DomainHost host = null); + DomainHost? host = null); /// /// Sends an order paid notification to a store owner @@ -55,7 +55,7 @@ Task SendOrderPlacedStoreOwnerMessage(Order order, Customer customer, strin /// /// Queued email identifier Task SendOrderPaidCustomerMessage(Order order, Customer customer, string languageId, - string invoiceDownloadId = null); + string? invoiceDownloadId = null); /// /// Sends an order paid notification to a vendor @@ -80,7 +80,7 @@ Task SendOrderPaidCustomerMessage(Order order, Customer customer, string la /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendOrderPlacedCustomerMessage(Order order, Customer customer, string languageId, - string invoiceDownloadId = null, DomainHost host = null); + string? invoiceDownloadId = null, DomainHost? host = null); /// /// Sends a shipment sent notification to a customer @@ -109,7 +109,7 @@ Task SendOrderPlacedCustomerMessage(Order order, Customer customer, string /// /// Queued email identifier Task SendOrderCompletedCustomerMessage(Order order, Customer customer, string languageId, - string invoiceDownloadId = null); + string? invoiceDownloadId = null); /// /// Sends an order cancelled notification to a customer @@ -183,7 +183,7 @@ Task SendOrderCompletedCustomerMessage(Order order, Customer customer, stri /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendNewOrderNoteAddedCustomerMessage(Order order, OrderNote orderNote, DomainHost host = null); + Task SendNewOrderNoteAddedCustomerMessage(Order order, OrderNote orderNote, DomainHost? host = null); /// /// Sends a gift voucher notification @@ -203,5 +203,5 @@ Task SendOrderCompletedCustomerMessage(Order order, Customer customer, stri /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// /// Queued email identifier - Task SendGuestOrderLinkCustomerMessage(Order order, string token, DomainHost host = null); + Task SendGuestOrderLinkCustomerMessage(Order order, string token, DomainHost? host = null); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IVendorMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IVendorMessageProviderService.cs index 7652ae707..89ea61c5e 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/IVendorMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IVendorMessageProviderService.cs @@ -19,7 +19,7 @@ public interface IVendorMessageProviderService /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendNewVendorAccountApplyStoreOwnerMessage(Customer customer, Vendor vendor, Store store, - string languageId, DomainHost host = null); + string languageId, DomainHost? host = null); /// /// Sends 'Vendor information change' message to a store owner @@ -41,7 +41,7 @@ Task SendNewVendorAccountApplyStoreOwnerMessage(Customer customer, Vendor v /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendVendorReviewMessage(VendorReview vendorReview, Store store, string languageId, - DomainHost host = null); + DomainHost? host = null); /// /// Sends "contact vendor" message @@ -60,5 +60,5 @@ Task SendVendorReviewMessage(VendorReview vendorReview, Store store, string /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendContactVendorMessage(Customer customer, Store store, Vendor vendor, string languageId, - string senderEmail, string senderName, string subject, string body, string ipaddress, DomainHost host = null); + string senderEmail, string senderName, string subject, string body, string ipaddress, DomainHost? host = null); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Storage/IFileStore.cs b/src/Business/Grand.Business.Core/Interfaces/Storage/IFileStore.cs index 8c417d12a..b744a15da 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Storage/IFileStore.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Storage/IFileStore.cs @@ -41,7 +41,7 @@ public interface IFileStore /// /// Results are grouped by entry type, where directories are followed by files. /// - IList GetDirectoryContent(string path = null, bool includeSubDirectories = false, + IList GetDirectoryContent(string? path = null, bool includeSubDirectories = false, bool listDirectories = true, bool listFiles = true); /// @@ -158,7 +158,7 @@ public static class IFileStoreExtensions /// The . /// The path parts to combine. /// The full combined path. - public static string Combine(this IFileStore fileStore, params ReadOnlySpan paths) + public static string? Combine(this IFileStore fileStore, params ReadOnlySpan paths) { if (paths.Length == 0) return null; @@ -185,7 +185,7 @@ public static string Combine(this IFileStore fileStore, params ReadOnlySpan - public static string NormalizePath(this IFileStore fileStore, string path) + public static string? NormalizePath(this IFileStore fileStore, string path) { return path?.Replace('\\', '/').Trim('/', ' '); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs b/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs index 3e82f876b..9c176ab08 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs @@ -38,7 +38,7 @@ public interface IPictureService /// The target picture size (longest side) /// Store location URL; null to use determine the current store location automatically /// Picture URL - Task GetDefaultPictureUrl(int targetSize = 0, string storeLocation = null); + Task GetDefaultPictureUrl(int targetSize = 0, string? storeLocation = null); /// /// Get a picture URL @@ -51,7 +51,7 @@ public interface IPictureService Task GetPictureUrl(string pictureId, int targetSize = 0, bool showDefaultPicture = true, - string storeLocation = null); + string? storeLocation = null); /// /// Get a picture URL @@ -64,7 +64,7 @@ Task GetPictureUrl(string pictureId, Task GetPictureUrl(Picture picture, int targetSize = 0, bool showDefaultPicture = true, - string storeLocation = null); + string? storeLocation = null); /// /// Get a picture local path @@ -129,7 +129,7 @@ Task GetPictureUrl(Picture picture, /// A value indicating whether to validated provided picture binary /// Picture Task InsertPicture(byte[] pictureBinary, string mimeType, string seoFilename, - string altAttribute = null, string titleAttribute = null, + string? altAttribute = null, string? titleAttribute = null, bool isNew = true, Reference reference = Reference.None, string objectId = "", bool validateBinary = false); /// @@ -147,8 +147,8 @@ Task InsertPicture(byte[] pictureBinary, string mimeType, string seoFil /// A value indicating whether to validated provided picture binary /// Picture Task UpdatePicture(string pictureId, byte[] pictureBinary, string mimeType, - string seoFilename, string altAttribute = null, string titleAttribute = null, - string style = null, string extraField = null, + string seoFilename, string? altAttribute = null, string? titleAttribute = null, + string? style = null, string? extraField = null, bool isNew = true, bool validateBinary = true); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/System/Reports/IOrderReportService.cs b/src/Business/Grand.Business.Core/Interfaces/System/Reports/IOrderReportService.cs index 5ca4fbe30..c72edaa66 100644 --- a/src/Business/Grand.Business.Core/Interfaces/System/Reports/IOrderReportService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/System/Reports/IOrderReportService.cs @@ -60,12 +60,12 @@ Task> GetOrderByTimeReport(string storeId = "", Dat /// Result Task GetOrderAverageReportLine(string storeId = "", string customerId = "", string vendorId = "", string salesEmployeeId = "", - string billingCountryId = "", string orderId = "", string paymentMethodSystemName = null, + string billingCountryId = "", string orderId = "", string? paymentMethodSystemName = null, int? os = null, PaymentStatus? ps = null, ShippingStatus? ss = null, DateTime? startTimeUtc = null, DateTime? endTimeUtc = null, - string billingEmail = null, string billingLastName = "", + string? billingEmail = null, string billingLastName = "", bool ignoreCancelledOrders = false, - string tagId = null); + string? tagId = null); /// diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetDiscountUsageHistoryQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetDiscountUsageHistoryQuery.cs index f6fea16de..2fadb3cb4 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetDiscountUsageHistoryQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetDiscountUsageHistoryQuery.cs @@ -6,9 +6,9 @@ namespace Grand.Business.Core.Queries.Catalog; public record GetDiscountUsageHistoryQuery : IRequest> { - public string DiscountId { get; set; } - public string CustomerId { get; set; } - public string OrderId { get; set; } + public string? DiscountId { get; set; } + public string? CustomerId { get; set; } + public string? OrderId { get; set; } public bool? Canceled { get; set; } = null; public int PageIndex { get; set; } public int PageSize { get; set; } = int.MaxValue; diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetPersonalizedProductsQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetPersonalizedProductsQuery.cs index 2cf03864c..857f5b757 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetPersonalizedProductsQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetPersonalizedProductsQuery.cs @@ -7,6 +7,6 @@ namespace Grand.Business.Core.Queries.Catalog; public class GetPersonalizedProductsQuery : IRequest> { public int ProductsNumber { get; set; } - public Customer Customer { get; set; } - public string StoreId { get; set; } + public Customer? Customer { get; set; } + public string? StoreId { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetPriceByCustomerProductQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetPriceByCustomerProductQuery.cs index e8593047d..b1b635c8a 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetPriceByCustomerProductQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetPriceByCustomerProductQuery.cs @@ -4,6 +4,6 @@ namespace Grand.Business.Core.Queries.Catalog; public class GetPriceByCustomerProductQuery : IRequest { - public string CustomerId { get; set; } - public string ProductId { get; set; } + public string? CustomerId { get; set; } + public string? ProductId { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetProductArchByIdQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetProductArchByIdQuery.cs index 1daee0782..4b289e887 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetProductArchByIdQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetProductArchByIdQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Catalog; public class GetProductArchByIdQuery : IRequest { - public string Id { get; set; } + public string? Id { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetRecommendedProductsQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetRecommendedProductsQuery.cs index 1fb839a05..4ce1d47ce 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetRecommendedProductsQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetRecommendedProductsQuery.cs @@ -6,6 +6,6 @@ namespace Grand.Business.Core.Queries.Catalog; public class GetRecommendedProductsQuery : IRequest> { - public string StoreId { get; set; } - public Customer Customer { get; set; } + public string? StoreId { get; set; } + public Customer? Customer { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetSearchProductsQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetSearchProductsQuery.cs index ec79a6620..0fe85706c 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetSearchProductsQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetSearchProductsQuery.cs @@ -8,18 +8,18 @@ namespace Grand.Business.Core.Queries.Catalog; public class GetSearchProductsQuery : IRequest<(IPagedList products, IList filterableSpecificationAttributeOptionIds)> { - public Customer Customer { get; set; } + public Customer? Customer { get; set; } /// /// Customer groups the ACL filter uses instead of the groups of ; /// lets callers without a customer (e.g. scheduled tasks) search as a given audience /// - public IList CustomerGroupIds { get; set; } + public IList? CustomerGroupIds { get; set; } public bool LoadFilterableSpecificationAttributeOptionIds { get; set; } = false; public int PageIndex { get; set; } = 0; public int PageSize { get; set; } = int.MaxValue; - public IList CategoryIds { get; set; } + public IList? CategoryIds { get; set; } public string BrandId { get; set; } = ""; public string CollectionId { get; set; } = ""; public string StoreId { get; set; } = ""; @@ -34,13 +34,13 @@ public class GetSearchProductsQuery : IRequest<(IPagedList products, IL public double? PriceMax { get; set; } public double? Rating { get; set; } public string ProductTag { get; set; } = ""; - public string Keywords { get; set; } + public string? Keywords { get; set; } public bool SearchDescriptions { get; set; } public bool SearchSku { get; set; } = true; public bool SearchProductTags { get; set; } public string LanguageId { get; set; } = ""; - public IList FilteredSpecs { get; set; } - public IList SpecificationOptions { get; set; } + public IList? FilteredSpecs { get; set; } + public IList? SpecificationOptions { get; set; } public ProductSortingEnum OrderBy { get; set; } = ProductSortingEnum.Position; public bool ShowHidden { get; set; } public bool? OverridePublished { get; set; } diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetShoppingCartItemsSubTotalQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetShoppingCartItemsSubTotalQuery.cs index 5998cd793..3c082a92c 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetShoppingCartItemsSubTotalQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetShoppingCartItemsSubTotalQuery.cs @@ -13,7 +13,7 @@ namespace Grand.Business.Core.Queries.Catalog; /// public class GetShoppingCartItemsSubTotalQuery : IRequest { - public Customer Customer { get; set; } - public Store Store { get; set; } + public Customer? Customer { get; set; } + public Store? Store { get; set; } public IList Items { get; set; } = new List(); } diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetSitemapProductsQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetSitemapProductsQuery.cs index 6bd67a2aa..b53d4f553 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetSitemapProductsQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetSitemapProductsQuery.cs @@ -8,14 +8,14 @@ namespace Grand.Business.Core.Queries.Catalog; /// public class GetSitemapProductsQuery : IRequest> { - public string StoreId { get; set; } + public string? StoreId { get; set; } public IList CustomerGroupIds { get; set; } = []; - public string LanguageId { get; set; } + public string? LanguageId { get; set; } /// /// Id of the last product of the previous batch; null for the first batch /// - public string AfterId { get; set; } + public string? AfterId { get; set; } public int PageSize { get; set; } = 1000; } diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetSuggestedProductsQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetSuggestedProductsQuery.cs index a0eb80aaf..26734f9e4 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetSuggestedProductsQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetSuggestedProductsQuery.cs @@ -7,6 +7,6 @@ namespace Grand.Business.Core.Queries.Catalog; public class GetSuggestedProductsQuery : IRequest> { public int ProductsNumber { get; set; } - public Customer Customer { get; set; } - public string StoreId { get; set; } + public Customer? Customer { get; set; } + public string? StoreId { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetVendorByIdQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetVendorByIdQuery.cs index d3b661c2a..379679800 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetVendorByIdQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetVendorByIdQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Catalog; public class GetVendorByIdQuery : IRequest { - public string Id { get; set; } + public string? Id { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanCancelOrderQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanCancelOrderQuery.cs index fb5b7afb9..799aabc26 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanCancelOrderQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanCancelOrderQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanCancelOrderQuery : IRequest { - public Order Order { get; set; } + public Order? Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanCaptureQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanCaptureQuery.cs index 8535a10f3..2c914d9a1 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanCaptureQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanCaptureQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanCaptureQuery : IRequest { - public PaymentTransaction PaymentTransaction { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanDeletePaymentTransactionQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanDeletePaymentTransactionQuery.cs index 6992c2525..a1607ec94 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanDeletePaymentTransactionQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanDeletePaymentTransactionQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanDeletePaymentTransactionQuery : IRequest { - public PaymentTransaction PaymentTransaction { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } } diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanMarkPaymentTransactionAsAuthorizedQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanMarkPaymentTransactionAsAuthorizedQuery.cs index fcff7f0de..60992c162 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanMarkPaymentTransactionAsAuthorizedQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanMarkPaymentTransactionAsAuthorizedQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanMarkPaymentTransactionAsAuthorizedQuery : IRequest { - public PaymentTransaction PaymentTransaction { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanMarkPaymentTransactionAsPaidQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanMarkPaymentTransactionAsPaidQuery.cs index 3d4f72f4a..68ab90983 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanMarkPaymentTransactionAsPaidQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanMarkPaymentTransactionAsPaidQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanMarkPaymentTransactionAsPaidQuery : IRequest { - public PaymentTransaction PaymentTransaction { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyPaidOfflineQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyPaidOfflineQuery.cs index a57120b80..9411dc6d4 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyPaidOfflineQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyPaidOfflineQuery.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanPartiallyPaidOfflineQuery : IRequest { - public PaymentTransaction PaymentTransaction { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } public double AmountToPaid { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyRefundOfflineQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyRefundOfflineQuery.cs index 3da0cbee0..8c890e615 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyRefundOfflineQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyRefundOfflineQuery.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanPartiallyRefundOfflineQuery : IRequest { - public PaymentTransaction PaymentTransaction { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } public double AmountToRefund { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyRefundQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyRefundQuery.cs index d3cec90db..f12d9528e 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyRefundQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyRefundQuery.cs @@ -6,5 +6,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanPartiallyRefundQuery : IRequest { public double AmountToRefund { get; set; } - public PaymentTransaction PaymentTransaction { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanRefundOfflineQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanRefundOfflineQuery.cs index 2bfc40d19..9ab5816a0 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanRefundOfflineQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanRefundOfflineQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanRefundOfflineQuery : IRequest { - public PaymentTransaction PaymentTransaction { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanRefundQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanRefundQuery.cs index deafc6e8b..dd30fac49 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanRefundQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanRefundQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanRefundQuery : IRequest { - public PaymentTransaction PaymentTransaction { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanVoidOfflineQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanVoidOfflineQuery.cs index fd6ad884d..62a458cc1 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanVoidOfflineQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanVoidOfflineQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanVoidOfflineQuery : IRequest { - public PaymentTransaction PaymentTransaction { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanVoidQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanVoidQuery.cs index e60b82288..90485c4ba 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanVoidQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanVoidQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanVoidQuery : IRequest { - public PaymentTransaction PaymentTransaction { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetGiftVoucherQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetGiftVoucherQuery.cs index cea320dcc..7998c4996 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetGiftVoucherQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetGiftVoucherQuery.cs @@ -13,7 +13,7 @@ public class GetGiftVoucherQuery : IRequest> public string Code { get; set; } = ""; public DateTime? CreatedFromUtc { get; set; } = null; public DateTime? CreatedToUtc { get; set; } = null; - public string RecipientName { get; set; } = null; + public string? RecipientName { get; set; } = null; public int PageIndex { get; set; } = 0; public int PageSize { get; set; } = int.MaxValue; } diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetMerchandiseReturnCountQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetMerchandiseReturnCountQuery.cs index 7712bca65..cae8779d5 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetMerchandiseReturnCountQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetMerchandiseReturnCountQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class GetMerchandiseReturnCountQuery : IRequest { public int RequestStatusId { get; set; } - public string StoreId { get; set; } + public string? StoreId { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetOrderQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetOrderQuery.cs index 2ff605597..39cf532f4 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetOrderQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetOrderQuery.cs @@ -18,19 +18,19 @@ public class GetOrderQuery : IRequest> public string BillingCountryId { get; set; } = ""; public string OwnerId { get; set; } = ""; public string SalesEmployeeId { get; set; } = ""; - public string PaymentMethodSystemName { get; set; } = null; + public string? PaymentMethodSystemName { get; set; } = null; public DateTime? CreatedFromUtc { get; set; } = null; public DateTime? CreatedToUtc { get; set; } = null; public int? Os { get; set; } = null; public PaymentStatus? Ps { get; set; } = null; public ShippingStatus? Ss { get; set; } = null; - public string BillingEmail { get; set; } = null; + public string? BillingEmail { get; set; } = null; public string BillingLastName { get; set; } = ""; - public string OrderGuid { get; set; } = null; - public string OrderCode { get; set; } = null; + public string? OrderGuid { get; set; } = null; + public string? OrderCode { get; set; } = null; public int PageIndex { get; set; } = 0; public int PageSize { get; set; } = int.MaxValue; public string OrderTagId { get; set; } = ""; - public string PurchaseOrderNumber { get; set; } = null; + public string? PurchaseOrderNumber { get; set; } = null; public bool OverdueOnly { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPaymentTransactionQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPaymentTransactionQuery.cs index a012978cb..83bdb60c2 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPaymentTransactionQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPaymentTransactionQuery.cs @@ -19,14 +19,14 @@ public class GetPaymentTransactionQuery : IRequest public bool IncludeTemp { get; set; } = true; - public string PaymentMethodSystemName { get; set; } + public string? PaymentMethodSystemName { get; set; } /// Only the payments of orders carrying this purchase order number, matched exactly. - public string PurchaseOrderNumber { get; set; } + public string? PurchaseOrderNumber { get; set; } /// Only the payments of orders bought on credit and past their due date. public bool OverdueOnly { get; set; } /// Only the payments of this sales employee's orders. - public string SalesEmployeeId { get; set; } + public string? SalesEmployeeId { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPickupPointById.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPickupPointById.cs index 64a8a1092..f904e64a9 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPickupPointById.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPickupPointById.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class GetPickupPointById : IRequest { - public string Id { get; set; } + public string? Id { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetRecurringPaymentsQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetRecurringPaymentsQuery.cs index 16ed8dd39..a95a9edb2 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetRecurringPaymentsQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetRecurringPaymentsQuery.cs @@ -9,15 +9,15 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; /// public class GetRecurringPaymentsQuery : IRequest> { - public string StoreId { get; set; } + public string? StoreId { get; set; } /// Only the recurring payments of the customers with this e-mail, matched exactly. - public string CustomerEmail { get; set; } + public string? CustomerEmail { get; set; } public RecurringPaymentStatus? Status { get; set; } /// Only the recurring payments whose initial order belongs to this sales employee. - public string SalesEmployeeId { get; set; } + public string? SalesEmployeeId { get; set; } public int PageIndex { get; set; } public int PageSize { get; set; } = int.MaxValue; diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetReturnableQuantitiesQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetReturnableQuantitiesQuery.cs index 468fe2905..327b83100 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetReturnableQuantitiesQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetReturnableQuantitiesQuery.cs @@ -9,7 +9,7 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; /// public class GetReturnableQuantitiesQuery : IRequest> { - public Order Order { get; set; } + public Order? Order { get; set; } /// /// For staff: only what was delivered less what the other returns take. The return period and products marked diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetVendorsInOrderQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetVendorsInOrderQuery.cs index 114e539a0..9df1c26bf 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetVendorsInOrderQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetVendorsInOrderQuery.cs @@ -6,5 +6,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class GetVendorsInOrderQuery : IRequest> { - public Order Order { get; set; } + public Order? Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/IsMerchandiseReturnAllowedQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/IsMerchandiseReturnAllowedQuery.cs index 338568e53..560935ec3 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/IsMerchandiseReturnAllowedQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/IsMerchandiseReturnAllowedQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class IsMerchandiseReturnAllowedQuery : IRequest { - public Order Order { get; set; } + public Order? Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Customers/GetCustomerQuery.cs b/src/Business/Grand.Business.Core/Queries/Customers/GetCustomerQuery.cs index b52d579b7..c7461f62f 100644 --- a/src/Business/Grand.Business.Core/Queries/Customers/GetCustomerQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Customers/GetCustomerQuery.cs @@ -20,25 +20,25 @@ public class GetCustomerQuery : IRequest> public string StoreId { get; set; } = ""; public string OwnerId { get; set; } = ""; public string SalesEmployeeId { get; set; } = ""; - public string[] CustomerGroupIds { get; set; } = null; - public string[] CustomerTagIds { get; set; } = null; + public string[]? CustomerGroupIds { get; set; } = null; + public string[]? CustomerTagIds { get; set; } = null; /// Customers in any of these groups are left out - public string[] ExcludedCustomerGroupIds { get; set; } = null; + public string[]? ExcludedCustomerGroupIds { get; set; } = null; /// Leaves out accounts tied to a vendor or a staff store public bool ExcludeVendorAndStaffAccounts { get; set; } = false; - public string Email { get; set; } = null; - public string Username { get; set; } = null; - public string FirstName { get; set; } = null; - public string LastName { get; set; } = null; - public string Company { get; set; } = null; - public string Phone { get; set; } = null; - public string ZipPostalCode { get; set; } = null; + public string? Email { get; set; } = null; + public string? Username { get; set; } = null; + public string? FirstName { get; set; } = null; + public string? LastName { get; set; } = null; + public string? Company { get; set; } = null; + public string? Phone { get; set; } = null; + public string? ZipPostalCode { get; set; } = null; public bool LoadOnlyWithShoppingCart { get; set; } = false; public ShoppingCartType? Sct { get; set; } = null; public int PageIndex { get; set; } = 0; public int PageSize { get; set; } = int.MaxValue; - public Expression> OrderBySelector { get; set; } = null; + public Expression>? OrderBySelector { get; set; } = null; } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Customers/GetPasswordIsExpiredQuery.cs b/src/Business/Grand.Business.Core/Queries/Customers/GetPasswordIsExpiredQuery.cs index a848bb4d9..69201dae7 100644 --- a/src/Business/Grand.Business.Core/Queries/Customers/GetPasswordIsExpiredQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Customers/GetPasswordIsExpiredQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Customers; public class GetPasswordIsExpiredQuery : IRequest { - public Customer Customer { get; set; } + public Customer? Customer { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Messages/GetBidsByProductIdQuery.cs b/src/Business/Grand.Business.Core/Queries/Messages/GetBidsByProductIdQuery.cs index 8a14a5eb7..27837677e 100644 --- a/src/Business/Grand.Business.Core/Queries/Messages/GetBidsByProductIdQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Messages/GetBidsByProductIdQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Messages; public class GetBidsByProductIdQuery : IRequest> { - public string ProductId { get; set; } + public string? ProductId { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Messages/GetCustomerByIdQuery.cs b/src/Business/Grand.Business.Core/Queries/Messages/GetCustomerByIdQuery.cs index 451f174d2..e4db4e4f0 100644 --- a/src/Business/Grand.Business.Core/Queries/Messages/GetCustomerByIdQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Messages/GetCustomerByIdQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Messages; public class GetCustomerByIdQuery : IRequest { - public string Id { get; set; } + public string? Id { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Messages/GetProductByIdQuery.cs b/src/Business/Grand.Business.Core/Queries/Messages/GetProductByIdQuery.cs index ea406bc15..9b0c2e031 100644 --- a/src/Business/Grand.Business.Core/Queries/Messages/GetProductByIdQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Messages/GetProductByIdQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Messages; public class GetProductByIdQuery : IRequest { - public string Id { get; set; } + public string? Id { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Messages/GetVendorByIdQuery.cs b/src/Business/Grand.Business.Core/Queries/Messages/GetVendorByIdQuery.cs index af75f1082..135dd8d4c 100644 --- a/src/Business/Grand.Business.Core/Queries/Messages/GetVendorByIdQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Messages/GetVendorByIdQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Messages; public class GetVendorByIdQuery : IRequest { - public string Id { get; set; } + public string? Id { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthParam.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthParam.cs index 135eb8c63..68a75aca1 100644 --- a/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthParam.cs +++ b/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthParam.cs @@ -10,27 +10,27 @@ public class ExternalAuthParam /// /// Gets or sets the external authentication provider's system name /// - public string ProviderSystemName { get; set; } + public string? ProviderSystemName { get; set; } /// /// Gets or sets user id /// - public string Identifier { get; set; } + public string? Identifier { get; set; } /// /// Gets or sets user name /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets access token /// - public string AccessToken { get; set; } + public string? AccessToken { get; set; } /// /// Gets or sets user email /// - public string Email { get; set; } + public string? Email { get; set; } /// /// Gets or sets the additional user info as a list of a custom claims diff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthResult.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthResult.cs index fd5866fd9..619bf43eb 100644 --- a/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthResult.cs +++ b/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthResult.cs @@ -41,7 +41,7 @@ public enum ExternalAuthStatus /// public class ExternalAuthResult { - private ExternalAuthResult(ExternalAuthStatus status, Customer customer, IReadOnlyList errors) + private ExternalAuthResult(ExternalAuthStatus status, Customer? customer, IReadOnlyList errors) { Status = status; Customer = customer; @@ -51,7 +51,7 @@ private ExternalAuthResult(ExternalAuthStatus status, Customer customer, IReadOn public ExternalAuthStatus Status { get; } /// The customer to sign in (LoggedIn, Registered) or the one the account was associated with - public Customer Customer { get; } + public Customer? Customer { get; } /// Technical reasons of an Error result; empty for every other status public IReadOnlyList Errors { get; } diff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/OidcCustomerResult.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/OidcCustomerResult.cs index db765231d..99bd5f547 100644 --- a/src/Business/Grand.Business.Core/Utilities/Authentication/OidcCustomerResult.cs +++ b/src/Business/Grand.Business.Core/Utilities/Authentication/OidcCustomerResult.cs @@ -7,18 +7,18 @@ namespace Grand.Business.Core.Utilities.Authentication; /// public class OidcCustomerResult { - private OidcCustomerResult(Customer customer, OidcFailureKind? failure, string description) + private OidcCustomerResult(Customer? customer, OidcFailureKind? failure, string? description) { Customer = customer; Failure = failure; Description = description; } - public Customer Customer { get; } + public Customer? Customer { get; } public OidcFailureKind? Failure { get; } /// Fixed, token-independent text safe for error_description - public string Description { get; } + public string? Description { get; } public bool Succeeded => Customer != null; diff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/OidcLoginResult.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/OidcLoginResult.cs index c3bea558e..0afbba499 100644 --- a/src/Business/Grand.Business.Core/Utilities/Authentication/OidcLoginResult.cs +++ b/src/Business/Grand.Business.Core/Utilities/Authentication/OidcLoginResult.cs @@ -38,7 +38,7 @@ public enum OidcLinkResult /// public class OidcLoginResult { - private OidcLoginResult(OidcLoginOutcome outcome, Customer customer, OidcLoginRefusal refusal) + private OidcLoginResult(OidcLoginOutcome outcome, Customer? customer, OidcLoginRefusal refusal) { Outcome = outcome; Customer = customer; @@ -48,7 +48,7 @@ private OidcLoginResult(OidcLoginOutcome outcome, Customer customer, OidcLoginRe public OidcLoginOutcome Outcome { get; } /// The customer to sign in (SignIn) or the account to connect (LinkRequired) - public Customer Customer { get; } + public Customer? Customer { get; } public OidcLoginRefusal Refusal { get; } diff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/OidcRefreshResult.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/OidcRefreshResult.cs index 4426bfdc3..436fc085c 100644 --- a/src/Business/Grand.Business.Core/Utilities/Authentication/OidcRefreshResult.cs +++ b/src/Business/Grand.Business.Core/Utilities/Authentication/OidcRefreshResult.cs @@ -20,7 +20,7 @@ public enum OidcRefreshOutcome /// The answer of the provider /// The rotated refresh token, or null when the provider keeps the old one -public sealed record OidcRefreshResult(OidcRefreshOutcome Outcome, string RefreshToken = null) +public sealed record OidcRefreshResult(OidcRefreshOutcome Outcome, string? RefreshToken = null) { public static OidcRefreshResult Refreshed(string refreshToken) => new(OidcRefreshOutcome.Refreshed, refreshToken); public static OidcRefreshResult Refused() => new(OidcRefreshOutcome.Refused); diff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/PasswordSignInDecision.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/PasswordSignInDecision.cs index 05439c3b9..ea829319e 100644 --- a/src/Business/Grand.Business.Core/Utilities/Authentication/PasswordSignInDecision.cs +++ b/src/Business/Grand.Business.Core/Utilities/Authentication/PasswordSignInDecision.cs @@ -7,7 +7,7 @@ namespace Grand.Business.Core.Utilities.Authentication; /// is not available: sign-in is refused, never re-opened to the password). BreakGlass marks a password allowed only as the /// emergency access of a provider-only installation /// -public sealed record PasswordSignInDecision(bool Allowed, IExternalAuthenticationProvider Provider, bool BreakGlass = false) +public sealed record PasswordSignInDecision(bool Allowed, IExternalAuthenticationProvider? Provider, bool BreakGlass = false) { public static readonly PasswordSignInDecision Password = new(true, null); } diff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/ScimResults.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/ScimResults.cs index 4e4264ad6..c69b1b2a9 100644 --- a/src/Business/Grand.Business.Core/Utilities/Authentication/ScimResults.cs +++ b/src/Business/Grand.Business.Core/Utilities/Authentication/ScimResults.cs @@ -33,7 +33,7 @@ public record ScimUserView( DateTime? LastModified); /// Why the operation was refused, for the SCIM error; never an e-mail or another personal value -public record ScimUserResult(ScimOutcome Outcome, ScimUserView User = null, string Detail = null); +public record ScimUserResult(ScimOutcome Outcome, ScimUserView? User = null, string? Detail = null); /// The attributes of a SCIM group that GrandNode keeps; members are SCIM user ids (customer ids) public record ScimGroupData(string DisplayName, string ExternalId, IList MemberIds); @@ -47,7 +47,7 @@ public record ScimGroupView( DateTime? LastModified); /// Why the operation was refused, for the SCIM error -public record ScimGroupResult(ScimOutcome Outcome, ScimGroupView Group = null, string Detail = null); +public record ScimGroupResult(ScimOutcome Outcome, ScimGroupView? Group = null, string? Detail = null); public record ScimPage(IList Items, int Total); diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/ApplyDiscount.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/ApplyDiscount.cs index 7e0e74cdb..453cdcb11 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/ApplyDiscount.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/ApplyDiscount.cs @@ -8,12 +8,12 @@ public class ApplyDiscount /// /// Gets or sets the discount Id /// - public string DiscountId { get; set; } + public string? DiscountId { get; set; } /// /// Gets or sets the discount /// - public string CouponCode { get; set; } + public string? CouponCode { get; set; } /// diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/CatalogAccess.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/CatalogAccess.cs index 4df6d8014..e8fcad482 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/CatalogAccess.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/CatalogAccess.cs @@ -1,5 +1,6 @@ using Grand.Domain.Customers; using Grand.Infrastructure.Configuration; +using System.Diagnostics.CodeAnalysis; namespace Grand.Business.Core.Utilities.Catalog; @@ -11,7 +12,7 @@ namespace Grand.Business.Core.Utilities.Catalog; /// public sealed record CatalogAccess { - private CatalogAccess(Customer customer, string storeId) + private CatalogAccess(Customer? customer, string storeId) { Customer = customer; StoreId = storeId ?? ""; @@ -20,7 +21,7 @@ private CatalogAccess(Customer customer, string storeId) /// /// Gets the customer whose groups limit the records; null when hidden records are included /// - public Customer Customer { get; } + public Customer? Customer { get; } /// /// Gets the store whose limitations apply; empty when no store limits the records @@ -30,6 +31,7 @@ private CatalogAccess(Customer customer, string storeId) /// /// Gets a value indicating whether unpublished and group-limited records are included /// + [MemberNotNullWhen(false, nameof(Customer))] public bool ShowHidden => Customer == null; /// diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationRequest.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationRequest.cs index 7ed6cbb62..dabd4328c 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationRequest.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationRequest.cs @@ -12,20 +12,20 @@ public class DiscountRuleValidationRequest /// /// Gets or sets the discount /// - public Discount Discount { get; set; } + public Discount? Discount { get; set; } /// /// Gets or sets the discount rule /// - public DiscountRule DiscountRule { get; set; } + public DiscountRule? DiscountRule { get; set; } /// /// Gets or sets the customer /// - public Customer Customer { get; set; } + public Customer? Customer { get; set; } /// /// Gets or sets the store /// - public Store Store { get; set; } + public Store? Store { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationResult.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationResult.cs index 16f825b88..f0ab970bf 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationResult.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountRuleValidationResult.cs @@ -14,5 +14,5 @@ public class DiscountRuleValidationResult /// Gets or sets an error for a customer that should be visible when a coupon code is entered (in case if "IsValid" is /// set to "false") /// - public string UserError { get; set; } + public string? UserError { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountValidationResult.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountValidationResult.cs index 67ce4b2d8..f10454983 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountValidationResult.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/DiscountValidationResult.cs @@ -14,10 +14,10 @@ public class DiscountValidationResult /// Gets or sets an error for a customer that should be visible when a coupon code is entered (in case if "IsValid" is /// set to "false") /// - public string UserErrorResource { get; set; } + public string? UserErrorResource { get; set; } /// /// Gets or sets a coupon code value /// - public string CouponCode { get; set; } + public string? CouponCode { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/InventoryTracking.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/InventoryTracking.cs index b8bf076ab..c54e83550 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/InventoryTracking.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/InventoryTracking.cs @@ -51,8 +51,8 @@ public static bool ExternallyManaged(Product product, ICollection extern if (!product.UseMultipleWarehouses) return externallyManagedWarehouseIds.Contains(product.WarehouseId ?? ""); - return product.ProductWarehouseInventory.Any(x => externallyManagedWarehouseIds.Contains(x.WarehouseId)) || + return product.ProductWarehouseInventory.Any(x => externallyManagedWarehouseIds.Contains(x.WarehouseId ?? "")) || product.ProductAttributeCombinations.Any(combination => - combination.WarehouseInventory.Any(x => externallyManagedWarehouseIds.Contains(x.WarehouseId))); + combination.WarehouseInventory.Any(x => externallyManagedWarehouseIds.Contains(x.WarehouseId ?? ""))); } } diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/ProductsCategory.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/ProductsCategory.cs index 55ebf83b6..03648ff7b 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/ProductsCategory.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/ProductsCategory.cs @@ -4,5 +4,5 @@ namespace Grand.Business.Core.Utilities.Catalog; public class ProductsCategory : ProductCategory { - public string ProductId { get; set; } + public string? ProductId { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/ProductsCollection.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/ProductsCollection.cs index 1279c99af..ae79f8395 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/ProductsCollection.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/ProductsCollection.cs @@ -4,5 +4,5 @@ namespace Grand.Business.Core.Utilities.Catalog; public class ProductsCollection : ProductCollection { - public string ProductId { get; set; } + public string? ProductId { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/SearchTermReportLine.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/SearchTermReportLine.cs index 1424bb642..958b562fe 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/SearchTermReportLine.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/SearchTermReportLine.cs @@ -8,7 +8,7 @@ public class SearchTermReportLine /// /// Gets or sets the keyword /// - public string Keyword { get; set; } + public string? Keyword { get; set; } /// /// Gets or sets search count diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/StockBuckets.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/StockBuckets.cs index de99c6298..782d65933 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/StockBuckets.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/StockBuckets.cs @@ -26,7 +26,7 @@ public static IList InitialEntries(Product product, InventoryM var entries = new List(); - void Add(string combinationId, IList attributes, string warehouseId, int stock) + void Add(string combinationId, IList attributes, string? warehouseId, int stock) { if (stock == 0) return; @@ -155,7 +155,8 @@ public static IEnumerable Warehouses(Product product) .Concat(product.ProductWarehouseInventory.Select(x => x.WarehouseId)) .Concat(product.ProductAttributeCombinations.SelectMany(x => x.WarehouseInventory) .Select(x => x.WarehouseId)) - .Where(x => !string.IsNullOrEmpty(x)) + .OfType() + .Where(x => x.Length > 0) .Distinct(); } } diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/StockChange.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/StockChange.cs index 835803908..8f161087a 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/StockChange.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/StockChange.cs @@ -51,7 +51,7 @@ public sealed record StockChange( /// A batch-tracked product: the batch the change moves; empty for the stock without a batch. For a /// the quantity is what the batch takes from that stock /// - public string BatchNumber { get; init; } + public string? BatchNumber { get; init; } /// /// A batch received: its expiry date @@ -67,11 +67,11 @@ public sealed record StockChange( /// A stock count of a serial-tracked bucket: every serial number found in it. The change is worked out under the /// lock against the units stored then; null for any other change /// - public IReadOnlyList CountedSerialNumbers { get; init; } + public IReadOnlyList? CountedSerialNumbers { get; init; } /// /// The idempotency key of the change, from the stock integration API. A change with a key writes exactly one /// journal entry, and a retried call with the same key is not applied again /// - public string IdempotencyKey { get; init; } + public string? IdempotencyKey { get; init; } } diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/TaxRequest.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/TaxRequest.cs index 98a14c26e..043499829 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/TaxRequest.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/TaxRequest.cs @@ -13,27 +13,27 @@ public class TaxRequest /// /// Gets or sets a product /// - public Product Product { get; set; } + public Product? Product { get; set; } /// /// Gets or sets a customer /// - public Customer Customer { get; set; } + public Customer? Customer { get; set; } /// /// Gets or sets an address /// - public Address Address { get; set; } + public Address? Address { get; set; } /// /// Gets or sets the store in which the tax is being calculated /// - public Store Store { get; set; } + public Store? Store { get; set; } /// /// Gets or sets a tax category identifier /// - public string TaxCategoryId { get; set; } + public string? TaxCategoryId { get; set; } /// /// Gets or sets a price diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/VatRequest.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/VatRequest.cs index 62d35760f..a2083dce4 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/VatRequest.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/VatRequest.cs @@ -2,7 +2,7 @@ public class VatRequest { - public string CountryCode { get; set; } + public string? CountryCode { get; set; } - public string VatNumber { get; set; } + public string? VatNumber { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/VatResponse.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/VatResponse.cs index 446932639..011fab8ad 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/VatResponse.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/VatResponse.cs @@ -2,10 +2,10 @@ public class VatResponse { - public string CountryCode { get; set; } - public string VatNumber { get; set; } + public string? CountryCode { get; set; } + public string? VatNumber { get; set; } public bool Valid { get; set; } public DateTime RequestDate { get; set; } - public string Name { get; set; } - public string Address { get; set; } + public string? Name { get; set; } + public string? Address { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/AppliedGiftVoucher.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/AppliedGiftVoucher.cs index 0682a3352..8f0ae1ba4 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/AppliedGiftVoucher.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/AppliedGiftVoucher.cs @@ -15,5 +15,5 @@ public class AppliedGiftVoucher /// /// Gets the gift voucher /// - public GiftVoucher GiftVoucher { get; set; } + public GiftVoucher? GiftVoucher { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/CapturePaymentResult.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/CapturePaymentResult.cs index 2dd97b933..bebdce074 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/CapturePaymentResult.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/CapturePaymentResult.cs @@ -28,12 +28,12 @@ public CapturePaymentResult() /// /// Gets or sets the capture transaction identifier /// - public string CaptureTransactionId { get; set; } + public string? CaptureTransactionId { get; set; } /// /// Gets or sets the capture transaction result /// - public string CaptureTransactionResult { get; set; } + public string? CaptureTransactionResult { get; set; } /// /// Gets or sets a payment transaction status after processing diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/CheckoutClaim.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/CheckoutClaim.cs index 2e45170b5..cbc54a6bd 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/CheckoutClaim.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/CheckoutClaim.cs @@ -13,11 +13,11 @@ public class CheckoutClaim /// /// The identifier the order is inserted with /// - public string OrderId { get; init; } + public string? OrderId { get; init; } - public string OrderCode { get; init; } - public string CustomerId { get; init; } - public string StoreId { get; init; } + public string? OrderCode { get; init; } + public string? CustomerId { get; init; } + public string? StoreId { get; init; } /// /// Everything the order spends was taken; when false, nothing is held diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/GetShippingOptionRequest.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/GetShippingOptionRequest.cs index 94310a644..9287c69ea 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/GetShippingOptionRequest.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/GetShippingOptionRequest.cs @@ -52,7 +52,7 @@ public int GetQuantity() /// /// Gets or sets a customer /// - public virtual Customer Customer { get; set; } + public virtual Customer? Customer { get; set; } /// /// Gets or sets a shopping cart items @@ -62,37 +62,37 @@ public int GetQuantity() /// /// Gets or sets a shipping address (where we ship to) /// - public Address ShippingAddress { get; set; } + public Address? ShippingAddress { get; set; } /// /// Shipped from country /// - public Country CountryFrom { get; set; } + public Country? CountryFrom { get; set; } /// /// Shipped from state/province /// - public StateProvince StateProvinceFrom { get; set; } + public StateProvince? StateProvinceFrom { get; set; } /// /// Shipped from zip/postal code /// - public string ZipPostalCodeFrom { get; set; } + public string? ZipPostalCodeFrom { get; set; } /// /// Shipped from city /// - public string CityFrom { get; set; } + public string? CityFrom { get; set; } /// /// Shipped from address /// - public string AddressFrom { get; set; } + public string? AddressFrom { get; set; } /// /// Limit to store (identifier) /// - public string StoreId { get; set; } + public string? StoreId { get; set; } #endregion } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/MerchandiseReturnRefundQuote.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/MerchandiseReturnRefundQuote.cs index 6febe0192..3c42d4bc5 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/MerchandiseReturnRefundQuote.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/MerchandiseReturnRefundQuote.cs @@ -8,7 +8,7 @@ public class MerchandiseReturnRefundQuote /// /// Why the return cannot be refunded now, as a key of MerchandiseReturnErrors; null when it can /// - public string Error { get; set; } + public string? Error { get; set; } /// /// What was paid for the items of the return: their price with the item discounts and the tax @@ -30,7 +30,7 @@ public class MerchandiseReturnRefundQuote /// public double MaxAmount { get; set; } - public string CurrencyCode { get; set; } + public string? CurrencyCode { get; set; } /// /// Whether the payment provider gives the money back itself diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/MerchandiseReturnSubmitRequest.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/MerchandiseReturnSubmitRequest.cs index bf329a384..dd085e3fa 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/MerchandiseReturnSubmitRequest.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/MerchandiseReturnSubmitRequest.cs @@ -8,25 +8,25 @@ namespace Grand.Business.Core.Utilities.Checkout; /// public class MerchandiseReturnSubmitRequest { - public Order Order { get; set; } - public string StoreId { get; set; } - public string CustomerId { get; set; } - public string OwnerId { get; set; } + public Order? Order { get; set; } + public string? StoreId { get; set; } + public string? CustomerId { get; set; } + public string? OwnerId { get; set; } /// /// The language the reason and action names are kept in, as the customer read them /// - public string LanguageId { get; set; } + public string? LanguageId { get; set; } - public string Comments { get; set; } - public Address PickupAddress { get; set; } + public string? Comments { get; set; } + public Address? PickupAddress { get; set; } public DateTime? PickupDate { get; set; } public IList Items { get; set; } = []; /// /// How the customer sends the items back; null when no return shipping option was picked /// - public ReturnShippingChoice ReturnShipping { get; set; } + public ReturnShippingChoice? ReturnShipping { get; set; } } /// @@ -41,7 +41,7 @@ public record MerchandiseReturnSubmitItem(string OrderItemId, int Quantity, stri public class MerchandiseReturnSubmitResult { public IList MerchandiseReturns { get; } = []; - public string Error { get; set; } + public string? Error { get; set; } /// /// Why the return shipping option picked cannot be used: keys of MerchandiseReturnErrors, or texts a provider diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/OrderPlacementContext.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/OrderPlacementContext.cs index be04ad7e2..2f76c9006 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/OrderPlacementContext.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/OrderPlacementContext.cs @@ -9,7 +9,7 @@ namespace Grand.Business.Core.Utilities.Checkout; public class OrderPlacementContext { private readonly Func> _getTotal; - private Task _total; + private Task? _total; public OrderPlacementContext(IList cart, CalculationContext calculation, Language language, string paymentMethodSystemName, Func> getTotal) diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/OrderPlacementRuleResult.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/OrderPlacementRuleResult.cs index 5f1eaf49e..d4d370296 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/OrderPlacementRuleResult.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/OrderPlacementRuleResult.cs @@ -6,7 +6,7 @@ namespace Grand.Business.Core.Utilities.Checkout; /// What the rule decides /// Plain text shown to the buyer and to whoever decides the approval /// The store decides the approval, also for a sub-account's order -public record OrderPlacementRuleResult(OrderPlacementDecision Decision, string Reason, bool StoreDecides = false) +public record OrderPlacementRuleResult(OrderPlacementDecision Decision, string? Reason, bool StoreDecides = false) { public static OrderPlacementRuleResult Allow() { diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainer.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainer.cs index 3d3ed0483..d5e2488c9 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainer.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainer.cs @@ -17,34 +17,34 @@ public class PlaceOrderContainer /// The identifier the order is inserted with, known before the payment so what the order spends can be claimed /// for it /// - public string OrderId { get; set; } + public string? OrderId { get; set; } /// /// Customer, store, working currency and tax display the order totals are calculated for /// - public CalculationContext Context { get; set; } + public CalculationContext? Context { get; set; } - public Customer Customer { get; set; } - public Store Store { get; set; } - public Language Language { get; set; } + public Customer? Customer { get; set; } + public Store? Store { get; set; } + public Language? Language { get; set; } /// /// Language of the request placing the order, used for the attribute descriptions /// - public Language WorkingLanguage { get; set; } + public Language? WorkingLanguage { get; set; } /// /// Store address used for file download links in the attribute descriptions /// - public DomainHost Host { get; set; } + public DomainHost? Host { get; set; } - public Currency Currency { get; set; } - public string AffiliateId { get; set; } + public Currency? Currency { get; set; } + public string? AffiliateId { get; set; } public TaxDisplayType TaxDisplayType { get; set; } public double CurrencyRate { get; set; } - public string PrimaryCurrencyCode { get; set; } - public string PaymentMethodSystemName { get; set; } - public string PurchaseOrderNumber { get; set; } + public string? PrimaryCurrencyCode { get; set; } + public string? PaymentMethodSystemName { get; set; } + public string? PurchaseOrderNumber { get; set; } /// /// An order placement rule requires an approval, so the order is placed awaiting one @@ -61,14 +61,14 @@ public class PlaceOrderContainer /// public bool ApprovalStoreDecides { get; set; } - public Address BillingAddress { get; set; } - public Address ShippingAddress { get; set; } + public Address? BillingAddress { get; set; } + public Address? ShippingAddress { get; set; } public ShippingStatus ShippingStatus { get; set; } - public string ShippingMethodName { get; set; } - public string ShippingRateProviderSystemName { get; set; } + public string? ShippingMethodName { get; set; } + public string? ShippingRateProviderSystemName { get; set; } public bool PickUpInStore { get; set; } - public PickupPoint PickupPoint { get; set; } - public string CheckoutAttributeDescription { get; set; } + public PickupPoint? PickupPoint { get; set; } + public string? CheckoutAttributeDescription { get; set; } public IList CheckoutAttributes { get; set; } = new List(); public IList Cart { get; set; } = new List(); public IList Taxes { get; set; } = new List(); diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderResult.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderResult.cs index cd98ea0db..c0e5a1054 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderResult.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderResult.cs @@ -29,12 +29,12 @@ public PlaceOrderResult() /// /// Gets or sets the placed order /// - public Order PlacedOrder { get; set; } + public Order? PlacedOrder { get; set; } /// /// Gets or sets the payment transaction /// - public PaymentTransaction PaymentTransaction { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } /// /// Add error diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/PurchaseOrderNumberRules.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/PurchaseOrderNumberRules.cs index e205f2d0c..491cd56e3 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/PurchaseOrderNumberRules.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/PurchaseOrderNumberRules.cs @@ -18,7 +18,7 @@ public static class PurchaseOrderNumberRules /// /// Number entered by the buyer /// Purchase order number mode - public static string Normalize(string value, PurchaseOrderNumberMode mode) + public static string? Normalize(string value, PurchaseOrderNumberMode mode) { if (mode == PurchaseOrderNumberMode.Disabled || string.IsNullOrWhiteSpace(value)) return null; @@ -32,7 +32,7 @@ public static string Normalize(string value, PurchaseOrderNumberMode mode) /// Number returned by /// Purchase order number mode /// Resource key of the error; null when the number is valid - public static string Validate(string normalized, PurchaseOrderNumberMode mode) + public static string? Validate(string normalized, PurchaseOrderNumberMode mode) { if (normalized == null) return mode == PurchaseOrderNumberMode.Required ? "Checkout.PurchaseOrderNumber.Required" : null; diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs index 2f18bda21..69a12cae4 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringCycleClaim.cs @@ -10,7 +10,7 @@ public class RecurringCycleClaim : RecurringReportResult /// /// The cycle that was recorded; null unless the outcome is Recorded /// - public RecurringPaymentCycle Cycle { get; init; } + public RecurringPaymentCycle? Cycle { get; init; } /// /// Gets a value indicating whether this cycle completed the recurring payment diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportResult.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportResult.cs index 3866ce8a1..3222d401b 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportResult.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/RecurringReportResult.cs @@ -12,5 +12,5 @@ public class RecurringReportResult /// /// The recurring payment as read under the lock, or as saved; null when it is unknown /// - public RecurringPayment RecurringPayment { get; init; } + public RecurringPayment? RecurringPayment { get; init; } } diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/RefundPaymentRequest.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/RefundPaymentRequest.cs index 1289c6a12..25b4a7b1e 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/RefundPaymentRequest.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/RefundPaymentRequest.cs @@ -10,7 +10,7 @@ public class RefundPaymentRequest /// /// Gets or sets an payment transaction /// - public PaymentTransaction PaymentTransaction { get; set; } + public PaymentTransaction? PaymentTransaction { get; set; } /// /// Gets or sets an amount diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/ReturnShipping.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/ReturnShipping.cs index 645a8a48f..e73d44eaf 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/ReturnShipping.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/ReturnShipping.cs @@ -9,24 +9,24 @@ namespace Grand.Business.Core.Utilities.Checkout; /// public class ReturnShippingRequest { - public Order Order { get; set; } - public Customer Customer { get; set; } - public string StoreId { get; set; } + public Order? Order { get; set; } + public Customer? Customer { get; set; } + public string? StoreId { get; set; } /// /// The vendor the items are sent back to; empty for the store /// - public string VendorId { get; set; } + public string? VendorId { get; set; } public IList<(OrderItem OrderItem, int Quantity)> Items { get; set; } = []; /// /// The address the parcel is sent to /// - public Address ReturnAddress { get; set; } + public Address? ReturnAddress { get; set; } - public Address PickupAddress { get; set; } - public string LanguageId { get; set; } + public Address? PickupAddress { get; set; } + public string? LanguageId { get; set; } } /// @@ -34,9 +34,9 @@ public class ReturnShippingRequest /// public class ReturnShippingOption { - public string Code { get; set; } - public string Name { get; set; } - public string Description { get; set; } + public string? Code { get; set; } + public string? Name { get; set; } + public string? Description { get; set; } /// /// The cost of the option, in the primary store currency, before the store's return fee rules @@ -76,7 +76,7 @@ public class ReturnShippingValidationResult /// public double? Cost { get; set; } - public ReturnDropOffPoint DropOffPoint { get; set; } + public ReturnDropOffPoint? DropOffPoint { get; set; } public Dictionary ProviderData { get; set; } = new(); } @@ -86,11 +86,11 @@ public class ReturnShippingValidationResult public class ReturnLabelResult { public bool Success { get; set; } - public string Error { get; set; } - public string TrackingNumber { get; set; } - public string ReturnCode { get; set; } - public ReturnLabelFile LabelFile { get; set; } - public string Instructions { get; set; } + public string? Error { get; set; } + public string? TrackingNumber { get; set; } + public string? ReturnCode { get; set; } + public ReturnLabelFile? LabelFile { get; set; } + public string? Instructions { get; set; } public Dictionary ProviderData { get; set; } = new(); } @@ -104,8 +104,8 @@ public record ReturnLabelFile(byte[] Content, string ContentType, string FileNam /// public class ReturnShippingChoice { - public string ProviderSystemName { get; set; } - public string OptionCode { get; set; } + public string? ProviderSystemName { get; set; } + public string? OptionCode { get; set; } /// /// The fields posted under the "returnshipping." prefix, prefix stripped @@ -118,10 +118,10 @@ public class ReturnShippingChoice /// public class ReturnShippingOffer { - public string ProviderSystemName { get; set; } - public string OptionCode { get; set; } - public string Name { get; set; } - public string Description { get; set; } + public string? ProviderSystemName { get; set; } + public string? OptionCode { get; set; } + public string? Name { get; set; } + public string? Description { get; set; } /// /// What the customer pays for all parcels, in the primary store currency @@ -140,7 +140,7 @@ public class ReturnShippingOffer public int Parcels { get; set; } public bool HasForm { get; set; } - public string FormRouteName { get; set; } + public string? FormRouteName { get; set; } } /// diff --git a/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyByName.cs b/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyByName.cs index 5b5716242..57d19e897 100644 --- a/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyByName.cs +++ b/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyByName.cs @@ -11,7 +11,7 @@ public class PropertyByName /// /// Property name /// Feature property access - public PropertyByName(string propertyName, Func func = null) + public PropertyByName(string propertyName, Func? func = null) { PropertyName = propertyName; GetProperty = func; @@ -27,7 +27,7 @@ public PropertyByName(string propertyName, Func func = null) /// /// Feature property access /// - public Func GetProperty { get; private set; } + public Func? GetProperty { get; private set; } /// /// Property name @@ -37,5 +37,5 @@ public PropertyByName(string propertyName, Func func = null) /// /// Property value /// - public object PropertyValue { get; set; } + public object? PropertyValue { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/CampaignRecipient.cs b/src/Business/Grand.Business.Core/Utilities/Messages/CampaignRecipient.cs index 0aa9f85a4..254b4a07e 100644 --- a/src/Business/Grand.Business.Core/Utilities/Messages/CampaignRecipient.cs +++ b/src/Business/Grand.Business.Core/Utilities/Messages/CampaignRecipient.cs @@ -35,12 +35,12 @@ public sealed record CampaignRecipient /// /// Recipient's customer account; null renders no customer and shopping cart tokens /// - public Customer Customer { get; init; } + public Customer? Customer { get; init; } /// /// Currency the shopping cart prices are rendered in /// - public Currency Currency { get; init; } + public Currency? Currency { get; init; } /// /// Whether the shopping cart prices include tax @@ -50,10 +50,10 @@ public sealed record CampaignRecipient /// /// Newsletter subscription; null renders no subscription tokens /// - public NewsLetterSubscription Subscription { get; init; } + public NewsLetterSubscription? Subscription { get; init; } /// /// Identifier of the queued email the message is sent as; null renders no email tokens /// - public string QueuedEmailId { get; init; } + public string? QueuedEmailId { get; init; } } diff --git a/src/Business/Grand.Business.Core/Utilities/System/BestCustomerReportLine.cs b/src/Business/Grand.Business.Core/Utilities/System/BestCustomerReportLine.cs index 18d1c0225..62eca6f59 100644 --- a/src/Business/Grand.Business.Core/Utilities/System/BestCustomerReportLine.cs +++ b/src/Business/Grand.Business.Core/Utilities/System/BestCustomerReportLine.cs @@ -8,7 +8,7 @@ public class BestCustomerReportLine /// /// Gets or sets the customer identifier /// - public string CustomerId { get; set; } + public string? CustomerId { get; set; } /// /// Gets or sets the order total diff --git a/src/Business/Grand.Business.Core/Utilities/System/BestsellersReportLine.cs b/src/Business/Grand.Business.Core/Utilities/System/BestsellersReportLine.cs index f05f45eb5..d563ae55a 100644 --- a/src/Business/Grand.Business.Core/Utilities/System/BestsellersReportLine.cs +++ b/src/Business/Grand.Business.Core/Utilities/System/BestsellersReportLine.cs @@ -9,7 +9,7 @@ public class BestsellersReportLine /// /// Gets or sets the product identifier /// - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// Gets or sets the total amount diff --git a/src/Business/Grand.Business.Core/Utilities/System/CustomerByTimeReportLine.cs b/src/Business/Grand.Business.Core/Utilities/System/CustomerByTimeReportLine.cs index 7a5b06acc..e2d9804a9 100644 --- a/src/Business/Grand.Business.Core/Utilities/System/CustomerByTimeReportLine.cs +++ b/src/Business/Grand.Business.Core/Utilities/System/CustomerByTimeReportLine.cs @@ -2,7 +2,7 @@ public class CustomerByTimeReportLine { - public string Time { get; set; } + public string? Time { get; set; } public int Registered { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Utilities/System/MerchandiseReturnReportLine.cs b/src/Business/Grand.Business.Core/Utilities/System/MerchandiseReturnReportLine.cs index c465d4931..1b7541343 100644 --- a/src/Business/Grand.Business.Core/Utilities/System/MerchandiseReturnReportLine.cs +++ b/src/Business/Grand.Business.Core/Utilities/System/MerchandiseReturnReportLine.cs @@ -19,12 +19,12 @@ public class MerchandiseReturnReportLine /// Gets or sets what the line counts: a reason identifier (or the reason's text for a return item without /// one), a product identifier, or a vendor identifier ("" for the store's own items) /// - public string Key { get; set; } + public string? Key { get; set; } /// /// Gets or sets the reason's text as the customer chose it, for a reason no longer found; null otherwise /// - public string Name { get; set; } + public string? Name { get; set; } /// /// Gets or sets the number of returns diff --git a/src/Business/Grand.Business.Core/Utilities/System/OrderByCountryReportLine.cs b/src/Business/Grand.Business.Core/Utilities/System/OrderByCountryReportLine.cs index d23e4e642..a00e83022 100644 --- a/src/Business/Grand.Business.Core/Utilities/System/OrderByCountryReportLine.cs +++ b/src/Business/Grand.Business.Core/Utilities/System/OrderByCountryReportLine.cs @@ -8,7 +8,7 @@ public class OrderByCountryReportLine /// /// Country identifier; null for un know country /// - public string CountryId { get; set; } + public string? CountryId { get; set; } /// /// Gets or sets the number of orders diff --git a/src/Business/Grand.Business.Core/Utilities/System/OrderByTimeReportLine.cs b/src/Business/Grand.Business.Core/Utilities/System/OrderByTimeReportLine.cs index 9fe2902fa..74776888e 100644 --- a/src/Business/Grand.Business.Core/Utilities/System/OrderByTimeReportLine.cs +++ b/src/Business/Grand.Business.Core/Utilities/System/OrderByTimeReportLine.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Utilities.System; /// public class OrderByTimeReportLine { - public string Time { get; set; } + public string? Time { get; set; } public int TotalOrders { get; set; } diff --git a/src/Business/Grand.Business.Core/Utilities/System/ProductsAttributeCombination.cs b/src/Business/Grand.Business.Core/Utilities/System/ProductsAttributeCombination.cs index f97b8e96e..eef5510b3 100644 --- a/src/Business/Grand.Business.Core/Utilities/System/ProductsAttributeCombination.cs +++ b/src/Business/Grand.Business.Core/Utilities/System/ProductsAttributeCombination.cs @@ -4,5 +4,5 @@ namespace Grand.Business.Core.Utilities.System; public class ProductsAttributeCombination : ProductAttributeCombination { - public string ProductId { get; set; } + public string? ProductId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs b/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs index e3764e299..2b4a2f59e 100644 --- a/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs +++ b/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs @@ -1,4 +1,5 @@ using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Security.Cryptography; using System.Text.RegularExpressions; @@ -82,7 +83,8 @@ public static int GenerateRandomInteger(int min = 0, int max = int.MaxValue) /// Maximum length /// A string to add to the end if the original string was shorten /// Input string if its lengh is OK; otherwise, truncated input string - public static string EnsureMaximumLength(string str, int maxLength, string? postfix = null) + [return: NotNullIfNotNull(nameof(str))] + public static string? EnsureMaximumLength(string? str, int maxLength, string? postfix = null) { if (string.IsNullOrEmpty(str)) return str; From cf277e4f56f05635a50875956b21bd080045505c Mon Sep 17 00:00:00 2001 From: support Date: Wed, 25 Nov 2026 10:50:08 +0100 Subject: [PATCH 07/30] Declare the required fields of Grand.Domain as not null 143 string fields are required by evidence in the code, and are declared "string X { get; set; } = null!" - the one ! at the declaration states the requirement once instead of at every use: - 100 fields every FluentValidation validator of their model or DTO requires unconditionally (a rule inside an if on a setting, or with When/Unless, does not count), never assigned null in code; - 43 keys every creation site in code sets from an entity Id or a literal (InventoryJournal.ProductId, BlogComment.BlogPostId, ...). Left nullable although a validator requires them: Store.Shortcut (code falls back to Name), Page.SystemName (a page without one is handled), UserField.Value (tested for empty), QueuedEmail.From/To and Picture.MimeType (created in code from several sources), and KnowledgebaseArticle.ParentCategoryId (ITreeNode shares it with KnowledgebaseCategory, where a root has none). Order.CustomerId and StoreId stay nullable: the order number reservation inserts an order without them. --- .../Grand.Business.Common/Services/Stores/StoreService.cs | 2 +- .../Interfaces/Common/Stores/IStoreService.cs | 2 +- src/Core/Grand.Domain/Affiliates/Affiliate.cs | 2 +- src/Core/Grand.Domain/Blogs/BlogCategory.cs | 2 +- src/Core/Grand.Domain/Blogs/BlogComment.cs | 6 +++--- src/Core/Grand.Domain/Blogs/BlogPost.cs | 4 ++-- src/Core/Grand.Domain/Catalog/Bid.cs | 2 +- src/Core/Grand.Domain/Catalog/Brand.cs | 2 +- src/Core/Grand.Domain/Catalog/BrandLayout.cs | 4 ++-- src/Core/Grand.Domain/Catalog/Category.cs | 2 +- src/Core/Grand.Domain/Catalog/CategoryLayout.cs | 4 ++-- src/Core/Grand.Domain/Catalog/Collection.cs | 2 +- src/Core/Grand.Domain/Catalog/CollectionLayout.cs | 4 ++-- .../Grand.Domain/Catalog/CustomerReservationsHelper.cs | 4 ++-- src/Core/Grand.Domain/Catalog/InventoryJournal.cs | 2 +- src/Core/Grand.Domain/Catalog/OutOfStockSubscription.cs | 6 +++--- .../Catalog/PredefinedProductAttributeValue.cs | 2 +- src/Core/Grand.Domain/Catalog/Product.cs | 2 +- src/Core/Grand.Domain/Catalog/ProductAlsoPurchased.cs | 2 +- src/Core/Grand.Domain/Catalog/ProductAttribute.cs | 2 +- src/Core/Grand.Domain/Catalog/ProductBatch.cs | 2 +- src/Core/Grand.Domain/Catalog/ProductLayout.cs | 4 ++-- src/Core/Grand.Domain/Catalog/ProductReview.cs | 4 ++-- src/Core/Grand.Domain/Catalog/ProductReviewHelpfulness.cs | 4 ++-- src/Core/Grand.Domain/Catalog/ProductSerialNumber.cs | 2 +- src/Core/Grand.Domain/Catalog/ProductTag.cs | 2 +- src/Core/Grand.Domain/Catalog/SpecificationAttribute.cs | 2 +- .../Grand.Domain/Catalog/SpecificationAttributeOption.cs | 2 +- .../Catalog/SpecificationAttributeOptionFilter.cs | 2 +- src/Core/Grand.Domain/Common/AddressAttribute.cs | 2 +- src/Core/Grand.Domain/Common/AddressAttributeValue.cs | 2 +- src/Core/Grand.Domain/Common/RobotsTxt.cs | 2 +- src/Core/Grand.Domain/Common/UserField.cs | 2 +- src/Core/Grand.Domain/Configuration/Setting.cs | 2 +- src/Core/Grand.Domain/Courses/Course.cs | 2 +- src/Core/Grand.Domain/Courses/CourseAction.cs | 6 +++--- src/Core/Grand.Domain/Courses/CourseLesson.cs | 6 +++--- src/Core/Grand.Domain/Courses/CourseLevel.cs | 2 +- src/Core/Grand.Domain/Courses/CourseSubject.cs | 4 ++-- src/Core/Grand.Domain/Customers/CustomerAttribute.cs | 2 +- src/Core/Grand.Domain/Customers/CustomerAttributeValue.cs | 2 +- src/Core/Grand.Domain/Customers/CustomerGroup.cs | 2 +- .../Grand.Domain/Customers/CustomerHistoryPassword.cs | 2 +- src/Core/Grand.Domain/Customers/CustomerTag.cs | 2 +- src/Core/Grand.Domain/Customers/ExternalAuthentication.cs | 2 +- src/Core/Grand.Domain/Customers/OidcSession.cs | 2 +- src/Core/Grand.Domain/Customers/SalesEmployee.cs | 2 +- src/Core/Grand.Domain/Customers/UserApi.cs | 2 +- src/Core/Grand.Domain/Directory/Country.cs | 6 +++--- src/Core/Grand.Domain/Directory/Currency.cs | 4 ++-- src/Core/Grand.Domain/Directory/MeasureDimension.cs | 4 ++-- src/Core/Grand.Domain/Directory/MeasureUnit.cs | 2 +- src/Core/Grand.Domain/Directory/MeasureWeight.cs | 4 ++-- src/Core/Grand.Domain/Directory/StateProvince.cs | 2 +- src/Core/Grand.Domain/Discounts/Discount.cs | 2 +- src/Core/Grand.Domain/Discounts/DiscountRule.cs | 2 +- src/Core/Grand.Domain/Discounts/DiscountUsageHistory.cs | 2 +- src/Core/Grand.Domain/Documents/Document.cs | 4 ++-- src/Core/Grand.Domain/Documents/DocumentType.cs | 2 +- src/Core/Grand.Domain/Knowledgebase/ITreeNode.cs | 2 +- .../Grand.Domain/Knowledgebase/KnowledgebaseArticle.cs | 2 +- .../Knowledgebase/KnowledgebaseArticleComment.cs | 4 ++-- .../Grand.Domain/Knowledgebase/KnowledgebaseCategory.cs | 2 +- src/Core/Grand.Domain/Localization/Language.cs | 4 ++-- src/Core/Grand.Domain/Localization/TranslationResource.cs | 2 +- src/Core/Grand.Domain/Messages/Campaign.cs | 6 +++--- src/Core/Grand.Domain/Messages/CampaignHistory.cs | 2 +- src/Core/Grand.Domain/Messages/ContactAttribute.cs | 2 +- src/Core/Grand.Domain/Messages/ContactAttributeValue.cs | 2 +- src/Core/Grand.Domain/Messages/ContactUs.cs | 6 +++--- src/Core/Grand.Domain/Messages/EmailAccount.cs | 4 ++-- src/Core/Grand.Domain/Messages/MessageTemplate.cs | 4 ++-- src/Core/Grand.Domain/Messages/NewsLetterSubscription.cs | 2 +- src/Core/Grand.Domain/Messages/NewsletterCategory.cs | 2 +- src/Core/Grand.Domain/News/NewsComment.cs | 6 +++--- src/Core/Grand.Domain/News/NewsItem.cs | 6 +++--- src/Core/Grand.Domain/Orders/CheckoutAttribute.cs | 2 +- src/Core/Grand.Domain/Orders/CheckoutAttributeValue.cs | 2 +- src/Core/Grand.Domain/Orders/GiftVoucher.cs | 2 +- src/Core/Grand.Domain/Orders/GiftVoucherUsageHistory.cs | 2 +- src/Core/Grand.Domain/Orders/MerchandiseReturn.cs | 2 +- src/Core/Grand.Domain/Orders/MerchandiseReturnAction.cs | 2 +- src/Core/Grand.Domain/Orders/MerchandiseReturnNote.cs | 2 +- src/Core/Grand.Domain/Orders/MerchandiseReturnReason.cs | 2 +- src/Core/Grand.Domain/Orders/MerchandiseReturnRefund.cs | 2 +- src/Core/Grand.Domain/Orders/MerchandiseReturnShipping.cs | 2 +- src/Core/Grand.Domain/Orders/OrderStatus.cs | 2 +- src/Core/Grand.Domain/Pages/PageLayout.cs | 4 ++-- src/Core/Grand.Domain/Payments/PaymentTransactionEntry.cs | 2 +- .../Grand.Domain/PushNotifications/PushRegistration.cs | 2 +- src/Core/Grand.Domain/Security/RefreshToken.cs | 2 +- src/Core/Grand.Domain/Shipping/DeliveryDate.cs | 2 +- src/Core/Grand.Domain/Shipping/PickupPoints.cs | 2 +- src/Core/Grand.Domain/Shipping/ShippingMethod.cs | 2 +- src/Core/Grand.Domain/Shipping/Warehouse.cs | 4 ++-- src/Core/Grand.Domain/Shipping/WarehouseLocation.cs | 4 ++-- src/Core/Grand.Domain/Stores/DomainHost.cs | 2 +- src/Core/Grand.Domain/Stores/Store.cs | 4 ++-- src/Core/Grand.Domain/Tax/TaxCategory.cs | 2 +- src/Core/Grand.Domain/Vendors/Vendor.cs | 4 ++-- src/Core/Grand.Domain/Vendors/VendorReview.cs | 8 ++++---- src/Core/Grand.Domain/Vendors/VendorReviewHelpfulness.cs | 4 ++-- 102 files changed, 146 insertions(+), 146 deletions(-) diff --git a/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs b/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs index 4c412771c..01d6d1070 100644 --- a/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs +++ b/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs @@ -61,7 +61,7 @@ public virtual async Task> GetAllStores() /// /// Store identifier /// Store - public virtual Task GetStoreById(string storeId) + public virtual Task GetStoreById(string storeId) { var key = string.Format(CacheKey.STORES_BY_ID_KEY, storeId); return _cacheBase.GetAsync(key, () => _storeRepository.GetByIdAsync(storeId)); diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Stores/IStoreService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Stores/IStoreService.cs index 80e5d7b13..bfc2da2ac 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Stores/IStoreService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Stores/IStoreService.cs @@ -20,7 +20,7 @@ public interface IStoreService /// /// Store identifier /// Store - Task GetStoreById(string storeId); + Task GetStoreById(string storeId); /// /// Inserts a store diff --git a/src/Core/Grand.Domain/Affiliates/Affiliate.cs b/src/Core/Grand.Domain/Affiliates/Affiliate.cs index 4565b7ef6..d4842ea93 100644 --- a/src/Core/Grand.Domain/Affiliates/Affiliate.cs +++ b/src/Core/Grand.Domain/Affiliates/Affiliate.cs @@ -10,7 +10,7 @@ public class Affiliate : BaseEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the admin comment diff --git a/src/Core/Grand.Domain/Blogs/BlogCategory.cs b/src/Core/Grand.Domain/Blogs/BlogCategory.cs index 7ac3ef5f4..df86bdfdf 100644 --- a/src/Core/Grand.Domain/Blogs/BlogCategory.cs +++ b/src/Core/Grand.Domain/Blogs/BlogCategory.cs @@ -9,7 +9,7 @@ public class BlogCategory : BaseEntity, IStoreLinkEntity, ITranslationEntity /// /// Gets or sets the blog category name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the blog category sename diff --git a/src/Core/Grand.Domain/Blogs/BlogComment.cs b/src/Core/Grand.Domain/Blogs/BlogComment.cs index f0685e590..586a373ce 100644 --- a/src/Core/Grand.Domain/Blogs/BlogComment.cs +++ b/src/Core/Grand.Domain/Blogs/BlogComment.cs @@ -13,13 +13,13 @@ public class BlogComment : BaseEntity /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string? CustomerId { get; set; } + public string CustomerId { get; set; } = null!; /// /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string? StoreId { get; set; } + public string StoreId { get; set; } = null!; /// /// Gets or sets the comment text @@ -37,5 +37,5 @@ public class BlogComment : BaseEntity /// [AuditReference(typeof(BlogPost))] [AuditOwner] - public string? BlogPostId { get; set; } + public string BlogPostId { get; set; } = null!; } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Blogs/BlogPost.cs b/src/Core/Grand.Domain/Blogs/BlogPost.cs index 919448bc0..aeeec35b2 100644 --- a/src/Core/Grand.Domain/Blogs/BlogPost.cs +++ b/src/Core/Grand.Domain/Blogs/BlogPost.cs @@ -14,7 +14,7 @@ public class BlogPost : BaseEntity, ISlugEntity, IStoreLinkEntity, ITranslationE /// Gets or sets the blog post title /// [AuditName] - public string? Title { get; set; } + public string Title { get; set; } = null!; /// /// Gets or sets the picture identifier @@ -24,7 +24,7 @@ public class BlogPost : BaseEntity, ISlugEntity, IStoreLinkEntity, ITranslationE /// /// Gets or sets the blog post body /// - public string? Body { get; set; } + public string Body { get; set; } = null!; /// /// Gets or sets the blog post overview. If specified, then it's used on the blog page instead of the "Body" diff --git a/src/Core/Grand.Domain/Catalog/Bid.cs b/src/Core/Grand.Domain/Catalog/Bid.cs index ad80188e1..c92912c31 100644 --- a/src/Core/Grand.Domain/Catalog/Bid.cs +++ b/src/Core/Grand.Domain/Catalog/Bid.cs @@ -15,7 +15,7 @@ public class Bid : BaseEntity /// Gets or sets the product identifier /// [AuditReference(typeof(Product))] - public string? ProductId { get; set; } + public string ProductId { get; set; } = null!; /// /// Gets or sets the warehouse identifier diff --git a/src/Core/Grand.Domain/Catalog/Brand.cs b/src/Core/Grand.Domain/Catalog/Brand.cs index dc423d043..95b215cc5 100644 --- a/src/Core/Grand.Domain/Catalog/Brand.cs +++ b/src/Core/Grand.Domain/Catalog/Brand.cs @@ -18,7 +18,7 @@ public class Brand : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEnti /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the description diff --git a/src/Core/Grand.Domain/Catalog/BrandLayout.cs b/src/Core/Grand.Domain/Catalog/BrandLayout.cs index 91f9180eb..8796f0e8e 100644 --- a/src/Core/Grand.Domain/Catalog/BrandLayout.cs +++ b/src/Core/Grand.Domain/Catalog/BrandLayout.cs @@ -8,12 +8,12 @@ public class BrandLayout : BaseEntity /// /// Gets or sets the layout name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the view path /// - public string? ViewPath { get; set; } + public string ViewPath { get; set; } = null!; /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Catalog/Category.cs b/src/Core/Grand.Domain/Catalog/Category.cs index 2580f9daa..d545a948a 100644 --- a/src/Core/Grand.Domain/Catalog/Category.cs +++ b/src/Core/Grand.Domain/Catalog/Category.cs @@ -18,7 +18,7 @@ public class Category : BaseEntity, ISlugEntity, IGroupLinkEntity, ITranslationE /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the description diff --git a/src/Core/Grand.Domain/Catalog/CategoryLayout.cs b/src/Core/Grand.Domain/Catalog/CategoryLayout.cs index 36a9821c8..c57e6255c 100644 --- a/src/Core/Grand.Domain/Catalog/CategoryLayout.cs +++ b/src/Core/Grand.Domain/Catalog/CategoryLayout.cs @@ -8,12 +8,12 @@ public class CategoryLayout : BaseEntity /// /// Gets or sets the layout name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the view path /// - public string? ViewPath { get; set; } + public string ViewPath { get; set; } = null!; /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Catalog/Collection.cs b/src/Core/Grand.Domain/Catalog/Collection.cs index b12494e9b..03b7fd086 100644 --- a/src/Core/Grand.Domain/Catalog/Collection.cs +++ b/src/Core/Grand.Domain/Catalog/Collection.cs @@ -18,7 +18,7 @@ public class Collection : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLin /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the description diff --git a/src/Core/Grand.Domain/Catalog/CollectionLayout.cs b/src/Core/Grand.Domain/Catalog/CollectionLayout.cs index 4bbf636d4..0c4e791bc 100644 --- a/src/Core/Grand.Domain/Catalog/CollectionLayout.cs +++ b/src/Core/Grand.Domain/Catalog/CollectionLayout.cs @@ -8,12 +8,12 @@ public class CollectionLayout : BaseEntity /// /// Gets or sets the layout name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the view path /// - public string? ViewPath { get; set; } + public string ViewPath { get; set; } = null!; /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Catalog/CustomerReservationsHelper.cs b/src/Core/Grand.Domain/Catalog/CustomerReservationsHelper.cs index 91c79f608..25112c3b8 100644 --- a/src/Core/Grand.Domain/Catalog/CustomerReservationsHelper.cs +++ b/src/Core/Grand.Domain/Catalog/CustomerReservationsHelper.cs @@ -8,12 +8,12 @@ public class CustomerReservationsHelper : BaseEntity /// /// Gets or sets customer identifier /// - public string? CustomerId { get; set; } + public string CustomerId { get; set; } = null!; /// /// Gets or sets shopping cart identifier /// - public string? ShoppingCartItemId { get; set; } + public string ShoppingCartItemId { get; set; } = null!; /// /// Gets or sets reservation identifier diff --git a/src/Core/Grand.Domain/Catalog/InventoryJournal.cs b/src/Core/Grand.Domain/Catalog/InventoryJournal.cs index 2c5f0f35c..2920e58ab 100644 --- a/src/Core/Grand.Domain/Catalog/InventoryJournal.cs +++ b/src/Core/Grand.Domain/Catalog/InventoryJournal.cs @@ -11,7 +11,7 @@ public class InventoryJournal : BaseEntity public string? ObjectType { get; set; } public string? PositionId { get; set; } public DateTime CreateDateUtc { get; set; } - public string? ProductId { get; set; } + public string ProductId { get; set; } = null!; public IList Attributes { get; set; } = new List(); public string? WarehouseId { get; set; } public int InQty { get; set; } diff --git a/src/Core/Grand.Domain/Catalog/OutOfStockSubscription.cs b/src/Core/Grand.Domain/Catalog/OutOfStockSubscription.cs index 13b2d22cd..011ceb15a 100644 --- a/src/Core/Grand.Domain/Catalog/OutOfStockSubscription.cs +++ b/src/Core/Grand.Domain/Catalog/OutOfStockSubscription.cs @@ -15,13 +15,13 @@ public class OutOfStockSubscription : BaseEntity /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string? StoreId { get; set; } + public string StoreId { get; set; } = null!; /// /// Gets or sets the product identifier /// [AuditReference(typeof(Product))] - public string? ProductId { get; set; } + public string ProductId { get; set; } = null!; /// /// Gets or sets the attribute @@ -43,5 +43,5 @@ public class OutOfStockSubscription : BaseEntity /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string? CustomerId { get; set; } + public string CustomerId { get; set; } = null!; } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Catalog/PredefinedProductAttributeValue.cs b/src/Core/Grand.Domain/Catalog/PredefinedProductAttributeValue.cs index 95fed1557..156d31fc9 100644 --- a/src/Core/Grand.Domain/Catalog/PredefinedProductAttributeValue.cs +++ b/src/Core/Grand.Domain/Catalog/PredefinedProductAttributeValue.cs @@ -10,7 +10,7 @@ public class PredefinedProductAttributeValue : SubBaseEntity, ITranslationEntity /// /// Gets or sets the product attribute name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the price adjustment diff --git a/src/Core/Grand.Domain/Catalog/Product.cs b/src/Core/Grand.Domain/Catalog/Product.cs index 92f5624ef..737124cf0 100644 --- a/src/Core/Grand.Domain/Catalog/Product.cs +++ b/src/Core/Grand.Domain/Catalog/Product.cs @@ -58,7 +58,7 @@ public class Product : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEn /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the short description diff --git a/src/Core/Grand.Domain/Catalog/ProductAlsoPurchased.cs b/src/Core/Grand.Domain/Catalog/ProductAlsoPurchased.cs index 394b1b78f..31e2283f9 100644 --- a/src/Core/Grand.Domain/Catalog/ProductAlsoPurchased.cs +++ b/src/Core/Grand.Domain/Catalog/ProductAlsoPurchased.cs @@ -7,7 +7,7 @@ public class ProductAlsoPurchased : BaseEntity { public string? ProductId { get; set; } public string? ProductId2 { get; set; } - public string? OrderId { get; set; } + public string OrderId { get; set; } = null!; public DateTime CreatedOrderOnUtc { get; set; } public int Quantity { get; set; } public string? StoreId { get; set; } diff --git a/src/Core/Grand.Domain/Catalog/ProductAttribute.cs b/src/Core/Grand.Domain/Catalog/ProductAttribute.cs index c9d4e60cd..5dc6a09a8 100644 --- a/src/Core/Grand.Domain/Catalog/ProductAttribute.cs +++ b/src/Core/Grand.Domain/Catalog/ProductAttribute.cs @@ -12,7 +12,7 @@ public class ProductAttribute : BaseEntity, IStoreLinkEntity, ITranslationEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the sename diff --git a/src/Core/Grand.Domain/Catalog/ProductBatch.cs b/src/Core/Grand.Domain/Catalog/ProductBatch.cs index 153882655..d6b53bc32 100644 --- a/src/Core/Grand.Domain/Catalog/ProductBatch.cs +++ b/src/Core/Grand.Domain/Catalog/ProductBatch.cs @@ -8,7 +8,7 @@ namespace Grand.Domain.Catalog; /// public class ProductBatch : BaseEntity { - public string? ProductId { get; set; } + public string ProductId { get; set; } = null!; /// /// The combination of a product stocked by attributes diff --git a/src/Core/Grand.Domain/Catalog/ProductLayout.cs b/src/Core/Grand.Domain/Catalog/ProductLayout.cs index cdcc6e336..9037764d7 100644 --- a/src/Core/Grand.Domain/Catalog/ProductLayout.cs +++ b/src/Core/Grand.Domain/Catalog/ProductLayout.cs @@ -8,12 +8,12 @@ public class ProductLayout : BaseEntity /// /// Gets or sets the layout name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the view path /// - public string? ViewPath { get; set; } + public string ViewPath { get; set; } = null!; /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Catalog/ProductReview.cs b/src/Core/Grand.Domain/Catalog/ProductReview.cs index 9e75f3c27..f87f77c7f 100644 --- a/src/Core/Grand.Domain/Catalog/ProductReview.cs +++ b/src/Core/Grand.Domain/Catalog/ProductReview.cs @@ -38,12 +38,12 @@ public class ProductReview : BaseEntity /// Gets or sets the title /// [AuditName] - public string? Title { get; set; } + public string Title { get; set; } = null!; /// /// Gets or sets the review text /// - public string? ReviewText { get; set; } + public string ReviewText { get; set; } = null!; /// /// Gets or sets the reply text diff --git a/src/Core/Grand.Domain/Catalog/ProductReviewHelpfulness.cs b/src/Core/Grand.Domain/Catalog/ProductReviewHelpfulness.cs index 4f3927b92..93d23a7cd 100644 --- a/src/Core/Grand.Domain/Catalog/ProductReviewHelpfulness.cs +++ b/src/Core/Grand.Domain/Catalog/ProductReviewHelpfulness.cs @@ -8,7 +8,7 @@ public class ProductReviewHelpfulness : SubBaseEntity /// /// Gets or sets the product review identifier /// - public string? ProductReviewId { get; set; } + public string ProductReviewId { get; set; } = null!; /// /// A value indicating whether a review a helpful @@ -18,5 +18,5 @@ public class ProductReviewHelpfulness : SubBaseEntity /// /// Gets or sets the customer identifier /// - public string? CustomerId { get; set; } + public string CustomerId { get; set; } = null!; } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Catalog/ProductSerialNumber.cs b/src/Core/Grand.Domain/Catalog/ProductSerialNumber.cs index b5901f0b7..9b4fb7fe7 100644 --- a/src/Core/Grand.Domain/Catalog/ProductSerialNumber.cs +++ b/src/Core/Grand.Domain/Catalog/ProductSerialNumber.cs @@ -7,7 +7,7 @@ namespace Grand.Domain.Catalog; /// public class ProductSerialNumber : BaseEntity { - public string? ProductId { get; set; } + public string ProductId { get; set; } = null!; /// /// The combination of a product stocked by attributes diff --git a/src/Core/Grand.Domain/Catalog/ProductTag.cs b/src/Core/Grand.Domain/Catalog/ProductTag.cs index 86a7f0052..1cf4948bf 100644 --- a/src/Core/Grand.Domain/Catalog/ProductTag.cs +++ b/src/Core/Grand.Domain/Catalog/ProductTag.cs @@ -10,7 +10,7 @@ public class ProductTag : BaseEntity, ITranslationEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the sename diff --git a/src/Core/Grand.Domain/Catalog/SpecificationAttribute.cs b/src/Core/Grand.Domain/Catalog/SpecificationAttribute.cs index 9e4bcaec1..ec934af63 100644 --- a/src/Core/Grand.Domain/Catalog/SpecificationAttribute.cs +++ b/src/Core/Grand.Domain/Catalog/SpecificationAttribute.cs @@ -14,7 +14,7 @@ public class SpecificationAttribute : BaseEntity, IStoreLinkEntity, ITranslation /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the sename diff --git a/src/Core/Grand.Domain/Catalog/SpecificationAttributeOption.cs b/src/Core/Grand.Domain/Catalog/SpecificationAttributeOption.cs index 2acc38f9d..7c7702258 100644 --- a/src/Core/Grand.Domain/Catalog/SpecificationAttributeOption.cs +++ b/src/Core/Grand.Domain/Catalog/SpecificationAttributeOption.cs @@ -10,7 +10,7 @@ public class SpecificationAttributeOption : SubBaseEntity, ITranslationEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the sename diff --git a/src/Core/Grand.Domain/Catalog/SpecificationAttributeOptionFilter.cs b/src/Core/Grand.Domain/Catalog/SpecificationAttributeOptionFilter.cs index a99f8d086..2b313d26a 100644 --- a/src/Core/Grand.Domain/Catalog/SpecificationAttributeOptionFilter.cs +++ b/src/Core/Grand.Domain/Catalog/SpecificationAttributeOptionFilter.cs @@ -8,7 +8,7 @@ public class SpecificationAttributeOptionFilter /// /// Gets or sets the specification attribute identifier /// - public string? SpecificationAttributeId { get; set; } + public string SpecificationAttributeId { get; set; } = null!; /// /// Gets or sets the specification attribute name diff --git a/src/Core/Grand.Domain/Common/AddressAttribute.cs b/src/Core/Grand.Domain/Common/AddressAttribute.cs index 4769c376a..a1d453b3b 100644 --- a/src/Core/Grand.Domain/Common/AddressAttribute.cs +++ b/src/Core/Grand.Domain/Common/AddressAttribute.cs @@ -15,7 +15,7 @@ public class AddressAttribute : BaseEntity, ITranslationEntity, IStoreLinkEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets a value indicating whether the attribute is required diff --git a/src/Core/Grand.Domain/Common/AddressAttributeValue.cs b/src/Core/Grand.Domain/Common/AddressAttributeValue.cs index 3bbdc7cc9..d6e73a0b7 100644 --- a/src/Core/Grand.Domain/Common/AddressAttributeValue.cs +++ b/src/Core/Grand.Domain/Common/AddressAttributeValue.cs @@ -17,7 +17,7 @@ public class AddressAttributeValue : BaseEntity, ITranslationEntity /// /// Gets or sets the checkout attribute name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets a value indicating whether the value is pre-selected diff --git a/src/Core/Grand.Domain/Common/RobotsTxt.cs b/src/Core/Grand.Domain/Common/RobotsTxt.cs index c55b67f55..d07e66dde 100644 --- a/src/Core/Grand.Domain/Common/RobotsTxt.cs +++ b/src/Core/Grand.Domain/Common/RobotsTxt.cs @@ -5,7 +5,7 @@ public class RobotsTxt : BaseEntity /// /// Gets or sets the name of robots.txt /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the text of robots.txt diff --git a/src/Core/Grand.Domain/Common/UserField.cs b/src/Core/Grand.Domain/Common/UserField.cs index ec919c7d5..0ac8eddd0 100644 --- a/src/Core/Grand.Domain/Common/UserField.cs +++ b/src/Core/Grand.Domain/Common/UserField.cs @@ -8,7 +8,7 @@ public class UserField /// /// Gets or sets the key /// - public string? Key { get; set; } + public string Key { get; set; } = null!; /// /// Gets or sets the value diff --git a/src/Core/Grand.Domain/Configuration/Setting.cs b/src/Core/Grand.Domain/Configuration/Setting.cs index de600313d..f65118623 100644 --- a/src/Core/Grand.Domain/Configuration/Setting.cs +++ b/src/Core/Grand.Domain/Configuration/Setting.cs @@ -8,7 +8,7 @@ public class Setting : BaseEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the store for which this setting is valid. 0 is set when the setting is for all stores diff --git a/src/Core/Grand.Domain/Courses/Course.cs b/src/Core/Grand.Domain/Courses/Course.cs index a62043573..3aff8b248 100644 --- a/src/Core/Grand.Domain/Courses/Course.cs +++ b/src/Core/Grand.Domain/Courses/Course.cs @@ -13,7 +13,7 @@ public class Course : BaseEntity, ITranslationEntity, ISlugEntity, IGroupLinkEnt /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the description diff --git a/src/Core/Grand.Domain/Courses/CourseAction.cs b/src/Core/Grand.Domain/Courses/CourseAction.cs index c3a5ed6db..4b0bdaaa3 100644 --- a/src/Core/Grand.Domain/Courses/CourseAction.cs +++ b/src/Core/Grand.Domain/Courses/CourseAction.cs @@ -9,19 +9,19 @@ public class CourseAction : BaseEntity /// Gets or sets the customer ident /// [AuditReference(typeof(Customer))] - public string? CustomerId { get; set; } + public string CustomerId { get; set; } = null!; /// /// Gets or sets the course ident /// [AuditReference(typeof(Course))] - public string? CourseId { get; set; } + public string CourseId { get; set; } = null!; /// /// Gets or sets the lesson ident /// [AuditReference(typeof(CourseLesson))] - public string? LessonId { get; set; } + public string LessonId { get; set; } = null!; /// /// Gets or sets the finished diff --git a/src/Core/Grand.Domain/Courses/CourseLesson.cs b/src/Core/Grand.Domain/Courses/CourseLesson.cs index e67436af5..a93336951 100644 --- a/src/Core/Grand.Domain/Courses/CourseLesson.cs +++ b/src/Core/Grand.Domain/Courses/CourseLesson.cs @@ -7,7 +7,7 @@ public class CourseLesson : BaseEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the short description @@ -28,13 +28,13 @@ public class CourseLesson : BaseEntity /// Gets or sets the course ident /// [AuditReference(typeof(Course))] - public string? CourseId { get; set; } + public string CourseId { get; set; } = null!; /// /// Gets or sets the subject ident /// [AuditReference(typeof(CourseSubject))] - public string? SubjectId { get; set; } + public string SubjectId { get; set; } = null!; /// /// Gets or sets the video file diff --git a/src/Core/Grand.Domain/Courses/CourseLevel.cs b/src/Core/Grand.Domain/Courses/CourseLevel.cs index 261b2ea5a..f41b9eac6 100644 --- a/src/Core/Grand.Domain/Courses/CourseLevel.cs +++ b/src/Core/Grand.Domain/Courses/CourseLevel.cs @@ -5,7 +5,7 @@ public class CourseLevel : BaseEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Courses/CourseSubject.cs b/src/Core/Grand.Domain/Courses/CourseSubject.cs index bfc41a840..00fc50f0b 100644 --- a/src/Core/Grand.Domain/Courses/CourseSubject.cs +++ b/src/Core/Grand.Domain/Courses/CourseSubject.cs @@ -7,7 +7,7 @@ public class CourseSubject : BaseEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the display order @@ -18,5 +18,5 @@ public class CourseSubject : BaseEntity /// Gets or sets the course ident /// [AuditReference(typeof(Course))] - public string? CourseId { get; set; } + public string CourseId { get; set; } = null!; } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Customers/CustomerAttribute.cs b/src/Core/Grand.Domain/Customers/CustomerAttribute.cs index c433ee185..07aa452f8 100644 --- a/src/Core/Grand.Domain/Customers/CustomerAttribute.cs +++ b/src/Core/Grand.Domain/Customers/CustomerAttribute.cs @@ -15,7 +15,7 @@ public class CustomerAttribute : BaseEntity, ITranslationEntity, IStoreLinkEntit /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets a value indicating whether the attribute is required diff --git a/src/Core/Grand.Domain/Customers/CustomerAttributeValue.cs b/src/Core/Grand.Domain/Customers/CustomerAttributeValue.cs index 1ca512548..be5c49baf 100644 --- a/src/Core/Grand.Domain/Customers/CustomerAttributeValue.cs +++ b/src/Core/Grand.Domain/Customers/CustomerAttributeValue.cs @@ -17,7 +17,7 @@ public class CustomerAttributeValue : SubBaseEntity, ITranslationEntity /// /// Gets or sets the checkout attribute name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets a value indicating whether the value is pre-selected diff --git a/src/Core/Grand.Domain/Customers/CustomerGroup.cs b/src/Core/Grand.Domain/Customers/CustomerGroup.cs index 2888ccc07..8097d4584 100644 --- a/src/Core/Grand.Domain/Customers/CustomerGroup.cs +++ b/src/Core/Grand.Domain/Customers/CustomerGroup.cs @@ -8,7 +8,7 @@ public class CustomerGroup : BaseEntity /// /// Gets or sets the customer group name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets a value indicating whether the customer group is marked as free shiping diff --git a/src/Core/Grand.Domain/Customers/CustomerHistoryPassword.cs b/src/Core/Grand.Domain/Customers/CustomerHistoryPassword.cs index 6c0112bd2..57fd13631 100644 --- a/src/Core/Grand.Domain/Customers/CustomerHistoryPassword.cs +++ b/src/Core/Grand.Domain/Customers/CustomerHistoryPassword.cs @@ -8,7 +8,7 @@ public class CustomerHistoryPassword : BaseEntity /// /// Gets or sets the customer identifier /// - public string? CustomerId { get; set; } + public string CustomerId { get; set; } = null!; /// /// Gets or sets the password diff --git a/src/Core/Grand.Domain/Customers/CustomerTag.cs b/src/Core/Grand.Domain/Customers/CustomerTag.cs index ad7b5aa66..e50dfe818 100644 --- a/src/Core/Grand.Domain/Customers/CustomerTag.cs +++ b/src/Core/Grand.Domain/Customers/CustomerTag.cs @@ -8,5 +8,5 @@ public class CustomerTag : BaseEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Customers/ExternalAuthentication.cs b/src/Core/Grand.Domain/Customers/ExternalAuthentication.cs index 3e1953d2c..8af8c951c 100644 --- a/src/Core/Grand.Domain/Customers/ExternalAuthentication.cs +++ b/src/Core/Grand.Domain/Customers/ExternalAuthentication.cs @@ -12,7 +12,7 @@ public class ExternalAuthentication : BaseEntity /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string? CustomerId { get; set; } + public string CustomerId { get; set; } = null!; /// /// Gets or sets the external email diff --git a/src/Core/Grand.Domain/Customers/OidcSession.cs b/src/Core/Grand.Domain/Customers/OidcSession.cs index 427a9e575..bc6ef51bc 100644 --- a/src/Core/Grand.Domain/Customers/OidcSession.cs +++ b/src/Core/Grand.Domain/Customers/OidcSession.cs @@ -6,7 +6,7 @@ namespace Grand.Domain.Customers; /// public class OidcSession : BaseEntity { - public string? CustomerId { get; set; } + public string CustomerId { get; set; } = null!; /// The store of the sign-in public string? StoreId { get; set; } diff --git a/src/Core/Grand.Domain/Customers/SalesEmployee.cs b/src/Core/Grand.Domain/Customers/SalesEmployee.cs index 27e68a8b9..312c5c430 100644 --- a/src/Core/Grand.Domain/Customers/SalesEmployee.cs +++ b/src/Core/Grand.Domain/Customers/SalesEmployee.cs @@ -5,7 +5,7 @@ public class SalesEmployee : BaseEntity /// /// Gets or sets the sales employee name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the sales employee email diff --git a/src/Core/Grand.Domain/Customers/UserApi.cs b/src/Core/Grand.Domain/Customers/UserApi.cs index 4e4c7c67d..c018c7183 100644 --- a/src/Core/Grand.Domain/Customers/UserApi.cs +++ b/src/Core/Grand.Domain/Customers/UserApi.cs @@ -6,7 +6,7 @@ namespace Grand.Domain.Customers; public class UserApi : BaseEntity { [AuditName] - public string? Email { get; set; } + public string Email { get; set; } = null!; public string? Password { get; set; } public string? PrivateKey { get; set; } public bool IsActive { get; set; } diff --git a/src/Core/Grand.Domain/Directory/Country.cs b/src/Core/Grand.Domain/Directory/Country.cs index d39546e1c..a69877193 100644 --- a/src/Core/Grand.Domain/Directory/Country.cs +++ b/src/Core/Grand.Domain/Directory/Country.cs @@ -14,7 +14,7 @@ public class Country : BaseEntity, ITranslationEntity, IStoreLinkEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets a value indicating whether billing is allowed to this country @@ -29,12 +29,12 @@ public class Country : BaseEntity, ITranslationEntity, IStoreLinkEntity /// /// Gets or sets the two letter ISO code /// - public string? TwoLetterIsoCode { get; set; } + public string TwoLetterIsoCode { get; set; } = null!; /// /// Gets or sets the three letter ISO code /// - public string? ThreeLetterIsoCode { get; set; } + public string ThreeLetterIsoCode { get; set; } = null!; /// /// Gets or sets the numeric ISO code diff --git a/src/Core/Grand.Domain/Directory/Currency.cs b/src/Core/Grand.Domain/Directory/Currency.cs index 6553d6bdc..24169c687 100644 --- a/src/Core/Grand.Domain/Directory/Currency.cs +++ b/src/Core/Grand.Domain/Directory/Currency.cs @@ -12,12 +12,12 @@ public class Currency : BaseEntity, ITranslationEntity, IStoreLinkEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the currency code /// - public string? CurrencyCode { get; set; } + public string CurrencyCode { get; set; } = null!; /// /// Gets or sets the rate diff --git a/src/Core/Grand.Domain/Directory/MeasureDimension.cs b/src/Core/Grand.Domain/Directory/MeasureDimension.cs index 9f6505bb8..672ccca9c 100644 --- a/src/Core/Grand.Domain/Directory/MeasureDimension.cs +++ b/src/Core/Grand.Domain/Directory/MeasureDimension.cs @@ -8,12 +8,12 @@ public class MeasureDimension : BaseEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the system keyword /// - public string? SystemKeyword { get; set; } + public string SystemKeyword { get; set; } = null!; /// /// Gets or sets the ratio diff --git a/src/Core/Grand.Domain/Directory/MeasureUnit.cs b/src/Core/Grand.Domain/Directory/MeasureUnit.cs index 28364afdb..08dd2e603 100644 --- a/src/Core/Grand.Domain/Directory/MeasureUnit.cs +++ b/src/Core/Grand.Domain/Directory/MeasureUnit.cs @@ -8,7 +8,7 @@ public class MeasureUnit : BaseEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Directory/MeasureWeight.cs b/src/Core/Grand.Domain/Directory/MeasureWeight.cs index 1415169ae..01a93f63f 100644 --- a/src/Core/Grand.Domain/Directory/MeasureWeight.cs +++ b/src/Core/Grand.Domain/Directory/MeasureWeight.cs @@ -8,12 +8,12 @@ public class MeasureWeight : BaseEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the system keyword /// - public string? SystemKeyword { get; set; } + public string SystemKeyword { get; set; } = null!; /// /// Gets or sets the ratio diff --git a/src/Core/Grand.Domain/Directory/StateProvince.cs b/src/Core/Grand.Domain/Directory/StateProvince.cs index 520bf9067..42f7fa1ee 100644 --- a/src/Core/Grand.Domain/Directory/StateProvince.cs +++ b/src/Core/Grand.Domain/Directory/StateProvince.cs @@ -10,7 +10,7 @@ public class StateProvince : SubBaseEntity, ITranslationEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the abbreviation diff --git a/src/Core/Grand.Domain/Discounts/Discount.cs b/src/Core/Grand.Domain/Discounts/Discount.cs index 4585a6113..6fd7d3496 100644 --- a/src/Core/Grand.Domain/Discounts/Discount.cs +++ b/src/Core/Grand.Domain/Discounts/Discount.cs @@ -13,7 +13,7 @@ public class Discount : BaseEntity, IStoreLinkEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the discount type identifier diff --git a/src/Core/Grand.Domain/Discounts/DiscountRule.cs b/src/Core/Grand.Domain/Discounts/DiscountRule.cs index e9655fb8c..63b21baea 100644 --- a/src/Core/Grand.Domain/Discounts/DiscountRule.cs +++ b/src/Core/Grand.Domain/Discounts/DiscountRule.cs @@ -11,7 +11,7 @@ public class DiscountRule : SubBaseEntity /// Gets or sets the discount requirement rule system name /// [AuditName] - public string? DiscountRequirementRuleSystemName { get; set; } + public string DiscountRequirementRuleSystemName { get; set; } = null!; /// /// Gets or sets the metadata diff --git a/src/Core/Grand.Domain/Discounts/DiscountUsageHistory.cs b/src/Core/Grand.Domain/Discounts/DiscountUsageHistory.cs index 99c6e96b7..441d5b7f4 100644 --- a/src/Core/Grand.Domain/Discounts/DiscountUsageHistory.cs +++ b/src/Core/Grand.Domain/Discounts/DiscountUsageHistory.cs @@ -30,7 +30,7 @@ public class DiscountUsageHistory : BaseEntity /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string? CustomerId { get; set; } + public string CustomerId { get; set; } = null!; /// /// Gets or sets the canceled identifier diff --git a/src/Core/Grand.Domain/Documents/Document.cs b/src/Core/Grand.Domain/Documents/Document.cs index 064c2d1c8..9e9ee302d 100644 --- a/src/Core/Grand.Domain/Documents/Document.cs +++ b/src/Core/Grand.Domain/Documents/Document.cs @@ -14,12 +14,12 @@ public class Document : BaseEntity, IGroupLinkEntity, IStoreLinkEntity /// /// Gets or sets the document number /// - public string? Number { get; set; } + public string Number { get; set; } = null!; /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the sales employee identifier diff --git a/src/Core/Grand.Domain/Documents/DocumentType.cs b/src/Core/Grand.Domain/Documents/DocumentType.cs index 877501e73..4d8e61ad4 100644 --- a/src/Core/Grand.Domain/Documents/DocumentType.cs +++ b/src/Core/Grand.Domain/Documents/DocumentType.cs @@ -5,7 +5,7 @@ /// public class DocumentType : BaseEntity { - public string? Name { get; set; } + public string Name { get; set; } = null!; public string? Description { get; set; } public int DisplayOrder { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Knowledgebase/ITreeNode.cs b/src/Core/Grand.Domain/Knowledgebase/ITreeNode.cs index 9702aff3e..c8ac9cfed 100644 --- a/src/Core/Grand.Domain/Knowledgebase/ITreeNode.cs +++ b/src/Core/Grand.Domain/Knowledgebase/ITreeNode.cs @@ -4,7 +4,7 @@ public interface ITreeNode { string Id { get; set; } - string? Name { get; set; } + string Name { get; set; } string? ParentCategoryId { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseArticle.cs b/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseArticle.cs index bf4ebb3f8..1f60b6f41 100644 --- a/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseArticle.cs +++ b/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseArticle.cs @@ -84,7 +84,7 @@ public class KnowledgebaseArticle : BaseEntity, ITreeNode, ITranslationEntity, I /// /// Gets or sets title of the article /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets parent category Id diff --git a/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseArticleComment.cs b/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseArticleComment.cs index 50fc82577..fcb92ac37 100644 --- a/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseArticleComment.cs +++ b/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseArticleComment.cs @@ -9,7 +9,7 @@ public class KnowledgebaseArticleComment : BaseEntity /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string? CustomerId { get; set; } + public string CustomerId { get; set; } = null!; /// /// Gets or sets the comment text @@ -27,5 +27,5 @@ public class KnowledgebaseArticleComment : BaseEntity /// [AuditReference(typeof(KnowledgebaseArticle))] [AuditOwner] - public string? ArticleId { get; set; } + public string ArticleId { get; set; } = null!; } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseCategory.cs b/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseCategory.cs index e63d30e58..4aefd927d 100644 --- a/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseCategory.cs +++ b/src/Core/Grand.Domain/Knowledgebase/KnowledgebaseCategory.cs @@ -69,7 +69,7 @@ public class KnowledgebaseCategory : BaseEntity, ITreeNode, ITranslationEntity, /// /// Gets or sets name of the category /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets parent category Id diff --git a/src/Core/Grand.Domain/Localization/Language.cs b/src/Core/Grand.Domain/Localization/Language.cs index 822ab921c..a9732f8de 100644 --- a/src/Core/Grand.Domain/Localization/Language.cs +++ b/src/Core/Grand.Domain/Localization/Language.cs @@ -12,7 +12,7 @@ public class Language : BaseEntity, IStoreLinkEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the language culture @@ -22,7 +22,7 @@ public class Language : BaseEntity, IStoreLinkEntity /// /// Gets or sets the unique SEO code /// - public string? UniqueSeoCode { get; set; } + public string UniqueSeoCode { get; set; } = null!; /// /// Gets or sets the flag image file name diff --git a/src/Core/Grand.Domain/Localization/TranslationResource.cs b/src/Core/Grand.Domain/Localization/TranslationResource.cs index 5c827342d..e5f8a6100 100644 --- a/src/Core/Grand.Domain/Localization/TranslationResource.cs +++ b/src/Core/Grand.Domain/Localization/TranslationResource.cs @@ -12,7 +12,7 @@ public class TranslationResource : BaseEntity /// [AuditReference(typeof(Language))] [AuditOwner] - public string? LanguageId { get; set; } + public string LanguageId { get; set; } = null!; /// /// Gets or sets the translation name diff --git a/src/Core/Grand.Domain/Messages/Campaign.cs b/src/Core/Grand.Domain/Messages/Campaign.cs index 222e0b604..4919415fa 100644 --- a/src/Core/Grand.Domain/Messages/Campaign.cs +++ b/src/Core/Grand.Domain/Messages/Campaign.cs @@ -17,17 +17,17 @@ public class Campaign : BaseEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the subject /// - public string? Subject { get; set; } + public string Subject { get; set; } = null!; /// /// Gets or sets the body /// - public string? Body { get; set; } + public string Body { get; set; } = null!; /// /// Gets or sets the store identifier diff --git a/src/Core/Grand.Domain/Messages/CampaignHistory.cs b/src/Core/Grand.Domain/Messages/CampaignHistory.cs index 02699aded..3adae4f51 100644 --- a/src/Core/Grand.Domain/Messages/CampaignHistory.cs +++ b/src/Core/Grand.Domain/Messages/CampaignHistory.cs @@ -7,7 +7,7 @@ namespace Grand.Domain.Messages; /// public class CampaignHistory : BaseEntity { - public string? CampaignId { get; set; } + public string CampaignId { get; set; } = null!; [AuditName] public string? Email { get; set; } diff --git a/src/Core/Grand.Domain/Messages/ContactAttribute.cs b/src/Core/Grand.Domain/Messages/ContactAttribute.cs index 32c8c7233..14a9a9d0d 100644 --- a/src/Core/Grand.Domain/Messages/ContactAttribute.cs +++ b/src/Core/Grand.Domain/Messages/ContactAttribute.cs @@ -18,7 +18,7 @@ public class ContactAttribute : BaseEntity, ITranslationEntity, IStoreLinkEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the text prompt diff --git a/src/Core/Grand.Domain/Messages/ContactAttributeValue.cs b/src/Core/Grand.Domain/Messages/ContactAttributeValue.cs index 7fd0679a7..ab3e0579e 100644 --- a/src/Core/Grand.Domain/Messages/ContactAttributeValue.cs +++ b/src/Core/Grand.Domain/Messages/ContactAttributeValue.cs @@ -17,7 +17,7 @@ public class ContactAttributeValue : SubBaseEntity, ITranslationEntity /// /// Gets or sets the checkout attribute name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the color RGB value (used with "Color squares" attribute type) diff --git a/src/Core/Grand.Domain/Messages/ContactUs.cs b/src/Core/Grand.Domain/Messages/ContactUs.cs index eee25379b..a773f1dbb 100644 --- a/src/Core/Grand.Domain/Messages/ContactUs.cs +++ b/src/Core/Grand.Domain/Messages/ContactUs.cs @@ -32,12 +32,12 @@ public class ContactUs : BaseEntity /// Gets or sets the email /// [AuditName] - public string? Email { get; set; } + public string Email { get; set; } = null!; /// /// Gets or sets full name /// - public string? FullName { get; set; } + public string FullName { get; set; } = null!; /// /// Gets or sets the subject @@ -47,7 +47,7 @@ public class ContactUs : BaseEntity /// /// Gets or sets enquiry /// - public string? Enquiry { get; set; } + public string Enquiry { get; set; } = null!; /// /// Gets or sets the email account identifier diff --git a/src/Core/Grand.Domain/Messages/EmailAccount.cs b/src/Core/Grand.Domain/Messages/EmailAccount.cs index aa0eb5d4b..8bcc9990e 100644 --- a/src/Core/Grand.Domain/Messages/EmailAccount.cs +++ b/src/Core/Grand.Domain/Messages/EmailAccount.cs @@ -12,12 +12,12 @@ public class EmailAccount : BaseEntity /// Gets or sets an email address /// [AuditName] - public string? Email { get; set; } + public string Email { get; set; } = null!; /// /// Gets or sets an email display name /// - public string? DisplayName { get; set; } + public string DisplayName { get; set; } = null!; /// /// Gets or sets an email host diff --git a/src/Core/Grand.Domain/Messages/MessageTemplate.cs b/src/Core/Grand.Domain/Messages/MessageTemplate.cs index 1ac425aaa..81edf5d55 100644 --- a/src/Core/Grand.Domain/Messages/MessageTemplate.cs +++ b/src/Core/Grand.Domain/Messages/MessageTemplate.cs @@ -22,12 +22,12 @@ public class MessageTemplate : BaseEntity, ITranslationEntity, IStoreLinkEntity /// /// Gets or sets the subject /// - public string? Subject { get; set; } + public string Subject { get; set; } = null!; /// /// Gets or sets the body /// - public string? Body { get; set; } + public string Body { get; set; } = null!; /// /// Gets or sets a value indicating whether the template is active diff --git a/src/Core/Grand.Domain/Messages/NewsLetterSubscription.cs b/src/Core/Grand.Domain/Messages/NewsLetterSubscription.cs index 89897cbf4..3884abfb4 100644 --- a/src/Core/Grand.Domain/Messages/NewsLetterSubscription.cs +++ b/src/Core/Grand.Domain/Messages/NewsLetterSubscription.cs @@ -27,7 +27,7 @@ public class NewsLetterSubscription : BaseEntity, IHistory /// Gets or sets the subcriber email /// [AuditName] - public string? Email { get; set; } + public string Email { get; set; } = null!; /// /// Gets or sets a value indicating whether subscription is active diff --git a/src/Core/Grand.Domain/Messages/NewsletterCategory.cs b/src/Core/Grand.Domain/Messages/NewsletterCategory.cs index f743290fd..0f974626c 100644 --- a/src/Core/Grand.Domain/Messages/NewsletterCategory.cs +++ b/src/Core/Grand.Domain/Messages/NewsletterCategory.cs @@ -9,7 +9,7 @@ public class NewsletterCategory : BaseEntity, ITranslationEntity, IStoreLinkEnti /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the description diff --git a/src/Core/Grand.Domain/News/NewsComment.cs b/src/Core/Grand.Domain/News/NewsComment.cs index 94c38579f..0bf7817bb 100644 --- a/src/Core/Grand.Domain/News/NewsComment.cs +++ b/src/Core/Grand.Domain/News/NewsComment.cs @@ -24,19 +24,19 @@ public class NewsComment : SubBaseEntity /// Gets or sets the news item identifier /// [AuditReference(typeof(NewsItem))] - public string? NewsItemId { get; set; } + public string NewsItemId { get; set; } = null!; /// /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string? CustomerId { get; set; } + public string CustomerId { get; set; } = null!; /// /// Gets or sets the store identifier /// [AuditReference(typeof(Store))] - public string? StoreId { get; set; } + public string StoreId { get; set; } = null!; /// /// Gets or sets the date and time of instance creation diff --git a/src/Core/Grand.Domain/News/NewsItem.cs b/src/Core/Grand.Domain/News/NewsItem.cs index 3c57854ce..e09bad47c 100644 --- a/src/Core/Grand.Domain/News/NewsItem.cs +++ b/src/Core/Grand.Domain/News/NewsItem.cs @@ -18,7 +18,7 @@ public class NewsItem : BaseEntity, ISlugEntity, IStoreLinkEntity, ITranslationE /// Gets or sets the news title /// [AuditName] - public string? Title { get; set; } + public string Title { get; set; } = null!; /// /// Gets or sets the picture identifier @@ -28,12 +28,12 @@ public class NewsItem : BaseEntity, ISlugEntity, IStoreLinkEntity, ITranslationE /// /// Gets or sets the short text /// - public string? Short { get; set; } + public string Short { get; set; } = null!; /// /// Gets or sets the full text /// - public string? Full { get; set; } + public string Full { get; set; } = null!; /// /// Gets or sets a value indicating whether the news item is published diff --git a/src/Core/Grand.Domain/Orders/CheckoutAttribute.cs b/src/Core/Grand.Domain/Orders/CheckoutAttribute.cs index 229fc8638..a0feabcff 100644 --- a/src/Core/Grand.Domain/Orders/CheckoutAttribute.cs +++ b/src/Core/Grand.Domain/Orders/CheckoutAttribute.cs @@ -19,7 +19,7 @@ public class CheckoutAttribute : BaseEntity, ITranslationEntity, IStoreLinkEntit /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the text prompt diff --git a/src/Core/Grand.Domain/Orders/CheckoutAttributeValue.cs b/src/Core/Grand.Domain/Orders/CheckoutAttributeValue.cs index 251d6ab2b..358deccb0 100644 --- a/src/Core/Grand.Domain/Orders/CheckoutAttributeValue.cs +++ b/src/Core/Grand.Domain/Orders/CheckoutAttributeValue.cs @@ -17,7 +17,7 @@ public class CheckoutAttributeValue : SubBaseEntity, ITranslationEntity /// /// Gets or sets the checkout attribute name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the color RGB value (used with "Color squares" attribute type) diff --git a/src/Core/Grand.Domain/Orders/GiftVoucher.cs b/src/Core/Grand.Domain/Orders/GiftVoucher.cs index 81bd0cb8f..02167d56d 100644 --- a/src/Core/Grand.Domain/Orders/GiftVoucher.cs +++ b/src/Core/Grand.Domain/Orders/GiftVoucher.cs @@ -35,7 +35,7 @@ public class GiftVoucher : BaseEntity /// Gets or sets a gift voucher coupon code /// [AuditName] - public string? Code { get; set; } + public string Code { get; set; } = null!; /// /// Gets or sets a recipient name diff --git a/src/Core/Grand.Domain/Orders/GiftVoucherUsageHistory.cs b/src/Core/Grand.Domain/Orders/GiftVoucherUsageHistory.cs index cd96e15d3..a31bc7b23 100644 --- a/src/Core/Grand.Domain/Orders/GiftVoucherUsageHistory.cs +++ b/src/Core/Grand.Domain/Orders/GiftVoucherUsageHistory.cs @@ -11,7 +11,7 @@ public class GiftVoucherUsageHistory : SubBaseEntity /// Gets or sets the gift voucher identifier /// [AuditReference(typeof(GiftVoucher))] - public string? GiftVoucherId { get; set; } + public string GiftVoucherId { get; set; } = null!; /// /// Gets or sets the order identifier diff --git a/src/Core/Grand.Domain/Orders/MerchandiseReturn.cs b/src/Core/Grand.Domain/Orders/MerchandiseReturn.cs index 4fb921fae..762d9c3e9 100644 --- a/src/Core/Grand.Domain/Orders/MerchandiseReturn.cs +++ b/src/Core/Grand.Domain/Orders/MerchandiseReturn.cs @@ -29,7 +29,7 @@ public class MerchandiseReturn : BaseEntity /// Gets or sets the order item identifier /// [AuditReference(typeof(Order))] - public string? OrderId { get; set; } + public string OrderId { get; set; } = null!; /// /// Gets or sets the owner item identifier diff --git a/src/Core/Grand.Domain/Orders/MerchandiseReturnAction.cs b/src/Core/Grand.Domain/Orders/MerchandiseReturnAction.cs index 9ccb655eb..e3a859159 100644 --- a/src/Core/Grand.Domain/Orders/MerchandiseReturnAction.cs +++ b/src/Core/Grand.Domain/Orders/MerchandiseReturnAction.cs @@ -12,7 +12,7 @@ public class MerchandiseReturnAction : BaseEntity, ITranslationEntity, IStoreLin /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Orders/MerchandiseReturnNote.cs b/src/Core/Grand.Domain/Orders/MerchandiseReturnNote.cs index e40f08d18..e84c1a9e4 100644 --- a/src/Core/Grand.Domain/Orders/MerchandiseReturnNote.cs +++ b/src/Core/Grand.Domain/Orders/MerchandiseReturnNote.cs @@ -12,7 +12,7 @@ public class MerchandiseReturnNote : BaseEntity /// [AuditReference(typeof(MerchandiseReturn))] [AuditOwner] - public string? MerchandiseReturnId { get; set; } + public string MerchandiseReturnId { get; set; } = null!; /// /// Gets or sets the title diff --git a/src/Core/Grand.Domain/Orders/MerchandiseReturnReason.cs b/src/Core/Grand.Domain/Orders/MerchandiseReturnReason.cs index 2ed3210c5..4455cddea 100644 --- a/src/Core/Grand.Domain/Orders/MerchandiseReturnReason.cs +++ b/src/Core/Grand.Domain/Orders/MerchandiseReturnReason.cs @@ -12,7 +12,7 @@ public class MerchandiseReturnReason : BaseEntity, ITranslationEntity, IStoreLin /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Orders/MerchandiseReturnRefund.cs b/src/Core/Grand.Domain/Orders/MerchandiseReturnRefund.cs index 57d402442..0d39d8f1b 100644 --- a/src/Core/Grand.Domain/Orders/MerchandiseReturnRefund.cs +++ b/src/Core/Grand.Domain/Orders/MerchandiseReturnRefund.cs @@ -33,7 +33,7 @@ public class MerchandiseReturnRefund /// Gets or sets the payment transaction refunded /// [AuditReference(typeof(PaymentTransaction))] - public string? PaymentTransactionId { get; set; } + public string PaymentTransactionId { get; set; } = null!; /// /// Gets or sets whether the payment answered the refund with errors: it may have given the money back before it diff --git a/src/Core/Grand.Domain/Orders/MerchandiseReturnShipping.cs b/src/Core/Grand.Domain/Orders/MerchandiseReturnShipping.cs index 78d6c640d..c43f912be 100644 --- a/src/Core/Grand.Domain/Orders/MerchandiseReturnShipping.cs +++ b/src/Core/Grand.Domain/Orders/MerchandiseReturnShipping.cs @@ -94,7 +94,7 @@ public class ReturnDropOffPoint /// /// Gets or sets the provider's identifier of the point /// - public string? Id { get; set; } + public string Id { get; set; } = null!; /// /// Gets or sets the name diff --git a/src/Core/Grand.Domain/Orders/OrderStatus.cs b/src/Core/Grand.Domain/Orders/OrderStatus.cs index 59387f09b..282a75342 100644 --- a/src/Core/Grand.Domain/Orders/OrderStatus.cs +++ b/src/Core/Grand.Domain/Orders/OrderStatus.cs @@ -3,7 +3,7 @@ public class OrderStatus : BaseEntity { public int StatusId { get; set; } - public string? Name { get; set; } + public string Name { get; set; } = null!; public int DisplayOrder { get; set; } public bool IsSystem { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Pages/PageLayout.cs b/src/Core/Grand.Domain/Pages/PageLayout.cs index 36234c031..9ed9f47d5 100644 --- a/src/Core/Grand.Domain/Pages/PageLayout.cs +++ b/src/Core/Grand.Domain/Pages/PageLayout.cs @@ -8,12 +8,12 @@ public class PageLayout : BaseEntity /// /// Gets or sets the layout name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the view path /// - public string? ViewPath { get; set; } + public string ViewPath { get; set; } = null!; /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Payments/PaymentTransactionEntry.cs b/src/Core/Grand.Domain/Payments/PaymentTransactionEntry.cs index 10fd47b00..927e53d0f 100644 --- a/src/Core/Grand.Domain/Payments/PaymentTransactionEntry.cs +++ b/src/Core/Grand.Domain/Payments/PaymentTransactionEntry.cs @@ -10,7 +10,7 @@ public class PaymentTransactionEntry : BaseEntity { [AuditReference(typeof(PaymentTransaction))] [AuditOwner] - public string? PaymentTransactionId { get; set; } + public string PaymentTransactionId { get; set; } = null!; public PaymentTransactionEntryType EntryType { get; set; } diff --git a/src/Core/Grand.Domain/PushNotifications/PushRegistration.cs b/src/Core/Grand.Domain/PushNotifications/PushRegistration.cs index 258eb98f0..4b79d401c 100644 --- a/src/Core/Grand.Domain/PushNotifications/PushRegistration.cs +++ b/src/Core/Grand.Domain/PushNotifications/PushRegistration.cs @@ -2,7 +2,7 @@ public class PushRegistration : BaseEntity { - public string? CustomerId { get; set; } + public string CustomerId { get; set; } = null!; public bool Allowed { get; set; } diff --git a/src/Core/Grand.Domain/Security/RefreshToken.cs b/src/Core/Grand.Domain/Security/RefreshToken.cs index 684686702..e9731b2da 100644 --- a/src/Core/Grand.Domain/Security/RefreshToken.cs +++ b/src/Core/Grand.Domain/Security/RefreshToken.cs @@ -2,7 +2,7 @@ public class RefreshToken { - public string? RefreshId { get; set; } + public string RefreshId { get; set; } = null!; public string? Token { get; set; } public DateTime ValidTo { get; set; } public bool IsActive { get; set; } diff --git a/src/Core/Grand.Domain/Shipping/DeliveryDate.cs b/src/Core/Grand.Domain/Shipping/DeliveryDate.cs index 93e24d425..95b5e36a4 100644 --- a/src/Core/Grand.Domain/Shipping/DeliveryDate.cs +++ b/src/Core/Grand.Domain/Shipping/DeliveryDate.cs @@ -12,7 +12,7 @@ public class DeliveryDate : BaseEntity, ITranslationEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Shipping/PickupPoints.cs b/src/Core/Grand.Domain/Shipping/PickupPoints.cs index 450c4e105..7d417ea0b 100644 --- a/src/Core/Grand.Domain/Shipping/PickupPoints.cs +++ b/src/Core/Grand.Domain/Shipping/PickupPoints.cs @@ -12,7 +12,7 @@ public class PickupPoint : BaseEntity /// /// Gets or sets the point name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the description diff --git a/src/Core/Grand.Domain/Shipping/ShippingMethod.cs b/src/Core/Grand.Domain/Shipping/ShippingMethod.cs index 3b1bb05be..6978710a9 100644 --- a/src/Core/Grand.Domain/Shipping/ShippingMethod.cs +++ b/src/Core/Grand.Domain/Shipping/ShippingMethod.cs @@ -16,7 +16,7 @@ public class ShippingMethod : BaseEntity, ITranslationEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the description diff --git a/src/Core/Grand.Domain/Shipping/Warehouse.cs b/src/Core/Grand.Domain/Shipping/Warehouse.cs index 262133639..e32614dbd 100644 --- a/src/Core/Grand.Domain/Shipping/Warehouse.cs +++ b/src/Core/Grand.Domain/Shipping/Warehouse.cs @@ -12,12 +12,12 @@ public class Warehouse : BaseEntity /// /// Gets or sets the warehouse code /// - public string? Code { get; set; } + public string Code { get; set; } = null!; /// /// Gets or sets the warehouse name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the admin comment diff --git a/src/Core/Grand.Domain/Shipping/WarehouseLocation.cs b/src/Core/Grand.Domain/Shipping/WarehouseLocation.cs index c19601d2b..5a41257be 100644 --- a/src/Core/Grand.Domain/Shipping/WarehouseLocation.cs +++ b/src/Core/Grand.Domain/Shipping/WarehouseLocation.cs @@ -8,13 +8,13 @@ namespace Grand.Domain.Shipping; public class WarehouseLocation : BaseEntity { [AuditReference(typeof(Warehouse))] - public string? WarehouseId { get; set; } + public string WarehouseId { get; set; } = null!; /// /// The code written on the place, such as A-01-03 /// [AuditName] - public string? Code { get; set; } + public string Code { get; set; } = null!; public string? Name { get; set; } diff --git a/src/Core/Grand.Domain/Stores/DomainHost.cs b/src/Core/Grand.Domain/Stores/DomainHost.cs index 3643a7e91..7eb24451d 100644 --- a/src/Core/Grand.Domain/Stores/DomainHost.cs +++ b/src/Core/Grand.Domain/Stores/DomainHost.cs @@ -6,6 +6,6 @@ public class DomainHost : SubBaseEntity { [AuditName] public string? HostName { get; set; } - public string? Url { get; set; } + public string Url { get; set; } = null!; public bool Primary { get; set; } } \ No newline at end of file diff --git a/src/Core/Grand.Domain/Stores/Store.cs b/src/Core/Grand.Domain/Stores/Store.cs index 2a664ced3..c1ac29562 100644 --- a/src/Core/Grand.Domain/Stores/Store.cs +++ b/src/Core/Grand.Domain/Stores/Store.cs @@ -14,7 +14,7 @@ public class Store : BaseEntity, ITranslationEntity /// /// Gets or sets the store name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the store shortcut @@ -24,7 +24,7 @@ public class Store : BaseEntity, ITranslationEntity /// /// Gets or sets the store URL, including the scheme /// - public string? Url { get; set; } + public string Url { get; set; } = null!; /// /// Gets or sets the account told about the store's order approvals; it does not limit who may decide them diff --git a/src/Core/Grand.Domain/Tax/TaxCategory.cs b/src/Core/Grand.Domain/Tax/TaxCategory.cs index 27bf99a9e..f559d4464 100644 --- a/src/Core/Grand.Domain/Tax/TaxCategory.cs +++ b/src/Core/Grand.Domain/Tax/TaxCategory.cs @@ -11,7 +11,7 @@ public class TaxCategory : BaseEntity /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the display order diff --git a/src/Core/Grand.Domain/Vendors/Vendor.cs b/src/Core/Grand.Domain/Vendors/Vendor.cs index 0a0133b7c..81ea49ed3 100644 --- a/src/Core/Grand.Domain/Vendors/Vendor.cs +++ b/src/Core/Grand.Domain/Vendors/Vendor.cs @@ -24,7 +24,7 @@ public Vendor() /// /// Gets or sets the name /// - public string? Name { get; set; } + public string Name { get; set; } = null!; /// /// Gets or sets the picture identifier @@ -34,7 +34,7 @@ public Vendor() /// /// Gets or sets the email /// - public string? Email { get; set; } + public string Email { get; set; } = null!; /// /// Gets or sets the description diff --git a/src/Core/Grand.Domain/Vendors/VendorReview.cs b/src/Core/Grand.Domain/Vendors/VendorReview.cs index b8e613bca..6cd0c0464 100644 --- a/src/Core/Grand.Domain/Vendors/VendorReview.cs +++ b/src/Core/Grand.Domain/Vendors/VendorReview.cs @@ -14,13 +14,13 @@ public class VendorReview : BaseEntity /// Gets or sets the customer identifier /// [AuditReference(typeof(Customer))] - public string? CustomerId { get; set; } + public string CustomerId { get; set; } = null!; /// /// Gets or sets the vendor identifier /// [AuditReference(typeof(Vendor))] - public string? VendorId { get; set; } + public string VendorId { get; set; } = null!; /// /// Gets or sets a value indicating whether the content is approved @@ -31,12 +31,12 @@ public class VendorReview : BaseEntity /// Gets or sets the title /// [AuditName] - public string? Title { get; set; } + public string Title { get; set; } = null!; /// /// Gets or sets the review text /// - public string? ReviewText { get; set; } + public string ReviewText { get; set; } = null!; /// /// Review rating diff --git a/src/Core/Grand.Domain/Vendors/VendorReviewHelpfulness.cs b/src/Core/Grand.Domain/Vendors/VendorReviewHelpfulness.cs index 30188100e..1d2a156e0 100644 --- a/src/Core/Grand.Domain/Vendors/VendorReviewHelpfulness.cs +++ b/src/Core/Grand.Domain/Vendors/VendorReviewHelpfulness.cs @@ -8,7 +8,7 @@ public class VendorReviewHelpfulness : SubBaseEntity /// /// Gets or sets the vendor review identifier /// - public string? VendorReviewId { get; set; } + public string VendorReviewId { get; set; } = null!; /// /// A value indicating whether a review a helpful @@ -18,5 +18,5 @@ public class VendorReviewHelpfulness : SubBaseEntity /// /// Gets or sets the customer identifier /// - public string? CustomerId { get; set; } + public string CustomerId { get; set; } = null!; } \ No newline at end of file From 05e7f4eec45414fbea7ed06ca45e02fe78ddefe1 Mon Sep 17 00:00:00 2001 From: support Date: Wed, 25 Nov 2026 11:04:07 +0100 Subject: [PATCH 08/30] Mark the inputs every mediator request needs as required 93 properties of the commands and queries in Grand.Business.Core are "required" and not nullable: every creation site in code sets them and no code tests them for null, so the compiler now holds every new caller to it. Objects and ids only - notes, references and who-did-it strings stay optional. The guards in the handlers stay, for callers outside nullable checking. The tests of those guards pass null! - the one place a null is handed to a not-nullable member on purpose. --- .../Catalog/SendNotificationsToSubscribersCommand.cs | 2 +- .../Commands/Catalog/SendOutBidCustomerCommand.cs | 6 +++--- .../Catalog/SendQuantityBelowStoreOwnerCommand.cs | 2 +- .../Catalog/UpdateProductReviewTotalsCommand.cs | 2 +- .../ActivatedValueForPurchasedVouchersCommand.cs | 2 +- .../Checkout/Orders/AddCustomerReservationCommand.cs | 6 +++--- .../Checkout/Orders/AddRequiredProductsCommand.cs | 8 ++++---- .../Orders/ApplyOrderApprovalDecisionCommand.cs | 4 ++-- .../Checkout/Orders/AwardLoyaltyPointsCommand.cs | 2 +- .../Commands/Checkout/Orders/CancelOrderCommand.cs | 2 +- .../Checkout/Orders/CancelOrderItemCommand.cs | 4 ++-- .../Checkout/Orders/CancelRecurringPaymentCommand.cs | 2 +- .../Commands/Checkout/Orders/CaptureCommand.cs | 2 +- .../Checkout/Orders/CheckOrderStatusCommand.cs | 2 +- .../Orders/DecideStoreOrderApprovalCommand.cs | 4 ++-- .../Commands/Checkout/Orders/DeleteOrderCommand.cs | 2 +- .../Checkout/Orders/DeleteOrderItemCommand.cs | 4 ++-- .../Checkout/Orders/InsertOrderItemCommand.cs | 6 +++--- .../Commands/Checkout/Orders/MarkAsPaidCommand.cs | 2 +- .../Checkout/Orders/PartiallyPaidOfflineCommand.cs | 2 +- .../Checkout/Orders/PartiallyRefundCommand.cs | 2 +- .../Checkout/Orders/PartiallyRefundOfflineCommand.cs | 2 +- .../Commands/Checkout/Orders/PlaceOrderCommand.cs | 6 +++--- .../Orders/PlaceRecurringCycleOrderCommand.cs | 4 ++-- .../Checkout/Orders/ProcessOrderPaidCommand.cs | 2 +- .../Commands/Checkout/Orders/ReOrderCommand.cs | 4 ++-- .../Orders/RecordRecurringPaymentCycleCommand.cs | 2 +- .../Orders/RecordRecurringPaymentEndedCommand.cs | 2 +- .../Orders/RecordRecurringPaymentFailureCommand.cs | 2 +- .../Orders/RecordRecurringPaymentReferenceCommand.cs | 2 +- .../Checkout/Orders/ReduceLoyaltyPointsCommand.cs | 2 +- .../Commands/Checkout/Orders/RefundCommand.cs | 2 +- .../Commands/Checkout/Orders/RefundOfflineCommand.cs | 2 +- .../Orders/ReturnBackRedeemedLoyaltyPointsCommand.cs | 2 +- .../Checkout/Orders/SetOrderStatusCommand.cs | 2 +- .../Checkout/Orders/UpdateOrderItemCommand.cs | 4 ++-- .../ValidateMinShoppingCartSubtotalAmountCommand.cs | 4 ++-- .../Commands/Checkout/Orders/VoidCommand.cs | 2 +- .../Commands/Checkout/Orders/VoidOfflineCommand.cs | 2 +- .../Commands/Checkout/Shipping/DeliveryCommand.cs | 2 +- .../Commands/Checkout/Shipping/ShipCommand.cs | 2 +- .../Commands/Customers/ActiveVendorCommand.cs | 2 +- .../Messages/Common/OrderNotificationCommand.cs | 4 ++-- .../Commands/System/Common/GetSitemapXmlCommand.cs | 4 ++-- .../Queries/Catalog/GetPersonalizedProductsQuery.cs | 4 ++-- .../Catalog/GetPriceByCustomerProductQuery.cs | 4 ++-- .../Queries/Catalog/GetProductArchByIdQuery.cs | 2 +- .../Queries/Catalog/GetRecommendedProductsQuery.cs | 4 ++-- .../Queries/Catalog/GetSearchProductsQuery.cs | 2 +- .../Catalog/GetShoppingCartItemsSubTotalQuery.cs | 4 ++-- .../Queries/Catalog/GetSitemapProductsQuery.cs | 2 +- .../Queries/Catalog/GetSuggestedProductsQuery.cs | 4 ++-- .../Queries/Checkout/Orders/CanCancelOrderQuery.cs | 2 +- .../Queries/Checkout/Orders/CanCaptureQuery.cs | 2 +- .../Orders/CanDeletePaymentTransactionQuery.cs | 2 +- .../Orders/CanMarkPaymentTransactionAsPaidQuery.cs | 2 +- .../Checkout/Orders/CanPartiallyPaidOfflineQuery.cs | 2 +- .../Orders/CanPartiallyRefundOfflineQuery.cs | 2 +- .../Checkout/Orders/CanPartiallyRefundQuery.cs | 2 +- .../Queries/Checkout/Orders/CanRefundOfflineQuery.cs | 2 +- .../Queries/Checkout/Orders/CanRefundQuery.cs | 2 +- .../Queries/Checkout/Orders/CanVoidOfflineQuery.cs | 2 +- .../Queries/Checkout/Orders/CanVoidQuery.cs | 2 +- .../Queries/Checkout/Orders/GetPickupPointById.cs | 2 +- .../Checkout/Orders/GetReturnableQuantitiesQuery.cs | 2 +- .../Checkout/Orders/GetVendorsInOrderQuery.cs | 2 +- .../Queries/Messages/GetBidsByProductIdQuery.cs | 2 +- .../UpdateProductReviewTotalsCommandHandlerTest.cs | 3 ++- .../GetPersonalizedProductsQueryHandlerTests.cs | 6 ++++-- .../GetPriceByCustomerProductQueryHandlerTests.cs | 3 ++- .../Handlers/GetProductArchByIdQueryHandlerTests.cs | 2 +- .../GetRecommendedProductsQueryHandlerTests.cs | 3 ++- .../Handlers/GetSearchProductsQueryHandlerTests.cs | 3 ++- .../Handlers/GetSitemapProductsQueryHandlerTests.cs | 4 ++-- .../GetSuggestedProductsQueryHandlerTests.cs | 6 ++++-- .../Orders/AddRequiredProductsCommandHandlerTests.cs | 12 ++++++------ .../Handlers/Orders/PlaceOrderCommandHandlerTests.cs | 12 +++++++++--- 77 files changed, 127 insertions(+), 113 deletions(-) diff --git a/src/Business/Grand.Business.Core/Commands/Catalog/SendNotificationsToSubscribersCommand.cs b/src/Business/Grand.Business.Core/Commands/Catalog/SendNotificationsToSubscribersCommand.cs index 8c5100f82..f6ff01529 100644 --- a/src/Business/Grand.Business.Core/Commands/Catalog/SendNotificationsToSubscribersCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Catalog/SendNotificationsToSubscribersCommand.cs @@ -6,7 +6,7 @@ namespace Grand.Business.Core.Commands.Catalog; public class SendNotificationsToSubscribersCommand : IRequest> { - public Product? Product { get; set; } + public required Product Product { get; set; } public IList? Attributes { get; set; } public string? Warehouse { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Catalog/SendOutBidCustomerCommand.cs b/src/Business/Grand.Business.Core/Commands/Catalog/SendOutBidCustomerCommand.cs index 7374121d7..7c21c6324 100644 --- a/src/Business/Grand.Business.Core/Commands/Catalog/SendOutBidCustomerCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Catalog/SendOutBidCustomerCommand.cs @@ -6,7 +6,7 @@ namespace Grand.Business.Core.Commands.Catalog; public class SendOutBidCustomerCommand : IRequest { - public Product? Product { get; set; } - public Bid? Bid { get; set; } - public Language? Language { get; set; } + public required Product Product { get; set; } + public required Bid Bid { get; set; } + public required Language Language { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Catalog/SendQuantityBelowStoreOwnerCommand.cs b/src/Business/Grand.Business.Core/Commands/Catalog/SendQuantityBelowStoreOwnerCommand.cs index 8d6c349fc..70d2808b6 100644 --- a/src/Business/Grand.Business.Core/Commands/Catalog/SendQuantityBelowStoreOwnerCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Catalog/SendQuantityBelowStoreOwnerCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Catalog; public class SendQuantityBelowStoreOwnerCommand : IRequest { - public Product? Product { get; set; } + public required Product Product { get; set; } public ProductAttributeCombination? ProductAttributeCombination { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Catalog/UpdateProductReviewTotalsCommand.cs b/src/Business/Grand.Business.Core/Commands/Catalog/UpdateProductReviewTotalsCommand.cs index 6588dff0c..377d6fa9f 100644 --- a/src/Business/Grand.Business.Core/Commands/Catalog/UpdateProductReviewTotalsCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Catalog/UpdateProductReviewTotalsCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Commands.Catalog; public class UpdateProductReviewTotalsCommand : IRequest { - public Product? Product { get; set; } + public required Product Product { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ActivatedValueForPurchasedVouchersCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ActivatedValueForPurchasedVouchersCommand.cs index 89a5f390c..415acff76 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ActivatedValueForPurchasedVouchersCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ActivatedValueForPurchasedVouchersCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class ActivatedValueForPurchasedGiftVouchersCommand : IRequest { - public Order? Order { get; set; } + public required Order Order { get; set; } public bool Activate { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddCustomerReservationCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddCustomerReservationCommand.cs index 8c9c8ace9..53e12eceb 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddCustomerReservationCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddCustomerReservationCommand.cs @@ -7,10 +7,10 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class AddCustomerReservationCommand : IRequest { - public Customer? Customer { get; set; } - public Product? Product { get; set; } + public required Customer Customer { get; set; } + public required Product Product { get; set; } public DateTime? RentalStartDate { get; set; } public DateTime? RentalEndDate { get; set; } - public ShoppingCartItem? ShoppingCartItem { get; set; } + public required ShoppingCartItem ShoppingCartItem { get; set; } public string? ReservationId { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddRequiredProductsCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddRequiredProductsCommand.cs index d3b09e3f0..9ea738baf 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddRequiredProductsCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddRequiredProductsCommand.cs @@ -8,13 +8,13 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class AddRequiredProductsCommand : IRequest { - public Customer? Customer { get; set; } + public required Customer Customer { get; set; } public ShoppingCartType ShoppingCartType { get; set; } - public Product? Product { get; set; } - public string? StoreId { get; set; } + public required Product Product { get; set; } + public required string StoreId { get; set; } /// /// Language the cart warnings are written in /// - public Language? Language { get; set; } + public required Language Language { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ApplyOrderApprovalDecisionCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ApplyOrderApprovalDecisionCommand.cs index 1cd2e6b13..4821fa340 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ApplyOrderApprovalDecisionCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ApplyOrderApprovalDecisionCommand.cs @@ -12,8 +12,8 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; /// public class ApplyOrderApprovalDecisionCommand : IRequest { - public OrderApproval? Approval { get; set; } - public Customer? DecidedBy { get; set; } + public required OrderApproval Approval { get; set; } + public required Customer DecidedBy { get; set; } public bool Approve { get; set; } public string? Comment { get; set; } public Language? Language { get; set; } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AwardLoyaltyPointsCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AwardLoyaltyPointsCommand.cs index a6236df27..371bbdd04 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AwardLoyaltyPointsCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AwardLoyaltyPointsCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class AwardLoyaltyPointsCommand : IRequest { - public Order? Order { get; set; } + public required Order Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelOrderCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelOrderCommand.cs index 347949ed9..d8e0cf70d 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelOrderCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelOrderCommand.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class CancelOrderCommand : IRequest { - public Order? Order { get; set; } + public required Order Order { get; set; } public bool NotifyCustomer { get; set; } public bool NotifyStoreOwner { get; set; } = false; } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelOrderItemCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelOrderItemCommand.cs index 36ab44398..37ccb3a0a 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelOrderItemCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelOrderItemCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class CancelOrderItemCommand : IRequest<(bool error, string message)> { - public Order? Order { get; set; } - public OrderItem? OrderItem { get; set; } + public required Order Order { get; set; } + public required OrderItem OrderItem { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelRecurringPaymentCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelRecurringPaymentCommand.cs index 8e6ab889b..b57d18bcf 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelRecurringPaymentCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CancelRecurringPaymentCommand.cs @@ -10,7 +10,7 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; /// public class CancelRecurringPaymentCommand : IRequest { - public RecurringPayment? RecurringPayment { get; set; } + public required RecurringPayment RecurringPayment { get; set; } /// /// Who cancelled it: the customer's e-mail, the staff name, or the reason diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CaptureCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CaptureCommand.cs index 860385a57..d4591eb9d 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CaptureCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CaptureCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class CaptureCommand : IRequest> { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } public string? CreatedBy { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CheckOrderStatusCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CheckOrderStatusCommand.cs index 20ed1ae03..45a19b99b 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CheckOrderStatusCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/CheckOrderStatusCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class CheckOrderStatusCommand : IRequest { - public Order? Order { get; set; } + public required Order Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DecideStoreOrderApprovalCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DecideStoreOrderApprovalCommand.cs index a986646ae..5b73af82c 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DecideStoreOrderApprovalCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DecideStoreOrderApprovalCommand.cs @@ -11,8 +11,8 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; /// public class DecideStoreOrderApprovalCommand : IRequest { - public Order? Order { get; set; } - public Customer? DecidedBy { get; set; } + public required Order Order { get; set; } + public required Customer DecidedBy { get; set; } public bool Approve { get; set; } public string? Comment { get; set; } public Language? Language { get; set; } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DeleteOrderCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DeleteOrderCommand.cs index d4e9fd939..744006224 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DeleteOrderCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DeleteOrderCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class DeleteOrderCommand : IRequest { - public Order? Order { get; set; } + public required Order Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DeleteOrderItemCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DeleteOrderItemCommand.cs index d18a89c11..aa9bc9812 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DeleteOrderItemCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/DeleteOrderItemCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class DeleteOrderItemCommand : IRequest<(bool error, string message)> { - public Order? Order { get; set; } - public OrderItem? OrderItem { get; set; } + public required Order Order { get; set; } + public required OrderItem OrderItem { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/InsertOrderItemCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/InsertOrderItemCommand.cs index 278299b48..8c89e33e6 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/InsertOrderItemCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/InsertOrderItemCommand.cs @@ -6,7 +6,7 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class InsertOrderItemCommand : IRequest { - public Order? Order { get; set; } - public OrderItem? OrderItem { get; set; } - public Product? Product { get; set; } + public required Order Order { get; set; } + public required OrderItem OrderItem { get; set; } + public required Product Product { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/MarkAsPaidCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/MarkAsPaidCommand.cs index 37f123024..693c013c0 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/MarkAsPaidCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/MarkAsPaidCommand.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class MarkAsPaidCommand : IRequest { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } public string? CreatedBy { get; set; } /// diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyPaidOfflineCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyPaidOfflineCommand.cs index 34cf91a9b..7bc309ef2 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyPaidOfflineCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyPaidOfflineCommand.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class PartiallyPaidOfflineCommand : IRequest { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } public double AmountToPaid { get; set; } public string? CreatedBy { get; set; } public string? Reference { get; set; } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyRefundCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyRefundCommand.cs index dc05d3ec2..0e7b56e90 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyRefundCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyRefundCommand.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class PartiallyRefundCommand : IRequest> { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } public double AmountToRefund { get; set; } public string? CreatedBy { get; set; } public string? Reference { get; set; } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyRefundOfflineCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyRefundOfflineCommand.cs index 5ede0f12c..522aa5477 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyRefundOfflineCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PartiallyRefundOfflineCommand.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class PartiallyRefundOfflineCommand : IRequest { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } public double AmountToRefund { get; set; } public string? CreatedBy { get; set; } public string? Reference { get; set; } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceOrderCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceOrderCommand.cs index 90d0ac717..f2023d7d6 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceOrderCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceOrderCommand.cs @@ -11,17 +11,17 @@ public class PlaceOrderCommand : IRequest /// /// Customer, store, working currency and tax display the order is calculated for (required) /// - public CalculationContext? Context { get; set; } + public required CalculationContext Context { get; set; } /// /// Language used when the customer has no published language of their own (required) /// - public Language? Language { get; set; } + public required Language Language { get; set; } /// /// Store address used for file download links in the checkout attribute description (required) /// - public DomainHost? Host { get; set; } + public required DomainHost Host { get; set; } /// /// Staff member who places the order while impersonating the customer, if any diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceRecurringCycleOrderCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceRecurringCycleOrderCommand.cs index 2b1bdda59..0f21e7b57 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceRecurringCycleOrderCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/PlaceRecurringCycleOrderCommand.cs @@ -12,10 +12,10 @@ public class PlaceRecurringCycleOrderCommand : IRequest /// /// The recurring payment the cycle belongs to /// - public RecurringPayment? RecurringPayment { get; set; } + public required RecurringPayment RecurringPayment { get; set; } /// /// The cycle the gateway reported, already claimed: its order identifier is the one the order is inserted with /// - public RecurringPaymentCycle? Cycle { get; set; } + public required RecurringPaymentCycle Cycle { get; set; } } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ProcessOrderPaidCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ProcessOrderPaidCommand.cs index d7cdaaae5..a571f7977 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ProcessOrderPaidCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ProcessOrderPaidCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class ProcessOrderPaidCommand : IRequest { - public Order? Order { get; set; } + public required Order Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReOrderCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReOrderCommand.cs index 8894c456b..f50d5da90 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReOrderCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReOrderCommand.cs @@ -6,10 +6,10 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class ReOrderCommand : IRequest> { - public Order? Order { get; set; } + public required Order Order { get; set; } /// /// Language the returned warnings are written in /// - public Language? Language { get; set; } + public required Language Language { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs index 2f6838dbd..7af8fc71c 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentCycleCommand.cs @@ -12,7 +12,7 @@ public class RecordRecurringPaymentCycleCommand : IRequest /// /// The recurring payment the provider was given as gateway metadata /// - public string? RecurringPaymentId { get; set; } + public required string RecurringPaymentId { get; set; } /// /// The provider's reference of the subscription diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs index 83c8bb1e0..565d7286c 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentEndedCommand.cs @@ -8,7 +8,7 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; /// public class RecordRecurringPaymentEndedCommand : IRequest { - public string? RecurringPaymentId { get; set; } + public required string RecurringPaymentId { get; set; } /// /// The provider's reference of what ended (for example the subscription id), so the end of another diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs index fb8813882..074d31ee2 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentFailureCommand.cs @@ -8,7 +8,7 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; /// public class RecordRecurringPaymentFailureCommand : IRequest { - public string? RecurringPaymentId { get; set; } + public required string RecurringPaymentId { get; set; } /// /// The provider's reference of the recurring payment (for example the subscription id), used to stop the diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentReferenceCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentReferenceCommand.cs index 6f53bb811..3a188d2d8 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentReferenceCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RecordRecurringPaymentReferenceCommand.cs @@ -12,7 +12,7 @@ public class RecordRecurringPaymentReferenceCommand : IRequest /// /// The recurring payment the provider was given as gateway metadata /// - public string? RecurringPaymentId { get; set; } + public required string RecurringPaymentId { get; set; } /// /// The provider's reference of the recurring payment (for example the subscription id) diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReduceLoyaltyPointsCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReduceLoyaltyPointsCommand.cs index faa88dbbe..619639652 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReduceLoyaltyPointsCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReduceLoyaltyPointsCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class ReduceLoyaltyPointsCommand : IRequest { - public Order? Order { get; set; } + public required Order Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RefundCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RefundCommand.cs index 0bebb1c38..589e4ac0d 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RefundCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RefundCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class RefundCommand : IRequest> { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } public string? CreatedBy { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RefundOfflineCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RefundOfflineCommand.cs index 2b7dd5688..0d60df474 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RefundOfflineCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/RefundOfflineCommand.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class RefundOfflineCommand : IRequest { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } public string? CreatedBy { get; set; } public string? Reference { get; set; } public string? Note { get; set; } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReturnBackRedeemedLoyaltyPointsCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReturnBackRedeemedLoyaltyPointsCommand.cs index 987eba2e0..03e667ce1 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReturnBackRedeemedLoyaltyPointsCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ReturnBackRedeemedLoyaltyPointsCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class ReturnBackRedeemedLoyaltyPointsCommand : IRequest { - public Order? Order { get; set; } + public required Order Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/SetOrderStatusCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/SetOrderStatusCommand.cs index 5bacce5a3..2a3c28a2d 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/SetOrderStatusCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/SetOrderStatusCommand.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class SetOrderStatusCommand : IRequest { - public Order? Order { get; set; } + public required Order Order { get; set; } public OrderStatusSystem Os { get; set; } public bool NotifyCustomer { get; set; } public bool NotifyStoreOwner { get; set; } diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/UpdateOrderItemCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/UpdateOrderItemCommand.cs index acdb5fe00..2b0ba0f53 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/UpdateOrderItemCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/UpdateOrderItemCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class UpdateOrderItemCommand : IRequest { - public Order? Order { get; set; } - public OrderItem? OrderItem { get; set; } + public required Order Order { get; set; } + public required OrderItem OrderItem { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ValidateMinShoppingCartSubtotalAmountCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ValidateMinShoppingCartSubtotalAmountCommand.cs index fe2d361d2..11ff7b2cb 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ValidateMinShoppingCartSubtotalAmountCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/ValidateMinShoppingCartSubtotalAmountCommand.cs @@ -6,6 +6,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class ValidateMinShoppingCartSubtotalAmountCommand : IRequest { - public IList? Cart { get; set; } - public CalculationContext? Context { get; set; } + public required IList Cart { get; set; } + public required CalculationContext Context { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/VoidCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/VoidCommand.cs index c01c3a6f8..be406265c 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/VoidCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/VoidCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class VoidCommand : IRequest> { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } public string? CreatedBy { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/VoidOfflineCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/VoidOfflineCommand.cs index f869532d2..dfa92fa1d 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/VoidOfflineCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/VoidOfflineCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Commands.Checkout.Orders; public class VoidOfflineCommand : IRequest { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } public string? CreatedBy { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Shipping/DeliveryCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Shipping/DeliveryCommand.cs index 48a823b54..54c333e5d 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Shipping/DeliveryCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Shipping/DeliveryCommand.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Commands.Checkout.Shipping; public class DeliveryCommand : IRequest { - public Shipment? Shipment { get; set; } + public required Shipment Shipment { get; set; } public bool NotifyCustomer { get; set; } /// When a shipment is marked as delivered with a date of its own; null stamps now. diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Shipping/ShipCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Shipping/ShipCommand.cs index fde5fc274..c26c0e964 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Shipping/ShipCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Shipping/ShipCommand.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Commands.Checkout.Shipping; public class ShipCommand : IRequest { - public Shipment? Shipment { get; set; } + public required Shipment Shipment { get; set; } public bool NotifyCustomer { get; set; } /// When a shipment is marked as shipped with a date of its own; null stamps now. diff --git a/src/Business/Grand.Business.Core/Commands/Customers/ActiveVendorCommand.cs b/src/Business/Grand.Business.Core/Commands/Customers/ActiveVendorCommand.cs index e96d2a376..71155bf9b 100644 --- a/src/Business/Grand.Business.Core/Commands/Customers/ActiveVendorCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Customers/ActiveVendorCommand.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Commands.Customers; public class ActiveVendorCommand : IRequest { - public Vendor? Vendor { get; set; } + public required Vendor Vendor { get; set; } public bool Active { get; set; } public IList CustomerIds { get; set; } = new List(); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Commands/Messages/Common/OrderNotificationCommand.cs b/src/Business/Grand.Business.Core/Commands/Messages/Common/OrderNotificationCommand.cs index 984ced3ce..427ca0fd5 100644 --- a/src/Business/Grand.Business.Core/Commands/Messages/Common/OrderNotificationCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Messages/Common/OrderNotificationCommand.cs @@ -7,12 +7,12 @@ namespace Grand.Business.Core.Commands.Messages.Common; public class OrderNotificationCommand : IRequest { - public Order? Order { get; set; } + public required Order Order { get; set; } /// /// Customer the order was placed for /// - public Customer? Customer { get; set; } + public required Customer Customer { get; set; } /// /// Staff member who placed the order while impersonating the customer, if any diff --git a/src/Business/Grand.Business.Core/Commands/System/Common/GetSitemapXmlCommand.cs b/src/Business/Grand.Business.Core/Commands/System/Common/GetSitemapXmlCommand.cs index c81b2b729..8a90dd62b 100644 --- a/src/Business/Grand.Business.Core/Commands/System/Common/GetSitemapXmlCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/System/Common/GetSitemapXmlCommand.cs @@ -6,6 +6,6 @@ namespace Grand.Business.Core.Commands.System.Common; public class GetSitemapXmlCommand : IRequest { - public Store? Store { get; set; } - public Language? Language { get; set; } + public required Store Store { get; set; } + public required Language Language { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetPersonalizedProductsQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetPersonalizedProductsQuery.cs index 857f5b757..78305d31e 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetPersonalizedProductsQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetPersonalizedProductsQuery.cs @@ -7,6 +7,6 @@ namespace Grand.Business.Core.Queries.Catalog; public class GetPersonalizedProductsQuery : IRequest> { public int ProductsNumber { get; set; } - public Customer? Customer { get; set; } - public string? StoreId { get; set; } + public required Customer Customer { get; set; } + public required string StoreId { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetPriceByCustomerProductQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetPriceByCustomerProductQuery.cs index b1b635c8a..19a38687b 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetPriceByCustomerProductQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetPriceByCustomerProductQuery.cs @@ -4,6 +4,6 @@ namespace Grand.Business.Core.Queries.Catalog; public class GetPriceByCustomerProductQuery : IRequest { - public string? CustomerId { get; set; } - public string? ProductId { get; set; } + public required string CustomerId { get; set; } + public required string ProductId { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetProductArchByIdQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetProductArchByIdQuery.cs index 4b289e887..a5d9a52a3 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetProductArchByIdQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetProductArchByIdQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Catalog; public class GetProductArchByIdQuery : IRequest { - public string? Id { get; set; } + public required string Id { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetRecommendedProductsQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetRecommendedProductsQuery.cs index 4ce1d47ce..3bc54c873 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetRecommendedProductsQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetRecommendedProductsQuery.cs @@ -6,6 +6,6 @@ namespace Grand.Business.Core.Queries.Catalog; public class GetRecommendedProductsQuery : IRequest> { - public string? StoreId { get; set; } - public Customer? Customer { get; set; } + public required string StoreId { get; set; } + public required Customer Customer { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetSearchProductsQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetSearchProductsQuery.cs index 0fe85706c..6e3815017 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetSearchProductsQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetSearchProductsQuery.cs @@ -8,7 +8,7 @@ namespace Grand.Business.Core.Queries.Catalog; public class GetSearchProductsQuery : IRequest<(IPagedList products, IList filterableSpecificationAttributeOptionIds)> { - public Customer? Customer { get; set; } + public required Customer Customer { get; set; } /// /// Customer groups the ACL filter uses instead of the groups of ; diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetShoppingCartItemsSubTotalQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetShoppingCartItemsSubTotalQuery.cs index 3c082a92c..bb828df69 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetShoppingCartItemsSubTotalQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetShoppingCartItemsSubTotalQuery.cs @@ -13,7 +13,7 @@ namespace Grand.Business.Core.Queries.Catalog; /// public class GetShoppingCartItemsSubTotalQuery : IRequest { - public Customer? Customer { get; set; } - public Store? Store { get; set; } + public required Customer Customer { get; set; } + public required Store Store { get; set; } public IList Items { get; set; } = new List(); } diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetSitemapProductsQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetSitemapProductsQuery.cs index b53d4f553..7c3f48238 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetSitemapProductsQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetSitemapProductsQuery.cs @@ -10,7 +10,7 @@ public class GetSitemapProductsQuery : IRequest> { public string? StoreId { get; set; } public IList CustomerGroupIds { get; set; } = []; - public string? LanguageId { get; set; } + public required string LanguageId { get; set; } /// /// Id of the last product of the previous batch; null for the first batch diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetSuggestedProductsQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetSuggestedProductsQuery.cs index 26734f9e4..95c37024a 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetSuggestedProductsQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetSuggestedProductsQuery.cs @@ -7,6 +7,6 @@ namespace Grand.Business.Core.Queries.Catalog; public class GetSuggestedProductsQuery : IRequest> { public int ProductsNumber { get; set; } - public Customer? Customer { get; set; } - public string? StoreId { get; set; } + public required Customer Customer { get; set; } + public required string StoreId { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanCancelOrderQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanCancelOrderQuery.cs index 799aabc26..c6cdac778 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanCancelOrderQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanCancelOrderQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanCancelOrderQuery : IRequest { - public Order? Order { get; set; } + public required Order Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanCaptureQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanCaptureQuery.cs index 2c914d9a1..673b0c7ad 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanCaptureQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanCaptureQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanCaptureQuery : IRequest { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanDeletePaymentTransactionQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanDeletePaymentTransactionQuery.cs index a1607ec94..be40de749 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanDeletePaymentTransactionQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanDeletePaymentTransactionQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanDeletePaymentTransactionQuery : IRequest { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } } diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanMarkPaymentTransactionAsPaidQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanMarkPaymentTransactionAsPaidQuery.cs index 68ab90983..8c37b6357 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanMarkPaymentTransactionAsPaidQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanMarkPaymentTransactionAsPaidQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanMarkPaymentTransactionAsPaidQuery : IRequest { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyPaidOfflineQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyPaidOfflineQuery.cs index 9411dc6d4..0f0fd0283 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyPaidOfflineQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyPaidOfflineQuery.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanPartiallyPaidOfflineQuery : IRequest { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } public double AmountToPaid { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyRefundOfflineQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyRefundOfflineQuery.cs index 8c890e615..9d515c04f 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyRefundOfflineQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyRefundOfflineQuery.cs @@ -5,6 +5,6 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanPartiallyRefundOfflineQuery : IRequest { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } public double AmountToRefund { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyRefundQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyRefundQuery.cs index f12d9528e..654e777b7 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyRefundQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanPartiallyRefundQuery.cs @@ -6,5 +6,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanPartiallyRefundQuery : IRequest { public double AmountToRefund { get; set; } - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanRefundOfflineQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanRefundOfflineQuery.cs index 9ab5816a0..e76103ea2 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanRefundOfflineQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanRefundOfflineQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanRefundOfflineQuery : IRequest { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanRefundQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanRefundQuery.cs index dd30fac49..196d89240 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanRefundQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanRefundQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanRefundQuery : IRequest { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanVoidOfflineQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanVoidOfflineQuery.cs index 62a458cc1..6826bbaf8 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanVoidOfflineQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanVoidOfflineQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanVoidOfflineQuery : IRequest { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanVoidQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanVoidQuery.cs index 90485c4ba..297a3cf9e 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanVoidQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/CanVoidQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class CanVoidQuery : IRequest { - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPickupPointById.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPickupPointById.cs index f904e64a9..847de2b2c 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPickupPointById.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPickupPointById.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class GetPickupPointById : IRequest { - public string? Id { get; set; } + public required string Id { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetReturnableQuantitiesQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetReturnableQuantitiesQuery.cs index 327b83100..1503e35c9 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetReturnableQuantitiesQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetReturnableQuantitiesQuery.cs @@ -9,7 +9,7 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; /// public class GetReturnableQuantitiesQuery : IRequest> { - public Order? Order { get; set; } + public required Order Order { get; set; } /// /// For staff: only what was delivered less what the other returns take. The return period and products marked diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetVendorsInOrderQuery.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetVendorsInOrderQuery.cs index 9df1c26bf..4219c2793 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetVendorsInOrderQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetVendorsInOrderQuery.cs @@ -6,5 +6,5 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; public class GetVendorsInOrderQuery : IRequest> { - public Order? Order { get; set; } + public required Order Order { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Messages/GetBidsByProductIdQuery.cs b/src/Business/Grand.Business.Core/Queries/Messages/GetBidsByProductIdQuery.cs index 27837677e..065f67308 100644 --- a/src/Business/Grand.Business.Core/Queries/Messages/GetBidsByProductIdQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Messages/GetBidsByProductIdQuery.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Queries.Messages; public class GetBidsByProductIdQuery : IRequest> { - public string? ProductId { get; set; } + public required string ProductId { get; set; } } \ No newline at end of file diff --git a/src/Tests/Grand.Business.Catalog.Tests/Handlers/UpdateProductReviewTotalsCommandHandlerTest.cs b/src/Tests/Grand.Business.Catalog.Tests/Handlers/UpdateProductReviewTotalsCommandHandlerTest.cs index 2654784b2..5b2bf74d0 100644 --- a/src/Tests/Grand.Business.Catalog.Tests/Handlers/UpdateProductReviewTotalsCommandHandlerTest.cs +++ b/src/Tests/Grand.Business.Catalog.Tests/Handlers/UpdateProductReviewTotalsCommandHandlerTest.cs @@ -60,7 +60,8 @@ public void Init() [TestMethod] public async Task InsertProduct_NullArgument_ThrowException() { - var request = new UpdateProductReviewTotalsCommand(); + //null! only here: the handler's guard against a caller outside nullable checking is what is tested + var request = new UpdateProductReviewTotalsCommand { Product = null! }; await Assert.ThrowsExactlyAsync( async () => await _updateProductReviewTotalsCommandHandler.Handle(request, default)); diff --git a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetPersonalizedProductsQueryHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetPersonalizedProductsQueryHandlerTests.cs index b20830495..ccb9cd221 100644 --- a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetPersonalizedProductsQueryHandlerTests.cs +++ b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetPersonalizedProductsQueryHandlerTests.cs @@ -35,7 +35,8 @@ public void Init() [TestMethod] public async Task HandleTest() { - await handler.Handle(new GetPersonalizedProductsQuery { Customer = new Customer() }, CancellationToken.None); + await handler.Handle(new GetPersonalizedProductsQuery { Customer = new Customer(), StoreId = "" }, + CancellationToken.None); _casheManagerMock.Verify(c => c.GetAsync(It.IsAny(), It.IsAny>>>()), Times.Once); } @@ -44,7 +45,8 @@ public async Task HandleTest() public async Task Handle_WithoutCustomer_ThrowsBeforeCaching() { await Assert.ThrowsExactlyAsync(() => - handler.Handle(new GetPersonalizedProductsQuery { ProductsNumber = 1 }, + //null! only here: the handler's guard against a caller outside nullable checking is what is tested + handler.Handle(new GetPersonalizedProductsQuery { ProductsNumber = 1, Customer = null!, StoreId = "" }, CancellationToken.None)); _casheManagerMock.Verify(c => c.GetAsync(It.IsAny(), It.IsAny>>>()), Times.Never); diff --git a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetPriceByCustomerProductQueryHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetPriceByCustomerProductQueryHandlerTests.cs index 2273ce09f..a65668163 100644 --- a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetPriceByCustomerProductQueryHandlerTests.cs +++ b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetPriceByCustomerProductQueryHandlerTests.cs @@ -30,7 +30,8 @@ public void Init() [TestMethod] public async Task HandleTest() { - await handler.Handle(new GetPriceByCustomerProductQuery(), CancellationToken.None); + await handler.Handle(new GetPriceByCustomerProductQuery { CustomerId = "customer", ProductId = "product" }, + CancellationToken.None); _casheManagerMock.Verify(c => c.GetAsync(It.IsAny(), It.IsAny>>()), Times.Once); } diff --git a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetProductArchByIdQueryHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetProductArchByIdQueryHandlerTests.cs index 61f8bb725..0f2ce745c 100644 --- a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetProductArchByIdQueryHandlerTests.cs +++ b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetProductArchByIdQueryHandlerTests.cs @@ -26,7 +26,7 @@ public void Init() public async Task HandleTest() { //Act - var result = await handler.Handle(new GetProductArchByIdQuery(), CancellationToken.None); + var result = await handler.Handle(new GetProductArchByIdQuery { Id = "missing" }, CancellationToken.None); //Assert Assert.IsNull(result); } diff --git a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetRecommendedProductsQueryHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetRecommendedProductsQueryHandlerTests.cs index 45e2ac3e7..adf9bee7e 100644 --- a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetRecommendedProductsQueryHandlerTests.cs +++ b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetRecommendedProductsQueryHandlerTests.cs @@ -48,7 +48,8 @@ public async Task HandleTest() public async Task Handle_WithoutCustomer_ThrowsBeforeCaching() { await Assert.ThrowsExactlyAsync(() => - handler.Handle(new GetRecommendedProductsQuery { StoreId = "1" }, + //null! only here: the handler's guard against a caller outside nullable checking is what is tested + handler.Handle(new GetRecommendedProductsQuery { StoreId = "1", Customer = null! }, CancellationToken.None)); _casheManagerMock.Verify(c => c.GetAsync(It.IsAny(), It.IsAny>>>()), Times.Never); diff --git a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSearchProductsQueryHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSearchProductsQueryHandlerTests.cs index 832227f3c..59fcd217f 100644 --- a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSearchProductsQueryHandlerTests.cs +++ b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSearchProductsQueryHandlerTests.cs @@ -81,6 +81,7 @@ await _repository.InsertAsync(new Product { CustomerGroups = ["admins-group"] }); var searchProductsQuery = new GetSearchProductsQuery { + Customer = new Customer(), CustomerGroupIds = ["guests-group"] }; //Act @@ -98,7 +99,7 @@ await _repository.InsertAsync(new Product { Id = "admins", Published = true, VisibleIndividually = true, LimitedToGroups = true, CustomerGroups = ["admins-group"] }); - var searchProductsQuery = new GetSearchProductsQuery { ShowHidden = true }; + var searchProductsQuery = new GetSearchProductsQuery { Customer = new Customer(), ShowHidden = true }; //Act var result = await handler.Handle(searchProductsQuery, CancellationToken.None); //Assert diff --git a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSitemapProductsQueryHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSitemapProductsQueryHandlerTests.cs index cbc754aa7..dc418ab1a 100644 --- a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSitemapProductsQueryHandlerTests.cs +++ b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSitemapProductsQueryHandlerTests.cs @@ -136,7 +136,7 @@ await _repository.InsertAsync(new Product { }); //Act - var result = await _handler.Handle(new GetSitemapProductsQuery { StoreId = StoreId, CustomerGroupIds = null }, + var result = await _handler.Handle(new GetSitemapProductsQuery { StoreId = StoreId, LanguageId = "", CustomerGroupIds = null }, CancellationToken.None); //Assert @@ -154,7 +154,7 @@ public async Task Handle_LiteDB_ReturnsTheRestOfTheCatalogInOneBatch() //Act var result = await handler.Handle(new GetSitemapProductsQuery { - StoreId = StoreId, CustomerGroupIds = [GuestsGroupId], AfterId = "a", PageSize = 2 + StoreId = StoreId, LanguageId = "", CustomerGroupIds = [GuestsGroupId], AfterId = "a", PageSize = 2 }, CancellationToken.None); //Assert diff --git a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSuggestedProductsQueryHandlerTests.cs b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSuggestedProductsQueryHandlerTests.cs index ccd9094c9..02561ca2c 100644 --- a/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSuggestedProductsQueryHandlerTests.cs +++ b/src/Tests/Grand.Business.Catalog.Tests/Queries/Handlers/GetSuggestedProductsQueryHandlerTests.cs @@ -37,7 +37,8 @@ public async Task HandleTest() { var suggestedProductsQuery = new GetSuggestedProductsQuery { ProductsNumber = 10, - Customer = new Customer() + Customer = new Customer(), + StoreId = "" }; await handler.Handle(suggestedProductsQuery, CancellationToken.None); _casheManagerMock.Verify(c => c.GetAsync(It.IsAny(), It.IsAny>>>()), @@ -48,7 +49,8 @@ public async Task HandleTest() public async Task Handle_WithoutCustomer_ThrowsBeforeCaching() { await Assert.ThrowsExactlyAsync(() => - handler.Handle(new GetSuggestedProductsQuery { ProductsNumber = 1 }, + //null! only here: the handler's guard against a caller outside nullable checking is what is tested + handler.Handle(new GetSuggestedProductsQuery { ProductsNumber = 1, Customer = null!, StoreId = "" }, CancellationToken.None)); _casheManagerMock.Verify(c => c.GetAsync(It.IsAny(), It.IsAny>>>()), Times.Never); diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/AddRequiredProductsCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/AddRequiredProductsCommandHandlerTests.cs index 6610c123d..b841a13a7 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/AddRequiredProductsCommandHandlerTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/AddRequiredProductsCommandHandlerTests.cs @@ -35,15 +35,15 @@ public async Task HandleTest() { //Arrange var command = new AddRequiredProductsCommand { - Customer = new Customer() + Customer = new Customer(), + Product = new Product + { Id = "1", RequireOtherProducts = true, RequiredProductIds = "2,3", AutoAddRequiredProducts = true }, + ShoppingCartType = ShoppingCartType.ShoppingCart, + StoreId = "", + Language = new Language { Id = "lang1" } }; command.Customer.ShoppingCartItems.Add(new ShoppingCartItem { ProductId = "1", ShoppingCartTypeId = ShoppingCartType.ShoppingCart, StoreId = "" }); - command.Product = new Product - { Id = "1", RequireOtherProducts = true, RequiredProductIds = "2,3", AutoAddRequiredProducts = true }; - command.ShoppingCartType = ShoppingCartType.ShoppingCart; - command.StoreId = ""; - command.Language = new Language { Id = "lang1" }; _productServiceMock.Setup(a => a.GetProductById("2", false)).Returns(() => Task.FromResult(new Product { Id = "2", Published = true, Price = 10 })); diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerTests.cs index 1f4640a23..884ba8984 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerTests.cs @@ -71,7 +71,9 @@ public void Init() public async Task Handle_WithoutContext_ReturnsError() { //Act - var result = await _handler.Handle(new PlaceOrderCommand(), CancellationToken.None); + //null! only here: the handler's guard against a caller outside nullable checking is what is tested + var result = await _handler.Handle(new PlaceOrderCommand { Context = null!, Language = null!, Host = null! }, + CancellationToken.None); //Assert Assert.IsNotEmpty(result.Errors); @@ -84,7 +86,9 @@ public async Task Handle_WithoutLanguage_ReturnsError() //Arrange var command = new PlaceOrderCommand { Context = new CalculationContext(new Customer(), new Store(), new Currency(), TaxDisplayType.IncludingTax), - Host = new DomainHost { Url = "https://shop.example/" } + Host = new DomainHost { Url = "https://shop.example/" }, + //null! only here: the handler's guard against a caller outside nullable checking is what is tested + Language = null! }; //Act @@ -101,7 +105,9 @@ public async Task Handle_WithoutHost_ReturnsError() //Arrange var command = new PlaceOrderCommand { Context = new CalculationContext(new Customer(), new Store(), new Currency(), TaxDisplayType.IncludingTax), - Language = new Language { Id = "pl" } + Language = new Language { Id = "pl" }, + //null! only here: the handler's guard against a caller outside nullable checking is what is tested + Host = null! }; //Act From b6c431eab4ec34c3c7518dffecc7ecbc5346d833 Mon Sep 17 00:00:00 2001 From: support Date: Wed, 25 Nov 2026 14:23:54 +0100 Subject: [PATCH 09/30] Enable nullable reference types in the Business service projects All nine Grand.Business.* projects build with no nullable warnings. - Signatures follow what the code does: a parameter becomes nullable only where the body already copes with null (IsNullOrEmpty, ==, ?.), e.g. store, warehouse and language ids, the price formatter's currency. - Inputs every caller sets are required: PlaceOrderContainer, CheckoutClaim, ReturnShippingRequest/Option, CampaignRecipient, RefundPaymentRequest, InsertContactUsCommand and others. - A handler that returns null declares it in its request (IRequest); IRequestHandler.Handle keeps Task. - Where a lookup could only fail on a misconfigured or deleted record, an explicit GrandException replaces the NullReferenceException that would have followed (primary currency, store, language, e-mail account, the products of a cart being ordered). - A deleted product, tag or slug no longer breaks stock adjustment, tag counts or blog post deletion; it is skipped. - The country report keeps grouping orders without a billing address under no country; the Mongo driver translates the guard to $cond. --- .../Grand.Business.Authentication.csproj | 3 + .../Services/ExternalAuthenticationService.cs | 20 ++- .../JwtBearerAuthenticationService.cs | 6 +- .../JwtBearerCustomerAuthenticationService.cs | 6 +- .../Services/OidcCustomerResolver.cs | 29 +++-- .../Services/OidcLinkService.cs | 2 +- .../Services/OidcSessionService.cs | 9 +- .../Services/OidcSignInModeCheck.cs | 2 +- .../Services/OidcSsoSignInPolicy.cs | 4 +- .../Services/OidcTokenRevocationService.cs | 2 +- .../Services/RefreshTokenService.cs | 6 +- .../Services/Scim/ScimGroupService.cs | 17 ++- .../Services/Scim/ScimProtection.cs | 2 +- .../Services/Scim/ScimRoleSync.cs | 10 +- .../Services/Scim/ScimRoles.cs | 18 ++- .../Services/Scim/ScimUserService.cs | 29 ++--- .../TwoFactorAuthenticationService.cs | 17 +-- .../Handlers/WarehouseDeletedEventHandler.cs | 2 +- .../Grand.Business.Catalog.csproj | 3 + .../GetDiscountAmountProviderHandler.cs | 2 +- .../GetProductArchByIdQueryHandler.cs | 4 +- .../Handlers/GetSearchProductsQueryHandler.cs | 25 ++-- ...etShoppingCartItemsSubTotalQueryHandler.cs | 4 +- .../Handlers/GetVendorByIdQueryHandler.cs | 6 +- .../Services/Brands/BrandLayoutService.cs | 2 +- .../Services/Brands/BrandService.cs | 2 +- .../Categories/CategoryLayoutService.cs | 2 +- .../Services/Categories/CategoryService.cs | 12 +- .../Collections/CollectionLayoutService.cs | 2 +- .../Services/Collections/CollectionService.cs | 2 +- .../Services/Directory/MeasureService.cs | 18 +-- .../Services/Directory/SearchTermService.cs | 4 +- .../Discounts/DiscountProviderLoader.cs | 4 +- .../Services/Discounts/DiscountService.cs | 26 ++-- .../Discounts/DiscountValidationService.cs | 9 +- .../ExportImport/BrandImportDataObject.cs | 4 +- .../ExportImport/BrandSchemaProperty.cs | 2 +- .../ExportImport/CategoryImportDataObject.cs | 4 +- .../ExportImport/CategorySchemaProperty.cs | 2 +- .../CollectionImportDataObject.cs | 4 +- .../ExportImport/CollectionSchemaProperty.cs | 2 +- .../Services/ExportImport/DownloadUrl.cs | 6 +- .../Services/ExportImport/ExportPictures.cs | 8 +- .../Services/ExportImport/ImportHtmlGuard.cs | 6 +- .../Services/ExportImport/ImportPictures.cs | 10 +- .../Services/ExportImport/ImportRows.cs | 8 +- .../ProductAttributeImportDataObject.cs | 12 +- .../ExportImport/ProductImportDataObject.cs | 18 +-- .../ExportImport/ProductSchemaProperty.cs | 4 +- .../ProductVariantImportDataObject.cs | 20 +-- .../SpecificationAttributeImportDataObject.cs | 12 +- .../Inventory/InventoryDocumentService.cs | 76 ++++++----- .../Inventory/InventoryJournalService.cs | 4 +- .../Services/Inventory/ProductUnitService.cs | 46 ++++--- .../Services/Inventory/StockLedger.cs | 37 +++--- .../Services/Inventory/StockSideEffects.cs | 2 +- .../Services/Inventory/StockUnits.cs | 91 +++++++------ .../Services/Prices/PriceFormatter.cs | 4 +- .../Services/Prices/PricingService.cs | 6 +- .../Services/Products/AuctionService.cs | 8 +- .../Products/CustomerGroupProductService.cs | 4 +- .../Products/InventoryManageService.cs | 31 ++--- .../Products/OutOfStockSubscriptionService.cs | 4 +- .../Products/ProductAttributeFormatter.cs | 6 +- .../Products/ProductAttributeService.cs | 6 +- .../Services/Products/ProductCourseService.cs | 4 +- .../Services/Products/ProductLayoutService.cs | 2 +- .../Products/ProductReservationService.cs | 4 +- .../Services/Products/ProductReviewService.cs | 6 +- .../Services/Products/ProductService.cs | 39 +++--- .../Services/Products/ProductTagService.cs | 19 +-- .../Products/SpecificationAttributeService.cs | 14 +- .../Services/Products/StockQuantityService.cs | 14 +- .../Services/Tax/TaxCategoryService.cs | 2 +- .../Services/Tax/TaxService.cs | 25 ++-- .../Services/Tax/VatService.cs | 6 +- ...pplyOrderApprovalDecisionCommandHandler.cs | 8 +- .../AwardLoyaltyPointsCommandHandler.cs | 6 +- .../Orders/CancelOrderCommandHandler.cs | 3 + .../Handlers/Orders/CaptureCommandHandler.cs | 5 +- .../Orders/OrderNotificationCommandHandler.cs | 2 +- .../Orders/OrderStatusCommandHandler.cs | 2 +- .../Orders/PartiallyRefundCommandHandler.cs | 8 +- .../Orders/PlaceOrderCommandHandler.cs | 56 ++++---- .../Orders/ProcessOrderPaidCommandHandler.cs | 2 +- .../Handlers/Orders/ReOrderCommandHandler.cs | 4 +- ...cordRecurringPaymentCycleCommandHandler.cs | 29 +++-- ...cordRecurringPaymentEndedCommandHandler.cs | 4 +- ...rdRecurringPaymentFailureCommandHandler.cs | 13 +- ...RecurringPaymentReferenceCommandHandler.cs | 15 ++- .../Orders/RecurringPaymentGateway.cs | 7 +- .../ReduceLoyaltyPointsCommandHandler.cs | 6 +- .../Handlers/Orders/RefundCommandHandler.cs | 5 +- ...BackRedeemedLoyaltyPointsCommandHandler.cs | 2 +- .../Orders/UpdateOrderItemCommandHandler.cs | 8 +- .../Handlers/Orders/VoidCommandHandler.cs | 2 +- .../Shipping/DeliveryCommandHandler.cs | 2 +- .../Handlers/Shipping/ShipCommandHandler.cs | 2 +- .../MerchandiseReturnQuantityEventHandler.cs | 2 +- ...chandiseReturnReceiptPostedEventHandler.cs | 2 +- .../Orders/OrderPlacedOrderApprovalHandler.cs | 19 +-- .../Orders/RecurringPaymentMessagesHandler.cs | 4 +- .../Extensions/OrderItemWarehouse.cs | 2 +- .../Extensions/RecurringCycleOrder.cs | 12 +- .../Grand.Business.Checkout.csproj | 3 + .../Orders/GetPickupPointByIdQueryHandler.cs | 4 +- .../GetRecurringPaymentsQueryHandler.cs | 4 +- .../Orders/GetReturnableOrdersQueryHandler.cs | 9 +- .../Handlers/Orders/ReturnableQuantities.cs | 2 +- .../CheckoutAttributeFormatter.cs | 2 +- .../CheckoutAttributeParser.cs | 4 +- .../CheckoutAttributeService.cs | 4 +- .../GiftVouchers/GiftVoucherService.cs | 8 +- .../Services/Orders/CheckoutClaimService.cs | 9 +- .../Services/Orders/LoyaltyPointsService.cs | 14 +- .../Orders/MerchandiseReturnLabelService.cs | 63 +++++---- .../Orders/MerchandiseReturnRefundService.cs | 45 ++++--- .../Orders/MerchandiseReturnService.cs | 14 +- .../MerchandiseReturnWorkflowService.cs | 39 +++--- .../Orders/OrderApprovalLimitRuleProvider.cs | 4 +- .../Services/Orders/OrderApprovalService.cs | 8 +- .../Services/Orders/OrderPlacementService.cs | 2 +- .../Services/Orders/OrderReportService.cs | 33 ++--- .../Services/Orders/OrderService.cs | 24 ++-- .../Services/Orders/OrderStatusService.cs | 4 +- .../Services/Orders/OrderTagService.cs | 10 +- .../Orders/RecurringPaymentRuleProvider.cs | 2 +- .../Orders/RecurringPaymentService.cs | 39 +++--- .../Services/Orders/ShoppingCartService.cs | 42 +++--- .../Orders/ShoppingCartShippingService.cs | 27 ++-- .../Orders/ShoppingCartSubTotalService.cs | 45 +++---- .../Services/Orders/ShoppingCartTaxService.cs | 8 +- .../Services/Orders/ShoppingCartValidator.cs | 4 +- .../Services/Payments/PaymentService.cs | 19 +-- .../PaymentTransactionHistoryService.cs | 10 +- .../Payments/PaymentTransactionService.cs | 4 +- .../Services/Shipping/DeliveryDateService.cs | 2 +- .../Services/Shipping/PickupPointService.cs | 4 +- .../ReturnProviders/InStoreReturnProvider.cs | 2 +- .../ReturnProviders/ReturnProviderTexts.cs | 18 +-- .../SendYourselfReturnProvider.cs | 2 +- .../Shipping/ReturnShippingService.cs | 24 ++-- .../Services/Shipping/ShipmentService.cs | 10 +- .../Shipping/ShippingMethodService.cs | 4 +- .../Services/Shipping/ShippingService.cs | 12 +- .../Shipping/WarehouseLocationService.cs | 4 +- .../Services/Shipping/WarehouseService.cs | 2 +- .../ShoppingCartAuctionValidator.cs | 2 +- ...ShoppingCartCheckoutAttributesValidator.cs | 2 +- .../ShoppingCartCommonWarningsValidator.cs | 2 +- .../ShoppingCartItemAttributeValidator.cs | 6 +- .../ShoppingCartRequiredProductValidator.cs | 2 +- .../Events/BlogPostDeletedEventHandler.cs | 4 +- .../Grand.Business.Cms.csproj | 3 + .../Services/BlogService.cs | 18 +-- .../Services/KnowledgebaseService.cs | 20 +-- .../Services/NewsService.cs | 2 +- .../Services/PageLayoutService.cs | 2 +- .../Services/PageService.cs | 8 +- .../Services/RobotsTxtService.cs | 2 +- .../Services/WidgetService.cs | 8 +- .../Grand.Business.Common.csproj | 3 + .../Addresses/AddressAttributeParser.cs | 12 +- .../Addresses/AddressAttributeService.cs | 5 +- .../Services/Audit/AuditService.cs | 6 +- .../Services/Configuration/SettingService.cs | 25 ++-- .../Services/Directory/CountryService.cs | 13 +- .../Services/Directory/CurrencyService.cs | 21 +-- .../Services/Directory/DateTimeService.cs | 2 +- .../Services/Directory/ExchangeRateService.cs | 4 +- .../Services/Directory/GroupService.cs | 6 +- .../Services/Directory/HistoryService.cs | 6 +- .../ExportImport/CountryImportDataObject.cs | 5 +- .../ExportImport/ExcelExportProvider.cs | 8 +- .../Services/Localization/LanguageService.cs | 4 +- .../Localization/PluginTranslateResource.cs | 2 +- .../Localization/TranslationService.cs | 26 ++-- .../Services/Pdf/PdfComposer.cs | 54 ++++---- .../Services/Pdf/PdfHtmlText.cs | 2 +- .../Services/Pdf/PdfService.cs | 31 +++-- .../Services/Security/AclService.cs | 2 +- .../Services/Security/EncryptionService.cs | 19 +-- .../Services/Security/PermissionService.cs | 8 +- .../Services/Seo/SeNameService.cs | 12 +- .../Services/Seo/SlugService.cs | 16 +-- .../Services/Stores/StoreService.cs | 2 +- .../Utilities/PowerExcelExtensions.cs | 12 +- .../Utilities/PowerExcelMapper.cs | 28 ++-- .../Orders/AddRequiredProductsCommand.cs | 2 +- .../Messages/Common/InsertContactUsCommand.cs | 6 +- .../Common/OrderNotificationCommand.cs | 2 +- .../Customers/CustomerRegisteredEvent.cs | 4 +- .../Extensions/LanguageServiceExtensions.cs | 2 +- .../MerchandiseReturnShippingExtensions.cs | 4 +- .../Extensions/PaymentExtensions.cs | 2 +- .../Extensions/RecurringPaymentExtensions.cs | 2 +- .../Extensions/RoundingHelper.cs | 2 +- .../Extensions/TranslateExtensions.cs | 2 +- .../IExternalAuthenticationService.cs | 4 +- .../IJwtBearerAuthenticationService.cs | 2 +- ...IJwtBearerCustomerAuthenticationService.cs | 2 +- .../Authentication/IOidcLinkService.cs | 6 +- .../Authentication/IOidcSessionService.cs | 2 +- .../IOidcTokenRevocationService.cs | 2 +- .../Authentication/IRefreshTokenService.cs | 2 +- .../Authentication/ISMSVerificationService.cs | 2 +- .../ITwoFactorAuthenticationService.cs | 2 +- .../Catalog/Brands/IBrandLayoutService.cs | 2 +- .../Catalog/Brands/IBrandService.cs | 2 +- .../Categories/ICategoryLayoutService.cs | 2 +- .../Catalog/Categories/ICategoryService.cs | 12 +- .../Collections/ICollectionLayoutService.cs | 2 +- .../Catalog/Collections/ICollectionService.cs | 2 +- .../Catalog/Directory/IMeasureService.cs | 10 +- .../Catalog/Directory/ISearchTermService.cs | 4 +- .../Discounts/IDiscountAmountProvider.cs | 2 +- .../Discounts/IDiscountProviderLoader.cs | 4 +- .../Catalog/Discounts/IDiscountService.cs | 10 +- .../Inventory/IInventoryDocumentService.cs | 16 +-- .../Inventory/IInventoryJournalService.cs | 4 +- .../Catalog/Inventory/IProductUnitService.cs | 26 ++-- .../Catalog/Prices/IPriceFormatter.cs | 2 +- .../Catalog/Prices/IPricingService.cs | 4 +- .../Catalog/Products/IAuctionService.cs | 6 +- .../Products/ICustomerGroupProductService.cs | 4 +- .../Products/IInventoryManageService.cs | 6 +- .../IOutOfStockSubscriptionService.cs | 4 +- .../Products/IProductAttributeFormatter.cs | 2 +- .../Products/IProductAttributeService.cs | 2 +- .../Catalog/Products/IProductCourseService.cs | 4 +- .../Catalog/Products/IProductLayoutService.cs | 2 +- .../Products/IProductReservationService.cs | 4 +- .../Catalog/Products/IProductReviewService.cs | 6 +- .../Catalog/Products/IProductService.cs | 6 +- .../Catalog/Products/IProductTagService.cs | 6 +- .../ISpecificationAttributeService.cs | 6 +- .../Catalog/Products/IStockQuantityService.cs | 10 +- .../Catalog/Tax/ITaxCategoryService.cs | 2 +- .../Interfaces/Catalog/Tax/ITaxService.cs | 8 +- .../Interfaces/Catalog/Tax/IVatService.cs | 6 +- .../ICheckoutAttributeFormatter.cs | 2 +- .../ICheckoutAttributeParser.cs | 2 +- .../ICheckoutAttributeService.cs | 2 +- .../GiftVouchers/IGiftVoucherService.cs | 2 +- .../Checkout/Orders/ILoyaltyPointsService.cs | 8 +- .../Orders/IMerchandiseReturnLabelService.cs | 4 +- .../Orders/IMerchandiseReturnRefundService.cs | 4 +- .../Orders/IMerchandiseReturnService.cs | 14 +- .../IMerchandiseReturnWorkflowService.cs | 14 +- .../Checkout/Orders/IOrderApprovalService.cs | 6 +- .../Checkout/Orders/IOrderPlacementService.cs | 2 +- .../Checkout/Orders/IOrderService.cs | 12 +- .../Checkout/Orders/IOrderStatusService.cs | 4 +- .../Checkout/Orders/IOrderTagService.cs | 4 +- .../Orders/IRecurringPaymentService.cs | 14 +- .../Checkout/Orders/IShoppingCartService.cs | 10 +- .../Checkout/Orders/IShoppingCartValidator.cs | 4 +- .../Checkout/Payments/IPaymentService.cs | 12 +- .../IPaymentTransactionHistoryService.cs | 4 +- .../Payments/IPaymentTransactionService.cs | 4 +- .../Checkout/Shipping/IDeliveryDateService.cs | 2 +- .../Checkout/Shipping/IPickupPointService.cs | 4 +- .../Shipping/IReturnShippingProvider.cs | 2 +- .../Shipping/IReturnShippingService.cs | 6 +- .../Checkout/Shipping/IShipmentService.cs | 4 +- .../Shipping/IShippingMethodService.cs | 2 +- .../Checkout/Shipping/IShippingService.cs | 8 +- .../Shipping/IWarehouseLocationService.cs | 2 +- .../Checkout/Shipping/IWarehouseService.cs | 2 +- .../Interfaces/Cms/IBlogService.cs | 10 +- .../Interfaces/Cms/IKnowledgebaseService.cs | 8 +- .../Interfaces/Cms/INewsService.cs | 2 +- .../Interfaces/Cms/IPageLayoutService.cs | 2 +- .../Interfaces/Cms/IPageService.cs | 4 +- .../Interfaces/Cms/IRobotsTxtService.cs | 2 +- .../Interfaces/Cms/IWidgetService.cs | 2 +- .../Addresses/IAddressAttributeParser.cs | 4 +- .../Addresses/IAddressAttributeService.cs | 2 +- .../Interfaces/Common/Audit/IAuditService.cs | 2 +- .../Common/Configuration/ISettingService.cs | 6 +- .../Common/Directory/ICountryService.cs | 8 +- .../Common/Directory/ICurrencyService.cs | 10 +- .../Common/Directory/IExchangeRateService.cs | 4 +- .../Common/Directory/IGroupService.cs | 4 +- .../Common/Localization/ILanguageService.cs | 4 +- .../Localization/ITranslationService.cs | 6 +- .../Interfaces/Common/Pdf/IPdfService.cs | 8 +- .../Interfaces/Common/Security/IAclService.cs | 2 +- .../Common/Security/IEncryptionService.cs | 8 +- .../Common/Security/IPermissionService.cs | 4 +- .../Interfaces/Common/Seo/ISeNameService.cs | 2 +- .../Interfaces/Common/Seo/ISlugService.cs | 8 +- .../Interfaces/Common/Stores/IStoreService.cs | 2 +- .../Interfaces/Customers/IAffiliateService.cs | 4 +- .../Customers/ICustomerAttributeService.cs | 2 +- .../Customers/ICustomerNoteService.cs | 2 +- .../Interfaces/Customers/ICustomerService.cs | 16 +-- .../Customers/ISalesEmployeeService.cs | 2 +- .../Interfaces/Customers/IUserApiService.cs | 4 +- .../Interfaces/Customers/IVendorService.cs | 6 +- .../Interfaces/ExportImport/IRowImport.cs | 4 +- .../Marketing/Campaigns/ICampaignService.cs | 2 +- .../Contacts/IContactAttributeService.cs | 2 +- .../Marketing/Contacts/IContactUsService.cs | 2 +- .../Marketing/Courses/ICourseActionService.cs | 4 +- .../Marketing/Courses/ICourseLessonService.cs | 2 +- .../Marketing/Courses/ICourseLevelService.cs | 2 +- .../Marketing/Courses/ICourseService.cs | 2 +- .../Courses/ICourseSubjectService.cs | 2 +- .../Customers/ICustomerProductService.cs | 6 +- .../Customers/ICustomerTagService.cs | 8 +- .../Marketing/Documents/IDocumentService.cs | 2 +- .../Documents/IDocumentTypeService.cs | 2 +- .../INewsLetterSubscriptionService.cs | 8 +- .../Newsletters/INewsletterCategoryService.cs | 2 +- .../IPushNotificationsService.cs | 4 +- .../ICatalogMessageProviderService.cs | 26 ++-- .../Messages/ICmsMessageProviderService.cs | 6 +- .../ICustomerMessageProviderService.cs | 26 ++-- .../Messages/IEmailAccountService.cs | 2 +- .../Interfaces/Messages/IEmailSender.cs | 2 +- ...MerchandiseReturnMessageProviderService.cs | 8 +- .../Messages/IMessageLookupService.cs | 6 +- .../Messages/IMessageProviderService.cs | 6 +- .../Messages/IMessageTemplateService.cs | 4 +- .../INewsletterMessageProviderService.cs | 4 +- .../Messages/IOrderMessageProviderService.cs | 30 ++--- .../Messages/IQueuedEmailService.cs | 4 +- ...IRecurringPaymentMessageProviderService.cs | 8 +- .../Messages/IVendorMessageProviderService.cs | 8 +- .../Interfaces/Storage/IDownloadService.cs | 6 +- .../Interfaces/Storage/IFileStore.cs | 15 ++- .../Interfaces/Storage/IFileStoreEntry.cs | 2 +- .../Interfaces/Storage/IPictureService.cs | 20 +-- .../Catalog/GetDiscountAmountProvider.cs | 2 +- .../Catalog/GetProductArchByIdQuery.cs | 2 +- .../Queries/Catalog/GetSearchProductsQuery.cs | 2 +- .../Catalog/GetSitemapProductsQuery.cs | 2 +- .../Queries/Catalog/GetVendorByIdQuery.cs | 2 +- .../Checkout/Orders/GetPickupPointById.cs | 2 +- .../Customers/GetGroupBySystemNameQuery.cs | 2 +- .../Queries/Messages/GetCustomerByIdQuery.cs | 2 +- .../Queries/Messages/GetProductByIdQuery.cs | 2 +- .../Queries/Messages/GetVendorByIdQuery.cs | 2 +- .../Authentication/ExternalAuthParam.cs | 4 +- .../Authentication/OidcCustomerResult.cs | 2 + .../Utilities/Authentication/ScimResults.cs | 24 ++-- .../Utilities/Catalog/StockBuckets.cs | 4 +- .../Utilities/Catalog/StockChange.cs | 10 +- .../Utilities/Catalog/UnitNumbers.cs | 2 +- .../Utilities/Checkout/AppliedGiftVoucher.cs | 2 +- .../Utilities/Checkout/CheckoutClaim.cs | 10 +- .../MerchandiseReturnSubmitRequest.cs | 2 +- .../Checkout/OrderPlacementContext.cs | 4 +- .../Checkout/OrderPlacementRuleResult.cs | 4 +- .../Utilities/Checkout/PlaceOrderContainer.cs | 17 ++- .../Checkout/PurchaseOrderNumberRules.cs | 4 +- .../Checkout/RefundPaymentRequest.cs | 2 +- .../Utilities/Checkout/ReturnShipping.cs | 6 +- .../Utilities/ExportImport/PropertyByName.cs | 4 +- .../Utilities/Messages/CampaignRecipient.cs | 2 +- .../Handlers/ActiveVendorCommandHandler.cs | 2 + .../Grand.Business.Customers.csproj | 3 + .../Handlers/GetCustomerQueryHandler.cs | 8 +- .../GetGroupBySystemNameQueryHandler.cs | 4 +- .../Services/AffiliateService.cs | 12 +- .../Services/CustomerAttributeParser.cs | 2 +- .../Services/CustomerAttributeService.cs | 21 +-- .../Services/CustomerManagerService.cs | 8 +- .../Services/CustomerNoteService.cs | 4 +- .../Services/CustomerService.cs | 36 +++--- .../Services/SalesEmployeeService.cs | 2 +- .../Services/UserApiService.cs | 4 +- .../Services/VendorService.cs | 10 +- .../Grand.Business.Marketing.csproj | 3 + .../Services/Campaigns/CampaignService.cs | 35 +++-- .../Contacts/ContactAttributeParser.cs | 2 +- .../Contacts/ContactAttributeService.cs | 4 +- .../Services/Contacts/ContactUsService.cs | 2 +- .../Services/Courses/CourseActionService.cs | 4 +- .../Services/Courses/CourseLessonService.cs | 2 +- .../Services/Courses/CourseLevelService.cs | 2 +- .../Services/Courses/CourseService.cs | 2 +- .../Services/Courses/CourseSubjectService.cs | 2 +- .../Customers/CustomerProductService.cs | 11 +- .../Services/Customers/CustomerTagService.cs | 8 +- .../Services/Documents/DocumentService.cs | 2 +- .../Services/Documents/DocumentTypeService.cs | 2 +- .../NewsLetterSubscriptionService.cs | 19 +-- .../Newsletters/NewsletterCategoryService.cs | 2 +- .../PushNotificationsService.cs | 10 +- .../Utilities/JsonResponse.cs | 4 +- ...otificationsToSubscribersCommandHandler.cs | 2 +- .../Common/InsertContactUsCommandHandler.cs | 2 +- .../GetAuctionTokensCommandHandler.cs | 6 +- ...etMerchandiseReturnTokensCommandHandler.cs | 8 +- .../GetOrderApprovalTokensCommandHandler.cs | 4 +- .../Messages/GetOrderTokensCommandHandler.cs | 2 +- ...GetRecurringPaymentTokensCommandHandler.cs | 2 +- .../GetShoppingCartTokensCommandHandler.cs | 4 +- .../Messages/GetStoreTokensCommandHandler.cs | 2 +- .../GetAttributeCombinationTokensCommand.cs | 8 +- .../Tokens/GetAuctionTokensCommand.cs | 4 +- .../Tokens/GetGiftVoucherTokensCommand.cs | 4 +- .../GetMerchandiseReturnTokensCommand.cs | 14 +- .../Tokens/GetOrderApprovalTokensCommand.cs | 12 +- .../Commands/Tokens/GetOrderTokensCommand.cs | 12 +- .../GetRecurringPaymentTokensCommand.cs | 4 +- .../Tokens/GetShipmentTokensCommand.cs | 10 +- .../Tokens/GetShoppingCartTokensCommand.cs | 6 +- .../Commands/Tokens/GetStoreTokensCommand.cs | 6 +- .../Commands/Tokens/GetVendorTokensCommand.cs | 4 +- .../LiquidAttributeCombination.cs | 4 +- .../DotLiquidDrops/LiquidAuctions.cs | 12 +- .../DotLiquidDrops/LiquidBlogComment.cs | 6 +- .../DotLiquidDrops/LiquidCustomer.cs | 42 +++--- .../DotLiquidDrops/LiquidGiftVoucher.cs | 12 +- .../DotLiquidDrops/LiquidGuestOrderLink.cs | 2 +- .../DotLiquidDrops/LiquidInventory.cs | 6 +- .../DotLiquidDrops/LiquidKnowledgebase.cs | 6 +- .../DotLiquidDrops/LiquidMerchandiseReturn.cs | 38 +++--- .../LiquidMerchandiseReturnItem.cs | 24 ++-- .../DotLiquidDrops/LiquidNewsComment.cs | 8 +- .../LiquidNewsLetterSubscription.cs | 4 +- .../DotLiquidDrops/LiquidObjectBuilder.cs | 12 +- .../LiquidObjectBuilderExtensions.cs | 2 +- .../DotLiquidDrops/LiquidOrder.cs | 120 +++++++++--------- .../DotLiquidDrops/LiquidOrderApproval.cs | 22 ++-- .../DotLiquidDrops/LiquidOrderItem.cs | 60 ++++----- .../LiquidOutOfStockSubscription.cs | 6 +- .../DotLiquidDrops/LiquidProduct.cs | 16 +-- .../DotLiquidDrops/LiquidProductReview.cs | 4 +- .../DotLiquidDrops/LiquidRecurringPayment.cs | 6 +- .../DotLiquidDrops/LiquidShipment.cs | 6 +- .../DotLiquidDrops/LiquidShipmentItem.cs | 20 +-- .../DotLiquidDrops/LiquidShoppingCart.cs | 8 +- .../DotLiquidDrops/LiquidShoppingCartItem.cs | 8 +- .../DotLiquidDrops/LiquidStore.cs | 46 +++---- .../DotLiquidDrops/LiquidVendor.cs | 24 ++-- .../DotLiquidDrops/LiquidVendorReview.cs | 6 +- .../Grand.Business.Messages.csproj | 3 + .../Handlers/GetCustomerByIdQueryHandler.cs | 4 +- .../Handlers/GetProductByIdQueryHandler.cs | 4 +- .../Handlers/GetVendorByIdQueryHandler.cs | 4 +- .../Services/CatalogMessageProviderService.cs | 42 +++--- .../Services/CmsMessageProviderService.cs | 10 +- .../CustomerMessageProviderService.cs | 46 +++---- .../Services/EmailAccountService.cs | 2 +- .../Services/EmailSender.cs | 28 ++-- ...MerchandiseReturnMessageProviderService.cs | 20 +-- .../Services/MessageLookupService.cs | 12 +- .../Services/MessageProviderService.cs | 18 +-- .../Services/MessageTemplateNames.cs | 2 +- .../Services/MessageTemplateService.cs | 6 +- .../NewsletterMessageProviderService.cs | 6 +- .../Services/OrderMessageProviderService.cs | 84 ++++++------ .../Services/QueuedEmailService.cs | 16 +-- .../RecurringPaymentMessageProviderService.cs | 14 +- .../Services/VendorMessageProviderService.cs | 14 +- .../Grand.Business.Storage.csproj | 3 + .../Services/AmazonPictureService.cs | 10 +- .../Services/AzurePictureService.cs | 10 +- .../Services/DefaultMediaFileStore.cs | 8 +- .../Services/DownloadService.cs | 13 +- .../Services/FileSystemStore.cs | 17 +-- .../Services/FileSystemStoreEntry.cs | 4 +- .../Services/LayeredFileStore.cs | 12 +- .../Services/PictureService.cs | 50 ++++---- src/Core/Grand.Data/IRepository.cs | 4 +- .../Grand.Data/LiteDb/LiteDBRepository.cs | 4 +- src/Core/Grand.Data/Mongo/MongoRepository.cs | 4 +- src/Core/Grand.Domain/Catalog/ProductBatch.cs | 4 +- .../Grand.Domain/Catalog/ProductExtensions.cs | 2 +- .../Catalog/ProductSerialNumber.cs | 4 +- .../Common/UserFieldExtensions.cs | 2 +- .../Grand.Domain/Orders/OrderExtensions.cs | 4 +- .../Orders/ShoppingCartExtensions.cs | 2 +- .../Configuration/OidcLoginConfig.cs | 2 +- .../Extensions/ProviderExtensions.cs | 4 +- .../Grand.Infrastructure/Plugins/IProvider.cs | 2 +- .../Extensions/CommonHelper.cs | 12 +- .../Extensions/FormatText.cs | 2 +- .../ExternalAuthenticationServiceTests.cs | 2 +- .../PlaceOrderCommandHandlerApprovalTests.cs | 6 +- ...ceOrderCommandHandlerPurchaseOrderTests.cs | 6 +- .../Orders/PlaceOrderCommandHandlerTests.cs | 8 +- ...edeemedLoyaltyPointsCommandHandlerTests.cs | 4 +- .../Orders/CheckoutClaimServiceTests.cs | 12 +- .../InStoreReturnProviderTests.cs | 12 +- .../SendYourselfReturnProviderTests.cs | 8 +- .../BlogPostDeletedEventHandlerTests.cs | 3 +- ...chandiseReturnTokensCommandHandlerTests.cs | 1 + .../InsertContactUsCommandHandlerTests.cs | 2 + .../Services/CampaignMessageRendererTests.cs | 3 +- .../ExternalSignInServiceTests.cs | 3 +- 495 files changed, 2370 insertions(+), 2135 deletions(-) diff --git a/src/Business/Grand.Business.Authentication/Grand.Business.Authentication.csproj b/src/Business/Grand.Business.Authentication/Grand.Business.Authentication.csproj index 2ac20c3e9..4076c6016 100644 --- a/src/Business/Grand.Business.Authentication/Grand.Business.Authentication.csproj +++ b/src/Business/Grand.Business.Authentication/Grand.Business.Authentication.csproj @@ -7,4 +7,7 @@ + + enable + diff --git a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs index 960042429..a8b55afc7 100644 --- a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs +++ b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs @@ -70,7 +70,7 @@ public ExternalAuthenticationService( /// Working language of the request /// Result of an authentication protected virtual async Task AuthenticateExistingUser(Customer associatedUser, - Customer currentLoggedInUser, Customer customer, string storeId, Language language) + Customer? currentLoggedInUser, Customer customer, string storeId, Language language) { //log in guest user if (currentLoggedInUser == null) @@ -92,7 +92,7 @@ protected virtual async Task AuthenticateExistingUser(Custom /// Store identifier /// Working language of the request /// Result of an authentication - protected virtual async Task AuthenticateNewUser(Customer currentLoggedInUser, + protected virtual async Task AuthenticateNewUser(Customer? currentLoggedInUser, ExternalAuthParam parameters, Customer customer, string storeId, Language language) { //associate external account with logged-in user @@ -122,8 +122,11 @@ protected virtual async Task AuthenticateNewUser(Customer cu /// Whether another customer has the provider's e-mail as their e-mail or, with usernames enabled, as their /// username; registration stores the provider's e-mail in both fields /// - private async Task IsEmailOrUsernameTaken(string email, string storeId) + private async Task IsEmailOrUsernameTaken(string? email, string storeId) { + //a provider that gives no e-mail takes nothing over; registration then asks for it + if (string.IsNullOrWhiteSpace(email)) + return false; return await _customerService.GetCustomerByEmail(email, storeId) != null || (_customerSettings.UsernamesEnabled && await _customerService.GetCustomerByUsername(email, storeId) != null); @@ -144,9 +147,12 @@ protected virtual async Task RegisterNewUser(ExternalAuthPar _customerSettings.UserRegistrationType is UserRegistrationType.Standard or UserRegistrationType.EmailValidation; + //Authenticate registers only with the provider's e-mail + var email = parameters.Email ?? throw new ArgumentException("The provider gave no e-mail", nameof(parameters)); + //create registration request var registrationRequest = new RegistrationRequest(customer, - parameters.Email, parameters.Email, + email, email, CommonHelper.GenerateRandomDigitCode(20), PasswordFormat.Hashed, storeId, @@ -214,7 +220,7 @@ public virtual IList LoadActiveAuthenticationPr /// /// System name /// Found external authentication provider - public virtual IExternalAuthenticationProvider LoadAuthenticationProviderBySystemName(string systemName) + public virtual IExternalAuthenticationProvider? LoadAuthenticationProviderBySystemName(string systemName) { return _externalAuthenticationProviders.FirstOrDefault(x => x.SystemName.Equals(systemName, StringComparison.OrdinalIgnoreCase)); @@ -312,13 +318,13 @@ public virtual async Task AssociateCustomer(Customer customer, ExternalAuthParam /// /// External authentication parameters /// Customer - public virtual async Task GetCustomer(ExternalAuthParam parameters) + public virtual async Task GetCustomer(ExternalAuthParam parameters) { ArgumentNullException.ThrowIfNull(parameters); var associationRecord = (from q in _externalAuthenticationRecordRepository.Table where q.ExternalIdentifier == parameters.Identifier - && q.ProviderSystemName.ToLowerInvariant() == parameters.ProviderSystemName.ToLowerInvariant() + && q.ProviderSystemName != null && q.ProviderSystemName.ToLowerInvariant() == parameters.ProviderSystemName.ToLowerInvariant() select q).FirstOrDefault(); if (associationRecord == null) diff --git a/src/Business/Grand.Business.Authentication/Services/JwtBearerAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/JwtBearerAuthenticationService.cs index 8707367f4..cbcdcc55a 100644 --- a/src/Business/Grand.Business.Authentication/Services/JwtBearerAuthenticationService.cs +++ b/src/Business/Grand.Business.Authentication/Services/JwtBearerAuthenticationService.cs @@ -12,9 +12,9 @@ public class JwtBearerAuthenticationService : IJwtBearerAuthenticationService private readonly ICustomerService _customerService; private readonly IUserApiService _userApiService; private readonly OidcLoginConfig _oidcLoginConfig; - private string _email; + private string? _email; - private string _errorMessage; + private string? _errorMessage; public JwtBearerAuthenticationService( ICustomerService customerService, IUserApiService userApiService, OidcLoginConfig oidcLoginConfig) @@ -76,7 +76,7 @@ public virtual async Task Valid(ClaimsPrincipal principal) /// Get error message /// /// - public virtual Task ErrorMessage() + public virtual Task ErrorMessage() { return Task.FromResult(_errorMessage); } diff --git a/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs index ca480e95a..c7646dad6 100644 --- a/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs +++ b/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs @@ -18,7 +18,7 @@ public class JwtBearerCustomerAuthenticationService : IJwtBearerCustomerAuthenti private readonly IRefreshTokenService _refreshTokenService; private readonly IExternalSignInPolicy _externalSignInPolicy; private readonly OidcLoginConfig _oidcLoginConfig; - private string _errorMessage; + private string? _errorMessage; public JwtBearerCustomerAuthenticationService(ICustomerService customerService, IPermissionService permissionService, IGroupService groupService, IRefreshTokenService refreshTokenService, @@ -39,7 +39,7 @@ public async Task Valid(ClaimsPrincipal principal) var email = principal.Claims.FirstOrDefault(x => x.Type == "Email")?.Value; var passwordToken = principal.Claims.FirstOrDefault(x => x.Type == "Token")?.Value; var refreshId = principal.Claims.FirstOrDefault(x => x.Type == "RefreshId")?.Value; - Customer customer = null; + Customer? customer = null; if (!string.IsNullOrEmpty(customerId)) { //prefer the stable customer id - unambiguous with per-store identity @@ -101,7 +101,7 @@ public async Task Valid(ClaimsPrincipal principal) } - public Task ErrorMessage() + public Task ErrorMessage() { return Task.FromResult(_errorMessage); } diff --git a/src/Business/Grand.Business.Authentication/Services/OidcCustomerResolver.cs b/src/Business/Grand.Business.Authentication/Services/OidcCustomerResolver.cs index 55cfb931f..c8ef4dd74 100644 --- a/src/Business/Grand.Business.Authentication/Services/OidcCustomerResolver.cs +++ b/src/Business/Grand.Business.Authentication/Services/OidcCustomerResolver.cs @@ -102,8 +102,8 @@ public virtual async Task Resolve(ClaimsPrincipal principal, //a link made by e-mail proves no more than the e-mail: it stops serving an account that has since //become one that connects only with its password if (linkedResult.Succeeded && link.LinkedByEmail && !_loginConfig.ProviderOnly && - await RequiresPassword(linkedCustomer, storeId)) - return AccountConnectionRequired(linkedCustomer, sub); + await RequiresPassword(linkedResult.Customer, storeId)) + return AccountConnectionRequired(linkedResult.Customer, sub); return linkedResult; } @@ -159,8 +159,9 @@ public virtual async Task ResolveForLogin(string sub, string em if (link != null) { var linked = await _customerService.GetCustomerById(link.CustomerId); + //Check answers Missing for no customer var reason = await Check(linked, sub, storeId); - if (reason != Unusable.None) + if (linked == null || reason != Unusable.None) return OidcLoginResult.Refused(ToRefusal(reason)); //a link made by e-mail (by an access token or an earlier sign-in) is held to the rules of a first link; @@ -281,9 +282,10 @@ private async Task Register(string sub, string email, string var (outcome, customer, winner) = await CreateLinkedAccount(sub, email, storeId, null); return outcome switch { Provisioning.UserNameTaken => OidcCustomerResult.Forbidden("The user name is already taken"), - Provisioning.LinkedToOtherIdentity => LinkedToOtherIdentity(customer, sub), + Provisioning.LinkedToOtherIdentity when customer != null => LinkedToOtherIdentity(customer, sub), Provisioning.LostRace => await Usable(winner, sub, storeId), - _ => OidcCustomerResult.Success(customer) + Provisioning.Created when customer != null => OidcCustomerResult.Success(customer), + _ => OidcCustomerResult.Forbidden("The customer account could not be created") }; } @@ -300,7 +302,8 @@ private async Task ProvisionForLogin(string sub, string email, Provisioning.LinkedToOtherIdentity => OidcLoginResult.Refused(OidcLoginRefusal.LinkedToOtherIdentity), //another request of the same user created the account first: its link answers now Provisioning.LostRace => await ResolveForLogin(sub, email, emailVerified, storeId, language), - _ => OidcLoginResult.SignIn(customer) + Provisioning.Created when customer != null => OidcLoginResult.SignIn(customer), + _ => OidcLoginResult.Refused(OidcLoginRefusal.AccountUnusable) }; } @@ -316,8 +319,8 @@ private enum Provisioning /// Creates an active account with the Registered group for the subject and links it (not by e-mail). The store's /// e-mail validation / admin approval does not apply: access comes from the provider and from permissions an admin grants /// - private async Task<(Provisioning Outcome, Customer Customer, Customer Winner)> CreateLinkedAccount(string sub, - string email, string storeId, Language language) + private async Task<(Provisioning Outcome, Customer? Customer, Customer? Winner)> CreateLinkedAccount(string sub, + string email, string storeId, Language? language) { //the e-mail becomes the user name - another account may hold it as its user name without that e-mail var normalizedEmail = email.ToLowerInvariant(); @@ -361,7 +364,7 @@ await _customerManagerService.RegisterCustomer(new RegistrationRequest(customer, /// subject from linking this store's customer; without per-store identity: any link. /// Subjects are case-sensitive - exact comparison. /// - private async Task GetLink(string sub, string storeId) + private async Task GetLink(string sub, string storeId) { if (!_customerConfig.RegisterCustomersPerStore) return await _externalAuthenticationRepository.GetOneAsync(x => @@ -414,7 +417,7 @@ private OidcCustomerResult AccountConnectionRequired(Customer customer, string s /// first: the link of another subject now holding this customer (OtherLink), or the customer the subject's /// winning link points to (Customer). Rethrows when the insert failed for another reason. /// - private async Task<(Customer Customer, ExternalAuthentication OtherLink)> LinkOrGetWinner(Customer customer, + private async Task<(Customer? Customer, ExternalAuthentication? OtherLink)> LinkOrGetWinner(Customer customer, string sub, string email, string storeId, bool byEmail) { var linkId = OidcLinkId(customer.Id); @@ -468,7 +471,7 @@ private enum Unusable { None, Missing, Inactive, Unusable, OtherStore } //the checks every other login path applies: an active, registered, non-system account, and with per-store //identity one of the request's store (or of no store) - private async Task Check(Customer customer, string sub, string storeId) + private async Task Check(Customer? customer, string sub, string storeId) { if (customer == null) { @@ -498,8 +501,10 @@ private async Task Check(Customer customer, string sub, string storeId return Unusable.None; } - private async Task Usable(Customer customer, string sub, string storeId) => + private async Task Usable(Customer? customer, string sub, string storeId) => await Check(customer, sub, storeId) switch { + //Check answers Missing for no customer + _ when customer == null => OidcCustomerResult.Forbidden("The customer account no longer exists"), Unusable.None => OidcCustomerResult.Success(customer), Unusable.Missing => OidcCustomerResult.Forbidden("The customer account no longer exists"), Unusable.Inactive => OidcCustomerResult.Forbidden("The customer account is inactive"), diff --git a/src/Business/Grand.Business.Authentication/Services/OidcLinkService.cs b/src/Business/Grand.Business.Authentication/Services/OidcLinkService.cs index 5358b9647..5a5d8f6c4 100644 --- a/src/Business/Grand.Business.Authentication/Services/OidcLinkService.cs +++ b/src/Business/Grand.Business.Authentication/Services/OidcLinkService.cs @@ -116,7 +116,7 @@ private IQueryable OidcLinks() => private Task HasLinks() => externalAuthenticationRepository.AnyAsync(OidcLinks()); - private void LogMismatch(string linkedAuthority) + private void LogMismatch(string? linkedAuthority) { var now = DateTime.UtcNow.Ticks; var last = Interlocked.Read(ref _lastMismatchLogTicks); diff --git a/src/Business/Grand.Business.Authentication/Services/OidcSessionService.cs b/src/Business/Grand.Business.Authentication/Services/OidcSessionService.cs index 0e9a71634..83aae4b19 100644 --- a/src/Business/Grand.Business.Authentication/Services/OidcSessionService.cs +++ b/src/Business/Grand.Business.Authentication/Services/OidcSessionService.cs @@ -63,7 +63,7 @@ public OidcSessionService( _logger = logger; } - public virtual async Task Start(Customer customer, string subject, string sid, string refreshToken, string storeId) + public virtual async Task Start(Customer customer, string subject, string sid, string refreshToken, string storeId) { ArgumentNullException.ThrowIfNull(customer); ArgumentException.ThrowIfNullOrEmpty(subject); @@ -314,12 +314,15 @@ private async Task> EndAll(IList sessions, return sessions; } - private Task Get(string sessionId) => + private Task Get(string sessionId) => _cache.GetAsync(string.Format(CacheKey.OIDC_SESSION_BY_ID_KEY, sessionId), () => _sessionRepository.GetByIdAsync(sessionId), CacheTimeMinutes); - private string Unprotect(string protectedToken) + private string? Unprotect(string? protectedToken) { + //a session stored without a refresh token has none to refresh with + if (protectedToken == null) + return null; try { return _protector.Unprotect(protectedToken); diff --git a/src/Business/Grand.Business.Authentication/Services/OidcSignInModeCheck.cs b/src/Business/Grand.Business.Authentication/Services/OidcSignInModeCheck.cs index c36510fea..5bf341e83 100644 --- a/src/Business/Grand.Business.Authentication/Services/OidcSignInModeCheck.cs +++ b/src/Business/Grand.Business.Authentication/Services/OidcSignInModeCheck.cs @@ -8,7 +8,7 @@ namespace Grand.Business.Authentication.Services; /// public static class OidcSignInModeCheck { - public static string Problem(OidcLoginConfig config, OidcResourceServerConfig resourceServer) + public static string? Problem(OidcLoginConfig config, OidcResourceServerConfig resourceServer) { if (config is not { ProviderOnly: true }) return null; diff --git a/src/Business/Grand.Business.Authentication/Services/OidcSsoSignInPolicy.cs b/src/Business/Grand.Business.Authentication/Services/OidcSsoSignInPolicy.cs index e4b87351e..d886efdb8 100644 --- a/src/Business/Grand.Business.Authentication/Services/OidcSsoSignInPolicy.cs +++ b/src/Business/Grand.Business.Authentication/Services/OidcSsoSignInPolicy.cs @@ -30,7 +30,7 @@ public class OidcSsoSignInPolicy( { private const string UnavailableLogKey = "Grand.OidcSignInMode.Unavailable"; - private async Task RequiredProvider(Customer customer) + private async Task RequiredProvider(Customer customer) { if (customer == null || !config.SsoOnly) return null; @@ -66,7 +66,7 @@ public async Task PasswordSignIn(Customer customer, Sign return new PasswordSignInDecision(false, provider); } - private IExternalAuthenticationProvider AvailableProvider() + private IExternalAuthenticationProvider? AvailableProvider() { if (!config.IsConfigured(resourceServerConfig)) return null; diff --git a/src/Business/Grand.Business.Authentication/Services/OidcTokenRevocationService.cs b/src/Business/Grand.Business.Authentication/Services/OidcTokenRevocationService.cs index 1ccd8c396..ae7b3494e 100644 --- a/src/Business/Grand.Business.Authentication/Services/OidcTokenRevocationService.cs +++ b/src/Business/Grand.Business.Authentication/Services/OidcTokenRevocationService.cs @@ -15,7 +15,7 @@ namespace Grand.Business.Authentication.Services; public class OidcTokenRevocationService(IRepository revocationRepository) : IOidcTokenRevocationService { - public async Task RevokeTokens(string subject) + public async Task RevokeTokens(string? subject) { ArgumentException.ThrowIfNullOrEmpty(subject); var id = RevocationId(subject); diff --git a/src/Business/Grand.Business.Authentication/Services/RefreshTokenService.cs b/src/Business/Grand.Business.Authentication/Services/RefreshTokenService.cs index 269ee82b3..c96d0bfab 100644 --- a/src/Business/Grand.Business.Authentication/Services/RefreshTokenService.cs +++ b/src/Business/Grand.Business.Authentication/Services/RefreshTokenService.cs @@ -4,6 +4,7 @@ using Grand.Domain.Customers; using Grand.Domain.Security; using Grand.Infrastructure.Configuration; +using Grand.SharedKernel; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; @@ -42,7 +43,7 @@ public async Task SaveRefreshTokenToCustomer(Customer customer, st return token; } - public Task GetCustomerRefreshToken(Customer customer) + public Task GetCustomerRefreshToken(Customer customer) { return Task.FromResult(customer.GetUserFieldFromEntity(SystemCustomerFieldNames.RefreshToken)); } @@ -53,7 +54,8 @@ public ClaimsPrincipal GetPrincipalFromToken(string token) ValidateAudience = _apiConfig.ValidateAudience, ValidateIssuer = _apiConfig.ValidateIssuer, ValidateIssuerSigningKey = _apiConfig.ValidateIssuerSigningKey, - IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_apiConfig.SecretKey)), + IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_apiConfig.SecretKey ?? + throw new GrandException("The API secret key is not configured"))), ValidateLifetime = _apiConfig.ValidateLifetime }; diff --git a/src/Business/Grand.Business.Authentication/Services/Scim/ScimGroupService.cs b/src/Business/Grand.Business.Authentication/Services/Scim/ScimGroupService.cs index b0c47bc10..887e9ebc4 100644 --- a/src/Business/Grand.Business.Authentication/Services/Scim/ScimGroupService.cs +++ b/src/Business/Grand.Business.Authentication/Services/Scim/ScimGroupService.cs @@ -82,7 +82,7 @@ public virtual async Task> List(string displayName, stri if (!string.IsNullOrEmpty(displayName)) { var lowered = displayName.Trim().ToLowerInvariant(); - query = query.Where(x => x.DisplayName.ToLower() == lowered); + query = query.Where(x => x.DisplayName != null && x.DisplayName.ToLower() == lowered); } var total = await groups.CountAsync(query); @@ -129,7 +129,10 @@ public virtual async Task Rename(string id, string displayName, await groups.UpdateField(group.Id, x => x.DisplayName, name); if (externalId != null) await groups.UpdateField(group.Id, x => x.ExternalId, externalId); + //deleted by another request meanwhile var renamed = await groups.GetByIdAsync(group.Id); + if (renamed == null) + return new ScimGroupResult(ScimOutcome.NotFound); await mediator.EntityUpdated(renamed); return new ScimGroupResult(ScimOutcome.Ok, View(renamed)); } @@ -154,7 +157,7 @@ public virtual async Task SetMapping(string groupId, string custome if (!string.IsNullOrEmpty(customerGroupId)) { var customerGroup = await groupService.GetCustomerGroupById(customerGroupId); - if (!await ValidTarget(customerGroup, staffStoreId, vendorId)) + if (customerGroup == null || !await ValidTarget(customerGroup, staffStoreId, vendorId)) return ScimOutcome.Invalid; target = customerGroup.Id; store = IsSystemGroup(customerGroup, SystemCustomerGroupNames.StoreManager) ? staffStoreId : ""; @@ -164,7 +167,10 @@ public virtual async Task SetMapping(string groupId, string custome await groups.UpdateField(group.Id, x => x.CustomerGroupId, target); await groups.UpdateField(group.Id, x => x.StaffStoreId, store); await groups.UpdateField(group.Id, x => x.VendorId, vendor); + //deleted by another request meanwhile var mapped = await groups.GetByIdAsync(group.Id); + if (mapped == null) + return ScimOutcome.NotFound; await mediator.EntityUpdated(mapped); await roleSync.SyncMembers(mapped.Members); logger.LogInformation("SCIM group {GroupId} mapped to customer group {CustomerGroupId}", group.Id, target); @@ -193,7 +199,10 @@ private async Task ChangeMembers(ScimGroup group, IList } var changed = before.Except(after).Concat(after.Except(before)).ToList(); + //deleted by another request meanwhile var stored = await groups.GetByIdAsync(group.Id); + if (stored == null) + return new ScimGroupResult(ScimOutcome.NotFound); await mediator.EntityUpdated(stored); await roleSync.SyncMembers(changed); return new ScimGroupResult(ScimOutcome.Ok, View(stored)); @@ -218,7 +227,7 @@ private static bool IsSystemGroup(CustomerGroup group, string systemName) => group.IsSystem && group.SystemName == systemName; //display names may repeat (Entra allows it); the provider's id of a group may not - private async Task ExternalIdTaken(string externalId, string exceptId) => + private async Task ExternalIdTaken(string externalId, string? exceptId) => !string.IsNullOrEmpty(externalId) && await groups.AnyAsync(groups.Table.Where(x => x.Id != exceptId && x.ExternalId == externalId)); @@ -232,7 +241,7 @@ private async Task> ManagedOnly(IEnumerable ids) .ToList(); } - private async Task Load(string id) => string.IsNullOrEmpty(id) ? null : await groups.GetByIdAsync(id); + private async Task Load(string id) => string.IsNullOrEmpty(id) ? null : await groups.GetByIdAsync(id); private static ScimGroupView View(ScimGroup group) => new(group.Id, group.DisplayName, string.IsNullOrEmpty(group.ExternalId) ? null : group.ExternalId, diff --git a/src/Business/Grand.Business.Authentication/Services/Scim/ScimProtection.cs b/src/Business/Grand.Business.Authentication/Services/Scim/ScimProtection.cs index b69879113..85b06e5fc 100644 --- a/src/Business/Grand.Business.Authentication/Services/Scim/ScimProtection.cs +++ b/src/Business/Grand.Business.Authentication/Services/Scim/ScimProtection.cs @@ -7,7 +7,7 @@ namespace Grand.Business.Authentication.Services.Scim; internal static class ScimProtection { /// Why SCIM must leave the account alone; null when it may manage it - public static string Refusal(Customer customer, OidcLoginConfig loginConfig) + public static string? Refusal(Customer customer, OidcLoginConfig loginConfig) { if (customer.Deleted) return "The account is deleted"; diff --git a/src/Business/Grand.Business.Authentication/Services/Scim/ScimRoleSync.cs b/src/Business/Grand.Business.Authentication/Services/Scim/ScimRoleSync.cs index e39d7db17..ad59a8ec9 100644 --- a/src/Business/Grand.Business.Authentication/Services/Scim/ScimRoleSync.cs +++ b/src/Business/Grand.Business.Authentication/Services/Scim/ScimRoleSync.cs @@ -48,7 +48,7 @@ public virtual async Task Sync(Customer customer, ScimUser record) var customerId = customer.Id; var memberOf = await groups.ToListAsync(groups.Table.Where(x => x.Members.Contains(customerId))); - var targetIds = memberOf.Select(x => x.CustomerGroupId).Where(x => !string.IsNullOrEmpty(x)).Distinct().ToArray(); + var targetIds = memberOf.Select(x => x.CustomerGroupId).OfType().Where(x => x.Length > 0).Distinct().ToArray(); var targets = targetIds.Length == 0 ? new Dictionary() : (await groupService.GetAllByIds(targetIds)).Where(IsMappable).ToDictionary(x => x.Id); @@ -90,9 +90,9 @@ public virtual async Task TakeOver(Customer customer, ScimUser record) ArgumentNullException.ThrowIfNull(customer); ArgumentNullException.ThrowIfNull(record); - var managed = new HashSet(await groups.ToListAsync(groups.Table + var managed = new HashSet((await groups.ToListAsync(groups.Table .Where(x => x.CustomerGroupId != null && x.CustomerGroupId != "") - .Select(x => x.CustomerGroupId))); + .Select(x => x.CustomerGroupId))).OfType()); foreach (var systemName in BackOfficeGroups) { var group = await groupService.GetCustomerGroupBySystemName(systemName); @@ -168,8 +168,8 @@ private async Task Apply(Customer customer, ScimUser record, ScimWanted wanted) } //sets the wanted value, or clears the value SCIM set when nothing is wanted; returns what SCIM granted now - private async Task ApplyField(string customerId, string current, string granted, string wanted, - Expression> field) + private async Task ApplyField(string customerId, string? current, string? granted, string? wanted, + Expression> field) { if (!string.IsNullOrEmpty(wanted)) { diff --git a/src/Business/Grand.Business.Authentication/Services/Scim/ScimRoles.cs b/src/Business/Grand.Business.Authentication/Services/Scim/ScimRoles.cs index a7f04a796..893584dae 100644 --- a/src/Business/Grand.Business.Authentication/Services/Scim/ScimRoles.cs +++ b/src/Business/Grand.Business.Authentication/Services/Scim/ScimRoles.cs @@ -4,7 +4,7 @@ namespace Grand.Business.Authentication.Services.Scim; /// What the mapped SCIM groups of one user give /// The back-office roles cannot be combined, so none of them is given -public record ScimWanted(IReadOnlyCollection GroupIds, string StaffStoreId, string VendorId, bool Conflict); +public record ScimWanted(IReadOnlyCollection GroupIds, string? StaffStoreId, string? VendorId, bool Conflict); /// /// The roles a user gets from its mapped SCIM groups. The back-office roles must form a combination the customer validator @@ -15,7 +15,7 @@ public static class ScimRoles { /// The SCIM groups the user belongs to /// System name of a customer group; empty for a custom group - public static ScimWanted Wanted(IEnumerable groups, Func systemNameOf) + public static ScimWanted Wanted(IEnumerable groups, Func systemNameOf) { var mapped = groups.Where(x => !string.IsNullOrEmpty(x.CustomerGroupId)).ToList(); var custom = new HashSet(); @@ -26,25 +26,29 @@ public static ScimWanted Wanted(IEnumerable groups, Func(); foreach (var group in mapped) - switch (systemNameOf(group.CustomerGroupId)) + { + if (group.CustomerGroupId is not { } groupId) + continue; + switch (systemNameOf(groupId)) { case SystemCustomerGroupNames.Administrators: - admins.Add(group.CustomerGroupId); + admins.Add(groupId); break; case SystemCustomerGroupNames.StoreManager: - storeManagers.Add(group.CustomerGroupId); + storeManagers.Add(groupId); if (!string.IsNullOrEmpty(group.StaffStoreId)) stores.Add(group.StaffStoreId); break; case SystemCustomerGroupNames.Vendors: - vendorGroups.Add(group.CustomerGroupId); + vendorGroups.Add(groupId); if (!string.IsNullOrEmpty(group.VendorId)) vendors.Add(group.VendorId); break; default: - custom.Add(group.CustomerGroupId); + custom.Add(groupId); break; } + } var kinds = (admins.Count > 0 ? 1 : 0) + (storeManagers.Count > 0 ? 1 : 0) + (vendorGroups.Count > 0 ? 1 : 0); var conflict = kinds > 1 || diff --git a/src/Business/Grand.Business.Authentication/Services/Scim/ScimUserService.cs b/src/Business/Grand.Business.Authentication/Services/Scim/ScimUserService.cs index 5378d1e1e..077dac967 100644 --- a/src/Business/Grand.Business.Authentication/Services/Scim/ScimUserService.cs +++ b/src/Business/Grand.Business.Authentication/Services/Scim/ScimUserService.cs @@ -115,8 +115,7 @@ public virtual async Task Replace(string id, ScimUserData data) { ArgumentNullException.ThrowIfNull(data); - var (customer, record) = await Load(id); - if (customer == null) + if (await Load(id) is not (var customer, var record)) return new ScimUserResult(ScimOutcome.NotFound); //every check before the first write: a refused replace changes nothing @@ -169,10 +168,9 @@ public virtual async Task Replace(string id, ScimUserData data) public virtual async Task Get(string id) { - var (customer, record) = await Load(id); - return customer == null - ? new ScimUserResult(ScimOutcome.NotFound) - : new ScimUserResult(ScimOutcome.Ok, await View(customer, record)); + return await Load(id) is (var customer, var record) + ? new ScimUserResult(ScimOutcome.Ok, await View(customer, record)) + : new ScimUserResult(ScimOutcome.NotFound); } public virtual async Task> List(string userName, string externalId, int skip, int take) @@ -211,8 +209,7 @@ public virtual async Task> List(string userName, string e /// public virtual async Task Delete(string id) { - var (customer, record) = await Load(id); - if (customer == null) + if (await Load(id) is not (var customer, var record)) return ScimOutcome.NotFound; //an account may have become a break-glass account since it was provisioned @@ -357,7 +354,7 @@ private async Task Insert(ScimUser record) } /// False for a user the provider deleted and creates again: it was managed already - private async Task TakeOverRefusal(Customer customer, string externalId, bool mustBeStaff) + private async Task TakeOverRefusal(Customer customer, string externalId, bool mustBeStaff) { var refusal = ScimProtection.Refusal(customer, loginConfig); if (refusal != null) @@ -387,19 +384,19 @@ private async Task TakeOverRefusal(Customer customer, string externalId, } //a deprovisioned user keeps its externalId for a re-creation, so it does not block another user - private async Task ExternalIdTaken(string externalId, string exceptId) => + private async Task ExternalIdTaken(string externalId, string? exceptId) => externalId != "" && await users.GetOneAsync(x => x.ExternalId == externalId && !x.Deprovisioned && x.Id != exceptId) != null; - private async Task<(Customer Customer, ScimUser Record)> Load(string id) + private async Task<(Customer Customer, ScimUser Record)?> Load(string id) { if (string.IsNullOrEmpty(id)) - return (null, null); + return null; var record = await users.GetByIdAsync(id); if (record is not { Deprovisioned: false }) - return (null, null); + return null; var customer = await customerService.GetCustomerById(id); - return customer is { Deleted: false } ? (customer, record) : (null, null); + return customer is { Deleted: false } ? (customer, record) : null; } private async Task View(Customer customer, ScimUser record) @@ -419,10 +416,10 @@ private async Task View(Customer customer, ScimUser record) record.UpdatedOnUtc ?? record.CreatedOnUtc); } - private static bool OwnedByOther(Customer found, Customer customer) => found != null && found.Id != customer.Id; + private static bool OwnedByOther(Customer? found, Customer customer) => found != null && found.Id != customer.Id; //the first of userName and the e-mails that is an e-mail address, lower-cased - private static string EmailOf(ScimUserData data) => + private static string? EmailOf(ScimUserData data) => new[] { data.UserName, data.Email } .Select(x => x?.Trim()) .FirstOrDefault(x => !string.IsNullOrEmpty(x) && CommonHelper.IsValidEmail(x)) diff --git a/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs index f8ea4aa56..5accf03f0 100644 --- a/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs +++ b/src/Business/Grand.Business.Authentication/Services/TwoFactorAuthenticationService.cs @@ -30,22 +30,23 @@ public TwoFactorAuthenticationService( _twoFactorAuthentication = new TwoFactorAuthenticator(); } - public virtual async Task AuthenticateTwoFactor(string secretKey, string token, Customer customer, + public virtual async Task AuthenticateTwoFactor(string? secretKey, string? token, Customer customer, TwoFactorAuthenticationType twoFactorAuthenticationType) { switch (twoFactorAuthenticationType) { case TwoFactorAuthenticationType.AppVerification: - return _twoFactorAuthentication.ValidateTwoFactorPIN(secretKey, token.Trim()); + //an account without a secret key has no authenticator app set up; no code proves nothing + return secretKey != null && token != null && + _twoFactorAuthentication.ValidateTwoFactorPIN(secretKey, token.Trim()); case TwoFactorAuthenticationType.EmailVerification: return await UseEmailCode(customer, token?.Trim()); case TwoFactorAuthenticationType.SMSVerification: - if (!_smsVerificationService.Any()) - throw new Exception("ISMSVerificationService not registered in DI container"); - var smsVerificationService = _smsVerificationService.FirstOrDefault(); - return await smsVerificationService!.Authenticate(secretKey, token.Trim(), customer); + var smsVerificationService = _smsVerificationService.FirstOrDefault() ?? + throw new Exception("ISMSVerificationService not registered in DI container"); + return await smsVerificationService.Authenticate(secretKey, token?.Trim(), customer); default: return false; } @@ -87,7 +88,7 @@ await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.TwoFac } //a code signs in once: it is read again and cleared under a lock, so two requests with it cannot both pass - private async Task UseEmailCode(Customer customer, string token) + private async Task UseEmailCode(Customer customer, string? token) { await using var _ = await _resourceLock.Acquire([$"TwoFactorCode:{customer.Id}"]); @@ -111,7 +112,7 @@ private static string PrepareRandomCode() return RandomNumberGenerator.GetInt32(1_000_000).ToString("D6"); } - private static bool CodesMatch(string expected, string given) + private static bool CodesMatch(string expected, string? given) { return given != null && CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(given)); diff --git a/src/Business/Grand.Business.Catalog/Events/Handlers/WarehouseDeletedEventHandler.cs b/src/Business/Grand.Business.Catalog/Events/Handlers/WarehouseDeletedEventHandler.cs index 31aac4ca3..5fbfa5f1d 100644 --- a/src/Business/Grand.Business.Catalog/Events/Handlers/WarehouseDeletedEventHandler.cs +++ b/src/Business/Grand.Business.Catalog/Events/Handlers/WarehouseDeletedEventHandler.cs @@ -58,7 +58,7 @@ private async Task RemoveWarehouseRow(string productId, string warehouseId) var product = await _productRepository.GetByIdAsync(productId); var row = product?.ProductWarehouseInventory.FirstOrDefault(x => x.WarehouseId == warehouseId); - if (row == null) + if (product == null || row == null) return; if (product.ManageInventoryMethodId != ManageInventoryMethod.ManageStock || !product.UseMultipleWarehouses) diff --git a/src/Business/Grand.Business.Catalog/Grand.Business.Catalog.csproj b/src/Business/Grand.Business.Catalog/Grand.Business.Catalog.csproj index 8287b3943..8b7815aca 100644 --- a/src/Business/Grand.Business.Catalog/Grand.Business.Catalog.csproj +++ b/src/Business/Grand.Business.Catalog/Grand.Business.Catalog.csproj @@ -6,4 +6,7 @@ + + enable + diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountAmountProviderHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountAmountProviderHandler.cs index e43259244..50c434b00 100644 --- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountAmountProviderHandler.cs +++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountAmountProviderHandler.cs @@ -29,7 +29,7 @@ public Task Handle(GetDiscountAmountProvider request, CancellationToken /// /// /// - private async Task GetDiscountAmountProvider(Discount discount, Customer customer, Product product, + private async Task GetDiscountAmountProvider(Discount discount, Customer customer, Product? product, double amount) { var discountAmountProvider = diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetProductArchByIdQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetProductArchByIdQueryHandler.cs index e9ca46e3f..f5b1fd115 100644 --- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetProductArchByIdQueryHandler.cs +++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetProductArchByIdQueryHandler.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Catalog.Queries.Handlers; -public class GetProductArchByIdQueryHandler : IRequestHandler +public class GetProductArchByIdQueryHandler : IRequestHandler { private readonly IRepository _productDeletedRepository; @@ -14,7 +14,7 @@ public GetProductArchByIdQueryHandler(IRepository productDeleted _productDeletedRepository = productDeletedRepository; } - public async Task Handle(GetProductArchByIdQuery request, CancellationToken cancellationToken) + public async Task Handle(GetProductArchByIdQuery request, CancellationToken cancellationToken) { return await _productDeletedRepository.GetByIdAsync(request.Id); } diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs index 750efd03f..ec1e5d495 100644 --- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs +++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetSearchProductsQueryHandler.cs @@ -60,7 +60,7 @@ public GetSearchProductsQueryHandler( var allowedCustomerGroupsIds = request.CustomerGroupIds?.ToArray() ?? (request.ShowHidden || _accessControlConfig.IgnoreAcl ? [] - : request.Customer.GetCustomerGroupIds()); + : request.Customer?.GetCustomerGroupIds() ?? []); var search = TextSearchTerms(request); if (search != null) @@ -84,7 +84,7 @@ public GetSearchProductsQueryHandler( } private async Task<(IPagedList products, IList filterableSpecificationAttributeOptionIds)> Search( - GetSearchProductsQuery request, string[] allowedCustomerGroupsIds, string search, + GetSearchProductsQuery request, string[] allowedCustomerGroupsIds, string? search, CancellationToken cancellationToken) { // Build base query; a text search narrows the candidates to products with a whole query word, @@ -166,13 +166,13 @@ private async Task LoadListingSummary(GetSearchProductsQuery req /// private string ListingSummaryHash(GetSearchProductsQuery request, string[] allowedCustomerGroupsIds) { - static string[] Set(IEnumerable values) + static string[] Set(IEnumerable? values) { return values?.Order(StringComparer.Ordinal).ToArray() ?? []; } //JSON keeps the fields apart - a separator inside a tag or an id is escaped - and formats numbers invariantly - var filters = JsonSerializer.Serialize(new object[] { + var filters = JsonSerializer.Serialize(new object?[] { Set(request.CategoryIds), request.FeaturedProducts, request.BrandId, request.CollectionId, request.StoreId, request.VendorId, request.WarehouseId, request.ProductType, request.VisibleIndividuallyOnly, request.MarkedAsNewOnly, request.ShowOnHomePage, @@ -258,7 +258,7 @@ private static void CleanupRequestParameters(GetSearchProductsQuery request) IQueryable query, IQueryable querySpecification) { - var specAttributeMapping = await BuildSpecificationAttributeMapping(request.FilteredSpecs, querySpecification); + var specAttributeMapping = await BuildSpecificationAttributeMapping(request.FilteredSpecs ?? [], querySpecification); // Apply filters for each specification attribute foreach (var item in specAttributeMapping.Dictionary) @@ -266,7 +266,7 @@ private static void CleanupRequestParameters(GetSearchProductsQuery request) query = query.Where(x => x.ProductSpecificationAttributes.Any(y => y.SpecificationAttributeId == item.Key && y.AllowFiltering && - item.Value.Contains(y.SpecificationAttributeOptionId))); + y.SpecificationAttributeOptionId != null && item.Value.Contains(y.SpecificationAttributeOptionId))); } return (query, specAttributeMapping.QuerySpecification); @@ -301,8 +301,9 @@ private static void CleanupRequestParameters(GetSearchProductsQuery request) private static IQueryable ApplySpecificationOptions(GetSearchProductsQuery request, IQueryable query) { + var options = request.SpecificationOptions ?? []; return query.Where(x => x.ProductSpecificationAttributes.Any(y => - request.SpecificationOptions.Contains(y.SpecificationAttributeOptionId))); + y.SpecificationAttributeOptionId != null && options.Contains(y.SpecificationAttributeOptionId))); } private bool ShouldLoadFilterableSpecifications(GetSearchProductsQuery request) @@ -326,7 +327,7 @@ from item in p.ProductSpecificationAttributes .Select(x => x.SpecificationAttributeOptionId) .Distinct(); - return await _productRepository.ToListAsync(optionIds, cancellationToken); + return (await _productRepository.ToListAsync(optionIds, cancellationToken)).OfType().ToList(); } private IQueryable FilterQueryable(GetSearchProductsQuery request, IQueryable query, string[] allowedCustomerGroupsIds) @@ -357,9 +358,9 @@ private static IQueryable ApplyCategoryFiltering(GetSearchProductsQuery if (request.CategoryIds != null && request.CategoryIds.Any()) { if (request.FeaturedProducts.HasValue) - query = query.Where(x => x.ProductCategories.Any(y => request.CategoryIds.Contains(y.CategoryId) && y.IsFeaturedProduct == request.FeaturedProducts)); + query = query.Where(x => x.ProductCategories.Any(y => y.CategoryId != null && request.CategoryIds.Contains(y.CategoryId) && y.IsFeaturedProduct == request.FeaturedProducts)); else - query = query.Where(x => x.ProductCategories.Any(y => request.CategoryIds.Contains(y.CategoryId))); + query = query.Where(x => x.ProductCategories.Any(y => y.CategoryId != null && request.CategoryIds.Contains(y.CategoryId))); } return query; } @@ -457,7 +458,7 @@ private static IQueryable ApplyNewProductFiltering(GetSearchProductsQue return query; } - private string TextSearchTerms(GetSearchProductsQuery request) + private string? TextSearchTerms(GetSearchProductsQuery request) { //staff search by fragments and partial SKUs. The text index does not cover descriptions if (!_databaseConfig.UseProductTextSearch || request.ShowHidden || request.SearchDescriptions || @@ -487,7 +488,7 @@ private static IQueryable ApplyKeywordFiltering(GetSearchProductsQuery { //a SKU search finds a product by its own SKU and by the SKU of any of its attribute combinations if (!request.SearchDescriptions) - query = query.Where(p => p.Name.ToLower().Contains(request.Keywords.ToLower()) || p.Locales.Any(x => x.LocaleKey == "Name" && x.LocaleValue != null && x.LocaleValue.ToLower().Contains(request.Keywords.ToLower())) || (request.SearchSku && p.Sku != null && p.Sku.ToLower().Contains(request.Keywords.ToLower())) || (request.SearchSku && p.ProductAttributeCombinations.Any(c => c.Sku != null && c.Sku.ToLower().Contains(request.Keywords.ToLower())))); + query = query.Where(p => (p.Name != null && p.Name.ToLower().Contains(request.Keywords.ToLower())) || p.Locales.Any(x => x.LocaleKey == "Name" && x.LocaleValue != null && x.LocaleValue.ToLower().Contains(request.Keywords.ToLower())) || (request.SearchSku && p.Sku != null && p.Sku.ToLower().Contains(request.Keywords.ToLower())) || (request.SearchSku && p.ProductAttributeCombinations.Any(c => c.Sku != null && c.Sku.ToLower().Contains(request.Keywords.ToLower())))); else query = query.Where(p => (p.Name != null && p.Name.ToLower().Contains(request.Keywords.ToLower())) || (p.ShortDescription != null && p.ShortDescription.ToLower().Contains(request.Keywords.ToLower())) || (p.FullDescription != null && p.FullDescription.ToLower().Contains(request.Keywords.ToLower())) || p.Locales.Any(x => x.LocaleValue != null && x.LocaleValue.ToLower().Contains(request.Keywords.ToLower())) || (request.SearchSku && p.Sku != null && p.Sku.ToLower().Contains(request.Keywords.ToLower())) || (request.SearchSku && p.ProductAttributeCombinations.Any(c => c.Sku != null && c.Sku.ToLower().Contains(request.Keywords.ToLower())))); } diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetShoppingCartItemsSubTotalQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetShoppingCartItemsSubTotalQueryHandler.cs index 180ee4771..5ad025770 100644 --- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetShoppingCartItemsSubTotalQueryHandler.cs +++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetShoppingCartItemsSubTotalQueryHandler.cs @@ -3,6 +3,7 @@ using Grand.Business.Core.Interfaces.Common.Directory; using Grand.Business.Core.Queries.Catalog; using Grand.Mediator; +using Grand.SharedKernel; namespace Grand.Business.Catalog.Queries.Handlers; @@ -28,7 +29,8 @@ public async Task Handle(GetShoppingCartItemsSubTotalQuery request, Canc ArgumentNullException.ThrowIfNull(request.Store); //priced for the customer of the request, not the ambient one, in the currency the requirement is entered in - var currency = await _currencyService.GetPrimaryStoreCurrency(); + var currency = await _currencyService.GetPrimaryStoreCurrency() ?? + throw new GrandException("The primary store currency is not set"); double subTotal = 0; foreach (var item in request.Items) diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetVendorByIdQueryHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetVendorByIdQueryHandler.cs index ce8bdf5da..1189b15a9 100644 --- a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetVendorByIdQueryHandler.cs +++ b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetVendorByIdQueryHandler.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Catalog.Queries.Handlers; -public class GetVendorByIdQueryHandler : IRequestHandler +public class GetVendorByIdQueryHandler : IRequestHandler { private readonly IRepository _vendorRepository; @@ -14,10 +14,10 @@ public GetVendorByIdQueryHandler(IRepository vendorRepository) _vendorRepository = vendorRepository; } - public Task Handle(GetVendorByIdQuery request, CancellationToken cancellationToken) + public Task Handle(GetVendorByIdQuery request, CancellationToken cancellationToken) { return string.IsNullOrWhiteSpace(request.Id) - ? Task.FromResult(null) + ? Task.FromResult(null) : _vendorRepository.GetByIdAsync(request.Id); } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Catalog/Services/Brands/BrandLayoutService.cs b/src/Business/Grand.Business.Catalog/Services/Brands/BrandLayoutService.cs index 4867b423d..eef205956 100644 --- a/src/Business/Grand.Business.Catalog/Services/Brands/BrandLayoutService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Brands/BrandLayoutService.cs @@ -62,7 +62,7 @@ orderby pt.DisplayOrder /// /// Brand layout /// Brand layout - public virtual Task GetBrandLayoutById(string brandLayoutId) + public virtual Task GetBrandLayoutById(string brandLayoutId) { var key = string.Format(CacheKey.BRAND_LAYOUT_BY_ID_KEY, brandLayoutId); return _cacheBase.GetAsync(key, () => _brandLayoutRepository.GetByIdAsync(brandLayoutId)); diff --git a/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs b/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs index 3702dd958..66b7babbb 100644 --- a/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs @@ -96,7 +96,7 @@ public virtual async Task> GetAllBrands(string brandName, /// /// Brand id /// Brand - public virtual Task GetBrandById(string brandId) + public virtual Task GetBrandById(string brandId) { var key = string.Format(CacheKey.BRANDS_BY_ID_KEY, brandId); return _cacheBase.GetAsync(key, () => _brandRepository.GetByIdAsync(brandId)); diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryLayoutService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryLayoutService.cs index ab5a71ab9..8dba2ed7b 100644 --- a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryLayoutService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryLayoutService.cs @@ -62,7 +62,7 @@ orderby pt.DisplayOrder /// /// Category layout identifier /// Category layout - public virtual Task GetCategoryLayoutById(string categoryLayoutId) + public virtual Task GetCategoryLayoutById(string categoryLayoutId) { var key = string.Format(CacheKey.CATEGORY_LAYOUT_BY_ID_KEY, categoryLayoutId); return _cacheBase.GetAsync(key, () => _categoryLayoutRepository.GetByIdAsync(categoryLayoutId)); diff --git a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs index db5ac783a..fbb5fb77b 100644 --- a/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Categories/CategoryService.cs @@ -65,7 +65,7 @@ public CategoryService(ICacheBase cacheBase, /// Page index /// Page size /// Categories - public virtual async Task> GetAllCategories(string parentId, string categoryName, + public virtual async Task> GetAllCategories(string? parentId, string categoryName, CatalogAccess access, int pageIndex = 0, int pageSize = int.MaxValue) { ArgumentNullException.ThrowIfNull(access); @@ -200,7 +200,7 @@ public virtual async Task> GetAllCategoriesSearchBox(Customer cu /// Category /// Whose view of the categories to return, and the store whose limitations apply /// Category breadcrumb - public virtual async Task> GetCategoryBreadCrumb(Category category, CatalogAccess access) + public virtual async Task> GetCategoryBreadCrumb(Category? category, CatalogAccess access) { ArgumentNullException.ThrowIfNull(access); @@ -231,7 +231,7 @@ public virtual async Task> GetCategoryBreadCrumb(Category catego /// All categories /// Whose view of the categories to return, and the store whose limitations apply /// Category breadcrumb - public virtual IList GetCategoryBreadCrumb(Category category, IList allCategories, + public virtual IList GetCategoryBreadCrumb(Category? category, IList allCategories, CatalogAccess access) { ArgumentNullException.ThrowIfNull(access); @@ -266,7 +266,7 @@ public virtual IList GetCategoryBreadCrumb(Category category, IListSeparator /// Language ID /// Formatted breadcrumb - public virtual async Task GetFormattedBreadCrumb(Category category, string separator = ">>", + public virtual async Task GetFormattedBreadCrumb(Category category, string separator = ">>", string languageId = "") { var result = string.Empty; @@ -292,7 +292,7 @@ public virtual async Task GetFormattedBreadCrumb(Category category, stri /// Separator /// Language ID /// Formatted breadcrumb - public virtual string GetFormattedBreadCrumb(Category category, + public virtual string? GetFormattedBreadCrumb(Category category, IList allCategories, string separator = ">>", string languageId = "") { var result = string.Empty; @@ -327,7 +327,7 @@ where c.AppliedDiscounts.Any(x => x == discountId) /// /// Category identifier /// Category - public virtual async Task GetCategoryById(string categoryId) + public virtual async Task GetCategoryById(string? categoryId) { var key = string.Format(CacheKey.CATEGORIES_BY_ID_KEY, categoryId); return await _cacheBase.GetAsync(key, () => _categoryRepository.GetByIdAsync(categoryId)); diff --git a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionLayoutService.cs b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionLayoutService.cs index 3f252f6da..802b6ecff 100644 --- a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionLayoutService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionLayoutService.cs @@ -62,7 +62,7 @@ orderby pt.DisplayOrder /// /// Collection layout id /// Collection layout - public virtual Task GetCollectionLayoutById(string collectionLayoutId) + public virtual Task GetCollectionLayoutById(string collectionLayoutId) { var key = string.Format(CacheKey.COLLECTION_LAYOUT_BY_ID_KEY, collectionLayoutId); return _cacheBase.GetAsync(key, () => _collectionLayoutRepository.GetByIdAsync(collectionLayoutId)); diff --git a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs index e78d13265..c382e7048 100644 --- a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs @@ -120,7 +120,7 @@ public virtual async Task> GetAllCollectionFeaturedProductsOnH /// /// Collection id /// Collection - public virtual Task GetCollectionById(string collectionId) + public virtual Task GetCollectionById(string? collectionId) { var key = string.Format(CacheKey.COLLECTIONS_BY_ID_KEY, collectionId); return _cacheBase.GetAsync(key, () => _collectionRepository.GetByIdAsync(collectionId)); diff --git a/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs b/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs index ccb43e003..c8dc7870f 100644 --- a/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Directory/MeasureService.cs @@ -61,7 +61,7 @@ public MeasureService(ICacheBase cacheBase, /// /// Measure dimension identifier /// Measure dimension - public virtual Task GetMeasureDimensionById(string measureDimensionId) + public virtual Task GetMeasureDimensionById(string? measureDimensionId) { var key = string.Format(CacheKey.MEASUREDIMENSIONS_BY_ID_KEY, measureDimensionId); return _cacheBase.GetAsync(key, () => _measureDimensionRepository.GetByIdAsync(measureDimensionId)); @@ -72,7 +72,7 @@ public virtual Task GetMeasureDimensionById(string measureDime /// /// The system keyword /// Measure dimension - public virtual async Task GetMeasureDimensionBySystemKeyword(string systemKeyword) + public virtual async Task GetMeasureDimensionBySystemKeyword(string systemKeyword) { if (string.IsNullOrEmpty(systemKeyword)) return null; @@ -179,7 +179,7 @@ public virtual async Task ConvertToPrimaryMeasureDimension(double value, var result = value; var baseDimensionIn = await GetMeasureDimensionById(_measureSettings.BaseDimensionId); - if (sourceMeasureDimension.Id == baseDimensionIn.Id) return result; + if (sourceMeasureDimension.Id == baseDimensionIn?.Id) return result; result /= sourceMeasureDimension.Ratio; return result; } @@ -197,7 +197,7 @@ public virtual async Task ConvertFromPrimaryMeasureDimension(double valu var result = value; var baseDimensionIn = await GetMeasureDimensionById(_measureSettings.BaseDimensionId); - if (targetMeasureDimension.Id == baseDimensionIn.Id) return result; + if (targetMeasureDimension.Id == baseDimensionIn?.Id) return result; result *= targetMeasureDimension.Ratio; return result; } @@ -211,7 +211,7 @@ public virtual async Task ConvertFromPrimaryMeasureDimension(double valu /// /// Measure weight identifier /// Measure weight - public virtual Task GetMeasureWeightById(string measureWeightId) + public virtual Task GetMeasureWeightById(string? measureWeightId) { var key = string.Format(CacheKey.MEASUREWEIGHTS_BY_ID_KEY, measureWeightId); return _cacheBase.GetAsync(key, () => _measureWeightRepository.GetByIdAsync(measureWeightId)); @@ -222,7 +222,7 @@ public virtual Task GetMeasureWeightById(string measureWeightId) /// /// The system keyword /// Measure weight - public virtual async Task GetMeasureWeightBySystemKeyword(string systemKeyword) + public virtual async Task GetMeasureWeightBySystemKeyword(string systemKeyword) { if (string.IsNullOrEmpty(systemKeyword)) return null; @@ -328,7 +328,7 @@ public virtual async Task ConvertToPrimaryMeasureWeight(double value, Me var result = value; var baseWeightIn = await GetMeasureWeightById(_measureSettings.BaseWeightId); - if (sourceMeasureWeight.Id == baseWeightIn.Id) return result; + if (sourceMeasureWeight.Id == baseWeightIn?.Id) return result; result /= sourceMeasureWeight.Ratio; return result; } @@ -346,7 +346,7 @@ public virtual async Task ConvertFromPrimaryMeasureWeight(double value, var result = value; var baseWeightIn = await GetMeasureWeightById(_measureSettings.BaseWeightId); - if (targetMeasureWeight.Id == baseWeightIn.Id) return result; + if (targetMeasureWeight.Id == baseWeightIn?.Id) return result; result *= targetMeasureWeight.Ratio; return result; } @@ -360,7 +360,7 @@ public virtual async Task ConvertFromPrimaryMeasureWeight(double value, /// /// Measure unit identifier /// Measure dimension - public virtual Task GetMeasureUnitById(string measureUnitId) + public virtual Task GetMeasureUnitById(string measureUnitId) { var key = string.Format(CacheKey.MEASUREUNITS_BY_ID_KEY, measureUnitId); return _cacheBase.GetAsync(key, () => _measureUnitRepository.GetByIdAsync(measureUnitId)); diff --git a/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs b/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs index 664a77b8b..6b1294a17 100644 --- a/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Directory/SearchTermService.cs @@ -52,7 +52,7 @@ public virtual async Task DeleteSearchTerm(SearchTerm searchTerm) /// /// Search term identifier /// Search term - public virtual Task GetSearchTermById(string searchTermId) + public virtual Task GetSearchTermById(string searchTermId) { return _searchTermRepository.GetByIdAsync(searchTermId); } @@ -63,7 +63,7 @@ public virtual Task GetSearchTermById(string searchTermId) /// Search term keyword /// Store identifier /// Search term - public virtual async Task GetSearchTermByKeyword(string keyword, string storeId) + public virtual async Task GetSearchTermByKeyword(string keyword, string storeId) { if (string.IsNullOrEmpty(keyword)) return null; diff --git a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountProviderLoader.cs b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountProviderLoader.cs index 250293664..b0c20b34e 100644 --- a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountProviderLoader.cs +++ b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountProviderLoader.cs @@ -19,7 +19,7 @@ public DiscountProviderLoader(IEnumerable discountProviders, /// /// Rule system name /// Found discount - public virtual IDiscountProvider LoadDiscountProviderByRuleSystemName(string ruleSystemName) + public virtual IDiscountProvider? LoadDiscountProviderByRuleSystemName(string? ruleSystemName) { var discountPlugins = LoadAllDiscountProviders(); foreach (var discountPlugin in discountPlugins) @@ -57,7 +57,7 @@ public virtual IList LoadDiscountAmountProviders() /// /// /// - public virtual IDiscountAmountProvider LoadDiscountAmountProviderBySystemName(string systemName) + public virtual IDiscountAmountProvider? LoadDiscountAmountProviderBySystemName(string? systemName) { return _discountAmountProviders.FirstOrDefault(x => x.SystemName.Equals(systemName, StringComparison.OrdinalIgnoreCase)); diff --git a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs index 14b83aa1f..31be44ea6 100644 --- a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountService.cs @@ -62,7 +62,7 @@ public DiscountService(ICacheBase cacheBase, /// /// Discount identifier /// Discount - public virtual Task GetDiscountById(string discountId) + public virtual Task GetDiscountById(string? discountId) { var key = string.Format(CacheKey.DISCOUNTS_BY_ID_KEY, discountId); return _cacheBase.GetAsync(key, () => _discountRepository.GetByIdAsync(discountId)); @@ -170,7 +170,7 @@ public virtual async Task DeleteDiscount(Discount discount) /// Coupon code /// A value that indicates if it should shows hidden records /// Discount - public virtual async Task GetDiscountByCouponCode(string couponCode, bool showHidden = false) + public virtual async Task GetDiscountByCouponCode(string couponCode, bool showHidden = false) { if (string.IsNullOrWhiteSpace(couponCode)) return null; @@ -208,7 +208,7 @@ public virtual async Task> GetAllCouponCodesByDiscoun /// Gets a discount /// /// Discount - public virtual Task GetDiscountCodeById(string id) + public virtual Task GetDiscountCodeById(string id) { return _discountCouponRepository.GetByIdAsync(id); } @@ -218,7 +218,7 @@ public virtual Task GetDiscountCodeById(string id) /// /// Coupon code /// - public virtual async Task GetDiscountCodeByCode(string couponCode) + public virtual async Task GetDiscountCodeByCode(string couponCode) { return await _discountCouponRepository.GetOneAsync(x => x.CouponCode == couponCode); } @@ -253,7 +253,7 @@ public virtual async Task InsertDiscountCoupon(DiscountCoupon coupon) /// /// /// - public virtual async Task DiscountCouponSetAsUsed(string couponCode, bool used) + public virtual async Task DiscountCouponSetAsUsed(string? couponCode, bool used) { if (string.IsNullOrEmpty(couponCode)) return; @@ -297,7 +297,7 @@ public virtual async Task CancelDiscount(string orderId) /// /// Discount usage history record identifier /// Discount usage history - public virtual Task GetDiscountUsageHistoryById(string discountUsageHistoryId) + public virtual Task GetDiscountUsageHistoryById(string discountUsageHistoryId) { return _discountUsageHistoryRepository.GetByIdAsync(discountUsageHistoryId); } @@ -368,6 +368,9 @@ public virtual async Task TryInsertDiscountUsageHistory(Discount discount, if (singleUseCoupon) { + //a single-use coupon is recorded with its code + if (discountUsageHistory.CouponCode == null) + return false; var coupon = await GetDiscountCodeByCode(discountUsageHistory.CouponCode); if (coupon == null || coupon.DiscountId != discount.Id || coupon.Used) return false; @@ -380,6 +383,7 @@ public virtual async Task TryInsertDiscountUsageHistory(Discount discount, public virtual async Task ReleaseDiscountUsageHistory(DiscountUsageHistory discountUsageHistory) { ArgumentNullException.ThrowIfNull(discountUsageHistory); + ArgumentException.ThrowIfNullOrEmpty(discountUsageHistory.DiscountId); await using var _ = await _resourceLock.Acquire([LockKey(discountUsageHistory.DiscountId)]); @@ -396,7 +400,7 @@ public virtual async Task ReleaseDiscountUsageHistory(DiscountUsageHistory disco /// Customer /// Product public virtual async Task GetDiscountAmount(Discount discount, Customer customer, Currency currency, - Product product, double amount) + Product? product, double amount) { ArgumentNullException.ThrowIfNull(discount); @@ -436,7 +440,7 @@ public virtual async Task GetDiscountAmount(Discount discount, Customer /// Amount /// Preferred discount public virtual async Task<(List appliedDiscount, double discountAmount)> GetPreferredDiscount( - IList discounts, Customer customer, Currency currency, Product product, + IList discounts, Customer customer, Currency currency, Product? product, double amount) { ArgumentNullException.ThrowIfNull(discounts); @@ -449,7 +453,10 @@ public virtual async Task GetDiscountAmount(Discount discount, Customer //check simple discounts foreach (var applieddiscount in discounts) { + //a discount deleted meanwhile gives nothing var discount = await GetDiscountById(applieddiscount.DiscountId); + if (discount == null) + continue; var currentDiscountValue = await GetDiscountAmount(discount, customer, currency, product, amount); if (!(currentDiscountValue > discountAmount)) continue; discountAmount = currentDiscountValue; @@ -465,7 +472,8 @@ public virtual async Task GetDiscountAmount(Discount discount, Customer foreach (var item in cumulativeDiscounts) { var discount = await GetDiscountById(item.DiscountId); - cumulativeDiscountAmount += await GetDiscountAmount(discount, customer, currency, product, amount); + if (discount != null) + cumulativeDiscountAmount += await GetDiscountAmount(discount, customer, currency, product, amount); } if (!(cumulativeDiscountAmount > discountAmount)) return (appliedDiscount, discountAmount); diff --git a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountValidationService.cs b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountValidationService.cs index 530335039..dee7df7bf 100644 --- a/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountValidationService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Discounts/DiscountValidationService.cs @@ -39,10 +39,9 @@ public virtual async Task ValidateDiscount(Discount di Currency currency) { ArgumentNullException.ThrowIfNull(discount); + ArgumentNullException.ThrowIfNull(customer); - string[] couponCodesToValidate = null; - if (customer != null) - couponCodesToValidate = customer.ParseAppliedCouponCodes(SystemCustomerFieldNames.DiscountCoupons); + var couponCodesToValidate = customer.ParseAppliedCouponCodes(SystemCustomerFieldNames.DiscountCoupons); return await ValidateDiscount(discount, customer, store, currency, couponCodesToValidate); } @@ -78,7 +77,7 @@ public virtual Task ValidateDiscount(Discount discount /// Discount validation result public virtual async Task ValidateDiscount(Discount discount, Customer customer, Store store, - Currency currency, string[] couponCodesToValidate) + Currency currency, string[]? couponCodesToValidate) { ArgumentNullException.ThrowIfNull(discount); ArgumentNullException.ThrowIfNull(customer); @@ -218,7 +217,7 @@ public virtual async Task ValidateDiscount(Discount di /// /// Counts the usage history of a discount, of one customer when customerId is set /// - private Task GetUsedTimes(string discountId, string customerId) + private Task GetUsedTimes(string discountId, string? customerId) { var query = _discountUsageHistoryRepository.Table.Where(x => x.DiscountId == discountId); if (!string.IsNullOrEmpty(customerId)) diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandImportDataObject.cs index 00d2a2429..d1752f3ce 100644 --- a/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandImportDataObject.cs +++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandImportDataObject.cs @@ -133,7 +133,7 @@ private static string Key(BrandDto dto) /// Resolves the existing entity by Id; in Row mode, when no Id is given, by SeName, and with neither, by its stored /// name (any case) - more than one brand of that name is an error /// - private async Task<(Brand brand, bool matchedByName, string error)> FindBrand(BrandDto dto, ImportMode mode) + private async Task<(Brand? brand, bool matchedByName, string? error)> FindBrand(BrandDto dto, ImportMode mode) { if (!string.IsNullOrEmpty(dto.Id)) return (await _brandService.GetBrandById(dto.Id), false, null); @@ -153,7 +153,7 @@ private static string Key(BrandDto dto) return (found, found != null, error); } - private async Task UpdateBrandData(Brand brand, DownloadedImage image) + private async Task UpdateBrandData(Brand brand, DownloadedImage? image) { if (string.IsNullOrEmpty(brand.BrandLayoutId)) { diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandSchemaProperty.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandSchemaProperty.cs index 90f8b9626..b2c1f77c1 100644 --- a/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandSchemaProperty.cs +++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/BrandSchemaProperty.cs @@ -40,7 +40,7 @@ public virtual async Task[]> GetProperties(IEnumerable GetPictures(string pictureId) + protected virtual async Task GetPictures(string pictureId) { var picture = await _pictureService.GetPictureById(pictureId); return await _pictureService.GetThumbPhysicalPath(picture); diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/CategoryImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/CategoryImportDataObject.cs index fa58a96b1..9658db0fb 100644 --- a/src/Business/Grand.Business.Catalog/Services/ExportImport/CategoryImportDataObject.cs +++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/CategoryImportDataObject.cs @@ -138,7 +138,7 @@ private static string Key(CategoryDto dto) /// Resolves the existing entity by Id; in Row mode, when no Id is given, by SeName, and with neither, by its stored /// name (any case) - under the row's parent when it names one; more than one category of that name is an error /// - private async Task<(Category category, bool matchedByName, string error)> FindCategory(CategoryDto dto, + private async Task<(Category? category, bool matchedByName, string? error)> FindCategory(CategoryDto dto, ImportMode mode) { if (!string.IsNullOrEmpty(dto.Id)) @@ -161,7 +161,7 @@ private static string Key(CategoryDto dto) } private async Task UpdateCategoryData(CategoryDto categoryDto, Category category, bool parentMissing, - DownloadedImage image) + DownloadedImage? image) { if (string.IsNullOrEmpty(category.CategoryLayoutId)) { diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/CategorySchemaProperty.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/CategorySchemaProperty.cs index fa2f22d22..7794d1c42 100644 --- a/src/Business/Grand.Business.Catalog/Services/ExportImport/CategorySchemaProperty.cs +++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/CategorySchemaProperty.cs @@ -46,7 +46,7 @@ public virtual async Task[]> GetProperties(IEnumerable< return properties; } - protected virtual async Task GetPictures(string pictureId) + protected virtual async Task GetPictures(string pictureId) { var picture = await _pictureService.GetPictureById(pictureId); return await _pictureService.GetThumbPhysicalPath(picture); diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionImportDataObject.cs index 3f0579555..be9fed9c4 100644 --- a/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionImportDataObject.cs +++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionImportDataObject.cs @@ -133,7 +133,7 @@ private static string Key(CollectionDto dto) /// Resolves the existing entity by Id; in Row mode, when no Id is given, by SeName, and with neither, by its stored /// name (any case) - more than one collection of that name is an error /// - private async Task<(Collection collection, bool matchedByName, string error)> FindCollection(CollectionDto dto, + private async Task<(Collection? collection, bool matchedByName, string? error)> FindCollection(CollectionDto dto, ImportMode mode) { if (!string.IsNullOrEmpty(dto.Id)) @@ -154,7 +154,7 @@ private static string Key(CollectionDto dto) return (found, found != null, error); } - private async Task UpdateCollectionData(Collection collection, DownloadedImage image) + private async Task UpdateCollectionData(Collection collection, DownloadedImage? image) { if (string.IsNullOrEmpty(collection.CollectionLayoutId)) { diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionSchemaProperty.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionSchemaProperty.cs index c4bd38b53..ddc8aefd5 100644 --- a/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionSchemaProperty.cs +++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/CollectionSchemaProperty.cs @@ -40,7 +40,7 @@ public virtual async Task[]> GetProperties(IEnumerabl return properties; } - protected virtual async Task GetPictures(string pictureId) + protected virtual async Task GetPictures(string pictureId) { var picture = await _pictureService.GetPictureById(pictureId); return await _pictureService.GetThumbPhysicalPath(picture); diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/DownloadUrl.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/DownloadUrl.cs index 4967a22ba..809de90a7 100644 --- a/src/Business/Grand.Business.Catalog/Services/ExportImport/DownloadUrl.cs +++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/DownloadUrl.cs @@ -57,7 +57,7 @@ public static class DownloadUrl /// , so the caller does not go on as if the picture were missing /// Image binary with the MIME type detected from its content, or null when the URL is not allowed, /// the download fails or the content is not a supported image - public static async Task DownloadImage(string url, string[] allowedPrivateHosts = null, + public static async Task DownloadImage(string url, string[]? allowedPrivateHosts = null, CancellationToken cancellationToken = default) { if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || @@ -95,7 +95,7 @@ public static async Task DownloadImage(string url, string[] all /// /// Returns the MIME type of a JPEG, PNG, GIF or WebP image based on its signature, or null for any other content /// - public static string DetectImageMimeType(ReadOnlySpan binary) + public static string? DetectImageMimeType(ReadOnlySpan binary) { if (binary.StartsWith((ReadOnlySpan)[0xFF, 0xD8, 0xFF])) return "image/jpeg"; @@ -168,7 +168,7 @@ private static bool IsHostMatch(string host, string allowed) return string.Equals(host, allowed, StringComparison.OrdinalIgnoreCase); } - private static async Task ReadLimited(HttpContent content, CancellationToken cancellationToken) + private static async Task ReadLimited(HttpContent content, CancellationToken cancellationToken) { await using var stream = await content.ReadAsStreamAsync(cancellationToken); using var buffer = new MemoryStream(); diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/ExportPictures.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/ExportPictures.cs index 30f4e566f..28c092cb0 100644 --- a/src/Business/Grand.Business.Catalog/Services/ExportImport/ExportPictures.cs +++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/ExportPictures.cs @@ -8,11 +8,11 @@ internal static class ExportPictures /// an entity without a picture exports an empty cell instead of the default picture's path, which an import would /// read back as a picture to download. A cancelled token stops before the next picture. /// - public static async Task> Preload(IEnumerable pictureIds, - Func> getPicture, CancellationToken cancellationToken = default) + public static async Task> Preload(IEnumerable pictureIds, + Func> getPicture, CancellationToken cancellationToken = default) { - var pictures = new Dictionary(); - foreach (var pictureId in pictureIds.Where(x => !string.IsNullOrEmpty(x)).Distinct()) + var pictures = new Dictionary(); + foreach (var pictureId in pictureIds.OfType().Where(x => x.Length > 0).Distinct()) { cancellationToken.ThrowIfCancellationRequested(); pictures[pictureId] = await getPicture(pictureId); diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/ImportHtmlGuard.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/ImportHtmlGuard.cs index ecc2a0c70..cd0faa118 100644 --- a/src/Business/Grand.Business.Catalog/Services/ExportImport/ImportHtmlGuard.cs +++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/ImportHtmlGuard.cs @@ -19,18 +19,18 @@ public ImportHtmlGuard(IHtmlSanitizationService htmlSanitizationService, Securit } /// Fields that may hold rich text (descriptions) - public IEnumerable RichTextErrors(params (string Field, string Value)[] fields) + public IEnumerable RichTextErrors(params (string Field, string? Value)[] fields) { return Errors(fields, _htmlSanitizationService.ContainsDisallowedRichText); } /// Fields that must be plain text (names, SEO fields) - public IEnumerable PlainTextErrors(params (string Field, string Value)[] fields) + public IEnumerable PlainTextErrors(params (string Field, string? Value)[] fields) { return Errors(fields, _htmlSanitizationService.ContainsMarkup); } - private IEnumerable Errors((string Field, string Value)[] fields, Func isDisallowed) + private IEnumerable Errors((string Field, string? Value)[] fields, Func isDisallowed) { if (!_securityConfig.EnableHtmlSanitization) yield break; diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/ImportPictures.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/ImportPictures.cs index 5bd57dce6..4eaaa8c53 100644 --- a/src/Business/Grand.Business.Catalog/Services/ExportImport/ImportPictures.cs +++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/ImportPictures.cs @@ -14,16 +14,16 @@ internal static class ImportPictures /// any file on the server /// /// The image, or null when there is no URL or it could not be downloaded - public static Task Download(string url, string[] allowedPrivateHosts, + public static Task Download(string? url, string[]? allowedPrivateHosts, CancellationToken cancellationToken) { return string.IsNullOrEmpty(url) - ? Task.FromResult(null) + ? Task.FromResult(null) : DownloadUrl.DownloadImage(url, allowedPrivateHosts, cancellationToken); } /// Whether the stored picture has the image's content, as sent or after validation (like in database) - public static async Task IsStored(IPictureService pictureService, string pictureId, DownloadedImage image) + public static async Task IsStored(IPictureService pictureService, string? pictureId, DownloadedImage image) { if (string.IsNullOrEmpty(pictureId)) return false; @@ -39,8 +39,8 @@ public static async Task IsStored(IPictureService pictureService, string p /// Stores the image as the entity's picture /// The new picture, or null when there is no image or the current picture already has its content - public static async Task Save(IPictureService pictureService, DownloadedImage image, string name, - string currentPictureId) + public static async Task Save(IPictureService pictureService, DownloadedImage? image, string? name, + string? currentPictureId) { if (image == null || await IsStored(pictureService, currentPictureId, image)) return null; diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/ImportRows.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/ImportRows.cs index 44cad9211..70901c7b4 100644 --- a/src/Business/Grand.Business.Catalog/Services/ExportImport/ImportRows.cs +++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/ImportRows.cs @@ -24,7 +24,7 @@ internal static class ImportRows /// spreadsheet import leaves it off, so its error still reaches the panel. /// public static async Task RunBatch(IReadOnlyList rows, bool dryRun, - Func id, Func key, Func> importRow, + Func id, Func key, Func> importRow, bool isolateFailures, ILogger logger, CancellationToken cancellationToken) { var results = new List(rows.Count); @@ -58,8 +58,8 @@ public static async Task RunBatch(IReadOnlyList r /// The entity a slug points to, when it is of . A slug - active or a past one - is /// reserved for one entity (ISeNameService.ValidateSeName), so it never resolves to two. /// - public static async Task FindBySlug(ISlugService slugService, string slug, string entityName, - Func> getById) where T : class + public static async Task FindBySlug(ISlugService slugService, string slug, string entityName, + Func> getById) where T : class { var url = await slugService.GetBySlug(slug); if (url == null || url.EntityName != entityName || string.IsNullOrEmpty(url.EntityId)) @@ -73,7 +73,7 @@ public static async Task FindBySlug(ISlugService slugService, string slug, /// "name contains" filter, so a de-duplicated slug (apple-2) does not hide the entity. More than one is an error: /// the row has to name the entity by Id or SeName. /// - public static (T match, string error) SingleByName(IEnumerable candidates, Func name, + public static (T? match, string? error) SingleByName(IEnumerable candidates, Func name, string wanted, string entity) where T : class { var matches = candidates.Where(c => string.Equals(name(c), wanted, StringComparison.OrdinalIgnoreCase)) diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductAttributeImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductAttributeImportDataObject.cs index 5ba0dbb36..906767e83 100644 --- a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductAttributeImportDataObject.cs +++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductAttributeImportDataObject.cs @@ -78,7 +78,7 @@ private async Task ImportRow(int row, ProductAttributeDto dto, existing?.Id ?? "", key, errors, warnings); var isNew = existing == null; - var attribute = existing ?? new ProductAttribute { Name = dto.Name }; + var attribute = existing ?? new ProductAttribute { Name = dto.Name ?? "" }; if (!string.IsNullOrEmpty(dto.Name)) attribute.Name = dto.Name; if (dto.Description != null) attribute.Description = dto.Description; if (seName != null) attribute.SeName = seName; @@ -90,7 +90,7 @@ private async Task ImportRow(int row, ProductAttributeDto dto, .FirstOrDefault(v => string.Equals(v.Name, valueDto.Name, StringComparison.OrdinalIgnoreCase)); if (value == null) { - value = new PredefinedProductAttributeValue { Name = valueDto.Name }; + value = new PredefinedProductAttributeValue { Name = valueDto.Name ?? "" }; attribute.PredefinedProductAttributeValues.Add(value); } @@ -124,7 +124,7 @@ private static string Key(ProductAttributeDto dto) /// By Id, else by SeName normalized as a new attribute's is, else (best effort) by the SeName its Name would get, /// accepted only when the stored name is the same (any case) /// - private async Task<(ProductAttribute attribute, bool matchedByName)> Find(ProductAttributeDto dto, + private async Task<(ProductAttribute? attribute, bool matchedByName)> Find(ProductAttributeDto dto, List all) { if (!string.IsNullOrEmpty(dto.Id)) @@ -142,7 +142,7 @@ private static string Key(ProductAttributeDto dto) : (null, false); } - private static ProductAttribute FindBySeName(List all, string seName) + private static ProductAttribute? FindBySeName(List all, string seName) { return string.IsNullOrEmpty(seName) ? null @@ -150,9 +150,9 @@ private static ProductAttribute FindBySeName(List all, string } //same normalization as the panel's product attribute controller - private string GetSeName(string name) + private string GetSeName(string? name) { - return SeoExtensions.GetSeName(name, _seoSettings.ConvertNonWesternChars, _seoSettings.AllowUnicodeCharsInUrls, + return SeoExtensions.GetSeName(name ?? "", _seoSettings.ConvertNonWesternChars, _seoSettings.AllowUnicodeCharsInUrls, _seoSettings.SeoCharConversion); } } diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductImportDataObject.cs index 0289d32b7..350b7455a 100644 --- a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductImportDataObject.cs +++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductImportDataObject.cs @@ -47,7 +47,7 @@ public class ProductImportDataObject : IImportDataObject, IRowImport private readonly IStockMovementService _stockMovementService; private readonly ISettingService _settingService; private readonly ILogger _logger; - private readonly Func> _downloadImage; + private readonly Func> _downloadImage; /// Test seam; the default downloads through public ProductImportDataObject( @@ -71,7 +71,7 @@ public ProductImportDataObject( IStockMovementService stockMovementService, ISettingService settingService, ILogger logger, - Func> downloadImage = null) + Func>? downloadImage = null) { _productService = productService; _pictureService = pictureService; @@ -140,14 +140,14 @@ private async Task Import(IReadOnlyList rows, boo } private async Task ImportRow(int row, ProductDto dto, bool dryRun, ImportMode mode, - PictureBudget budget, ICollection externallyManagedWarehouseIds, + PictureBudget? budget, ICollection externallyManagedWarehouseIds, CancellationToken cancellationToken) { var errors = new List(); var warnings = new List(); var key = Key(dto); - Product existing = null; + Product? existing = null; if (!string.IsNullOrEmpty(dto.Id)) existing = await _productService.GetProductById(dto.Id); if (existing == null && (string.IsNullOrEmpty(dto.Id) || mode == ImportMode.Panel)) @@ -334,7 +334,7 @@ private async Task ResolveReferences(ProductDto dto, List wa return new References(brandMissing, categoryIds, collectionIds); } - private static IEnumerable SplitIds(string ids) + private static IEnumerable SplitIds(string? ids) { return string.IsNullOrEmpty(ids) ? [] @@ -453,13 +453,13 @@ private async Task PrepareProductCollections(Product product, List colle } } - private async Task> DownloadProductPictures(ProductDto productDto, PictureBudget budget, + private async Task> DownloadProductPictures(ProductDto productDto, PictureBudget? budget, List warnings, CancellationToken cancellationToken) { //PictureUrls, when sent, replaces Picture1..3 - IEnumerable urls = productDto.PictureUrls is { Count: > 0 } - ? productDto.PictureUrls - : new[] { productDto.Picture1, productDto.Picture2, productDto.Picture3 }; + IEnumerable urls = productDto.PictureUrls is { Count: > 0 } + ? (IEnumerable)productDto.PictureUrls + : new string?[] { productDto.Picture1, productDto.Picture2, productDto.Picture3 }; var images = new List(); foreach (var pictureUrl in urls) diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductSchemaProperty.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductSchemaProperty.cs index 951521c32..d3d72f6b9 100644 --- a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductSchemaProperty.cs +++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductSchemaProperty.cs @@ -129,13 +129,13 @@ public virtual async Task[]> GetProperties(IEnumerable

GetPicture(string pictureId) + private async Task GetPicture(string pictureId) { var picture = await _pictureService.GetPictureById(pictureId); return await _pictureService.GetThumbPhysicalPath(picture); } - private static string GetPicturePath(Dictionary pictures, Product product, int index) + private static string? GetPicturePath(Dictionary pictures, Product product, int index) { var productPicture = product.ProductPictures.ElementAtOrDefault(index); return productPicture != null ? pictures.GetValueOrDefault(productPicture.PictureId ?? "") : null; diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductVariantImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductVariantImportDataObject.cs index 91d331184..caf3a9392 100644 --- a/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductVariantImportDataObject.cs +++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/ProductVariantImportDataObject.cs @@ -98,7 +98,7 @@ private async Task ImportRow(int row, ProductVariantsDto dto, b //the product was read from the database, not the cache, so a dry run can change it in memory freely var changes = new Changes(); foreach (var attributeDto in attributeDtos) - MergeMapping(product, attributes[attributeDto.Attribute], attributeDto, changes, warnings); + MergeMapping(product, attributes[attributeDto.Attribute ?? ""], attributeDto, changes, warnings); //the storefront matches a combination only when it names every selectable, combinable mapping var combinable = product.ProductAttributeMappings.Where(m => IsSelectable(m) && m.Combination).ToList(); @@ -119,7 +119,7 @@ private async Task ImportRow(int row, ProductVariantsDto dto, b return new ImportRowResult(row, ImportRowStatus.Updated, product.Id, key, errors, warnings); } - private async Task FindProduct(ProductVariantsDto dto, List errors) + private async Task FindProduct(ProductVariantsDto dto, List errors) { if (!string.IsNullOrEmpty(dto.ProductId)) { @@ -149,11 +149,11 @@ private async Task> ResolveAttributes( { var keys = attributeDtos.Select(a => a.Attribute) .Concat(combinationDtos.SelectMany(c => c.Values?.Keys ?? [])) - .Where(k => !string.IsNullOrEmpty(k)) + .OfType().Where(k => k.Length > 0) .Distinct(); var resolved = new Dictionary(); - IList all = null; + IList? all = null; foreach (var attributeKey in keys) { var attribute = await _productAttributeService.GetProductAttributeById(attributeKey); @@ -185,7 +185,7 @@ private async Task> MappingNames(List a.Id == mapping.ProductAttributeId) ?? await _productAttributeService.GetProductAttributeById(mapping.ProductAttributeId); - names[mapping.Id] = attribute?.Name ?? mapping.ProductAttributeId; + names[mapping.Id] = attribute?.Name ?? mapping.ProductAttributeId ?? ""; } return names; @@ -234,7 +234,7 @@ private static void MergeMapping(Product product, ProductAttribute attribute, Pr var value = mapping.ProductAttributeValues .FirstOrDefault(v => string.Equals(v.Name, valueDto.Name, StringComparison.OrdinalIgnoreCase)); var isNew = value == null; - if (isNew) + if (value == null) { value = new ProductAttributeValue { Name = valueDto.Name, @@ -262,7 +262,7 @@ private static void MergeMapping(Product product, ProductAttribute attribute, Pr } /// The (mapping, value) pairs of the combination, or null when it was skipped - private static List MergeCombination(Product product, int number, + private static List? MergeCombination(Product product, int number, ProductVariantCombinationDto dto, Dictionary attributes, Changes changes, List warnings) { @@ -416,7 +416,7 @@ private static bool Assign(T? provided, T current, Action set) where T : s return true; } - private static bool Assign(string provided, string current, Action set) + private static bool Assign(string? provided, string? current, Action set) { if (provided == null || provided == current) return false; @@ -431,9 +431,9 @@ private static string Key(ProductVariantsDto dto) } //same normalization as the product attribute import - private string GetSeName(string name) + private string GetSeName(string? name) { - return SeoExtensions.GetSeName(name, _seoSettings.ConvertNonWesternChars, _seoSettings.AllowUnicodeCharsInUrls, + return SeoExtensions.GetSeName(name ?? "", _seoSettings.ConvertNonWesternChars, _seoSettings.AllowUnicodeCharsInUrls, _seoSettings.SeoCharConversion); } diff --git a/src/Business/Grand.Business.Catalog/Services/ExportImport/SpecificationAttributeImportDataObject.cs b/src/Business/Grand.Business.Catalog/Services/ExportImport/SpecificationAttributeImportDataObject.cs index 62965fe87..df6640ffe 100644 --- a/src/Business/Grand.Business.Catalog/Services/ExportImport/SpecificationAttributeImportDataObject.cs +++ b/src/Business/Grand.Business.Catalog/Services/ExportImport/SpecificationAttributeImportDataObject.cs @@ -76,7 +76,7 @@ private async Task ImportRow(int row, SpecificationAttributeDto existing?.Id ?? "", key, errors, warnings); var isNew = existing == null; - var attribute = existing ?? new SpecificationAttribute { Name = dto.Name }; + var attribute = existing ?? new SpecificationAttribute { Name = dto.Name ?? "" }; if (!string.IsNullOrEmpty(dto.Name)) attribute.Name = dto.Name; if (dto.DisplayOrder.HasValue) attribute.DisplayOrder = dto.DisplayOrder.Value; if (seName != null) attribute.SeName = seName; @@ -89,7 +89,7 @@ private async Task ImportRow(int row, SpecificationAttributeDto if (option == null) { option = new SpecificationAttributeOption { - Name = optionDto.Name, + Name = optionDto.Name ?? "", SeName = GetSeName(optionDto.Name) }; attribute.SpecificationAttributeOptions.Add(option); @@ -115,7 +115,7 @@ private static string Key(SpecificationAttributeDto dto) /// By Id, else by SeName normalized as a new attribute's is, else (best effort) by the SeName its Name would get, /// accepted only when the stored name is the same (any case) ///

- private async Task<(SpecificationAttribute attribute, bool matchedByName)> Find(SpecificationAttributeDto dto) + private async Task<(SpecificationAttribute? attribute, bool matchedByName)> Find(SpecificationAttributeDto dto) { if (!string.IsNullOrEmpty(dto.Id)) return (await _specificationAttributeService.GetSpecificationAttributeById(dto.Id), false); @@ -132,7 +132,7 @@ private static string Key(SpecificationAttributeDto dto) : (null, false); } - private async Task FindBySeName(string seName) + private async Task FindBySeName(string seName) { return string.IsNullOrEmpty(seName) ? null @@ -140,9 +140,9 @@ private async Task FindBySeName(string seName) } //same normalization as the panel's specification attribute controller - private string GetSeName(string name) + private string GetSeName(string? name) { - return SeoExtensions.GetSeName(name, _seoSettings.ConvertNonWesternChars, _seoSettings.AllowUnicodeCharsInUrls, + return SeoExtensions.GetSeName(name ?? "", _seoSettings.ConvertNonWesternChars, _seoSettings.AllowUnicodeCharsInUrls, _seoSettings.SeoCharConversion); } } diff --git a/src/Business/Grand.Business.Catalog/Services/Inventory/InventoryDocumentService.cs b/src/Business/Grand.Business.Catalog/Services/Inventory/InventoryDocumentService.cs index 9c914d5be..4b85dc4c4 100644 --- a/src/Business/Grand.Business.Catalog/Services/Inventory/InventoryDocumentService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Inventory/InventoryDocumentService.cs @@ -37,16 +37,16 @@ public class InventoryDocumentService( ///
public const int MaxLines = 5000; - public async Task<(InventoryDocument Document, IList Errors)> CreateStockCount(string warehouseId, + public async Task<(InventoryDocument? Document, IList Errors)> CreateStockCount(string warehouseId, IList categoryIds, IList brandIds, string customerId) { ArgumentException.ThrowIfNullOrEmpty(warehouseId); var query = productRepository.Table.Where(StockBuckets.KeptIn(warehouseId)); if (categoryIds is { Count: > 0 }) - query = query.Where(x => x.ProductCategories.Any(c => categoryIds.Contains(c.CategoryId))); + query = query.Where(x => x.ProductCategories.Any(c => c.CategoryId != null && categoryIds.Contains(c.CategoryId))); if (brandIds is { Count: > 0 }) - query = query.Where(x => brandIds.Contains(x.BrandId)); + query = query.Where(x => x.BrandId != null && brandIds.Contains(x.BrandId)); query = query.OrderBy(x => x.Id); var document = new InventoryDocument { @@ -105,18 +105,19 @@ private async Task AddStockCountLines(InventoryDocument document, Product produc var shipped = new Dictionary, List)>(); foreach (var item in (await shipmentService.GetShipmentsByOrder(orderId)).SelectMany(x => x.ShipmentItems)) { - var (quantity, serialNumbers, batches) = shipped.GetValueOrDefault(item.OrderItemId, + var orderItemId = item.OrderItemId ?? ""; + var (quantity, serialNumbers, batches) = shipped.GetValueOrDefault(orderItemId, (0, new List(), new List())); serialNumbers.AddRange(item.SerialNumbers ?? []); batches.AddRange(item.Batches ?? []); - shipped[item.OrderItemId] = (quantity + item.Quantity, serialNumbers, batches); + shipped[orderItemId] = (quantity + item.Quantity, serialNumbers, batches); } return shipped; } - public async Task<(InventoryDocument Document, IList Errors)> CreateReturnReceipt( - string merchandiseReturnId, string customerId, IList inspection = null) + public async Task<(InventoryDocument? Document, IList Errors)> CreateReturnReceipt( + string merchandiseReturnId, string customerId, IList? inspection = null) { var merchandiseReturn = await merchandiseReturnService.GetMerchandiseReturnById(merchandiseReturnId); if (merchandiseReturn == null) @@ -129,9 +130,9 @@ private async Task AddStockCountLines(InventoryDocument document, Product produc inspection ??= []; //what the form posted is checked against what is left, never trusted: another return's item, an item named //twice or more scrapped than came back refuses the receipt - var left = leftToReceive.GroupBy(x => (x.ReturnItemId, x.ProductId)) + var left = leftToReceive.GroupBy(x => ((string?)x.ReturnItemId, x.ProductId)) .ToDictionary(x => x.Key, x => x.Sum(y => y.Quantity)); - if (inspection.GroupBy(x => (x.ReturnItemId, x.ProductId)).Any(x => x.Count() > 1) || + if (inspection.GroupBy(x => ((string?)x.ReturnItemId, x.ProductId)).Any(x => x.Count() > 1) || inspection.Any(x => !left.TryGetValue((x.ReturnItemId, x.ProductId), out var quantity) || x.ScrapQuantity < 0 || x.ScrapQuantity > quantity)) return (null, [InventoryDocumentErrors.InspectionQuantity]); @@ -141,7 +142,7 @@ private async Task AddStockCountLines(InventoryDocument document, Product produc MerchandiseReturnId = merchandiseReturn.Id, CreatedBy = customerId }; - Dictionary SerialNumbers, List Batches)> shipped = null; + Dictionary SerialNumbers, List Batches)>? shipped = null; foreach (var item in leftToReceive) { var line = new InventoryDocumentLine { @@ -226,11 +227,11 @@ private static void Inspect(InventoryDocument document, ReturnReceiptInspection /// /// What a merchandise return gives back, by product: a returned bundle gives back its products /// - private async Task Attributes, int Quantity, - string WarehouseId)>> + private async Task Attributes, int Quantity, + string? WarehouseId)>> Returned(MerchandiseReturn merchandiseReturn) { - var returned = new List<(string, string, IList, int, string)>(); + var returned = new List<(string, string?, IList, int, string?)>(); var order = await orderService.GetOrderById(merchandiseReturn.OrderId); if (order == null) return returned; @@ -260,8 +261,8 @@ private static void Inspect(InventoryDocument document, ReturnReceiptInspection ///
/// The merchandise return /// A document left out - private async Task> Received(string merchandiseReturnId, - string exceptDocumentId) + private async Task> Received(string merchandiseReturnId, + string? exceptDocumentId) { var receipts = await inventoryDocumentRepository.ToListAsync(inventoryDocumentRepository.Table.Where(x => x.DocumentTypeId == InventoryDocumentType.ReturnReceipt && x.MerchandiseReturnId == merchandiseReturnId && @@ -275,11 +276,11 @@ private static void Inspect(InventoryDocument document, ReturnReceiptInspection /// What a merchandise return gives back and no return receipt of it takes in yet, posted or draft, with the /// quantity left of each ///
- private async Task Attributes, int Quantity, - string WarehouseId)>> + private async Task Attributes, int Quantity, + string? WarehouseId)>> LeftToReceive(string merchandiseReturnId, - IEnumerable<(string ReturnItemId, string ProductId, IList Attributes, int Quantity, - string WarehouseId)> returned) + IEnumerable<(string ReturnItemId, string? ProductId, IList Attributes, int Quantity, + string? WarehouseId)> returned) { var received = await Received(merchandiseReturnId, null); return returned @@ -334,7 +335,7 @@ public async Task GetReturnReceipts(string merchandis public async Task> Post(string id, string customerId) { //every line is checked before the first write - InventoryDocument document; + InventoryDocument? document; await using (await resourceLock.Acquire([DocumentLockKey(id)])) { document = await inventoryDocumentRepository.GetByIdAsync(id); @@ -358,14 +359,19 @@ public async Task> Post(string id, string customerId) //too, and posting again continues after the products booked foreach (var productLines in document.Lines.GroupBy(x => x.ProductId)) { + //a document is checked before it is posted: each of its lines names a product + if (productLines.Key is not { } productId) + return [StockErrors.ProductNotFound]; await using var _ = await resourceLock.Acquire(Keys(DocumentLockKey(id), - ProductStockLock.Key(productLines.Key))); + ProductStockLock.Key(productId))); if (await Changed(document)) return [InventoryDocumentErrors.ChangedWhilePosting]; if (!await ReturnReceivable(document)) return [InventoryDocumentErrors.ReturnNotReceivable]; - var product = await productRepository.GetByIdAsync(productLines.Key); + var product = await productRepository.GetByIdAsync(productId); + if (product == null) + return [StockErrors.ProductNotFound]; var booked = await inventoryJournalRepository.ToListAsync(inventoryJournalRepository.Table .Where(x => x.ObjectType == nameof(InventoryDocument) && x.ObjectId == document.Id && x.ProductId == productLines.Key) @@ -412,7 +418,7 @@ await inventoryDocumentRepository.UpdateOneAsync(x => x.Id == document.Id, /// /// The lock key of the merchandise return's order for a receipt of one; null for any other document /// - private async Task ReturnLockKey(InventoryDocument document) + private async Task ReturnLockKey(InventoryDocument document) { if (!OfMerchandiseReturn(document)) return null; @@ -449,7 +455,7 @@ public async Task IsReturnReceived(string merchandiseReturnId) var ids = receipts.Select(x => x.Id).ToList(); return ids.Count > 0 && await inventoryJournalRepository.AnyAsync(inventoryJournalRepository.Table - .Where(x => x.ObjectType == nameof(InventoryDocument) && ids.Contains(x.ObjectId))); + .Where(x => x.ObjectType == nameof(InventoryDocument) && x.ObjectId != null && ids.Contains(x.ObjectId))); } /// @@ -468,14 +474,14 @@ private async Task Changed(InventoryDocument document) /// The stock changes a line books /// private static IEnumerable Changes(InventoryDocument document, InventoryDocumentLine line, - string customerId, Product product) + string customerId, Product? product) { var serialTracked = product != null && InventoryTracking.Tracked(product) && product.InventoryTrackingModeId == InventoryTrackingMode.SerialNumber; var source = new StockSource(nameof(InventoryDocument), document.Id, line.Id, document.Number, customerId, line.Comment ?? document.Comment ?? ""); //the units a line names; the ledger books them for a product tracking them and ignores them otherwise - StockChange Change(string warehouseId, int quantity, InventoryMovementType movementType) => + StockChange Change(string? warehouseId, int quantity, InventoryMovementType movementType) => new(line.Attributes, warehouseId, quantity, false, movementType, source) { BatchNumber = string.IsNullOrWhiteSpace(line.BatchNumber) ? null : line.BatchNumber.Trim(), ExpiryDateUtc = line.ExpiryDateUtc, @@ -525,7 +531,7 @@ StockChange Change(string warehouseId, int quantity, InventoryMovementType movem } } - public Task GetById(string id) + public Task GetById(string id) { return inventoryDocumentRepository.GetByIdAsync(id); } @@ -545,7 +551,7 @@ public Task> Search(InventoryDocumentSearch search if (search.StoreId != null) query = query.Where(x => x.StoreId == search.StoreId); if (!string.IsNullOrEmpty(search.Number)) - query = query.Where(x => x.Number.Contains(search.Number)); + query = query.Where(x => x.Number != null && x.Number.Contains(search.Number)); if (!string.IsNullOrEmpty(search.MerchandiseReturnId)) query = query.Where(x => x.MerchandiseReturnId == search.MerchandiseReturnId); if (search.FromUtc.HasValue) @@ -700,10 +706,10 @@ await warehouseService.GetWarehouseById(document.TargetWarehouseId) is if (merchandiseReturn != null && await ReturnQuantityExceeded(document, merchandiseReturn)) Add(InventoryDocumentErrors.ReturnQuantityExceeded); - var products = new Dictionary(); + var products = new Dictionary(); foreach (var line in document.Lines) { - Product product = null; + Product? product = null; if (!string.IsNullOrEmpty(line.ProductId) && !products.TryGetValue(line.ProductId, out product)) products[line.ProductId] = product = await productRepository.GetByIdAsync(line.ProductId); if (product == null) @@ -785,7 +791,7 @@ await warehouseService.GetWarehouseById(document.TargetWarehouseId) is /// and only units shipped without a number may come back without one ///
private async Task> ReturnedUnitErrors(InventoryDocument document, - MerchandiseReturn merchandiseReturn, Dictionary products) + MerchandiseReturn merchandiseReturn, Dictionary products) { var errors = new List(); if (!document.Lines.Any(x => products.GetValueOrDefault(x.ProductId ?? "") is { } product && @@ -852,7 +858,7 @@ or InventoryDocumentType.Assignment && private async Task ReturnQuantityExceeded(InventoryDocument document, MerchandiseReturn merchandiseReturn) { var returned = (await Returned(merchandiseReturn)) - .GroupBy(x => (x.ReturnItemId, x.ProductId)) + .GroupBy(x => ((string?)x.ReturnItemId, x.ProductId)) .ToDictionary(x => x.Key, x => x.Sum(y => y.Quantity)); var received = await Received(merchandiseReturn.Id, document.Id); foreach (var line in document.Lines.Where(x => !string.IsNullOrEmpty(x.MerchandiseReturnItemId))) @@ -862,7 +868,7 @@ private async Task ReturnQuantityExceeded(InventoryDocument document, Merc return received.Any(x => x.Value > returned.GetValueOrDefault(x.Key)); } - private async Task StoreOf(string warehouseId) + private async Task StoreOf(string? warehouseId) { return string.IsNullOrEmpty(warehouseId) ? "" @@ -891,7 +897,7 @@ private async Task> BookedLines(string documentId) var positions = await inventoryJournalRepository.ToListAsync(inventoryJournalRepository.Table .Where(x => x.ObjectType == nameof(InventoryDocument) && x.ObjectId == documentId) .Select(x => x.PositionId)); - return positions.ToHashSet(); + return positions.OfType().ToHashSet(); } private static string DocumentLockKey(string documentId) @@ -916,7 +922,7 @@ private static string AttributesKey(IList attributes) return string.Join("|", (attributes ?? []).Select(x => $"{x.Key}={x.Value}").Order(StringComparer.Ordinal)); } - private static bool SameBooking(InventoryDocumentLine stored, InventoryDocumentLine line) + private static bool SameBooking(InventoryDocumentLine stored, InventoryDocumentLine? line) { return line != null && line.ProductId == stored.ProductId && line.Quantity == stored.Quantity && line.CountedQuantity == stored.CountedQuantity && line.UnitCost == stored.UnitCost && diff --git a/src/Business/Grand.Business.Catalog/Services/Inventory/InventoryJournalService.cs b/src/Business/Grand.Business.Catalog/Services/Inventory/InventoryJournalService.cs index 0a6a8348e..24f754ee3 100644 --- a/src/Business/Grand.Business.Catalog/Services/Inventory/InventoryJournalService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Inventory/InventoryJournalService.cs @@ -23,8 +23,8 @@ public Task> GetProductHistory(string productId, st //an entry written before entries named their store belongs to no store, like a shared warehouse if (storeIds != null) query = storeIds.Contains("") - ? query.Where(x => storeIds.Contains(x.StoreId) || x.StoreId == null) - : query.Where(x => storeIds.Contains(x.StoreId)); + ? query.Where(x => x.StoreId != null && storeIds.Contains(x.StoreId) || x.StoreId == null) + : query.Where(x => x.StoreId != null && storeIds.Contains(x.StoreId)); return inventoryJournalRepository.PagedAsync( query.OrderByDescending(x => x.CreateDateUtc).ThenByDescending(x => x.StockRevision), pageIndex, diff --git a/src/Business/Grand.Business.Catalog/Services/Inventory/ProductUnitService.cs b/src/Business/Grand.Business.Catalog/Services/Inventory/ProductUnitService.cs index c37e7f7ee..d32ba69b8 100644 --- a/src/Business/Grand.Business.Catalog/Services/Inventory/ProductUnitService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Inventory/ProductUnitService.cs @@ -98,7 +98,7 @@ public Task> SearchSerialNumbers(UnitSearch sear var key = UnitNumbers.Key(search.Number); if (key != "") query = search.Prefix - ? query.Where(x => x.NumberKey.StartsWith(key)) + ? query.Where(x => x.NumberKey != null && x.NumberKey.StartsWith(key)) : query.Where(x => x.NumberKey == key); if (!string.IsNullOrEmpty(search.ProductId)) query = query.Where(x => x.ProductId == search.ProductId); @@ -121,7 +121,7 @@ public async Task> SearchBatches(UnitSearch search, int var key = UnitNumbers.Key(search.Number); if (key != "") query = search.Prefix - ? query.Where(x => x.NumberKey.StartsWith(key)) + ? query.Where(x => x.NumberKey != null && x.NumberKey.StartsWith(key)) : query.Where(x => x.NumberKey == key); if (!string.IsNullOrEmpty(search.ProductId)) query = query.Where(x => x.ProductId == search.ProductId); @@ -147,12 +147,12 @@ public async Task> SearchBatches(UnitSearch search, int pageIndex, pageSize); } - public Task GetSerialNumber(string id) + public Task GetSerialNumber(string id) { return serialNumberRepository.GetByIdAsync(id); } - public Task GetBatch(string id) + public Task GetBatch(string id) { return batchRepository.GetByIdAsync(id); } @@ -234,7 +234,7 @@ public async Task>> ShippedUnitViews( units.Add(new ShippedUnitView(number, true, 1, null, comment)); } - var product = products.GetValueOrDefault(item.ProductId); + var product = products.GetValueOrDefault(item.ProductId ?? ""); //the batch of the bucket the item shipped from: the same number in another warehouse is another batch var warehouseId = product == null ? null : StockBuckets.UnitWarehouse(product, item.WarehouseId); var combinationId = product?.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByAttributes @@ -272,7 +272,7 @@ public Task> History(ProductSerialNumber serialNumb var query = journalRepository.Table.Where(x => x.ProductId == serialNumber.ProductId && x.SerialNumbers.Contains(serialNumber.Number)); if (warehouseIds != null) - query = query.Where(x => warehouseIds.Contains(x.WarehouseId)); + query = query.Where(x => x.WarehouseId != null && warehouseIds.Contains(x.WarehouseId)); return journalRepository.PagedAsync(query.OrderByDescending(x => x.StockRevision), pageIndex, pageSize); } @@ -299,8 +299,8 @@ public async Task> BatchRecipients(ProductBatch batch return new PagedList(entries.Select(entry => { - var shipment = shipments.GetValueOrDefault(entry.ObjectId); - var order = shipment == null ? null : orders.GetValueOrDefault(shipment.OrderId); + var shipment = shipments.GetValueOrDefault(entry.ObjectId ?? ""); + var order = shipment == null ? null : orders.GetValueOrDefault(shipment.OrderId ?? ""); return new BatchRecipient(entry.ObjectId, shipment?.ShipmentNumber ?? 0, shipment?.OrderId, order?.OrderNumber ?? 0, order?.CustomerId, order?.CustomerEmail, entry.OutQty - entry.InQty, shipment?.CreatedOnUtc ?? entry.CreateDateUtc, order?.StoreId); @@ -346,7 +346,7 @@ public async Task> Buckets(Product product) .GroupBy(x => (x.CombinationId ?? "", x.WarehouseId ?? "")) .ToDictionary(x => x.Key, x => x.Sum(y => y.Quantity)); - IEnumerable warehouses = product.UseMultipleWarehouses ? StockBuckets.Warehouses(product) : [product.WarehouseId]; + IEnumerable warehouses = product.UseMultipleWarehouses ? StockBuckets.Warehouses(product) : [product.WarehouseId ?? ""]; foreach (var warehouseId in warehouses) foreach (var (combinationId, attributes, stock) in StockBuckets.In(product, warehouseId)) { @@ -364,8 +364,8 @@ public async Task> Buckets(Product product) ///
private sealed class UnitCount { - public string CombinationId { get; set; } - public string WarehouseId { get; set; } + public string? CombinationId { get; set; } + public string? WarehouseId { get; set; } public int Quantity { get; set; } } @@ -416,7 +416,7 @@ public async Task> PrepareShipmentUnits(Shipment shipme if (product == null) continue; - string error; + string? error; if (InventoryTracking.Tracked(product)) { if (product.WarrantyMonths > 0) @@ -443,12 +443,16 @@ public async Task> PrepareShipmentUnits(Shipment shipme /// item is checked against what those leave; the changes of an item without errors join them ///
/// The changes of the items checked so far, by product - private async Task LedgerError(Product product, List changes, + private async Task LedgerError(Product product, List changes, Dictionary> booked) { List all = [..booked.GetValueOrDefault(product.Id) ?? [], ..changes]; //read again for every check: the ledger works the changes out on the product it is given - var errors = await stockLedger.Check(await productRepository.GetByIdAsync(product.Id), all); + //deleted meanwhile + var current = await productRepository.GetByIdAsync(product.Id); + if (current == null) + return StockErrors.ProductNotFound; + var errors = await stockLedger.Check(current, all); if (errors.Count > 0) return errors[0]; @@ -480,7 +484,7 @@ private static (string CombinationId, int Stock) Bucket(Product product, IList /// The batches a shipment item names cover its quantity at most: the rest comes from the stock without one ///
- private static string BatchError(ShipmentItem item) + private static string? BatchError(ShipmentItem item) { return (item.Batches ?? []).Where(x => x.Quantity > 0).Sum(x => x.Quantity) > item.Quantity ? UnitErrors.BatchQuantityExceeded @@ -491,7 +495,7 @@ private static string BatchError(ShipmentItem item) /// A serial number is named once a shipment; a known one is named as it was received ///
/// The serial numbers the shipment's items named so far, by product - private async Task SerialNumberError(Product product, ShipmentItem item, + private async Task SerialNumberError(Product product, ShipmentItem item, Dictionary> named) { var numbers = item.SerialNumbers ?? []; @@ -513,10 +517,10 @@ private async Task SerialNumberError(Product product, ShipmentItem item, /// The products of a bundle, and those associated with the attributes chosen, ship from their stock without /// units: never one tracking serial numbers, and one tracking batches only while the ledger books it ///
- private async Task TrackedChildError(Product product, Shipment shipment, ShipmentItem item, + private async Task TrackedChildError(Product product, Shipment shipment, ShipmentItem item, Dictionary> booked) { - var children = new List<(string ProductId, int Quantity)>(); + var children = new List<(string? ProductId, int Quantity)>(); if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByBundleProducts) children.AddRange(product.BundleProducts.Select(x => (x.ProductId, x.Quantity * item.Quantity))); children.AddRange(product.ParseProductAttributeValues(item.Attributes ?? []) @@ -533,7 +537,7 @@ private async Task TrackedChildError(Product product, Shipment shipment, //booked as the booking books it: the item's attributes and warehouse, the child's quantity var childItem = new ShipmentItem { - Id = item.Id, Attributes = item.Attributes, Quantity = quantity, WarehouseId = item.WarehouseId + Id = item.Id, Attributes = item.Attributes ?? [], Quantity = quantity, WarehouseId = item.WarehouseId }; if (await LedgerError(child, ShipmentStock.Changes(child, shipment, childItem), booked) != null) return UnitErrors.TrackedBundleChild; @@ -542,7 +546,7 @@ private async Task TrackedChildError(Product product, Shipment shipment, return null; } - public async Task AssignedQuantity(string productId, string combinationId = null) + public async Task AssignedQuantity(string productId, string? combinationId = null) { var batches = batchRepository.Table.Where(x => x.ProductId == productId && x.Quantity != 0); var serialNumbers = serialNumberRepository.Table.Where(x => @@ -574,7 +578,7 @@ public async Task> Batches(string productId, string combinat .ToList(); } - public async Task TrackingChangeRefused(Product stored, Product changed) + public async Task TrackingChangeRefused(Product stored, Product changed) { ArgumentNullException.ThrowIfNull(stored); ArgumentNullException.ThrowIfNull(changed); diff --git a/src/Business/Grand.Business.Catalog/Services/Inventory/StockLedger.cs b/src/Business/Grand.Business.Catalog/Services/Inventory/StockLedger.cs index db09f4d2d..7fe9c8c1c 100644 --- a/src/Business/Grand.Business.Catalog/Services/Inventory/StockLedger.cs +++ b/src/Business/Grand.Business.Catalog/Services/Inventory/StockLedger.cs @@ -106,7 +106,9 @@ private async Task> Run(Product product, IReadOnlyList public async Task Reopen(Product product, ManageInventoryMethod previousMethod, bool previousMultipleWarehouses, - string previousWarehouseId, string customerId) + string? previousWarehouseId, string customerId) { ArgumentNullException.ThrowIfNull(product); @@ -298,7 +300,7 @@ private static bool Tracked(ManageInventoryMethod method) /// Applies the entries whose product write was lost, with their units, to the product and the units read ///
/// Whether an entry was applied, and the units read for a product tracking them, or null - private async Task<(bool Repaired, UnitSet Units)> RepairWithUnits(Product product, + private async Task<(bool Repaired, UnitSet? Units)> RepairWithUnits(Product product, IReadOnlyList changes) { var pending = await Pending(product); @@ -335,7 +337,7 @@ private async Task> AppliedKeys(Product product, IReadOnlyList x.ProductId == product.Id && keys.Contains(x.IdempotencyKey)) .Select(x => x.IdempotencyKey))) - .ToHashSet(); + .OfType().ToHashSet(); } /// @@ -374,8 +376,8 @@ private static void Move(Bucket bucket, int delta, InventoryMovementType movemen /// /// The bucket a change applies to, by the product's inventory method; a missing warehouse row is created /// - private static Bucket Locate(Product product, string combinationId, IList attributes, - string warehouseId, out string error) + private static Bucket? Locate(Product product, string? combinationId, IList attributes, + string? warehouseId, out string? error) { error = null; if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock) @@ -440,7 +442,7 @@ private static Bucket Locate(Product product, string combinationId, IList private static IEnumerable Buckets(Product product, ManageInventoryMethod method, bool multipleWarehouses, - string warehouseId) + string? warehouseId) { switch (method) { @@ -449,7 +451,7 @@ private static IEnumerable Buckets(Product product, ManageInventoryMetho break; case ManageInventoryMethod.ManageStock: foreach (var row in product.ProductWarehouseInventory) - yield return new Bucket(row, null, row.WarehouseId, row.WarehouseId); + yield return new Bucket(row, null, row.WarehouseId ?? "", row.WarehouseId ?? ""); break; case ManageInventoryMethod.ManageStockByAttributes: foreach (var combination in product.ProductAttributeCombinations) @@ -457,7 +459,7 @@ private static IEnumerable Buckets(Product product, ManageInventoryMetho yield return new Bucket(combination, combination, "", warehouseId ?? ""); else foreach (var row in combination.WarehouseInventory) - yield return new Bucket(row, combination, row.WarehouseId, row.WarehouseId); + yield return new Bucket(row, combination, row.WarehouseId ?? "", row.WarehouseId ?? ""); break; } } @@ -490,7 +492,7 @@ private static void Sum(Product product) /// The change whose units the entry names; null for a product tracking none private static InventoryJournal Entry(Product product, Bucket bucket, int delta, - InventoryMovementType movementType, StockSource source, StockChange units = null) + InventoryMovementType movementType, StockSource source, StockChange? units = null) { return new InventoryJournal { BatchNumber = string.IsNullOrWhiteSpace(units?.BatchNumber) ? null : units.BatchNumber.Trim(), @@ -519,12 +521,13 @@ private async Task Insert(Product product, IList entries) var warehouseStores = new Dictionary(); foreach (var entry in entries) { - if (!warehouseStores.TryGetValue(entry.WarehouseId, out var storeId)) + var warehouseId = entry.WarehouseId ?? ""; + if (!warehouseStores.TryGetValue(warehouseId, out var storeId)) { - storeId = string.IsNullOrEmpty(entry.WarehouseId) + storeId = warehouseId == "" ? "" - : (await warehouseService.GetWarehouseById(entry.WarehouseId))?.StoreId ?? ""; - warehouseStores[entry.WarehouseId] = storeId; + : (await warehouseService.GetWarehouseById(warehouseId))?.StoreId ?? ""; + warehouseStores[warehouseId] = storeId; } entry.StoreId = storeId; @@ -572,12 +575,12 @@ private async Task Write(Product product, bool costChanged = false) [("", "")] = product.StockQuantity - product.ReservedQuantity }; foreach (var row in product.ProductWarehouseInventory) - available[("", row.WarehouseId)] = row.StockQuantity - row.ReservedQuantity; + available[("", row.WarehouseId ?? "")] = row.StockQuantity - row.ReservedQuantity; foreach (var combination in product.ProductAttributeCombinations) { available[(combination.Id, "")] = combination.StockQuantity - combination.ReservedQuantity; foreach (var row in combination.WarehouseInventory) - available[(combination.Id, row.WarehouseId)] = row.StockQuantity - row.ReservedQuantity; + available[(combination.Id, row.WarehouseId ?? "")] = row.StockQuantity - row.ReservedQuantity; } return available; @@ -615,7 +618,7 @@ private static UnitBucket UnitsOf(Bucket bucket) /// the combination, for a product stocked by attributes /// the warehouse of a row; empty for a product or combination /// the warehouse the journal entry names - private sealed class Bucket(object target, ProductAttributeCombination combination, string rowWarehouseId, + private sealed class Bucket(object target, ProductAttributeCombination? combination, string rowWarehouseId, string warehouseId) { public (string, string) Key => (CombinationId, rowWarehouseId); diff --git a/src/Business/Grand.Business.Catalog/Services/Inventory/StockSideEffects.cs b/src/Business/Grand.Business.Catalog/Services/Inventory/StockSideEffects.cs index 155df5b75..f6de23d23 100644 --- a/src/Business/Grand.Business.Catalog/Services/Inventory/StockSideEffects.cs +++ b/src/Business/Grand.Business.Catalog/Services/Inventory/StockSideEffects.cs @@ -208,7 +208,7 @@ await productRepository.UpdateOneAsync(x => x.Id == product.Id, /// /// Tells the store owner the stock of the product, or of its combination, fell below the quantity to notify at /// - public Task QuantityBelow(Product product, ProductAttributeCombination combination = null) + public Task QuantityBelow(Product product, ProductAttributeCombination? combination = null) { return mediator.Send(new SendQuantityBelowStoreOwnerCommand { Product = product, diff --git a/src/Business/Grand.Business.Catalog/Services/Inventory/StockUnits.cs b/src/Business/Grand.Business.Catalog/Services/Inventory/StockUnits.cs index 5cbf3199e..a93fe995b 100644 --- a/src/Business/Grand.Business.Catalog/Services/Inventory/StockUnits.cs +++ b/src/Business/Grand.Business.Catalog/Services/Inventory/StockUnits.cs @@ -148,7 +148,7 @@ public IReadOnlyList StillShipped(UnitSet set, IReadOnlyList /// The order a shipment item belongs to, as its shipped serial numbers record it /// - public async Task ShipmentInfo(string shipmentId, string shipmentItemId) + public async Task ShipmentInfo(string? shipmentId, string? shipmentItemId) { var shipment = string.IsNullOrEmpty(shipmentId) ? null : await shipmentRepository.GetByIdAsync(shipmentId); var item = shipment?.ShipmentItems.FirstOrDefault(x => x.Id == shipmentItemId); @@ -165,7 +165,7 @@ public async Task ShipmentInfo(string shipmentId, string shipm /// The change of the bucket's stock; 0 for an assignment /// The change /// The key of the error, or null - public async Task Apply(UnitSet set, Product product, UnitBucket bucket, int delta, StockChange change) + public async Task Apply(UnitSet set, Product product, UnitBucket bucket, int delta, StockChange change) { ArgumentNullException.ThrowIfNull(set); ArgumentNullException.ThrowIfNull(bucket); @@ -206,7 +206,10 @@ public async Task Replay(UnitSet set, Product product, UnitBucket bucket, Invent if (batch == null) { + //a batch whose expiry date contradicts the one stored is left as it is batch = (await Receive(set, product, bucket, key, change)).Batch; + if (batch == null) + return; batch.ExpiryDateUtc ??= Date(entry.ExpiryDateUtc); } @@ -243,11 +246,11 @@ public async Task Replay(UnitSet set, Product product, UnitBucket bucket, Invent case InventoryMovementType.Shipment: serialNumber.StatusId = SerialNumberStatus.Shipped; serialNumber.WarehouseId = bucket.WarehouseId ?? ""; - serialNumber.OrderId = shipment.OrderId; - serialNumber.OrderItemId = shipment.OrderItemId; - serialNumber.ShipmentId = shipment.ShipmentId; - serialNumber.ShippedOnUtc = shipment.ShippedOnUtc; - serialNumber.WarrantyUntilUtc = shipment.WarrantyUntilUtc; + serialNumber.OrderId = shipment?.OrderId; + serialNumber.OrderItemId = shipment?.OrderItemId; + serialNumber.ShipmentId = shipment?.ShipmentId; + serialNumber.ShippedOnUtc = shipment?.ShippedOnUtc; + serialNumber.WarrantyUntilUtc = shipment?.WarrantyUntilUtc; break; case InventoryMovementType.ReturnScrapped: serialNumber.StatusId = SerialNumberStatus.Scrapped; @@ -282,7 +285,7 @@ public async Task Replay(UnitSet set, Product product, UnitBucket bucket, Invent /// missing, and the stock without numbers left is booked out ///
/// The changes, or the key of the error - public async Task<(IReadOnlyList Changes, string Error)> ExpandCount(UnitSet set, Product product, + public async Task<(IReadOnlyList Changes, string? Error)> ExpandCount(UnitSet set, Product product, UnitBucket bucket, StockChange change) { ArgumentNullException.ThrowIfNull(set); @@ -350,24 +353,24 @@ StockChange Part(int quantity, InventoryMovementType movementType, IReadOnlyList /// The units read for the call /// The buckets the call changed, with their stock after it /// The key of the error, or null - public Task CheckPools(UnitSet set, IEnumerable buckets) + public Task CheckPools(UnitSet set, IEnumerable buckets) { ArgumentNullException.ThrowIfNull(set); ArgumentNullException.ThrowIfNull(buckets); //a transfer puts in the other warehouse every serial number it takes out if (set.InTransit.Count > 0) - return Task.FromResult(UnitErrors.SerialNotInStock); + return Task.FromResult(UnitErrors.SerialNotInStock); foreach (var bucket in buckets) { var pool = bucket.Stock - Assigned(set, bucket); if (pool < 0 && pool < set.InitialPool.GetValueOrDefault(bucket.Key) && !(set.Mode == InventoryTrackingMode.Batch && set.Backordered.Contains(bucket.Key))) - return Task.FromResult(UnitErrors.PoolExceeded); + return Task.FromResult(UnitErrors.PoolExceeded); } - return Task.FromResult(null); + return Task.FromResult(null); } /// @@ -465,7 +468,7 @@ await serialNumberRepository.UpdateOneAsync(x => x.Id == serialNumber.Id, /// /// Reads how many serial numbers are in stock in the bucket, once per call; the call keeps the count since /// - private async Task CountInStock(UnitSet set, Product product, string combinationId, string warehouseId) + private async Task CountInStock(UnitSet set, Product product, string? combinationId, string? warehouseId) { var key = (combinationId ?? "", warehouseId ?? ""); if (set.Mode != InventoryTrackingMode.SerialNumber || set.InStock.ContainsKey(key)) @@ -498,7 +501,7 @@ private static int Assigned(UnitSet set, UnitBucket bucket) }; } - private static bool InBucket(string combinationId, string warehouseId, UnitBucket bucket) + private static bool InBucket(string? combinationId, string? warehouseId, UnitBucket bucket) { return (combinationId ?? "") == (bucket.CombinationId ?? "") && (warehouseId ?? "") == (bucket.WarehouseId ?? ""); } @@ -511,7 +514,7 @@ private static void Touch(UnitSet set, StockChange change, object record) set.Changed.Add(record); } - private async Task ApplyBatch(UnitSet set, Product product, UnitBucket bucket, int delta, + private async Task ApplyBatch(UnitSet set, Product product, UnitBucket bucket, int delta, StockChange change) { var key = UnitNumbers.Key(change.BatchNumber); @@ -522,8 +525,9 @@ private async Task ApplyBatch(UnitSet set, Product product, UnitBucket b if (change.Quantity <= 0) return UnitErrors.BatchQuantityExceeded; + //Receive gives a batch or an error var (assigned, error) = await Receive(set, product, bucket, key, change); - if (error != null) + if (assigned == null) return error; assigned.Quantity += change.Quantity; @@ -541,8 +545,9 @@ private async Task ApplyBatch(UnitSet set, Product product, UnitBucket b if (delta > 0) { + //Receive gives a batch or an error var (received, error) = await Receive(set, product, bucket, key, change); - if (error != null) + if (received == null) return error; received.Quantity += delta; @@ -563,7 +568,7 @@ private async Task ApplyBatch(UnitSet set, Product product, UnitBucket b return null; } - private async Task ApplySerialNumbers(UnitSet set, Product product, UnitBucket bucket, int delta, + private async Task ApplySerialNumbers(UnitSet set, Product product, UnitBucket bucket, int delta, StockChange change) { var numbers = change.SerialNumbers; @@ -577,8 +582,9 @@ private async Task ApplySerialNumbers(UnitSet set, Product product, Unit return UnitErrors.SerialCountMismatch; foreach (var number in numbers) { + //Arrive gives a serial number or an error var (serialNumber, error) = await Arrive(set, product, bucket, number, change); - if (error != null) + if (serialNumber == null) return error; Touch(set, change, serialNumber); } @@ -611,16 +617,16 @@ private async Task ApplySerialNumbers(UnitSet set, Product product, Unit return null; } - private async Task In(UnitSet set, Product product, UnitBucket bucket, StockChange change) + private async Task In(UnitSet set, Product product, UnitBucket bucket, StockChange change) { foreach (var number in change.SerialNumbers) { var key = UnitNumbers.Key(number); var serialNumber = set.SerialNumbers.GetValueOrDefault(key); - string error = null; + string? error = null; switch (change.MovementType) { - case InventoryMovementType.TransferIn when set.InTransit.Remove(key): + case InventoryMovementType.TransferIn when serialNumber != null && set.InTransit.Remove(key): await Place(set, serialNumber, bucket); break; case InventoryMovementType.ShipmentReversal or InventoryMovementType.ReturnReceipt: @@ -637,7 +643,8 @@ private async Task In(UnitSet set, Product product, UnitBucket bucket, S break; } - if (error != null) + //every case but a failed Arrive leaves a serial number + if (serialNumber == null) return error; Touch(set, change, serialNumber); } @@ -645,7 +652,7 @@ private async Task In(UnitSet set, Product product, UnitBucket bucket, S return null; } - private async Task Out(UnitSet set, Product product, UnitBucket bucket, StockChange change) + private async Task Out(UnitSet set, Product product, UnitBucket bucket, StockChange change) { var shipment = change.MovementType == InventoryMovementType.Shipment ? await ShipmentInfo(change.Source.ObjectId, change.Source.PositionId) @@ -654,10 +661,9 @@ private async Task Out(UnitSet set, Product product, UnitBucket bucket, { var key = UnitNumbers.Key(number); var serialNumber = set.SerialNumbers.GetValueOrDefault(key); - var here = serialNumber is { StatusId: SerialNumberStatus.InStock } && - InBucket(serialNumber.CombinationId, serialNumber.WarehouseId, bucket) && - !set.InTransit.Contains(key); - if (!here) + if (serialNumber is not { StatusId: SerialNumberStatus.InStock } || + !InBucket(serialNumber.CombinationId, serialNumber.WarehouseId, bucket) || + set.InTransit.Contains(key)) { if (serialNumber is { StatusId: SerialNumberStatus.InStock }) return UnitErrors.SerialInOtherWarehouse; @@ -680,11 +686,11 @@ private async Task Out(UnitSet set, Product product, UnitBucket bucket, { case InventoryMovementType.Shipment: serialNumber.StatusId = SerialNumberStatus.Shipped; - serialNumber.OrderId = shipment.OrderId; - serialNumber.OrderItemId = shipment.OrderItemId; - serialNumber.ShipmentId = shipment.ShipmentId; - serialNumber.ShippedOnUtc = shipment.ShippedOnUtc; - serialNumber.WarrantyUntilUtc = shipment.WarrantyUntilUtc; + serialNumber.OrderId = shipment?.OrderId; + serialNumber.OrderItemId = shipment?.OrderItemId; + serialNumber.ShipmentId = shipment?.ShipmentId; + serialNumber.ShippedOnUtc = shipment?.ShippedOnUtc; + serialNumber.WarrantyUntilUtc = shipment?.WarrantyUntilUtc; break; case InventoryMovementType.TransferOut: set.InTransit.Add(key); @@ -706,7 +712,7 @@ private async Task Out(UnitSet set, Product product, UnitBucket bucket, /// /// A serial number taking stock in the bucket: new for the product, or one scrapped or missing coming back /// - private async Task<(ProductSerialNumber SerialNumber, string Error)> Arrive(UnitSet set, Product product, + private async Task<(ProductSerialNumber? SerialNumber, string? Error)> Arrive(UnitSet set, Product product, UnitBucket bucket, string number, StockChange change) { var serialNumber = set.SerialNumbers.GetValueOrDefault(UnitNumbers.Key(number)); @@ -777,7 +783,7 @@ private async Task Place(UnitSet set, ProductSerialNumber serialNumber, UnitBuck set.InStock[bucket.Key] = set.InStock.GetValueOrDefault(bucket.Key) + 1; } - private static ProductBatch Find(UnitSet set, UnitBucket bucket, string key) + private static ProductBatch? Find(UnitSet set, UnitBucket bucket, string key) { return set.Batches.FirstOrDefault(x => x.NumberKey == key && InBucket(x.CombinationId, x.WarehouseId, bucket)); } @@ -786,7 +792,7 @@ private static ProductBatch Find(UnitSet set, UnitBucket bucket, string key) /// The batch of the bucket that takes stock in; a batch new in the bucket keeps the expiry date, cost and /// receipt the number has elsewhere, and only a batch new for the product takes them from the change /// - private async Task<(ProductBatch Batch, string Error)> Receive(UnitSet set, Product product, UnitBucket bucket, + private async Task<(ProductBatch? Batch, string? Error)> Receive(UnitSet set, Product product, UnitBucket bucket, string key, StockChange change) { var batch = Find(set, bucket, key); @@ -804,7 +810,8 @@ private static ProductBatch Find(UnitSet set, UnitBucket bucket, string key) Attributes = bucket.Attributes ?? [], WarehouseId = bucket.WarehouseId ?? "", StoreId = await StoreOf(bucket.WarehouseId), - Number = known?.Number ?? change.BatchNumber.Trim(), + //the key was made from the batch number + Number = known?.Number ?? change.BatchNumber?.Trim() ?? key, NumberKey = key, ExpiryDateUtc = known != null ? known.ExpiryDateUtc : Date(change.ExpiryDateUtc), UnitCost = known != null ? known.UnitCost : change.UnitCost, @@ -828,7 +835,7 @@ private static ProductBatch Find(UnitSet set, UnitBucket bucket, string key) return value.HasValue ? DateTime.SpecifyKind(value.Value.Date, DateTimeKind.Utc) : null; } - private static string ReceiptDocument(StockChange change) + private static string? ReceiptDocument(StockChange change) { return change.MovementType == InventoryMovementType.Receipt && change.Source.ObjectType == nameof(InventoryDocument) @@ -836,7 +843,7 @@ private static string ReceiptDocument(StockChange change) : null; } - private async Task StoreOf(string warehouseId) + private async Task StoreOf(string? warehouseId) { return string.IsNullOrEmpty(warehouseId) ? "" @@ -848,8 +855,8 @@ private async Task StoreOf(string warehouseId) /// The shipment item a shipped serial number belongs to ///
public sealed record ShipmentUnitInfo( - string ShipmentId, - string OrderId, - string OrderItemId, + string? ShipmentId, + string? OrderId, + string? OrderItemId, DateTime ShippedOnUtc, DateTime? WarrantyUntilUtc); diff --git a/src/Business/Grand.Business.Catalog/Services/Prices/PriceFormatter.cs b/src/Business/Grand.Business.Catalog/Services/Prices/PriceFormatter.cs index aa8e38142..8a0dbc856 100644 --- a/src/Business/Grand.Business.Catalog/Services/Prices/PriceFormatter.cs +++ b/src/Business/Grand.Business.Catalog/Services/Prices/PriceFormatter.cs @@ -17,7 +17,7 @@ public class PriceFormatter : IPriceFormatter /// Amount /// Target currency /// Currency string without exchange rate - protected virtual string GetCurrencyString(double amount, Currency targetCurrency) + protected virtual string GetCurrencyString(double amount, Currency? targetCurrency) { if (targetCurrency == null) return amount.ToString("C"); @@ -56,7 +56,7 @@ protected virtual string GetCurrencyString(double amount, Currency targetCurrenc /// Price /// Target currency /// Price - public string FormatPrice(double price, Currency targetCurrency) + public string FormatPrice(double price, Currency? targetCurrency) { var currencyString = GetCurrencyString(price, targetCurrency); return currencyString; diff --git a/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs b/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs index c49feb991..67f1524da 100644 --- a/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Prices/PricingService.cs @@ -48,7 +48,7 @@ protected class ProductPrice public double Price { get; set; } public double AppliedDiscountAmount { get; set; } public IList AppliedDiscounts { get; set; } = new List(); - public TierPrice PreferredTierPrice { get; set; } + public TierPrice? PreferredTierPrice { get; set; } } #endregion @@ -78,7 +78,7 @@ protected class ProductPrice /// Shopping cart item quantity /// Final price public virtual async - Task<(double finalPrice, double discountAmount, List appliedDiscounts, TierPrice + Task<(double finalPrice, double discountAmount, List appliedDiscounts, TierPrice? preferredTierPrice)> GetFinalPrice( Product product, @@ -107,7 +107,7 @@ public virtual async /// Rental period end date (for rental products) /// Final price public virtual async - Task<(double finalPrice, double discountAmount, List appliedDiscounts, TierPrice + Task<(double finalPrice, double discountAmount, List appliedDiscounts, TierPrice? preferredTierPrice)> GetFinalPrice( Product product, diff --git a/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs b/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs index cef22edad..5c3022cc3 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/AuctionService.cs @@ -30,12 +30,12 @@ public AuctionService(IRepository bidRepository, _mediator = mediator; } - public virtual Task GetBid(string id) + public virtual Task GetBid(string id) { return _bidRepository.GetByIdAsync(id); } - public virtual async Task GetLatestBid(string productId) + public virtual async Task GetLatestBid(string productId) { var bid = _bidRepository.Table .Where(x => x.ProductId == productId) @@ -87,10 +87,10 @@ public virtual async Task DeleteBid(Bid bid) var highestBid = bids.MaxBy(x => x.Amount); if (productToUpdate != null) await UpdateHighestBid(productToUpdate, highestBid?.Amount ?? 0, - highestBid != null ? highestBid.CustomerId : ""); + highestBid?.CustomerId ?? ""); } - public virtual async Task UpdateHighestBid(Product product, double bid, string highestBidder) + public virtual async Task UpdateHighestBid(Product product, double bid, string? highestBidder) { product.HighestBid = bid; product.HighestBidder = highestBidder; diff --git a/src/Business/Grand.Business.Catalog/Services/Products/CustomerGroupProductService.cs b/src/Business/Grand.Business.Catalog/Services/Products/CustomerGroupProductService.cs index e801ca8a1..9e16cc477 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/CustomerGroupProductService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/CustomerGroupProductService.cs @@ -92,7 +92,7 @@ public virtual async Task> GetCustomerGroupProducts( /// Customer group id /// Product id /// Customer group product - public virtual async Task GetCustomerGroupProduct(string customerGroupId, string productId) + public virtual async Task GetCustomerGroupProduct(string customerGroupId, string productId) { return await _customerGroupProductRepository.FirstOrDefaultAsync(_customerGroupProductRepository.Table .Where(x => x.CustomerGroupId == customerGroupId && x.ProductId == productId) @@ -104,7 +104,7 @@ public virtual async Task GetCustomerGroupProduct(string c ///
/// Ident /// Customer group product - public virtual async Task GetCustomerGroupProductById(string id) + public virtual async Task GetCustomerGroupProductById(string id) { var query = from cr in _customerGroupProductRepository.Table where cr.Id == id diff --git a/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs b/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs index f6e72f999..7cb8cd053 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/InventoryManageService.cs @@ -105,7 +105,7 @@ private async Task ManageAttributesInventory(Product product, Shipment shipment, /// /// The journal entries of a shipment item: its bookings and their reversals, for every product it touched /// - private async Task> ShipmentEntries(string positionId, string productId = null) + private async Task> ShipmentEntries(string positionId, string? productId = null) { var query = _inventoryJournalRepository.Table.Where(j => j.PositionId == positionId && j.ObjectType == nameof(Shipment)); @@ -145,16 +145,17 @@ private static List ShippedNumbers(IEnumerable entries /// The keys of every product a stock write for this product touches: its bundle products and the products /// associated with the chosen attribute values ///
- private static IEnumerable ProductKeys(Product product, IList attributes) + private static IEnumerable ProductKeys(Product product, IList? attributes) { yield return LockKey(product.Id); if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStockByBundleProducts) foreach (var item in product.BundleProducts) - yield return LockKey(item.ProductId); + if (item.ProductId != null) + yield return LockKey(item.ProductId); foreach (var attributeValue in product.ParseProductAttributeValues(attributes)) - if (attributeValue.AttributeValueTypeId == AttributeValueType.AssociatedToProduct) + if (attributeValue.AttributeValueTypeId == AttributeValueType.AssociatedToProduct && attributeValue.AssociatedProductId != null) yield return LockKey(attributeValue.AssociatedProductId); } @@ -167,7 +168,7 @@ private static string LockKey(string productId) /// The warehouse to count the stock of: a product kept in one warehouse has all its stock there, also when the /// order item names the store's default warehouse ///
- private static string StockWarehouse(Product product, string warehouseId) + private static string? StockWarehouse(Product product, string? warehouseId) { return product.UseMultipleWarehouses ? warehouseId : ""; } @@ -176,7 +177,7 @@ private static string StockWarehouse(Product product, string warehouseId) /// Whether the stored stock covers the quantity, by the rule the shopping cart applies ///
private async Task IsAvailable(Product product, int quantity, IList attributes, - string warehouseId) + string? warehouseId) { if (product.ManageInventoryMethodId != ManageInventoryMethod.ManageStockByBundleProducts) return _stockQuantityService.CheckStock(product, quantity, attributes, StockWarehouse(product, warehouseId)) @@ -207,7 +208,7 @@ private async Task IsAvailable(Product product, int quantity, IListAttributes /// Warehouse ident public virtual async Task AdjustReserved(Product product, int quantityToChange, - IList attributes = null, string warehouseId = "") + IList? attributes = null, string? warehouseId = "") { ArgumentNullException.ThrowIfNull(product); @@ -225,7 +226,7 @@ public virtual async Task AdjustReserved(Product product, int quantityToChange, } public virtual async Task TryReserve(Product product, int quantity, IList attributes, - string warehouseId) + string? warehouseId) { ArgumentNullException.ThrowIfNull(product); @@ -240,7 +241,7 @@ public virtual async Task TryReserve(Product product, int quantity, IList< } public virtual async Task CancelReservation(Product product, int quantity, IList attributes, - string warehouseId) + string? warehouseId) { ArgumentNullException.ThrowIfNull(product); @@ -260,8 +261,8 @@ public virtual async Task CancelReservation(Product product, int quantity, IList /// Adjusts the reserved inventory of a product read under the lock; never takes the lock itself ///
/// The reservation is given back for an order that was never placed - private async Task AdjustReservedCore(Product product, int quantityToChange, IList attributes, - string warehouseId, bool restoreLowStock = false) + private async Task AdjustReservedCore(Product product, int quantityToChange, IList? attributes, + string? warehouseId, bool restoreLowStock = false) { if (quantityToChange == 0) return; @@ -353,7 +354,7 @@ await AdjustReservedCore(associatedProduct, quantityToChange * attributeValue.Qu /// Product /// Quantity, must be negative /// - protected virtual async Task ReserveInventory(Product product, int quantity, string warehouseId) + protected virtual async Task ReserveInventory(Product product, int quantity, string? warehouseId) { ArgumentNullException.ThrowIfNull(product); @@ -395,7 +396,7 @@ protected virtual async Task ReserveInventory(Product product, int quantity, str /// Quantity, must be negative /// Warehouse ident protected virtual async Task ReserveInventoryCombination(Product product, ProductAttributeCombination combination, - int quantity, string warehouseId) + int quantity, string? warehouseId) { ArgumentNullException.ThrowIfNull(product); ArgumentNullException.ThrowIfNull(combination); @@ -449,7 +450,7 @@ await _productRepository.UpdateOneAsync(x => x.Id == product.Id, /// Product /// Quantity, must be positive /// Warehouse ident - protected virtual async Task UnblockReservedInventory(Product product, int quantity, string warehouseId) + protected virtual async Task UnblockReservedInventory(Product product, int quantity, string? warehouseId) { ArgumentNullException.ThrowIfNull(product); @@ -493,7 +494,7 @@ protected virtual async Task UnblockReservedInventory(Product product, int quant /// Quantity, must be positive /// Warehouse ident protected virtual async Task UnblockReservedInventoryCombination(Product product, - ProductAttributeCombination combination, int quantity, string warehouseId) + ProductAttributeCombination combination, int quantity, string? warehouseId) { ArgumentNullException.ThrowIfNull(product); diff --git a/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs b/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs index 29c4e5b62..9d68270e0 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/OutOfStockSubscriptionService.cs @@ -71,7 +71,7 @@ public virtual async Task> GetAllSubscription /// Store identifier /// Warehouse identifier /// Subscriptions - public virtual async Task FindSubscription(string customerId, string productId, + public virtual async Task FindSubscription(string customerId, string productId, IList attributes, string storeId, string warehouseId) { var query = from biss in _outOfStockSubscriptionRepository.Table @@ -95,7 +95,7 @@ orderby biss.CreatedOnUtc descending ///
/// Subscription identifier /// Subscription - public virtual async Task GetSubscriptionById(string subscriptionId) + public virtual async Task GetSubscriptionById(string subscriptionId) { var subscription = await _outOfStockSubscriptionRepository.GetByIdAsync(subscriptionId); return subscription; diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs index ec13d9c5d..c9f2bdf4e 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeFormatter.cs @@ -54,7 +54,7 @@ public ProductAttributeFormatter(IProductAttributeService productAttributeServic /// Show in admin /// Attributes public virtual async Task FormatAttributes(Product product, IList customAttributes, - CalculationContext context, Language language, DomainHost host, + CalculationContext? context, Language? language, DomainHost host, string separator = "
", bool htmlEncode = true, bool renderPrices = true, bool renderProductAttributes = true, bool renderGiftVoucherAttributes = true, bool allowHyperlinks = true, bool showInAdmin = false) @@ -137,7 +137,7 @@ public virtual async Task FormatAttributes(Product product, IList PrepareFormattedAttribute(Product product, - IList customAttributes, CalculationContext context, string langId, + IList customAttributes, CalculationContext? context, string langId, DomainHost host, string separator, bool htmlEncode, bool renderPrices, bool allowHyperlinks, bool showInAdmin) { @@ -217,7 +217,7 @@ private async Task PrepareFormattedAttribute(Product product, formattedAttribute = $"{productAttribute.GetTranslation(a => a.Name, langId)}: {attributeValue.GetTranslation(a => a.Name, langId)}"; - if (renderPrices) + if (renderPrices && context != null) { var attributeValuePriceAdjustment = await _pricingService.GetProductAttributeValuePriceAdjustment(attributeValue, diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs index b89be22a6..7e1027083 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductAttributeService.cs @@ -98,7 +98,7 @@ public virtual async Task> GetAllProductAttributes( ///
/// Product attribute identifier /// Product attribute - public virtual Task GetProductAttributeById(string productAttributeId) + public virtual Task GetProductAttributeById(string? productAttributeId) { var key = string.Format(CacheKey.PRODUCTATTRIBUTES_BY_ID_KEY, productAttributeId); return _cacheBase.GetAsync(key, () => _productAttributeRepository.GetByIdAsync(productAttributeId)); @@ -229,7 +229,7 @@ public virtual async Task DeleteProductAttributeValue(ProductAttributeValue prod { var pavs = p.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMappingId); var pav = pavs?.ProductAttributeValues.FirstOrDefault(x => x.Id == productAttributeValue.Id); - if (pav != null) + if (pavs != null && pav != null) { pavs.ProductAttributeValues.Remove(pav); await _productRepository.UpdateCollectionFieldItem(productId, x => x.ProductAttributeMappings, z => z.Id == productAttributeMappingId, pavs); @@ -283,7 +283,7 @@ public virtual async Task UpdateProductAttributeValue(ProductAttributeValue prod var p = await _productRepository.GetByIdAsync(productId); var pavs = p?.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMappingId); var pav = pavs?.ProductAttributeValues.FirstOrDefault(x => x.Id == productAttributeValue.Id); - if (pav != null) + if (pavs != null && pav != null) { pav.AttributeValueTypeId = productAttributeValue.AttributeValueTypeId; pav.AssociatedProductId = productAttributeValue.AssociatedProductId; diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs index b070529a7..acc376880 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductCourseService.cs @@ -21,12 +21,12 @@ public ProductCourseService(IRepository productRepository, IRepository< _mediator = mediator; } - public virtual async Task GetCourseByProductId(string productId) + public virtual async Task GetCourseByProductId(string productId) { return await _courseRepository.GetOneAsync(p => p.ProductId == productId); } - public virtual async Task GetProductByCourseId(string courseId) + public virtual async Task GetProductByCourseId(string courseId) { return await _productRepository.GetOneAsync(p => p.CourseId == courseId); } diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductLayoutService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductLayoutService.cs index 7e2faacd5..4755fe736 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductLayoutService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductLayoutService.cs @@ -62,7 +62,7 @@ orderby pt.DisplayOrder ///
/// Product layout identifier /// Product layout - public virtual Task GetProductLayoutById(string productLayoutId) + public virtual Task GetProductLayoutById(string productLayoutId) { var key = string.Format(CacheKey.PRODUCT_LAYOUT_BY_ID_KEY, productLayoutId); return _cacheBase.GetAsync(key, () => _productLayoutRepository.GetByIdAsync(productLayoutId)); diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs index d2e6f2db3..745b13c89 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductReservationService.cs @@ -106,7 +106,7 @@ public virtual async Task DeleteProductReservation(ProductReservation productRes ///
/// Product ident /// Product reservation - public virtual Task GetProductReservation(string id) + public virtual Task GetProductReservation(string? id) { return _productReservationRepository.GetByIdAsync(id); } @@ -156,7 +156,7 @@ await _productReservationRepository.UpdateManyAsync(x => x.OrderId == orderId, ///
/// /// CustomerReservationsHelper - public virtual Task GetCustomerReservationsHelperById(string id) + public virtual Task GetCustomerReservationsHelperById(string id) { return _customerReservationsHelperRepository.GetByIdAsync(id); } diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs index 90803d956..db4d10110 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductReviewService.cs @@ -35,9 +35,9 @@ public ProductReviewService(IRepository productReviewRepository, /// Page index /// Page size /// Reviews - public virtual async Task> GetAllProductReviews(string customerId, bool? approved, + public virtual async Task> GetAllProductReviews(string? customerId, bool? approved, DateTime? fromUtc = null, DateTime? toUtc = null, - string message = null, string storeId = "", string productId = "", int pageIndex = 0, + string? message = null, string? storeId = "", string productId = "", int pageIndex = 0, int pageSize = int.MaxValue) { var query = from p in _productReviewRepository.Table @@ -117,7 +117,7 @@ public virtual async Task DeleteProductReview(ProductReview productReview) ///
/// Product review identifier /// Product review - public virtual Task GetProductReviewById(string productReviewId) + public virtual Task GetProductReviewById(string productReviewId) { return _productReviewRepository.GetByIdAsync(productReviewId); } diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs index a93d566f3..51a2a3145 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductService.cs @@ -99,7 +99,7 @@ public virtual async Task> GetAllProductsDisplayedOnBestSeller() /// Product identifier /// get data from db (not from cache) /// Product - public virtual async Task GetProductById(string productId, bool fromDb = false) + public virtual async Task GetProductById(string? productId, bool fromDb = false) { if (string.IsNullOrEmpty(productId)) return null; @@ -116,7 +116,7 @@ public virtual async Task GetProductById(string productId, bool fromDb ///
/// Product identifier /// Product - public virtual async Task GetProductByIdIncludeArch(string productId) + public virtual async Task GetProductByIdIncludeArch(string? productId) { if (string.IsNullOrEmpty(productId)) return null; @@ -140,14 +140,14 @@ public virtual async Task> GetProductsByIds(string[] productIds, //cached products are taken as they are; only the misses are read from the database, with one //query per batch, so a cold cache costs one round trip instead of one per identifier - var resolved = new Dictionary(); + var resolved = new Dictionary(); var missing = new List(); foreach (var id in productIds) { if (string.IsNullOrEmpty(id) || resolved.ContainsKey(id)) continue; - if (_cacheBase.TryGet(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, id), out Product cached)) + if (_cacheBase.TryGet(string.Format(CacheKey.PRODUCTS_BY_ID_KEY, id), out Product? cached)) resolved[id] = cached; else { @@ -223,9 +223,10 @@ public virtual async Task UpdateProduct(Product product) { ArgumentNullException.ThrowIfNull(product); - var oldProduct = await _productRepository.GetByIdAsync(product.Id); + var oldProduct = await _productRepository.GetByIdAsync(product.Id) ?? + throw new ArgumentException("The product to update does not exist", nameof(product)); //the batches and serial numbers assigned stay where they are: nothing else may break them - if (oldProduct != null && await _productUnitService.TrackingChangeRefused(oldProduct, product) is { } refused) + if (await _productUnitService.TrackingChangeRefused(oldProduct, product) is { } refused) throw new InvalidOperationException(refused); //update var update = UpdateBuilder.Create() @@ -485,7 +486,7 @@ public virtual async Task UnPublishProduct(Product product) /// Ignore acl /// Ignore store /// Product number - public virtual int GetCategoryProductNumber(Customer customer, IList categoryIds = null, + public virtual int GetCategoryProductNumber(Customer customer, IList? categoryIds = null, string storeId = "", bool ignoreAcl = true, bool ignoreStore = true) { //validate "categoryIds" parameter @@ -499,7 +500,7 @@ public virtual int GetCategoryProductNumber(Customer customer, IList cat ////category filtering if (categoryIds != null && categoryIds.Any()) - query = query.Where(p => p.ProductCategories.Any(x => categoryIds.Contains(x.CategoryId))); + query = query.Where(p => p.ProductCategories.Any(x => x.CategoryId != null && categoryIds.Contains(x.CategoryId))); if (!ignoreAcl) { @@ -569,7 +570,7 @@ public virtual int GetCategoryProductNumber(Customer customer, IList cat bool loadFilterableSpecificationAttributeOptionIds = false, int pageIndex = 0, int pageSize = int.MaxValue, - IList categoryIds = null, + IList? categoryIds = null, string brandId = "", string collectionId = "", string vendorId = "", @@ -582,13 +583,13 @@ public virtual int GetCategoryProductNumber(Customer customer, IList cat double? priceMin = null, double? priceMax = null, string productTag = "", - string keywords = null, + string? keywords = null, bool searchDescriptions = false, bool searchSku = true, bool searchProductTags = false, string languageId = "", - IList filteredSpecs = null, - IList specificationOptions = null, + IList? filteredSpecs = null, + IList? specificationOptions = null, ProductSortingEnum orderBy = ProductSortingEnum.Position, bool? overridePublished = null) { @@ -697,7 +698,7 @@ public virtual async Task> GetAssociatedProducts(string parentGro ///
/// SKU /// Product - public virtual async Task GetProductBySku(string sku) + public virtual async Task GetProductBySku(string? sku) { if (string.IsNullOrEmpty(sku)) return null; @@ -785,6 +786,7 @@ public virtual async Task InsertSimilarProduct(SimilarProduct similarProduct) { ArgumentNullException.ThrowIfNull(similarProduct); + ArgumentException.ThrowIfNullOrEmpty(similarProduct.ProductId1); await _productRepository.AddToCollectionField(similarProduct.ProductId1, x => x.SimilarProducts, similarProduct); await _mediator.Publish(new ProductChangedEvent(similarProduct.ProductId1)); @@ -801,6 +803,7 @@ public virtual async Task UpdateSimilarProduct(SimilarProduct similarProduct) { ArgumentNullException.ThrowIfNull(similarProduct); + ArgumentException.ThrowIfNullOrEmpty(similarProduct.ProductId1); await _productRepository.UpdateCollectionFieldItem(similarProduct.ProductId1, x => x.SimilarProducts, z => z.Id == similarProduct.Id, similarProduct); await _mediator.Publish(new ProductChangedEvent(similarProduct.ProductId1)); @@ -817,6 +820,7 @@ public virtual async Task DeleteSimilarProduct(SimilarProduct similarProduct) { ArgumentNullException.ThrowIfNull(similarProduct); + ArgumentException.ThrowIfNullOrEmpty(similarProduct.ProductId1); await _productRepository.RemoveCollectionFieldItem(similarProduct.ProductId1, x => x.SimilarProducts, z => z.Id == similarProduct.Id); await _mediator.Publish(new ProductChangedEvent(similarProduct.ProductId1)); @@ -892,6 +896,7 @@ public virtual async Task InsertCrossSellProduct(CrossSellProduct crossSellProdu { ArgumentNullException.ThrowIfNull(crossSellProduct); + ArgumentException.ThrowIfNullOrEmpty(crossSellProduct.ProductId1); await _productRepository.AddToCollectionField(crossSellProduct.ProductId1, x => x.CrossSellProduct, crossSellProduct.ProductId2); @@ -909,6 +914,7 @@ public virtual async Task DeleteCrossSellProduct(CrossSellProduct crossSellProdu { ArgumentNullException.ThrowIfNull(crossSellProduct); + ArgumentException.ThrowIfNullOrEmpty(crossSellProduct.ProductId1); await _productRepository.RemoveCollectionFieldItem(crossSellProduct.ProductId1, x => x.CrossSellProduct, y => y == crossSellProduct.ProductId2); await _mediator.Publish(new ProductChangedEvent(crossSellProduct.ProductId1)); @@ -941,7 +947,7 @@ public virtual async Task> GetCrossSellProductsByShoppingCart(ILi var cartProductIds = new List(); foreach (var sci in cart) - if (!cartProductIds.Contains(sci.ProductId)) + if (sci.ProductId != null && !cartProductIds.Contains(sci.ProductId)) cartProductIds.Add(sci.ProductId); foreach (var sci in cart) @@ -1075,6 +1081,7 @@ public virtual async Task InsertProductPrice(ProductPrice productPrice) { ArgumentNullException.ThrowIfNull(productPrice); + ArgumentException.ThrowIfNullOrEmpty(productPrice.ProductId); await _productRepository.AddToCollectionField(productPrice.ProductId, x => x.ProductPrices, productPrice); await _mediator.Publish(new ProductChangedEvent(productPrice.ProductId)); @@ -1091,6 +1098,7 @@ public virtual async Task UpdateProductPrice(ProductPrice productPrice) { ArgumentNullException.ThrowIfNull(productPrice); + ArgumentException.ThrowIfNullOrEmpty(productPrice.ProductId); await _productRepository.UpdateCollectionFieldItem(productPrice.ProductId, x => x.ProductPrices, z => z.Id == productPrice.Id, productPrice); await _mediator.Publish(new ProductChangedEvent(productPrice.ProductId)); @@ -1107,6 +1115,7 @@ public virtual async Task DeleteProductPrice(ProductPrice productPrice) { ArgumentNullException.ThrowIfNull(productPrice); + ArgumentException.ThrowIfNullOrEmpty(productPrice.ProductId); await _productRepository.RemoveCollectionFieldItem(productPrice.ProductId, x => x.ProductPrices, x => x.Id == productPrice.Id); await _mediator.Publish(new ProductChangedEvent(productPrice.ProductId)); @@ -1238,7 +1247,7 @@ public virtual async Task DeleteProductWarehouseInventory(ProductWarehouseInvent { var product = await _productRepository.GetByIdAsync(productId); var row = product?.ProductWarehouseInventory.FirstOrDefault(x => x.Id == pwi.Id); - if (row == null) + if (product == null || row == null) return; if (product.ManageInventoryMethodId == ManageInventoryMethod.ManageStock && product.UseMultipleWarehouses) diff --git a/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs b/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs index 70ba84735..ef37a9184 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/ProductTagService.cs @@ -83,7 +83,7 @@ public virtual async Task> GetAllProductTags() ///
/// Product tag identifier /// Product tag - public virtual Task GetProductTagById(string productTagId) + public virtual Task GetProductTagById(string productTagId) { return _productTagRepository.GetByIdAsync(productTagId); } @@ -93,7 +93,7 @@ public virtual Task GetProductTagById(string productTagId) ///
/// Product tag name /// Product tag - public virtual Task GetProductTagByName(string name) + public virtual Task GetProductTagByName(string name) { return _productTagRepository.GetOneAsync(x => x.Name == name); } @@ -103,7 +103,7 @@ public virtual Task GetProductTagByName(string name) ///
/// Product tag se-name /// Product tag - public virtual Task GetProductTagBySeName(string sename) + public virtual Task GetProductTagBySeName(string sename) { return _productTagRepository.GetOneAsync(x => x.SeName == sename); } @@ -134,12 +134,15 @@ public virtual async Task UpdateProductTag(ProductTag productTag) await _productTagRepository.UpdateAsync(productTag); - //update on products - var products = _productRepository.Table.Where(x => x.ProductTags.Contains(previous.Name)).ToList(); - foreach (var product in products) + //update on products; a tag that was not stored has no products to rename it on + if (previous != null) { - var tags = product.ProductTags.Select(t => t == previous.Name ? productTag.Name : t).ToList(); - await _productRepository.UpdateField(product.Id, x => x.ProductTags, tags); + var products = _productRepository.Table.Where(x => x.ProductTags.Contains(previous.Name)).ToList(); + foreach (var product in products) + { + var tags = product.ProductTags.Select(t => t == previous.Name ? productTag.Name : t).ToList(); + await _productRepository.UpdateField(product.Id, x => x.ProductTags, tags); + } } //event notification diff --git a/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs b/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs index 00000d23c..644fb5389 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs @@ -52,7 +52,7 @@ public SpecificationAttributeService(ICacheBase cacheBase, ///
/// The specification attribute identifier /// Specification attribute - public virtual async Task GetSpecificationAttributeById(string specificationAttributeId) + public virtual async Task GetSpecificationAttributeById(string specificationAttributeId) { var key = string.Format(CacheKey.SPECIFICATION_BY_ID_KEY, specificationAttributeId); return await _cacheBase.GetAsync(key, @@ -64,10 +64,10 @@ public virtual async Task GetSpecificationAttributeById( ///
/// Se-name /// Specification attribute - public virtual async Task GetSpecificationAttributeBySeName(string sename) + public virtual async Task GetSpecificationAttributeBySeName(string sename) { if (string.IsNullOrEmpty(sename)) - return await Task.FromResult(null); + return await Task.FromResult(null); sename = sename.ToLowerInvariant(); @@ -157,11 +157,11 @@ public virtual async Task DeleteSpecificationAttribute(SpecificationAttribute sp ///
/// The specification attribute option identifier /// Specification attribute option - public virtual async Task GetSpecificationAttributeByOptionId( + public virtual async Task GetSpecificationAttributeByOptionId( string specificationAttributeOptionId) { if (string.IsNullOrEmpty(specificationAttributeOptionId)) - return await Task.FromResult(null); + return await Task.FromResult(null); var key = string.Format(CacheKey.SPECIFICATION_BY_OPTIONID_KEY, specificationAttributeOptionId); return await _cacheBase.GetAsync(key, async () => @@ -186,9 +186,9 @@ public virtual async Task DeleteSpecificationAttributeOption( await _productRepository.RemoveCollectionFieldItem(string.Empty, x => x.ProductSpecificationAttributes, z => z.SpecificationAttributeOptionId == specificationAttributeOption.Id); var specificationAttribute = await GetSpecificationAttributeByOptionId(specificationAttributeOption.Id); - var sao = specificationAttribute.SpecificationAttributeOptions.FirstOrDefault(x => + var sao = specificationAttribute?.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == specificationAttributeOption.Id); - if (sao == null) + if (specificationAttribute == null || sao == null) throw new ArgumentException("No specification attribute option found with the specified id"); specificationAttribute.SpecificationAttributeOptions.Remove(sao); diff --git a/src/Business/Grand.Business.Catalog/Services/Products/StockQuantityService.cs b/src/Business/Grand.Business.Catalog/Services/Products/StockQuantityService.cs index bafe6c526..b79476a4b 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/StockQuantityService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/StockQuantityService.cs @@ -10,7 +10,7 @@ namespace Grand.Business.Catalog.Services.Products; public class StockQuantityService : IStockQuantityService { public virtual int GetTotalStockQuantity(Product product, bool useReservedQuantity = true, - string warehouseId = "", bool total = false) + string? warehouseId = "", bool total = false) { ArgumentNullException.ThrowIfNull(product); @@ -41,7 +41,7 @@ public virtual int GetTotalStockQuantity(Product product, bool useReservedQuanti } public virtual int GetTotalStockQuantityForCombination(Product product, ProductAttributeCombination combination, - bool useReservedQuantity = true, string warehouseId = "") + bool useReservedQuantity = true, string? warehouseId = "") { ArgumentNullException.ThrowIfNull(product); ArgumentNullException.ThrowIfNull(combination); @@ -67,7 +67,7 @@ public virtual int GetTotalStockQuantityForCombination(Product product, ProductA return 0; } - public virtual (string resource, object? arg0) FormatStockMessage(Product product, string warehouseId, + public virtual (string resource, object? arg0) FormatStockMessage(Product product, string? warehouseId, IList attributes) { var status = GetStockStatus(product, warehouseId, attributes); @@ -75,7 +75,7 @@ public virtual (string resource, object? arg0) FormatStockMessage(Product produc } public virtual StockCheck CheckStock(Product product, int quantity, IList? attributes, - string warehouseId) + string? warehouseId) { ArgumentNullException.ThrowIfNull(product); @@ -104,7 +104,7 @@ public virtual StockCheck CheckStock(Product product, int quantity, IList attributes) { ArgumentNullException.ThrowIfNull(product); @@ -129,7 +129,7 @@ public virtual StockStatus GetStockStatus(Product product, string warehouseId, return status; } - private StockStatus StockByAttributesStatus(Product product, string warehouseId, + private StockStatus StockByAttributesStatus(Product product, string? warehouseId, IList attributes) { var combination = product.FindProductAttributeCombination(attributes); @@ -155,7 +155,7 @@ private StockStatus StockByAttributesStatus(Product product, string warehouseId, }; } - private StockStatus StockInventoryStatus(Product product, string warehouseId) + private StockStatus StockInventoryStatus(Product product, string? warehouseId) { var stockQuantity = GetTotalStockQuantity(product, warehouseId: warehouseId); if (stockQuantity > 0) diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs index 029d020e7..09959b99b 100644 --- a/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Tax/TaxCategoryService.cs @@ -64,7 +64,7 @@ public virtual async Task> GetAllTaxCategories(string storeId ///
/// Tax category identifier /// Tax category - public virtual Task GetTaxCategoryById(string taxCategoryId) + public virtual Task GetTaxCategoryById(string taxCategoryId) { var key = string.Format(CacheKey.TAXCATEGORIES_BY_ID_KEY, taxCategoryId); return _cacheBase.GetAsync(key, () => _taxCategoryRepository.GetByIdAsync(taxCategoryId)); diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs index f3e3a6a43..923947c98 100644 --- a/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Tax/TaxService.cs @@ -66,7 +66,7 @@ protected virtual async Task IsEuConsumer(Customer customer) { ArgumentNullException.ThrowIfNull(customer); - Country country = null; + Country? country = null; //get country from billing address if (_addressSettings.CountryEnabled && customer.BillingAddress != null) @@ -96,7 +96,7 @@ protected virtual async Task IsEuConsumer(Customer customer) /// Customer /// Price /// Package for tax calculation - protected virtual async Task CreateCalculateTaxRequest(Product product, string taxCategoryId, Customer customer, Store store, double price) + protected virtual async Task CreateCalculateTaxRequest(Product? product, string? taxCategoryId, Customer customer, Store? store, double price) { ArgumentNullException.ThrowIfNull(customer); @@ -130,7 +130,7 @@ protected virtual async Task CreateCalculateTaxRequest(Product produ if (basedOn == TaxBasedOn.ShippingAddress && customer.ShippingAddress == null) basedOn = TaxBasedOn.DefaultAddress; - Address address; + Address? address; switch (basedOn) { @@ -183,7 +183,7 @@ protected virtual double CalculatePrice(double price, double percent, bool incre /// Tax category identifier /// Customer /// Price (taxable value) - protected virtual async Task<(double taxRate, bool isTaxable)> GetTaxRate(Product product, string taxCategoryId, Customer customer, Store store, double price) + protected virtual async Task<(double taxRate, bool isTaxable)> GetTaxRate(Product? product, string? taxCategoryId, Customer customer, Store? store, double price) { double taxRate = 0; var isTaxable = true; @@ -234,7 +234,7 @@ await IsVatExempt(calculateTaxRequest.Address, calculateTaxRequest.Customer)) /// Customer whose groups limit the fallback providers /// Store whose providers are the fallback /// Active tax provider - public virtual ITaxProvider LoadActiveTaxProvider(Customer customer, string storeId) + public virtual ITaxProvider? LoadActiveTaxProvider(Customer customer, string? storeId) { var taxProvider = LoadTaxProviderBySystemName(_taxProviderSettings.ActiveTaxProviderSystemName) ?? LoadAllTaxProviders(customer, storeId) @@ -247,7 +247,7 @@ public virtual ITaxProvider LoadActiveTaxProvider(Customer customer, string stor ///
/// System name /// Found tax provider - public virtual ITaxProvider LoadTaxProviderBySystemName(string systemName) + public virtual ITaxProvider? LoadTaxProviderBySystemName(string? systemName) { return _taxProviders.FirstOrDefault(x => x.SystemName.Equals(systemName, StringComparison.OrdinalIgnoreCase)); } @@ -258,7 +258,7 @@ public virtual ITaxProvider LoadTaxProviderBySystemName(string systemName) /// Customer /// Store ident /// Tax providers - public virtual IList LoadAllTaxProviders(Customer customer = null, string storeId = "") + public virtual IList LoadAllTaxProviders(Customer? customer = null, string? storeId = "") { return _taxProviders .Where(x => @@ -295,8 +295,8 @@ public virtual IList LoadAllTaxProviders(Customer customer = null, /// Store /// A value indicating whether price already includes tax /// Price - public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product product, - string taxCategoryId, + public virtual async Task<(double productprice, double taxRate)> GetProductPrice(Product? product, + string? taxCategoryId, double price, bool includingTax, Customer customer, Store store, bool priceIncludesTax) { @@ -502,7 +502,7 @@ bool priceIncludesTax /// Product /// Customer /// A value indicating whether a product is tax exempt - public virtual async Task IsTaxExempt(Product product, Customer customer) + public virtual async Task IsTaxExempt(Product? product, Customer? customer) { if (customer == null) return product is { IsTaxExempt: true }; if (customer.IsTaxExempt) @@ -521,7 +521,7 @@ public virtual async Task IsTaxExempt(Product product, Customer customer) /// Address /// Customer /// Result - public virtual async Task IsVatExempt(Address address, Customer customer) + public virtual async Task IsVatExempt(Address? address, Customer? customer) { if (!_taxSettings.EuVatEnabled) return false; @@ -530,7 +530,8 @@ public virtual async Task IsVatExempt(Address address, Customer customer) return false; var country = await _countryService.GetCountryById(address.CountryId); - if (!country.SubjectToVat) + //an unknown country is outside the VAT zone + if (country?.SubjectToVat != true) // VAT not chargeable if shipping outside VAT zone return true; diff --git a/src/Business/Grand.Business.Catalog/Services/Tax/VatService.cs b/src/Business/Grand.Business.Catalog/Services/Tax/VatService.cs index e707c362a..12d6636d7 100644 --- a/src/Business/Grand.Business.Catalog/Services/Tax/VatService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Tax/VatService.cs @@ -19,7 +19,7 @@ public VatService(TaxSettings taxSettings) ///
/// Two letter ISO code of a country and VAT number (e.g. GB 111 1111 111) /// VAT Number status - public virtual async Task<(VatNumberStatus status, string name, string address, Exception exception)> + public virtual async Task<(VatNumberStatus status, string? name, string? address, Exception? exception)> GetVatNumberStatus(string fullVatNumber) { var name = string.Empty; @@ -48,7 +48,7 @@ public VatService(TaxSettings taxSettings) /// Two letter ISO code of a country /// VAT number /// VAT Number status - public virtual async Task<(VatNumberStatus status, string name, string address, Exception exception)> + public virtual async Task<(VatNumberStatus status, string? name, string? address, Exception? exception)> GetVatNumberStatus(string twoLetterIsoCode, string vatNumber) { var name = string.Empty; @@ -75,7 +75,7 @@ public VatService(TaxSettings taxSettings) /// Two letter ISO code of a country /// VAT number /// VAT number status - public virtual async Task<(VatNumberStatus status, string name, string address, Exception exception)> + public virtual async Task<(VatNumberStatus status, string? name, string? address, Exception? exception)> DoVatCheck(string twoLetterIsoCode, string vatNumber) { vatNumber ??= string.Empty; diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ApplyOrderApprovalDecisionCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ApplyOrderApprovalDecisionCommandHandler.cs index 8e8fa7e0f..95fbf7b4b 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ApplyOrderApprovalDecisionCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ApplyOrderApprovalDecisionCommandHandler.cs @@ -8,6 +8,7 @@ using Grand.Domain.Orders; using Grand.Domain.Payments; using Grand.Mediator; +using Grand.SharedKernel; using Microsoft.Extensions.Logging; namespace Grand.Business.Checkout.Commands.Handlers.Orders; @@ -99,7 +100,8 @@ await Guard(approval.Id, "decision e-mail", async () => return; // the buyer reads it: in the language the order was placed in, not the approver's - var store = await _storeService.GetStoreById(approval.StoreId); + var store = await _storeService.GetStoreById(approval.StoreId) ?? + throw new GrandException($"The store {approval.StoreId} of the order approval does not exist"); var languageId = string.IsNullOrEmpty(order.CustomerLanguageId) ? request.Language?.Id : order.CustomerLanguageId; @@ -116,7 +118,7 @@ await _messageProviderService.SendOrderApprovalDecidedMessage(approval, buyer, s return true; } - private async Task ContinueApproved(Order order, Customer buyer, ApplyOrderApprovalDecisionCommand request, + private async Task ContinueApproved(Order order, Customer? buyer, ApplyOrderApprovalDecisionCommand request, CancellationToken cancellationToken) { await Guard(order.Id, "order status check", @@ -149,7 +151,7 @@ private async Task Guard(string id, string step, Func run) } } - private static string NormalizeComment(string comment) + private static string? NormalizeComment(string? comment) { if (string.IsNullOrWhiteSpace(comment)) return null; diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandler.cs index 0f30e2ddc..3b5b495d0 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/AwardLoyaltyPointsCommandHandler.cs @@ -7,6 +7,7 @@ using Grand.Business.Core.Interfaces.Customers; using Grand.Domain.Orders; using Grand.Mediator; +using Grand.SharedKernel; namespace Grand.Business.Checkout.Commands.Handlers.Orders; @@ -46,13 +47,14 @@ public async Task Handle(AwardLoyaltyPointsCommand request, CancellationTo ArgumentNullException.ThrowIfNull(request.Order); var customer = await _customerService.GetCustomerById(request.Order.CustomerId); - var currency = await _currencyService.GetCurrencyByCode(request.Order.CustomerCurrencyCode); + var currency = await _currencyService.GetCurrencyByCode(request.Order.CustomerCurrencyCode) ?? + throw new GrandException($"The currency {request.Order.CustomerCurrencyCode} of order {request.Order.OrderNumber} does not exist"); var amount = await _currencyService.ConvertToPrimaryStoreCurrency( request.Order.OrderTotal - request.Order.OrderShippingInclTax, currency); var points = await _mediator.Send(new CalculateLoyaltyPointsCommand { Customer = customer, Amount = amount }, cancellationToken); - if (points <= 0) + if (customer == null || points <= 0) return false; //add loyalty points diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderCommandHandler.cs index a107d2778..ddcd526ca 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CancelOrderCommandHandler.cs @@ -80,6 +80,9 @@ await _orderService.InsertOrderNote(new OrderNote { foreach (var orderItem in request.Order.OrderItems) { var product = await _productService.GetProductById(orderItem.ProductId); + //a product deleted meanwhile has no stock to give back + if (product == null) + continue; await _inventoryManageService.AdjustReserved(product, orderItem.Quantity - orderItem.CancelQty, orderItem.Attributes, orderItem.WarehouseId); } diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs index b588dfdc6..ff198e9fe 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/CaptureCommandHandler.cs @@ -46,7 +46,7 @@ public async Task> Handle(CaptureCommand command, CancellationToke if (!canCapture) throw new GrandException("Cannot do capture for order."); - CapturePaymentResult result = null; + CapturePaymentResult? result = null; try { result = await _paymentService.Capture(paymentTransaction); @@ -56,7 +56,8 @@ public async Task> Handle(CaptureCommand command, CancellationToke if (result.Success) { - paymentTransaction = await _paymentTransaction.GetById(paymentTransaction.Id); + paymentTransaction = await _paymentTransaction.GetById(paymentTransaction.Id) ?? + throw new GrandException("The payment transaction was deleted while it was processed"); //a capture the gateway settles later is not money in yet: it is paid, and recorded, when it is var captured = result.NewPaymentStatus == TransactionStatus.Paid ? paymentTransaction.AmountLeftToPay() diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderNotificationCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderNotificationCommandHandler.cs index faec880b7..2c4223ab5 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderNotificationCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderNotificationCommandHandler.cs @@ -65,7 +65,7 @@ await _orderMessageProviderService.SendOrderPlacedStoreOwnerMessage(request.Orde if (request.NotifyCustomer) { - string invoiceDownloadId = null; + string? invoiceDownloadId = null; try { diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderStatusCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderStatusCommandHandler.cs index d5f7ce0ac..46cc1bdb3 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderStatusCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/OrderStatusCommandHandler.cs @@ -73,7 +73,7 @@ await _orderService.InsertOrderNote(new OrderNote { { //notification - string invoiceDownloadId = null; + string? invoiceDownloadId = null; try { diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs index a640b6821..3e9638f3f 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundCommandHandler.cs @@ -58,11 +58,10 @@ await _mediator.Send( if (!canPartiallyRefund) throw new GrandException("Cannot do partial refund for order."); - var request = new RefundPaymentRequest(); - RefundPaymentResult result = null; + var request = new RefundPaymentRequest { PaymentTransaction = paymentTransaction }; + RefundPaymentResult? result = null; try { - request.PaymentTransaction = paymentTransaction; request.AmountToRefund = amountToRefund; request.IsPartialRefund = true; @@ -70,7 +69,8 @@ await _mediator.Send( if (result.Success) { - paymentTransaction = await _paymentTransactionService.GetById(paymentTransaction.Id); + paymentTransaction = await _paymentTransactionService.GetById(paymentTransaction.Id) ?? + throw new GrandException("The payment transaction was deleted while it was processed"); paymentTransaction.RefundedAmount += amountToRefund; //a provider that gives no status leaves the one the refunded amount comes to, as the offline partial //refund sets it: a transaction left pending could not be refunded again diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs index 7e16f8915..102977a13 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PlaceOrderCommandHandler.cs @@ -226,7 +226,9 @@ public async Task Handle(PlaceOrderCommand command, Cancellati var paymentTransaction = await PreparePaymentTransaction(details); //what the order spends is taken before the payment, so no payment is taken for what is already gone - var claim = await _checkoutClaimService.Claim(details, paymentTransaction.OrderCode); + var orderCode = paymentTransaction.OrderCode ?? + throw new GrandException("The order code was not prepared"); + var claim = await _checkoutClaimService.Claim(details, orderCode); if (!claim.Succeeded) { var changed = _translationService.GetResource("ShoppingCart.ChangedDuringCheckout", @@ -406,7 +408,7 @@ protected virtual async Task PreparePaymentTransaction(Place paymentTransaction.TransactionAmount = details.OrderTotal; paymentTransaction.CurrencyRate = details.CurrencyRate; paymentTransaction.CurrencyCode = details.Currency.CurrencyCode; - paymentTransaction.CustomerEmail = details.Customer.BillingAddress.Email; + paymentTransaction.CustomerEmail = details.Customer.BillingAddress?.Email; paymentTransaction.Temp = true; if (update) @@ -518,10 +520,10 @@ protected virtual async Task PreparePlaceOrderDetails(Place throw new GrandException("Anonymous checkout is not allowed"); //billing address - if (details.Customer.BillingAddress == null) - throw new GrandException("Billing address is not provided"); + var billingAddress = details.Customer.BillingAddress ?? + throw new GrandException("Billing address is not provided"); - if (!CommonHelper.IsValidEmail(details.Customer.BillingAddress.Email)) + if (!CommonHelper.IsValidEmail(billingAddress.Email)) throw new GrandException("Email is not valid"); //affiliate @@ -538,22 +540,21 @@ protected virtual async Task PreparePlaceOrderDetails(Place details.Store.Id)); var customerCurrency = currencyTmp is { Published: true } ? currencyTmp : details.Context.Currency; details.Currency = customerCurrency; - var primaryStoreCurrency = await _currencyService.GetPrimaryStoreCurrency(); + var primaryStoreCurrency = await _currencyService.GetPrimaryStoreCurrency() ?? + throw new GrandException("The primary store currency is not set"); details.CurrencyRate = Math.Round(customerCurrency.Rate / primaryStoreCurrency.Rate, 6); details.PrimaryCurrencyCode = primaryStoreCurrency.CurrencyCode; //customer language - details.Language = await _languageService.GetLanguageById( + var language = await _languageService.GetLanguageById( details.Customer.GetUserFieldFromEntity(SystemCustomerFieldNames.LanguageId, details.Store.Id)); + details.Language = language is { Published: true } ? language : command.Language; - if (details.Language is not { Published: true }) - details.Language = command.Language; - - details.BillingAddress = details.Customer.BillingAddress; - if (!string.IsNullOrEmpty(details.BillingAddress.CountryId)) + details.BillingAddress = billingAddress; + if (!string.IsNullOrEmpty(billingAddress.CountryId)) { - var country = await _countryService.GetCountryById(details.BillingAddress.CountryId); + var country = await _countryService.GetCountryById(billingAddress.CountryId); if (country is { AllowsBilling: false }) throw new GrandException($"Country '{country.Name}' is not allowed for billing"); } @@ -561,7 +562,7 @@ protected virtual async Task PreparePlaceOrderDetails(Place //checkout attributes details.CheckoutAttributes = details.Customer.GetUserFieldFromEntity>(SystemCustomerFieldNames.CheckoutAttributes, - details.Store.Id); + details.Store.Id) ?? []; details.CheckoutAttributeDescription = await _checkoutAttributeFormatter.FormatAttributes(details.CheckoutAttributes, details.Context, details.WorkingLanguage, details.Host); @@ -584,7 +585,8 @@ await _shoppingCartValidator.GetShoppingCartWarnings(details.Cart, details.Check //validate individual cart items foreach (var sci in details.Cart) { - var product = await _productService.GetProductById(sci.ProductId); + var product = await _productService.GetProductById(sci.ProductId) ?? + throw new GrandException($"The product {sci.ProductId} of the cart does not exist"); var sciWarnings = await _shoppingCartValidator.GetShoppingCartItemWarnings(details.Customer, sci, product, new ShoppingCartValidatorOptions(), details.WorkingLanguage); if (sciWarnings.Any()) @@ -753,7 +755,8 @@ protected virtual async Task> PrepareOrderItems(PlaceOr var orderItems = new List(); foreach (var sc in details.Cart) { - var product = await _productService.GetProductById(sc.ProductId); + var product = await _productService.GetProductById(sc.ProductId) ?? + throw new GrandException($"The product {sc.ProductId} of the cart does not exist"); orderItems.Add(new PreparedOrderItem(sc, product, await PrepareOrderItem(sc, product, details))); } @@ -842,7 +845,7 @@ await _productAttributeFormatter.FormatAttributes(product, sc.Attributes, detail return orderItem; } - private static string ReservationInfo(ShoppingCartItem sc, Product product) + private static string? ReservationInfo(ShoppingCartItem sc, Product product) { var reservationInfo = ""; if (product.ProductTypeId == ProductType.Reservation) @@ -904,10 +907,11 @@ protected virtual async Task UpdateProductReservation(Order order, PlaceOrderCon if (!string.IsNullOrEmpty(sc.ReservationId)) { var reservation = await _productReservationService.GetProductReservation(sc.ReservationId); - reservationsToUpdate.Add(reservation); + if (reservation != null) + reservationsToUpdate.Add(reservation); } - if (!sc.RentalStartDateUtc.HasValue || !sc.RentalEndDateUtc.HasValue) continue; + if (product == null || !sc.RentalStartDateUtc.HasValue || !sc.RentalEndDateUtc.HasValue) continue; var reservations = await _productReservationService.GetProductReservationsByProductId(product.Id, true, null); var groupToBook = reservations.FindGroupToBook(product, sc.RentalStartDateUtc.Value, @@ -927,7 +931,7 @@ protected virtual async Task UpdateProductReservation(Order order, PlaceOrderCon reservationsToUpdate.AddRange(temp); } - var reserved = await _productReservationService.GetCustomerReservationsHelpers(order.CustomerId); + var reserved = await _productReservationService.GetCustomerReservationsHelpers(details.Customer.Id); foreach (var res in reserved) await _productReservationService.DeleteCustomerReservationsHelper(res); foreach (var resToUpdate in reservationsToUpdate) @@ -1029,7 +1033,7 @@ protected virtual Order PrepareOrderHeader(PaymentTransaction paymentTransaction PaymentMethodSystemName = paymentTransaction.PaymentMethodSystemName, PaymentOptionAttribute = details.Customer.GetUserFieldFromEntity(SystemCustomerFieldNames.PaymentOptionAttribute, - paymentTransaction.StoreId), + details.Store.Id), PaymentStatusId = paymentStatus, PaidAmount = processPaymentResult.PaidAmount, PaidDateUtc = processPaymentResult.PaidAmount > 0 ? DateTime.UtcNow : null, @@ -1050,10 +1054,10 @@ protected virtual Order PrepareOrderHeader(PaymentTransaction paymentTransaction CustomerEmail = details.Customer.Email, ShippingOptionAttributeDescription = details.Customer.GetUserFieldFromEntity( - SystemCustomerFieldNames.ShippingOptionAttributeDescription, paymentTransaction.StoreId), + SystemCustomerFieldNames.ShippingOptionAttributeDescription, details.Store.Id), ShippingOptionAttribute = details.Customer.GetUserFieldFromEntity(SystemCustomerFieldNames.ShippingOptionAttribute, - paymentTransaction.StoreId), + details.Store.Id), RedeemedLoyaltyPoints = details.RedeemedLoyaltyPoints, RedeemedLoyaltyPointsAmount = details.RedeemedLoyaltyPointsAmount, LoyaltyPointsWereAdded = details.RedeemedLoyaltyPoints > 0, @@ -1084,7 +1088,7 @@ protected virtual async Task SaveOrderDetails(PlaceOrderContainer details order.OrderItems.Add(orderItem); //gift vouchers - if (product.IsGiftVoucher) await GenerateGiftVoucher(details, sc, order, orderItem, product); + if (product is { IsGiftVoucher: true }) await GenerateGiftVoucher(details, sc, order, orderItem, product); //update auction ended await UpdateAuctionEnded(sc, product, order); @@ -1120,9 +1124,9 @@ protected virtual async Task CompleteOrderDetails(PlaceOrderContainer details, O await UpdateBids(order, details); //clear shopping cart - await _customerService.ClearShoppingCartItem(order.CustomerId, details.Cart); + await _customerService.ClearShoppingCartItem(details.Customer.Id, details.Cart); //reset checkout data - await _customerService.ResetCheckoutData(details.Customer, order.StoreId, true, true); + await _customerService.ResetCheckoutData(details.Customer, details.Store.Id, true, true); } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ProcessOrderPaidCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ProcessOrderPaidCommandHandler.cs index 523431311..8a0dd596d 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ProcessOrderPaidCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ProcessOrderPaidCommandHandler.cs @@ -68,7 +68,7 @@ protected virtual async Task ProcessOrderPaid(Order order) //the order's store, not the current one: a scheduled task or another store's admin marks it paid too var orderSettings = await _settingService.LoadSetting(order.StoreId); - string invoiceDownloadId = null; + string? invoiceDownloadId = null; try { diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.cs index 668fcd8a8..f74361005 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReOrderCommandHandler.cs @@ -7,6 +7,7 @@ using Grand.Domain.Orders; using Grand.Domain.Tax; using Grand.Mediator; +using Grand.SharedKernel; namespace Grand.Business.Checkout.Commands.Handlers.Orders; @@ -35,7 +36,8 @@ public async Task> Handle(ReOrderCommand request, CancellationToke ArgumentNullException.ThrowIfNull(request.Language); var warnings = new List(); - var customer = await _customerService.GetCustomerById(request.Order.CustomerId); + var customer = await _customerService.GetCustomerById(request.Order.CustomerId) ?? + throw new GrandException("The customer of the order does not exist"); foreach (var orderItem in request.Order.OrderItems) { diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs index 26939f488..f27b112cc 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentCycleCommandHandler.cs @@ -26,50 +26,51 @@ public async Task Handle(RecordRecurringPaymentCycleCommand request, Cance var claim = await recurringPaymentService.ClaimCycle(request.RecurringPaymentId, request.ProviderReference, request.CycleReference, request.Amount, request.PaidOnUtc, request.NextPaymentDateUtc); - if (claim.Outcome == RecurringReportOutcome.OtherReference) + if (claim is { Outcome: RecurringReportOutcome.OtherReference, RecurringPayment: { } otherPayment }) { await RecurringPaymentGateway.StopOtherReference(paymentService, orderService, logger, - claim.RecurringPayment, request.ProviderReference, + otherPayment, request.ProviderReference, $"a paid cycle ({request.CycleReference})", "check whether the customer must be refunded"); return false; } - // a resend is the usual reason - if (claim.Outcome != RecurringReportOutcome.Recorded) + // a resend is the usual reason; a recorded claim carries its payment and cycle + if (claim is not + { Outcome: RecurringReportOutcome.Recorded, RecurringPayment: { } recurringPayment, Cycle: { } cycle }) return false; // the cycle is recorded: an aborted webhook request must not leave it half done, so nothing below is cancellable cancellationToken = CancellationToken.None; // the first cycle is the initial order's own payment, which the provider marks paid on its existing path - ExceptionDispatchInfo placementFailure = null; - if (claim.Cycle.CycleNumber > 1) + ExceptionDispatchInfo? placementFailure = null; + if (cycle.CycleNumber > 1) try { await mediator.Send(new PlaceRecurringCycleOrderCommand { - RecurringPayment = claim.RecurringPayment, Cycle = claim.Cycle + RecurringPayment = recurringPayment, Cycle = cycle }, cancellationToken); } catch (Exception e) { logger.LogError(e, "Recurring payment {RecurringPaymentId}: the order {OrderId} of cycle {CycleNumber} ({CycleReference}) could not be placed or marked paid", - claim.RecurringPayment.Id, claim.Cycle.OrderId, claim.Cycle.CycleNumber, request.CycleReference); + recurringPayment.Id, cycle.OrderId, cycle.CycleNumber, request.CycleReference); // the order may exist already (the failure can come after it was inserted), so the note names it - await RecurringPaymentGateway.AddNote(orderService, logger, claim.RecurringPayment, - $"Cycle {claim.Cycle.CycleNumber} was paid at the payment gateway ({request.CycleReference}), but its order {claim.Cycle.OrderId} could not be placed or marked paid: {e.Message}"); + await RecurringPaymentGateway.AddNote(orderService, logger, recurringPayment, + $"Cycle {cycle.CycleNumber} was paid at the payment gateway ({request.CycleReference}), but its order {cycle.OrderId} could not be placed or marked paid: {e.Message}"); // the failure must reach the provider so it can log or report it, but only after the gateway was // asked to stop: the claim is recorded, so a resend is a no-op and would never stop it placementFailure = ExceptionDispatchInfo.Capture(e); } // a cycle claimed while the payment is already completed or cancelled means the gateway still charges - if (claim.RecurringPayment.Status is RecurringPaymentStatus.Completed or RecurringPaymentStatus.Cancelled) + if (recurringPayment.Status is RecurringPaymentStatus.Completed or RecurringPaymentStatus.Cancelled) { // the last cycle completing the payment is expected; any other was taken after the shop ended it if (!claim.Completed) - await RecurringPaymentGateway.AddNote(orderService, logger, claim.RecurringPayment, - $"Cycle {claim.Cycle.CycleNumber} was charged at the payment gateway ({request.CycleReference}) after the recurring payment was {claim.RecurringPayment.Status.ToString().ToLowerInvariant()}: check whether the customer must be refunded"); - await RecurringPaymentGateway.Stop(paymentService, orderService, logger, claim.RecurringPayment); + await RecurringPaymentGateway.AddNote(orderService, logger, recurringPayment, + $"Cycle {cycle.CycleNumber} was charged at the payment gateway ({request.CycleReference}) after the recurring payment was {recurringPayment.Status.ToString().ToLowerInvariant()}: check whether the customer must be refunded"); + await RecurringPaymentGateway.Stop(paymentService, orderService, logger, recurringPayment); } placementFailure?.Throw(); diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs index a3ffb1ccb..ccc1fed94 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentEndedCommandHandler.cs @@ -18,9 +18,9 @@ public async Task Handle(RecordRecurringPaymentEndedCommand request, Cance var report = await recurringPaymentService.RecordEnded(request.RecurringPaymentId, request.ProviderReference); // another subscription that ended charges nothing more, typically one the shop stopped: nothing for staff to do - if (report.Outcome == RecurringReportOutcome.OtherReference) + if (report is { Outcome: RecurringReportOutcome.OtherReference, RecurringPayment: { } otherPayment }) logger.LogInformation("Recurring payment {RecurringPaymentId} runs on {ProviderReference}; {ReportedReference} ended at the payment gateway", - report.RecurringPayment.Id, report.RecurringPayment.ProviderReference, request.ProviderReference); + otherPayment.Id, otherPayment.ProviderReference, request.ProviderReference); return report.Outcome == RecurringReportOutcome.Recorded; } diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs index a5d567eb2..c9133b962 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentFailureCommandHandler.cs @@ -22,19 +22,20 @@ public async Task Handle(RecordRecurringPaymentFailureCommand request, Can var report = await recurringPaymentService.RecordFailure(request.RecurringPaymentId, request.ProviderReference, request.CycleReference, request.Reason); - switch (report.Outcome) + //a payment is reported with every outcome but NotFound + switch (report) { - case RecurringReportOutcome.Recorded: + case { Outcome: RecurringReportOutcome.Recorded }: return true; - case RecurringReportOutcome.OtherReference: + case { Outcome: RecurringReportOutcome.OtherReference, RecurringPayment: { } otherPayment }: await RecurringPaymentGateway.StopOtherReference(paymentService, orderService, logger, - report.RecurringPayment, request.ProviderReference, + otherPayment, request.ProviderReference, $"a failed cycle ({request.CycleReference})"); return false; - case RecurringReportOutcome.Ended: + case { Outcome: RecurringReportOutcome.Ended, RecurringPayment: { } endedPayment }: // a failed charge on a payment the shop ended means the gateway still tries to charge, typically a // payment cancelled while pending; the service recorded the reported reference so it can be stopped - await RecurringPaymentGateway.Stop(paymentService, orderService, logger, report.RecurringPayment); + await RecurringPaymentGateway.Stop(paymentService, orderService, logger, endedPayment); return false; default: return false; diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs index d861d1d29..d42a29f5b 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecordRecurringPaymentReferenceCommandHandler.cs @@ -23,19 +23,20 @@ public async Task Handle(RecordRecurringPaymentReferenceCommand request, C var report = await recurringPaymentService.RecordProviderReference(request.RecurringPaymentId, request.ProviderReference); - switch (report.Outcome) + //a payment is reported with every outcome but NotFound + switch (report) { - case RecurringReportOutcome.Recorded: + case { Outcome: RecurringReportOutcome.Recorded, RecurringPayment: { } recorded }: // cancelled before the reference was known, so the cancel could not stop the gateway: it is stopped // now, once, as a resend finds the reference recorded - if (report.RecurringPayment.Status.HasEnded()) - await RecurringPaymentGateway.Stop(paymentService, orderService, logger, report.RecurringPayment); + if (recorded.Status.HasEnded()) + await RecurringPaymentGateway.Stop(paymentService, orderService, logger, recorded); return true; - case RecurringReportOutcome.Duplicate: + case { Outcome: RecurringReportOutcome.Recorded or RecurringReportOutcome.Duplicate }: return true; - case RecurringReportOutcome.OtherReference: + case { Outcome: RecurringReportOutcome.OtherReference, RecurringPayment: { } otherPayment }: await RecurringPaymentGateway.StopOtherReference(paymentService, orderService, logger, - report.RecurringPayment, request.ProviderReference, "a second subscription"); + otherPayment, request.ProviderReference, "a second subscription"); return false; default: return false; diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs index 832edcd32..09249f206 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RecurringPaymentGateway.cs @@ -28,8 +28,8 @@ await AddNote(orderService, logger, recurringPayment, /// not charge the customer ///
public static async Task StopOtherReference(IPaymentService paymentService, IOrderService orderService, - ILogger logger, RecurringPayment recurringPayment, string providerReference, string reported, - string advice = null) + ILogger logger, RecurringPayment recurringPayment, string? providerReference, string reported, + string? advice = null) { logger.LogWarning("Recurring payment {RecurringPaymentId} runs on {ProviderReference}, but the payment gateway reported {Reported} on {ReportedReference}", recurringPayment.Id, recurringPayment.ProviderReference, reported, providerReference); @@ -76,7 +76,8 @@ public static async Task AddNote(IOrderService orderService, ILogger logger, Rec { try { - if (once && (await orderService.GetOrderNotes(recurringPayment.InitialOrderId)).Any(x => x.Note == note)) + if (once && recurringPayment.InitialOrderId != null && + (await orderService.GetOrderNotes(recurringPayment.InitialOrderId)).Any(x => x.Note == note)) return; await orderService.InsertOrderNote(new OrderNote { diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandler.cs index c0586a446..9fcfcb4f8 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReduceLoyaltyPointsCommandHandler.cs @@ -7,6 +7,7 @@ using Grand.Business.Core.Interfaces.Customers; using Grand.Domain.Orders; using Grand.Mediator; +using Grand.SharedKernel; namespace Grand.Business.Checkout.Commands.Handlers.Orders; @@ -47,7 +48,8 @@ public async Task Handle(ReduceLoyaltyPointsCommand request, CancellationT var customer = await _customerService.GetCustomerById(request.Order.CustomerId); - var currency = await _currencyService.GetCurrencyByCode(request.Order.CustomerCurrencyCode); + var currency = await _currencyService.GetCurrencyByCode(request.Order.CustomerCurrencyCode) ?? + throw new GrandException($"The currency {request.Order.CustomerCurrencyCode} of order {request.Order.OrderNumber} does not exist"); var amount = await _currencyService.ConvertToPrimaryStoreCurrency( @@ -55,7 +57,7 @@ await _currencyService.ConvertToPrimaryStoreCurrency( var points = await _mediator.Send(new CalculateLoyaltyPointsCommand { Customer = customer, Amount = amount }, cancellationToken); - if (points <= 0) + if (customer == null || points <= 0) return false; if (request.Order.CalcLoyaltyPoints < points) diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs index 9ba23927b..f1ccefeef 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/RefundCommandHandler.cs @@ -56,11 +56,10 @@ public async Task> Handle(RefundCommand command, CancellationToken if (!canRefund) throw new GrandException("You can't refund this payment transaction"); - var request = new RefundPaymentRequest(); - RefundPaymentResult result = null; + var request = new RefundPaymentRequest { PaymentTransaction = paymentTransaction }; + RefundPaymentResult? result = null; try { - request.PaymentTransaction = paymentTransaction; request.AmountToRefund = paymentTransaction.PaidAmount; request.IsPartialRefund = false; result = await _paymentService.Refund(request); diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandler.cs index 4d995c33d..f3379533a 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandler.cs @@ -33,7 +33,7 @@ public async Task Handle(ReturnBackRedeemedLoyaltyPointsCommand request, C ArgumentNullException.ThrowIfNull(request.Order); //were some points redeemed when placing an order? - if (request.Order.RedeemedLoyaltyPoints == 0) + if (request.Order.RedeemedLoyaltyPoints == 0 || request.Order.CustomerId == null) return false; //return back diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/UpdateOrderItemCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/UpdateOrderItemCommandHandler.cs index 972fed8b9..c51c3305f 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/UpdateOrderItemCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/UpdateOrderItemCommandHandler.cs @@ -36,7 +36,7 @@ public async Task Handle(UpdateOrderItemCommand request, CancellationToken ArgumentNullException.ThrowIfNull(request.OrderItem); var originalOrder = await _orderService.GetOrderById(request.Order.Id); - var originalOrderItem = originalOrder.OrderItems.FirstOrDefault(x => x.Id == request.OrderItem.Id); + var originalOrderItem = originalOrder?.OrderItems.FirstOrDefault(x => x.Id == request.OrderItem.Id); if (originalOrderItem != null) { request.Order.OrderSubtotalExclTax += request.OrderItem.PriceExclTax - originalOrderItem.PriceExclTax; @@ -54,8 +54,10 @@ public async Task Handle(UpdateOrderItemCommand request, CancellationToken { var qtyDifference = originalOrderItem.Quantity - request.OrderItem.Quantity; var product = await _productService.GetProductById(request.OrderItem.ProductId); - await _inventoryManageService.AdjustReserved(product, qtyDifference, request.OrderItem.Attributes, - request.OrderItem.WarehouseId); + //a product deleted meanwhile has no stock to adjust + if (product != null) + await _inventoryManageService.AdjustReserved(product, qtyDifference, request.OrderItem.Attributes, + request.OrderItem.WarehouseId); if (request.Order.ShippingStatusId == ShippingStatus.PartiallyShipped) { diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs index 59b826feb..8fdb53053 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/VoidCommandHandler.cs @@ -46,7 +46,7 @@ public async Task> Handle(VoidCommand command, CancellationToken c if (!canVoid) throw new GrandException("Cannot do void for order."); - VoidPaymentResult result = null; + VoidPaymentResult? result = null; try { result = await _paymentService.Void(paymentTransaction); diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/DeliveryCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/DeliveryCommandHandler.cs index b880f5133..daf914b39 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/DeliveryCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/DeliveryCommandHandler.cs @@ -46,7 +46,7 @@ public async Task Handle(DeliveryCommand request, CancellationToken cancel request.Shipment.DeliveryDateUtc = request.DeliveryDateUtc ?? DateTime.UtcNow; await _shipmentService.UpdateShipment(request.Shipment); - var shipments = await _shipmentService.GetShipmentsByOrder(request.Shipment.OrderId); + var shipments = await _shipmentService.GetShipmentsByOrder(order.Id); if (!order.HasItemsToAddToShipment() && shipments.All(x => x.DeliveryDateUtc != null)) { order.ShippingStatusId = ShippingStatus.Delivered; diff --git a/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/ShipCommandHandler.cs b/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/ShipCommandHandler.cs index 75df0956b..f195b0460 100644 --- a/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/ShipCommandHandler.cs +++ b/src/Business/Grand.Business.Checkout/Commands/Handlers/Shipping/ShipCommandHandler.cs @@ -50,7 +50,7 @@ public async Task Handle(ShipCommand request, CancellationToken cancellati } else { - var shipments = await _shipmentService.GetShipmentsByOrder(request.Shipment.OrderId); + var shipments = await _shipmentService.GetShipmentsByOrder(order.Id); order.ShippingStatusId = shipments.All(x => x.ShippedDateUtc != null) ? ShippingStatus.Shipped : ShippingStatus.PartiallyShipped; diff --git a/src/Business/Grand.Business.Checkout/Events/Orders/MerchandiseReturnQuantityEventHandler.cs b/src/Business/Grand.Business.Checkout/Events/Orders/MerchandiseReturnQuantityEventHandler.cs index acbc2ce9c..ddd5dbd4d 100644 --- a/src/Business/Grand.Business.Checkout/Events/Orders/MerchandiseReturnQuantityEventHandler.cs +++ b/src/Business/Grand.Business.Checkout/Events/Orders/MerchandiseReturnQuantityEventHandler.cs @@ -48,7 +48,7 @@ public Task Handle(EntityDeleted notification, CancellationTo return Recount(notification.Entity.OrderId, cancellationToken); } - private async Task Recount(string orderId, CancellationToken cancellationToken) + private async Task Recount(string? orderId, CancellationToken cancellationToken) { var order = await _orderService.GetOrderById(orderId); if (order == null) diff --git a/src/Business/Grand.Business.Checkout/Events/Orders/MerchandiseReturnReceiptPostedEventHandler.cs b/src/Business/Grand.Business.Checkout/Events/Orders/MerchandiseReturnReceiptPostedEventHandler.cs index 2e939fcc5..146126616 100644 --- a/src/Business/Grand.Business.Checkout/Events/Orders/MerchandiseReturnReceiptPostedEventHandler.cs +++ b/src/Business/Grand.Business.Checkout/Events/Orders/MerchandiseReturnReceiptPostedEventHandler.cs @@ -32,7 +32,7 @@ public async Task Handle(EntityUpdated notification, Cancella return; //the staff note names who posted the receipt; one whose account is gone by the id it had - string postedBy = null; + string? postedBy = null; if (!string.IsNullOrEmpty(document.PostedBy)) postedBy = (await _customerService.GetCustomerById(document.PostedBy))?.StatusChangedBy() ?? $"staff ({document.PostedBy})"; diff --git a/src/Business/Grand.Business.Checkout/Events/Orders/OrderPlacedOrderApprovalHandler.cs b/src/Business/Grand.Business.Checkout/Events/Orders/OrderPlacedOrderApprovalHandler.cs index 18d424ea2..5449de567 100644 --- a/src/Business/Grand.Business.Checkout/Events/Orders/OrderPlacedOrderApprovalHandler.cs +++ b/src/Business/Grand.Business.Checkout/Events/Orders/OrderPlacedOrderApprovalHandler.cs @@ -14,6 +14,7 @@ using Grand.Domain.Stores; using Grand.Domain.Tax; using Grand.Mediator; +using Grand.SharedKernel; using Microsoft.Extensions.Logging; namespace Grand.Business.Checkout.Events.Orders; @@ -109,7 +110,8 @@ private async Task CreateApprovalRequest(Order order, IReadOnlyList reas ? await GetApprovers(buyer, buyer.OwnerId, order.StoreId) : []; var companyDecides = approvers.Count > 0; - var currency = await _currencyService.GetCurrencyByCode(order.CustomerCurrencyCode); + var currency = await _currencyService.GetCurrencyByCode(order.CustomerCurrencyCode) ?? + throw new GrandException($"The currency {order.CustomerCurrencyCode} of the order does not exist"); var approval = new OrderApproval { StoreId = order.StoreId, @@ -128,7 +130,8 @@ private async Task CreateApprovalRequest(Order order, IReadOnlyList reas await _orderApprovalService.Insert(approval); - var store = await _storeService.GetStoreById(order.StoreId); + var store = await _storeService.GetStoreById(order.StoreId) ?? + throw new GrandException($"The store {order.StoreId} of the order does not exist"); if (!companyDecides) { await NotifyStore(approval, order, buyer, store); @@ -172,10 +175,10 @@ await _messageProviderService.SendOrderApprovalStaffMessage(approval, buyer, sto /// The order's sales employee as well: that record does not prove its person can open the panel, so they are /// never the only one told. Never the buyer: nobody decides their own order. ///
- private async Task> GetStoreRecipients(Order order, + private async Task> GetStoreRecipients(Order order, Customer buyer, Store store) { - var recipients = new List<(string Email, string Name, string PanelArea)> { + var recipients = new List<(string? Email, string? Name, string PanelArea)> { await GetOwnerRecipient(buyer, store) }; @@ -191,7 +194,7 @@ await GetOwnerRecipient(buyer, store) return recipients; } - private async Task<(string Email, string Name, string PanelArea)> GetOwnerRecipient(Customer buyer, Store store) + private async Task<(string? Email, string? Name, string PanelArea)> GetOwnerRecipient(Customer buyer, Store store) { if (!string.IsNullOrEmpty(store.OwnerCustomerId) && store.OwnerCustomerId != buyer.Id) { @@ -260,7 +263,7 @@ private OrderApprovalSummary PrepareSummary(Order order, Currency currency) private static readonly System.Text.RegularExpressions.Regex Tag = new("<[^>]*>", System.Text.RegularExpressions.RegexOptions.Compiled); - private static string ToPlainText(string html) + private static string? ToPlainText(string? html) { if (string.IsNullOrWhiteSpace(html)) return html; @@ -276,7 +279,7 @@ private static string ToPlainText(string html) /// The company owner and every active approver sub-account of the store that has an e-mail address; /// never the buyer ///
- private async Task> GetApprovers(Customer buyer, string companyOwnerId, string storeId) + private async Task> GetApprovers(Customer buyer, string companyOwnerId, string? storeId) { var approvers = new List(); @@ -284,7 +287,7 @@ private async Task> GetApprovers(Customer buyer, string companyO if (owner is { Active: true, Deleted: false }) approvers.Add(owner); - var subAccounts = await _customerService.GetAllCustomers(ownerId: companyOwnerId, storeId: storeId); + var subAccounts = await _customerService.GetAllCustomers(ownerId: companyOwnerId, storeId: storeId ?? ""); approvers.AddRange(subAccounts.Where(x => x.SubAccountRole == SubAccountRole.Approver && x is { Active: true, Deleted: false })); return approvers diff --git a/src/Business/Grand.Business.Checkout/Events/Orders/RecurringPaymentMessagesHandler.cs b/src/Business/Grand.Business.Checkout/Events/Orders/RecurringPaymentMessagesHandler.cs index 6795b10ed..61906866d 100644 --- a/src/Business/Grand.Business.Checkout/Events/Orders/RecurringPaymentMessagesHandler.cs +++ b/src/Business/Grand.Business.Checkout/Events/Orders/RecurringPaymentMessagesHandler.cs @@ -48,8 +48,8 @@ public Task Handle(RecurringPaymentPastDueEvent notification, CancellationToken } private async Task Send(RecurringPayment recurringPayment, - Func> sendToCustomer, - Func> sendToStoreOwner) + Func> sendToCustomer, + Func> sendToStoreOwner) { try { diff --git a/src/Business/Grand.Business.Checkout/Extensions/OrderItemWarehouse.cs b/src/Business/Grand.Business.Checkout/Extensions/OrderItemWarehouse.cs index 9b582d45e..e6dba3891 100644 --- a/src/Business/Grand.Business.Checkout/Extensions/OrderItemWarehouse.cs +++ b/src/Business/Grand.Business.Checkout/Extensions/OrderItemWarehouse.cs @@ -9,7 +9,7 @@ public static class OrderItemWarehouse /// The warehouse an order item is served from: the one chosen in the cart, else the store's default, else the /// product's own when it is kept in a single warehouse ///
- public static string Resolve(ShoppingCartItem item, Product product, string storeDefaultWarehouseId) + public static string? Resolve(ShoppingCartItem item, Product product, string? storeDefaultWarehouseId) { var warehouseId = !string.IsNullOrEmpty(item.WarehouseId) ? item.WarehouseId diff --git a/src/Business/Grand.Business.Checkout/Extensions/RecurringCycleOrder.cs b/src/Business/Grand.Business.Checkout/Extensions/RecurringCycleOrder.cs index 0dfafdc50..a70be65dd 100644 --- a/src/Business/Grand.Business.Checkout/Extensions/RecurringCycleOrder.cs +++ b/src/Business/Grand.Business.Checkout/Extensions/RecurringCycleOrder.cs @@ -15,7 +15,7 @@ public static class RecurringCycleOrder /// back to the total. ///
/// The gift voucher amount redeemed on the initial order - public static Order Copy(Order initialOrder, string orderId, int cycleNumber, string orderCode, + public static Order Copy(Order initialOrder, string? orderId, int cycleNumber, string orderCode, DateTime createdOnUtc, double giftVouchersAmount) { var order = new Order { @@ -148,12 +148,12 @@ private static OrderItem CopyItem(OrderItem item, DateTime createdOnUtc) }; } - private static IList CopyAttributes(IList attributes) + private static IList CopyAttributes(IList? attributes) { - return attributes?.Select(x => new CustomAttribute { Key = x.Key, Value = x.Value }).ToList(); + return attributes?.Select(x => new CustomAttribute { Key = x.Key, Value = x.Value }).ToList() ?? []; } - private static Address CopyAddress(Address address) + private static Address? CopyAddress(Address? address) { if (address == null) return null; return new Address { @@ -178,12 +178,12 @@ private static Address CopyAddress(Address address) }; } - private static PickupPoint CopyPickupPoint(PickupPoint point) + private static PickupPoint? CopyPickupPoint(PickupPoint? point) { if (point == null) return null; return new PickupPoint { Id = point.Id, - UserFields = point.UserFields?.Select(x => new UserField { Key = x.Key, Value = x.Value }).ToList(), + UserFields = point.UserFields?.Select(x => new UserField { Key = x.Key, Value = x.Value }).ToList() ?? [], CreatedOnUtc = point.CreatedOnUtc, CreatedBy = point.CreatedBy, UpdatedOnUtc = point.UpdatedOnUtc, diff --git a/src/Business/Grand.Business.Checkout/Grand.Business.Checkout.csproj b/src/Business/Grand.Business.Checkout/Grand.Business.Checkout.csproj index 2ac20c3e9..4076c6016 100644 --- a/src/Business/Grand.Business.Checkout/Grand.Business.Checkout.csproj +++ b/src/Business/Grand.Business.Checkout/Grand.Business.Checkout.csproj @@ -7,4 +7,7 @@ + + enable + diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPickupPointByIdQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPickupPointByIdQueryHandler.cs index 56593cbb7..92c0e9131 100644 --- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPickupPointByIdQueryHandler.cs +++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetPickupPointByIdQueryHandler.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Checkout.Queries.Handlers.Orders; -public class GetPickupPointByIdQueryHandler : IRequestHandler +public class GetPickupPointByIdQueryHandler : IRequestHandler { private readonly IPickupPointService _pickupPointService; @@ -14,7 +14,7 @@ public GetPickupPointByIdQueryHandler(IPickupPointService pickupPointService) _pickupPointService = pickupPointService; } - public async Task Handle(GetPickupPointById request, CancellationToken cancellationToken) + public async Task Handle(GetPickupPointById request, CancellationToken cancellationToken) { return await _pickupPointService.GetPickupPointById(request.Id); } diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetRecurringPaymentsQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetRecurringPaymentsQueryHandler.cs index e6d84b9ef..6dcb55cb2 100644 --- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetRecurringPaymentsQueryHandler.cs +++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetRecurringPaymentsQueryHandler.cs @@ -40,7 +40,7 @@ public async Task> Handle(GetRecurringPaymentsQuery var email = request.CustomerEmail.Trim().ToLowerInvariant(); var customerIds = await _customerRepository.ToListAsync( _customerRepository.Table.Where(c => c.Email == email).Select(c => c.Id), cancellationToken); - query = query.Where(x => customerIds.Contains(x.CustomerId)); + query = query.Where(x => x.CustomerId != null && customerIds.Contains(x.CustomerId)); } //the sales employee is on the order, the same one the order list narrows by @@ -49,7 +49,7 @@ public async Task> Handle(GetRecurringPaymentsQuery var orderIds = await _orderRepository.ToListAsync( _orderRepository.Table.Where(o => o.SeId == request.SalesEmployeeId && o.RecurringCycleNumber == 1) .Select(o => o.Id), cancellationToken); - query = query.Where(x => orderIds.Contains(x.InitialOrderId)); + query = query.Where(x => x.InitialOrderId != null && orderIds.Contains(x.InitialOrderId)); } query = query.OrderByDescending(x => x.CreatedOnUtc); diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetReturnableOrdersQueryHandler.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetReturnableOrdersQueryHandler.cs index bf74ca7d0..b0318f079 100644 --- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetReturnableOrdersQueryHandler.cs +++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/GetReturnableOrdersQueryHandler.cs @@ -51,7 +51,7 @@ public async Task> Handle(GetReturnableOrdersQuery request, var orderIds = orders.Select(x => x.Id).ToList(); var delivered = await _shipmentRepository.ToListAsync(_shipmentRepository.Table - .Where(x => orderIds.Contains(x.OrderId) && x.DeliveryDateUtc != null), cancellationToken); + .Where(x => x.OrderId != null && orderIds.Contains(x.OrderId) && x.DeliveryDateUtc != null), cancellationToken); //nothing delivered, nothing to return: an order list of recent orders stops here if (delivered.Count == 0) return returnable; @@ -64,20 +64,21 @@ public async Task> Handle(GetReturnableOrdersQuery request, merchandiseReturns.Where(x => x.OrderId == order.Id).ToList(), days, fromDelivery, utcNow)); var productIds = orders.SelectMany(order => order.OrderItems.Where(item => left[order.Id][item.Id] > 0)) - .Select(x => x.ProductId).Distinct().ToList(); + .Select(x => x.ProductId).OfType().Distinct().ToList(); if (productIds.Count == 0) return returnable; var products = (await _productRepository.ToListAsync(_productRepository.Table .Where(x => productIds.Contains(x.Id)), cancellationToken)) - .ToDictionary(x => x.Id); + .ToDictionary(x => x.Id, Product? (x) => x); //a product not in the catalog any more may be in its archive foreach (var productId in productIds.Where(x => !products.ContainsKey(x))) products[productId] = await _productService.GetProductByIdIncludeArch(productId); foreach (var order in orders) if (order.OrderItems.Any(item => - left[order.Id][item.Id] > 0 && ReturnableQuantities.MayBeReturned(products[item.ProductId]))) + left[order.Id][item.Id] > 0 && item.ProductId != null && + ReturnableQuantities.MayBeReturned(products.GetValueOrDefault(item.ProductId)))) returnable.Add(order.Id); return returnable; diff --git a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/ReturnableQuantities.cs b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/ReturnableQuantities.cs index eb09aa8d9..19115414d 100644 --- a/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/ReturnableQuantities.cs +++ b/src/Business/Grand.Business.Checkout/Queries/Handlers/Orders/ReturnableQuantities.cs @@ -54,7 +54,7 @@ public static bool PeriodEnded(Order order, int days, bool fromDelivery, DateTim /// Whether the customer may return the product: not one marked not returnable, nor one in neither the catalog /// nor its archive ///
- public static bool MayBeReturned(Product product) + public static bool MayBeReturned(Product? product) { return product is { NotReturnable: false }; } diff --git a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs index bbc29f808..1784bc966 100644 --- a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs +++ b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeFormatter.cs @@ -47,7 +47,7 @@ public CheckoutAttributeFormatter(ICheckoutAttributeParser checkoutAttributePars /// A value indicating whether to render prices /// A value indicating whether to HTML hyperlink tags could be rendered (if required) /// Attributes - public virtual async Task FormatAttributes(IList customAttributes, + public virtual async Task FormatAttributes(IList? customAttributes, CalculationContext context, Language language, DomainHost host, diff --git a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeParser.cs b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeParser.cs index 5bd07a654..9dd484d6d 100644 --- a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeParser.cs +++ b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeParser.cs @@ -72,7 +72,7 @@ into value /// Attributes /// Checkout attribute values with checkout attribute public virtual async Task> ParseCheckoutAttributeValue( - IList customAttributes) + IList? customAttributes) { var values = new List<(CheckoutAttribute ca, CheckoutAttributeValue cav)>(); if (customAttributes == null || !customAttributes.Any()) @@ -130,7 +130,7 @@ public virtual async Task> EnsureOnlyActiveAttributes( foreach (var attr in checkoutAttributeIdsToRemove .Select(id => customAttributes.FirstOrDefault(x => x.Key == id)) - .Where(attr => attr != null)) customAttributes.Remove(attr); + .OfType()) customAttributes.Remove(attr); return customAttributes; } diff --git a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs index 4f540025f..7eb6f0b79 100644 --- a/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs +++ b/src/Business/Grand.Business.Checkout/Services/CheckoutAttributes/CheckoutAttributeService.cs @@ -58,7 +58,7 @@ public virtual async Task> GetAllCheckoutAttributes(Cat ArgumentNullException.ThrowIfNull(access); var applyAcl = !access.ShowHidden && !_accessControlConfig.IgnoreAcl; - var allowedCustomerGroupsIds = applyAcl ? access.Customer.GetCustomerGroupIds() : []; + var allowedCustomerGroupsIds = applyAcl ? access.Customer?.GetCustomerGroupIds() ?? [] : []; var key = string.Format(CacheKey.CHECKOUTATTRIBUTES_ALL_KEY, access.StoreId, excludeShippableAttributes, access.ShowHidden, string.Join(",", allowedCustomerGroupsIds)); return await _cacheBase.GetAsync(key, async () => @@ -89,7 +89,7 @@ public virtual async Task> GetAllCheckoutAttributes(Cat ///
/// Checkout attribute identifier /// Checkout attribute - public virtual Task GetCheckoutAttributeById(string checkoutAttributeId) + public virtual Task GetCheckoutAttributeById(string? checkoutAttributeId) { var key = string.Format(CacheKey.CHECKOUTATTRIBUTES_BY_ID_KEY, checkoutAttributeId); return _cacheBase.GetAsync(key, () => _checkoutAttributeRepository.GetByIdAsync(checkoutAttributeId)); diff --git a/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs b/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs index 14e1ccecf..084d9a373 100644 --- a/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs +++ b/src/Business/Grand.Business.Checkout/Services/GiftVouchers/GiftVoucherService.cs @@ -46,7 +46,7 @@ public GiftVoucherService(IRepository giftVoucherRepository, IMedia ///
/// Gift voucher identifier /// Gift voucher entry - public virtual Task GetGiftVoucherById(string giftVoucherId) + public virtual Task GetGiftVoucherById(string? giftVoucherId) { return _giftVoucherRepository.GetByIdAsync(giftVoucherId); } @@ -66,14 +66,14 @@ public virtual Task GetGiftVoucherById(string giftVoucherId) /// Gift vouchers public virtual async Task> GetAllGiftVouchers(string purchasedWithOrderItemId = "", DateTime? createdFromUtc = null, DateTime? createdToUtc = null, - bool? isGiftVoucherActivated = null, string giftVoucherCouponCode = null, - string recipientName = null, + bool? isGiftVoucherActivated = null, string? giftVoucherCouponCode = null, + string? recipientName = null, int pageIndex = 0, int pageSize = int.MaxValue, string storeId = "") { var model = new GetGiftVoucherQuery { CreatedFromUtc = createdFromUtc, CreatedToUtc = createdToUtc, - Code = giftVoucherCouponCode, + Code = giftVoucherCouponCode ?? "", IsGiftVoucherActivated = isGiftVoucherActivated, PageIndex = pageIndex, PageSize = pageSize, diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/CheckoutClaimService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/CheckoutClaimService.cs index 7c0f962d4..a7f9af674 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/CheckoutClaimService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/CheckoutClaimService.cs @@ -42,7 +42,7 @@ public virtual async Task Claim(PlaceOrderContainer details, stri ArgumentNullException.ThrowIfNull(details); var claim = new CheckoutClaim { - OrderId = details.OrderId, + OrderId = details.OrderId ?? throw new ArgumentException("The order id is not set", nameof(details)), OrderCode = orderCode, CustomerId = details.Customer.Id, StoreId = details.Store.Id @@ -104,6 +104,9 @@ private async Task ClaimStock(PlaceOrderContainer details, CheckoutClaim c foreach (var sc in details.Cart) { var product = await _productService.GetProductById(sc.ProductId); + //a product deleted meanwhile cannot be ordered, so nothing is claimed for the order + if (product == null) + return false; var warehouseId = OrderItemWarehouse.Resolve(sc, product, details.Store.DefaultWarehouseId); if (!await _inventoryManageService.TryReserve(product, sc.Quantity, sc.Attributes, warehouseId)) return false; @@ -143,7 +146,7 @@ private async Task ClaimGiftVouchers(PlaceOrderContainer details, Checkout foreach (var appliedGiftVoucher in details.AppliedGiftVouchers ?? []) { if (!await _giftVoucherService.TryRedeem(appliedGiftVoucher.GiftVoucher.Id, - appliedGiftVoucher.AmountCanBeUsed, details.OrderId)) + appliedGiftVoucher.AmountCanBeUsed, claim.OrderId)) return false; claim.GiftVoucherIds.Add(appliedGiftVoucher.GiftVoucher.Id); @@ -159,7 +162,7 @@ private async Task ClaimLoyaltyPoints(PlaceOrderContainer details, Checkou var redeemed = await _loyaltyPointsService.TryRedeemLoyaltyPoints(details.Customer.Id, details.RedeemedLoyaltyPoints, details.Store.Id, $"Loyalty points redeemed for order {claim.OrderCode}", - details.OrderId, details.RedeemedLoyaltyPointsAmount); + claim.OrderId, details.RedeemedLoyaltyPointsAmount); if (redeemed == null) return false; diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/LoyaltyPointsService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/LoyaltyPointsService.cs index 9ea9957cf..296fe8eab 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/LoyaltyPointsService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/LoyaltyPointsService.cs @@ -50,7 +50,7 @@ public LoyaltyPointsService(IRepository rphRepository, /// Customer Id /// Store ident /// PointsBalance - public virtual async Task GetLoyaltyPointsBalance(string customerId, string storeId) + public virtual async Task GetLoyaltyPointsBalance(string customerId, string? storeId) { var query = from p in _rphRepository.Table select p; @@ -77,7 +77,7 @@ public virtual async Task GetLoyaltyPointsBalance(string customerId, string /// Used amount /// LoyaltyPointsHistory public virtual async Task AddLoyaltyPointsHistory(string customerId, int points, - string storeId, string message = "", + string? storeId, string message = "", string usedWithOrderId = "", double usedAmount = 0) { //each record carries the balance after it, read from the record before it @@ -86,8 +86,8 @@ public virtual async Task AddLoyaltyPointsHistory(string c return await InsertLoyaltyPointsHistory(customerId, points, storeId, message, usedWithOrderId, usedAmount); } - public virtual async Task TryRedeemLoyaltyPoints(string customerId, int points, - string storeId, string message, string usedWithOrderId, double usedAmount) + public virtual async Task TryRedeemLoyaltyPoints(string customerId, int points, + string? storeId, string message, string usedWithOrderId, double usedAmount) { await using var _ = await _resourceLock.Acquire([LockKey(customerId, storeId)]); @@ -98,7 +98,7 @@ public virtual async Task TryRedeemLoyaltyPoints(string cu } public virtual async Task> GetLoyaltyPointsHistory(string customerId = "", - string storeId = "", bool showAll = false) + string? storeId = "", bool showAll = false) { var query = from p in _rphRepository.Table select p; @@ -122,7 +122,7 @@ public virtual async Task> GetLoyaltyPointsHistory(s /// Inserts a record; the caller holds the balance's lock ///
private async Task InsertLoyaltyPointsHistory(string customerId, int points, - string storeId, string message, string usedWithOrderId, double usedAmount) + string? storeId, string message, string usedWithOrderId, double usedAmount) { var loyaltyPointsHistory = new LoyaltyPointsHistory { CustomerId = customerId, @@ -144,7 +144,7 @@ private async Task InsertLoyaltyPointsHistory(string custo /// /// One key per balance: shared by all stores, or one per store /// - private string LockKey(string customerId, string storeId) + private string LockKey(string customerId, string? storeId) { return _loyaltyPointsSettings.PointsAccumulatedForAllStores ? $"LoyaltyPoints:{customerId}" diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnLabelService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnLabelService.cs index 3c8d761f8..04089ffb7 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnLabelService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnLabelService.cs @@ -25,7 +25,7 @@ public class MerchandiseReturnLabelService( ///
protected virtual TimeSpan ProviderTimeout => TimeSpan.FromSeconds(IReturnShippingProvider.LabelCallTimeoutSeconds); - public Task CreateLabel(string merchandiseReturnId) + public Task CreateLabel(string merchandiseReturnId) { return UnderLabelLock(merchandiseReturnId, async stored => { @@ -55,7 +55,7 @@ public async Task CancelLabel(string merchandiseReturnId) var error = await UnderLabelLock(merchandiseReturnId, stored => stored.ReturnShipping?.LabelStatus == ReturnLabelStatus.Created ? CancelProviderLabel(stored) - : Task.FromResult(null)); + : Task.FromResult(null)); //best effort: the status of the return is changed already, whatever happens to its label if (error != null) @@ -63,27 +63,31 @@ public async Task CancelLabel(string merchandiseReturnId) merchandiseReturnId, error); } - public Task UpdateShipping(string merchandiseReturnId, Action apply, - Func allowed = null) + public Task UpdateShipping(string merchandiseReturnId, Action apply, + Func? allowed = null) { ArgumentNullException.ThrowIfNull(apply); return UnderLabelLock(merchandiseReturnId, stored => stored.ReturnShipping == null - ? Task.FromResult(MerchandiseReturnErrors.NotFound) + ? Task.FromResult(MerchandiseReturnErrors.NotFound) : SaveUnderOrderLock(stored, current => { //nothing is saved when the change is no longer allowed, and the caller is told if (allowed != null && !allowed(current)) - return Task.FromResult(MerchandiseReturnErrors.ShippingChangeNotAllowed); + return Task.FromResult(MerchandiseReturnErrors.ShippingChangeNotAllowed); + //read again under the lock: the shipping may be gone meanwhile + if (current.ReturnShipping == null) + return Task.FromResult(MerchandiseReturnErrors.NotFound); apply(current.ReturnShipping); - return Task.FromResult(null); + return Task.FromResult(null); })); } - private async Task CreateInstructions(MerchandiseReturn stored) + private async Task CreateInstructions(MerchandiseReturn stored) { + //RequestLabel gives a result or an error var (result, error) = await RequestLabel(stored); - if (error != null) + if (result == null) { await InsertStaffNote(stored, $"The return instructions were not created: {error}"); return null; @@ -91,22 +95,27 @@ private async Task CreateInstructions(MerchandiseReturn stored) return await SaveUnderOrderLock(stored, current => { + if (current.ReturnShipping == null) + return Task.FromResult(MerchandiseReturnErrors.NotFound); current.ReturnShipping.Instructions = result.Instructions; current.ReturnShipping.ReturnCode = result.ReturnCode ?? current.ReturnShipping.ReturnCode; - return Task.FromResult(null); + return Task.FromResult(null); }); } - private async Task CreateProviderLabel(MerchandiseReturn stored) + private async Task CreateProviderLabel(MerchandiseReturn stored) { var (result, error) = await RequestLabel(stored); - MerchandiseReturn saved = null; + MerchandiseReturn? saved = null; var saveError = await SaveUnderOrderLock(stored, async current => { var shipping = current.ReturnShipping; + if (shipping == null) + return MerchandiseReturnErrors.NotFound; saved = current; - if (error != null) + //RequestLabel gives a result or an error + if (result == null) { //the return stays as it is; the label is retried from the panel or by the customer shipping.LabelStatus = ReturnLabelStatus.Failed; @@ -128,8 +137,11 @@ private async Task CreateProviderLabel(MerchandiseReturn stored) }); if (saveError != null) return saveError; + //saved by the change above, which ran when no error came back + if (saved == null) + return MerchandiseReturnErrors.NotFound; - if (error != null) + if (result == null) { await InsertStaffNote(saved, $"The return label was not created: {error}"); return null; @@ -148,9 +160,9 @@ private async Task CreateProviderLabel(MerchandiseReturn stored) return null; } - private async Task CancelProviderLabel(MerchandiseReturn stored) + private async Task CancelProviderLabel(MerchandiseReturn stored) { - var systemName = stored.ReturnShipping.ProviderSystemName; + var systemName = stored.ReturnShipping?.ProviderSystemName; var provider = returnShippingService.LoadProviderBySystemName(systemName); string reason; if (provider == null) @@ -161,15 +173,16 @@ private async Task CancelProviderLabel(MerchandiseReturn stored) } else { - Task call = null; + Task? call = null; try { call = provider.CancelLabel(stored); if (await call.WaitAsync(ProviderTimeout)) return await SaveUnderOrderLock(stored, current => { - current.ReturnShipping.LabelStatus = ReturnLabelStatus.Cancelled; - return Task.FromResult(null); + if (current.ReturnShipping != null) + current.ReturnShipping.LabelStatus = ReturnLabelStatus.Cancelled; + return Task.FromResult(null); }); logger.LogWarning("Return shipping provider {SystemName} did not cancel the label of merchandise " + @@ -198,9 +211,9 @@ private async Task CancelProviderLabel(MerchandiseReturn stored) /// Asks the provider for the label; a provider that is missing, fails, throws or does not answer in time gives /// the error instead ///
- private async Task<(ReturnLabelResult Result, string Error)> RequestLabel(MerchandiseReturn stored) + private async Task<(ReturnLabelResult? Result, string? Error)> RequestLabel(MerchandiseReturn stored) { - var systemName = stored.ReturnShipping.ProviderSystemName; + var systemName = stored.ReturnShipping?.ProviderSystemName; var provider = returnShippingService.LoadProviderBySystemName(systemName); if (provider == null) { @@ -209,7 +222,7 @@ private async Task CancelProviderLabel(MerchandiseReturn stored) return (null, ProviderNotInstalled); } - Task call = null; + Task? call = null; try { call = provider.CreateLabel(stored); @@ -268,7 +281,7 @@ private Task InsertStaffNote(MerchandiseReturn stored, string note) /// that held the lock before is seen. The provider is called under this lock only, so the order's returns can /// still be changed meanwhile ///
- private async Task UnderLabelLock(string merchandiseReturnId, Func> change) + private async Task UnderLabelLock(string merchandiseReturnId, Func> change) { try { @@ -295,8 +308,8 @@ private async Task UnderLabelLock(string merchandiseReturnId, Func - private async Task SaveUnderOrderLock(MerchandiseReturn stored, - Func> apply) + private async Task SaveUnderOrderLock(MerchandiseReturn stored, + Func> apply) { try { diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnRefundService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnRefundService.cs index 673d5aee2..230f86e64 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnRefundService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnRefundService.cs @@ -61,8 +61,8 @@ public async Task GetEstimate(IList Refund(string merchandiseReturnId, double amount, bool offline, - string refundedBy = null) + public async Task Refund(string merchandiseReturnId, double amount, bool offline, + string? refundedBy = null) { var merchandiseReturn = await merchandiseReturnService.GetMerchandiseReturnById(merchandiseReturnId); if (merchandiseReturn == null) @@ -70,12 +70,13 @@ public async Task Refund(string merchandiseReturnId, double amount, bool return await UnderRefundLock(merchandiseReturn, async () => { + //a start without an error carries the refund and its payment var start = await Start(merchandiseReturn, amount, offline, refundedBy); - if (start.Error != null) - return start.Error; + if (start is not { Transaction: { } transaction, Refund: { } refund }) + return start.Error ?? MerchandiseReturnErrors.NotFound; - var errors = await PayBack(merchandiseReturn, start.Transaction, start.Refund); - var saved = await Finish(merchandiseReturn, start.Refund, errors); + var errors = await PayBack(merchandiseReturn, transaction, refund); + var saved = await Finish(merchandiseReturn, refund, errors); //the payment may have given the money back before it failed: the staff check it and say so if (errors.Count > 0) @@ -89,7 +90,7 @@ public async Task Refund(string merchandiseReturnId, double amount, bool }); } - public async Task ResolveRefund(string merchandiseReturnId, bool wentBack, string checkedBy = null) + public async Task ResolveRefund(string merchandiseReturnId, bool wentBack, string? checkedBy = null) { var merchandiseReturn = await merchandiseReturnService.GetMerchandiseReturnById(merchandiseReturnId); if (merchandiseReturn == null) @@ -98,7 +99,7 @@ public async Task ResolveRefund(string merchandiseReturnId, bool wentBac var by = string.IsNullOrWhiteSpace(checkedBy) ? null : checkedBy.Trim(); return await UnderRefundLock(merchandiseReturn, async () => { - MerchandiseReturnRefund refunded = null; + MerchandiseReturnRefund? refunded = null; var error = await UnderOrderLock(merchandiseReturn, async stored => { var refund = stored.Refund; @@ -138,7 +139,7 @@ public async Task ResolveRefund(string merchandiseReturnId, bool wentBac /// for the lock, or one asked again after a crash, finds it there and pays nothing twice ///
private async Task Start(MerchandiseReturn merchandiseReturn, double amount, bool offline, - string refundedBy) + string? refundedBy) { var start = new RefundStart(); start.Error = await UnderOrderLock(merchandiseReturn, async stored => @@ -156,6 +157,8 @@ private async Task Start(MerchandiseReturn merchandiseReturn, doubl var (quote, transaction, rounding) = await Quote(stored, order); if (quote.Error != null) return quote.Error; + if (transaction == null) + return MerchandiseReturnErrors.RefundNotAllowed; //checked before the rounding as well, which cannot take NaN, infinity or amounts beyond a decimal if (double.IsNaN(amount) || amount <= 0 || amount > quote.MaxAmount) @@ -187,7 +190,7 @@ private async Task Start(MerchandiseReturn merchandiseReturn, doubl /// What the refund comes to now: the items less the return shipping cost, at most what is left to refund of /// the order's payment ///
- private async Task<(MerchandiseReturnRefundQuote Quote, PaymentTransaction Transaction, Rounding Rounding)> Quote( + private async Task<(MerchandiseReturnRefundQuote Quote, PaymentTransaction? Transaction, Rounding Rounding)> Quote( MerchandiseReturn merchandiseReturn, Order order) { var quote = new MerchandiseReturnRefundQuote { CurrencyCode = order.CustomerCurrencyCode }; @@ -327,7 +330,7 @@ await InsertStaffNote(stored, $"The refund of {Format(refund.Amount)} by {by} ga /// A refunded return is done: a note on the order, and the return completed, which tells the customer ///
private async Task Complete(MerchandiseReturn merchandiseReturn, MerchandiseReturnRefund refund, - string changedBy) + string? changedBy) { try { @@ -364,7 +367,7 @@ private async Task RoundingOf(Order order) /// /// The order's returns other than the one given that are refunded, being refunded or waiting for their check /// - private async Task> RefundedReturns(Order order, string merchandiseReturnId) + private async Task> RefundedReturns(Order order, string? merchandiseReturnId) { return (await mediator.Send(new GetMerchandiseReturnQuery { OrderId = order.Id })) .Where(x => x.Id != merchandiseReturnId && x.Refund != null) @@ -391,9 +394,9 @@ private static (double ItemsAmount, double ReturnShippingCost) Amounts(Merchandi private static double Left(PaymentTransaction transaction, IEnumerable refunded, Rounding rounding) { - var underWay = refunded - .Where(x => x.Refund.RefundedOnUtc == null && x.Refund.PaymentTransactionId == transaction.Id) - .Sum(x => x.Refund.Amount); + var underWay = refunded.Select(x => x.Refund).OfType() + .Where(x => x.RefundedOnUtc == null && x.PaymentTransactionId == transaction.Id) + .Sum(x => x.Amount); return rounding.Round(transaction.TransactionAmount - transaction.RefundedAmount - underWay); } @@ -417,7 +420,7 @@ private Task InsertStaffNote(MerchandiseReturn merchandiseReturn, string note) /// is short; a provider slower than it may let a second refund of the order start, which still finds the first /// under way and keeps its amount off what is left ///
- private async Task UnderRefundLock(MerchandiseReturn merchandiseReturn, Func> refund) + private async Task UnderRefundLock(MerchandiseReturn merchandiseReturn, Func> refund) { try { @@ -439,8 +442,8 @@ private async Task UnderRefundLock(MerchandiseReturn merchandiseReturn, /// Runs the change on the return as stored once the lock of its order is held, which every writer of the /// order's returns holds. Always taken inside the refund lock, never the other way round ///
- private async Task UnderOrderLock(MerchandiseReturn merchandiseReturn, - Func> change) + private async Task UnderOrderLock(MerchandiseReturn merchandiseReturn, + Func> change) { try { @@ -463,9 +466,9 @@ private async Task UnderOrderLock(MerchandiseReturn merchandiseReturn, private sealed class RefundStart { - public string Error { get; set; } - public MerchandiseReturnRefund Refund { get; set; } - public PaymentTransaction Transaction { get; set; } + public string? Error { get; set; } + public MerchandiseReturnRefund? Refund { get; set; } + public PaymentTransaction? Transaction { get; set; } } /// diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs index 1790d2be5..83080bd1b 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs @@ -63,7 +63,7 @@ public MerchandiseReturnService(IRepository merchandiseReturn /// /// Merchandise return identifier /// Merchandise return - public virtual Task GetMerchandiseReturnById(string merchandiseReturnId) + public virtual Task GetMerchandiseReturnById(string? merchandiseReturnId) { return _merchandiseReturnRepository.GetByIdAsync(merchandiseReturnId); } @@ -73,7 +73,7 @@ public virtual Task GetMerchandiseReturnById(string merchandi ///
/// Merchandise return identifier /// Merchandise return - public virtual async Task GetMerchandiseReturnById(int id) + public virtual async Task GetMerchandiseReturnById(int id) { return await _merchandiseReturnRepository.FirstOrDefaultAsync( _merchandiseReturnRepository.Table.Where(x => x.ReturnNumber == id)); @@ -126,7 +126,7 @@ public virtual async Task> SearchMerchandiseReturn ///
/// Store identifier; empty to load all entries /// Merchandise return actions - public virtual async Task> GetAllMerchandiseReturnActions(string storeId = "") + public virtual async Task> GetAllMerchandiseReturnActions(string? storeId = "") { var key = string.Format(CacheKey.MERCHANDISE_RETURN_ACTIONS_ALL_KEY, storeId); return await _cacheBase.GetAsync(key, async () => @@ -146,7 +146,7 @@ orderby rra.DisplayOrder ///
/// Merchandise return action identifier /// Merchandise return action - public virtual Task GetMerchandiseReturnActionById(string merchandiseReturnActionId) + public virtual Task GetMerchandiseReturnActionById(string merchandiseReturnActionId) { return _merchandiseReturnActionRepository.GetByIdAsync(merchandiseReturnActionId); } @@ -277,7 +277,7 @@ public virtual async Task DeleteMerchandiseReturnReason(MerchandiseReturnReason ///
/// Store identifier; empty to load all entries /// Merchandise return reasons - public virtual async Task> GetAllMerchandiseReturnReasons(string storeId = "") + public virtual async Task> GetAllMerchandiseReturnReasons(string? storeId = "") { var key = string.Format(CacheKey.MERCHANDISE_RETURN_REASONS_ALL_KEY, storeId); return await _cacheBase.GetAsync(key, async () => @@ -297,7 +297,7 @@ orderby rra.DisplayOrder ///
/// Merchandise return reasons identifier /// Merchandise return reasons - public virtual Task GetMerchandiseReturnReasonById(string merchandiseReturnReasonId) + public virtual Task GetMerchandiseReturnReasonById(string merchandiseReturnReasonId) { return _merchandiseReturnReasonRepository.GetByIdAsync(merchandiseReturnReasonId); } @@ -380,7 +380,7 @@ orderby merchandiseReturnNote.CreatedOnUtc descending ///
/// The merchandise return note identifier /// MerchandiseReturnNote - public virtual async Task GetMerchandiseReturnNote(string merchandiseReturnNoteId) + public virtual async Task GetMerchandiseReturnNote(string merchandiseReturnNoteId) { return await _merchandiseReturnNoteRepository.FirstOrDefaultAsync( _merchandiseReturnNoteRepository.Table.Where(x => x.Id == merchandiseReturnNoteId)); diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnWorkflowService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnWorkflowService.cs index 12ffca0da..783c05592 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnWorkflowService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnWorkflowService.cs @@ -183,7 +183,7 @@ private async Task WithNewLabel(MerchandiseReturn merchandise }, //checked again on the return as stored: it may have been rejected or cancelled since stored => stored.MerchandiseReturnStatus == MerchandiseReturnStatus.Pending - && stored.ReturnShipping.LabelStatus == ReturnLabelStatus.Cancelled); + && stored.ReturnShipping != null && stored.ReturnShipping.LabelStatus == ReturnLabelStatus.Cancelled); if (error != null) { logger.LogWarning("The cancelled label of merchandise return {MerchandiseReturnId}, opened again, " + @@ -253,7 +253,7 @@ private async Task InsertAllOrNone(IList merchandiseReturns) } private async Task NewMerchandiseReturn(MerchandiseReturnSubmitRequest request, - string vendorId, IEnumerable items, MerchandiseReturnShipping shipping) + string vendorId, IEnumerable items, MerchandiseReturnShipping? shipping) { var merchandiseReturn = new MerchandiseReturn { StoreId = request.StoreId, @@ -298,7 +298,7 @@ private async Task NewMerchandiseReturn(MerchandiseReturnSubm /// The return shipping of one return: the label and the provider's data of one vendor's parcel are never /// those of another's. The addresses and the drop-off point are built for each vendor already ///
- private static MerchandiseReturnShipping Copy(MerchandiseReturnShipping shipping) + private static MerchandiseReturnShipping? Copy(MerchandiseReturnShipping? shipping) { if (shipping == null) return null; @@ -321,22 +321,22 @@ private static MerchandiseReturnShipping Copy(MerchandiseReturnShipping shipping }; } - public Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus status, - string customerNote = null, string changedBy = null) + public Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus status, + string? customerNote = null, string? changedBy = null) { return ChangeStatus(merchandiseReturnId, status, customerNote, changedBy, null); } - public Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus status, - string customerNote, string changedBy, Func allowed) + public Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus status, + string? customerNote, string? changedBy, Func? allowed) { return ChangeStatus(merchandiseReturnId, status, customerNote, changedBy, allowed, false); } - public async Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus status, - string customerNote, string changedBy, Func allowed, bool withoutReturnReceipts) + public async Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus status, + string? customerNote, string? changedBy, Func? allowed, bool withoutReturnReceipts) { - MerchandiseReturn changed = null; + MerchandiseReturn? changed = null; var error = await UnderOrderLock(merchandiseReturnId, async stored => { if (allowed != null && !allowed(stored)) @@ -369,6 +369,9 @@ await merchandiseReturnService.InsertMerchandiseReturnNote(new MerchandiseReturn }); if (error != null) return error; + //set by the change above, which ran when no error came back + if (changed == null) + return MerchandiseReturnErrors.NotFound; //the goods are not sent back: the label is cancelled with the carrier once the order's lock is let go, as //the label service takes it again to save; a label not cancelled leaves the status change as it is @@ -414,7 +417,7 @@ await merchandiseReturnMessageProviderService.SendMerchandiseReturnStatusChanged return null; } - public Task Update(string merchandiseReturnId, Action apply) + public Task Update(string merchandiseReturnId, Action apply) { ArgumentNullException.ThrowIfNull(apply); return UnderOrderLock(merchandiseReturnId, async stored => @@ -427,7 +430,7 @@ public Task Update(string merchandiseReturnId, Action }); } - public Task Delete(string merchandiseReturnId) + public Task Delete(string merchandiseReturnId) { //the order's returned quantities are counted again under the lock its returns are saved with return UnderOrderLock(merchandiseReturnId, async stored => @@ -442,7 +445,7 @@ public Task Delete(string merchandiseReturnId) }); } - public async Task MarkReceived(string merchandiseReturnId, string changedBy = null) + public async Task MarkReceived(string merchandiseReturnId, string? changedBy = null) { //read without the lock, which ChangeStatus takes and which is not reentrant; a status changed in between is //checked again under it, and such a refusal leaves the return as it is @@ -463,7 +466,7 @@ public async Task MarkReceived(string merchandiseReturnId, string changedBy = nu /// Runs the change on the return as stored once the lock of its order is held: another change that held the /// lock before has been saved by then ///
- private async Task UnderOrderLock(string merchandiseReturnId, Func> change) + private async Task UnderOrderLock(string merchandiseReturnId, Func> change) { var merchandiseReturn = await merchandiseReturnService.GetMerchandiseReturnById(merchandiseReturnId); if (merchandiseReturn == null) @@ -499,7 +502,7 @@ public Task CanMarkReceived(MerchandiseReturn merchandiseReturn, Order ord return CanMarkReceived(merchandiseReturn, order, false); } - private async Task CanMarkReceived(MerchandiseReturn merchandiseReturn, Order order, bool readOrder) + private async Task CanMarkReceived(MerchandiseReturn merchandiseReturn, Order? order, bool readOrder) { ArgumentNullException.ThrowIfNull(merchandiseReturn); @@ -530,13 +533,13 @@ private async Task CanMarkReceived(MerchandiseReturn merchandiseReturn, Or return true; } - private static bool TracksStock(Product product) + private static bool TracksStock(Product? product) { return product?.ManageInventoryMethodId is ManageInventoryMethod.ManageStock or ManageInventoryMethod.ManageStockByAttributes; } - private async Task StatusChangeError(MerchandiseReturn stored, MerchandiseReturnStatus status, + private async Task StatusChangeError(MerchandiseReturn stored, MerchandiseReturnStatus status, bool withoutReturnReceipts) { if (!stored.MerchandiseReturnStatus.CanChangeTo(status)) @@ -581,6 +584,6 @@ private async Task IsQuantityLeft(MerchandiseReturn merchandiseReturn) var returnable = await mediator.Send(new GetReturnableQuantitiesQuery { Order = order, ForStaff = true }); return merchandiseReturn.MerchandiseReturnItems.GroupBy(x => x.OrderItemId) - .All(x => x.Sum(item => item.Quantity) <= returnable.GetValueOrDefault(x.Key)); + .All(x => x.Key != null && x.Sum(item => item.Quantity) <= returnable.GetValueOrDefault(x.Key)); } } diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderApprovalLimitRuleProvider.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderApprovalLimitRuleProvider.cs index 777a138e9..ffe96594a 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderApprovalLimitRuleProvider.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderApprovalLimitRuleProvider.cs @@ -26,7 +26,7 @@ public OrderApprovalLimitRuleProvider(CustomerSettings customerSettings, ICurren _translationService = translationService; } - public string ConfigurationUrl => null; + public string? ConfigurationUrl => null; public string SystemName => "OrderPlacementRule.ApprovalLimit"; public string FriendlyName => SystemName; public int Priority => 0; @@ -54,7 +54,7 @@ public async Task Evaluate(OrderPlacementContext conte return OrderPlacementRuleResult.RequireApproval(await LimitExceededText(limit.Value, context)); } - private async Task LimitExceededText(double limit, OrderPlacementContext context) + private async Task LimitExceededText(double limit, OrderPlacementContext context) { var currency = context.Calculation.Currency; var message = _translationService.GetResource("Checkout.OrderApproval.LimitExceeded", context.Language.Id); diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderApprovalService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderApprovalService.cs index 606bcc688..27a14ddf2 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderApprovalService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderApprovalService.cs @@ -35,7 +35,7 @@ public OrderApprovalService(IRepository repository, #region Methods - public virtual async Task GetById(string id, string companyOwnerId) + public virtual async Task GetById(string id, string companyOwnerId) { if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(companyOwnerId)) return null; @@ -44,7 +44,7 @@ public virtual async Task GetById(string id, string companyOwnerI _repository.Table.Where(x => x.Id == id && x.CompanyOwnerId == companyOwnerId)); } - public virtual async Task GetByOrderId(string orderId) + public virtual async Task GetByOrderId(string orderId) { if (string.IsNullOrEmpty(orderId)) return null; @@ -90,7 +90,7 @@ public virtual async Task Insert(OrderApproval approval) } public virtual async Task Close(OrderApproval approval, OrderApprovalStatus status, - string decidedByCustomerId = null, string decisionComment = null) + string? decidedByCustomerId = null, string? decisionComment = null) { ArgumentNullException.ThrowIfNull(approval); @@ -138,7 +138,7 @@ await _repository.UpdateOneAsync(x => x.Id == approval.Id && x.CloseId == approv await _mediator.EntityUpdated(approval); } - public virtual bool IsPaymentMethodAllowed(string paymentMethodSystemName) + public virtual bool IsPaymentMethodAllowed(string? paymentMethodSystemName) { return !string.IsNullOrEmpty(paymentMethodSystemName) && _approvalSettings.PaymentMethodSystemNames?.Contains(paymentMethodSystemName, diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderPlacementService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderPlacementService.cs index 29998c216..0625ee234 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderPlacementService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderPlacementService.cs @@ -32,7 +32,7 @@ public OrderPlacementService(IEnumerable rules, } public virtual async Task Evaluate(IList cart, - CalculationContext calculation, Language language, string paymentMethodSystemName, + CalculationContext calculation, Language language, string? paymentMethodSystemName, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(cart); diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderReportService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderReportService.cs index 23ab5f365..a1813aff7 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderReportService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderReportService.cs @@ -92,7 +92,7 @@ public virtual async Task> GetCountryReport(stri if (string.IsNullOrEmpty(vendorId)) { var report = (from oq in query - group oq by oq.BillingAddress.CountryId + group oq by oq.BillingAddress != null ? oq.BillingAddress.CountryId : null into result select new { CountryId = result.Key, @@ -114,7 +114,7 @@ into result from item in p.OrderItems select new { item.VendorId, OrderId = p.Id, - p.BillingAddress.CountryId, + CountryId = p.BillingAddress != null ? p.BillingAddress.CountryId : null, item.PriceInclTax, p.CurrencyRate }; @@ -241,11 +241,11 @@ public virtual async Task> GetOrderByTimeReport(str public virtual async Task GetOrderAverageReportLine(string storeId = "", string customerId = "", string vendorId = "", string salesEmployeeId = "", string billingCountryId = "", - string orderId = "", string paymentMethodSystemName = null, + string orderId = "", string? paymentMethodSystemName = null, int? os = null, PaymentStatus? ps = null, ShippingStatus? ss = null, DateTime? startTimeUtc = null, DateTime? endTimeUtc = null, - string billingEmail = null, string billingLastName = "", bool ignoreCancelledOrders = false, - string tagId = null) + string? billingEmail = null, string billingLastName = "", bool ignoreCancelledOrders = false, + string? tagId = null) { var builderquery = from p in _orderRepository.Table select p; @@ -491,13 +491,13 @@ public virtual async Task> MerchandiseRe //each item returned, with the return it belongs to var returned = returns.SelectMany(x => x.MerchandiseReturnItems.Select(item => (Return: x.Id, Item: item, Vendor: x.VendorId ?? "", x.OrderId))).ToList(); - IEnumerable<(string Key, string Name, string Return, int Quantity)> keyed = groupBy switch { + IEnumerable<(string Key, string? Name, string Return, int Quantity)> keyed = groupBy switch { //a return item from before reasons were kept by identifier is counted by the text the customer chose MerchandiseReturnReportGrouping.Reason => returned.Select(x => (string.IsNullOrEmpty(x.Item.ReasonId) ? x.Item.ReasonForReturn?.Trim() ?? "" : x.Item.ReasonId, x.Item.ReasonForReturn?.Trim(), x.Return, x.Item.Quantity)), MerchandiseReturnReportGrouping.Vendor => returned.Select(x => - (x.Vendor, (string)null, x.Return, x.Item.Quantity)), + (x.Vendor, (string?)null, x.Return, x.Item.Quantity)), _ => await ByProduct(returned.Select(x => (x.OrderId, x.Item.OrderItemId, x.Return, x.Item.Quantity)) .ToList()) }; @@ -515,10 +515,10 @@ public virtual async Task> MerchandiseRe if (groupBy == MerchandiseReturnReportGrouping.Product && page.Count > 0) { - var sold = await SoldQuantities(page.Select(x => x.Key).ToList(), createdFromUtc, createdToUtc, storeId, - vendorId); + var sold = await SoldQuantities(page.Select(x => x.Key).OfType().ToList(), createdFromUtc, + createdToUtc, storeId, vendorId); foreach (var line in page) - line.SoldQuantity = sold.GetValueOrDefault(line.Key); + line.SoldQuantity = line.Key != null ? sold.GetValueOrDefault(line.Key) : 0; } return page; @@ -527,8 +527,8 @@ public virtual async Task> MerchandiseRe /// /// The product of each item returned, read from the orders of the returns /// - private async Task> ByProduct( - IList<(string OrderId, string OrderItemId, string Return, int Quantity)> returned) + private async Task> ByProduct( + IList<(string OrderId, string? OrderItemId, string Return, int Quantity)> returned) { var orderIds = returned.Select(x => x.OrderId).Distinct().ToList(); var orders = await _orderRepository.ToListAsync(_orderRepository.Table @@ -536,8 +536,11 @@ public virtual async Task> MerchandiseRe .Select(x => new { x.OrderItems })); var products = orders.SelectMany(x => x.OrderItems).GroupBy(x => x.Id) .ToDictionary(x => x.Key, x => x.First().ProductId); - return returned.Where(x => products.ContainsKey(x.OrderItemId)) - .Select(x => (products[x.OrderItemId], (string)null, x.Return, x.Quantity)); + var keyed = new List<(string Key, string? Name, string Return, int Quantity)>(); + foreach (var x in returned) + if (x.OrderItemId != null && products.TryGetValue(x.OrderItemId, out var productId)) + keyed.Add((productId ?? "", null, x.Return, x.Quantity)); + return keyed; } /// @@ -554,7 +557,7 @@ private async Task> SoldQuantities(IList product var items = from o in orders from item in o.OrderItems - where productIds.Contains(item.ProductId) + where item.ProductId != null && productIds.Contains(item.ProductId) select new { item.ProductId, item.VendorId, item.Quantity }; if (!string.IsNullOrEmpty(vendorId)) items = items.Where(x => x.VendorId == vendorId); diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs index 5a1468235..7fc7e639e 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderService.cs @@ -63,7 +63,7 @@ IMediator mediator /// /// The order identifier /// Order - public virtual Task GetOrderById(string orderId) + public virtual Task GetOrderById(string? orderId) { return _orderRepository.GetByIdAsync(orderId); } @@ -74,7 +74,7 @@ public virtual Task GetOrderById(string orderId) ///
/// The order item identifier /// Order - public virtual async Task GetOrderByOrderItemId(string orderItemId) + public virtual async Task GetOrderByOrderItemId(string orderItemId) { var query = from o in _orderRepository.Table where o.OrderItems.Any(x => x.Id == orderItemId) @@ -88,7 +88,7 @@ where o.OrderItems.Any(x => x.Id == orderItemId) ///
/// The order number /// Order - public virtual async Task GetOrderByNumber(int orderNumber) + public virtual async Task GetOrderByNumber(int orderNumber) { return await _orderRepository.FirstOrDefaultAsync( _orderRepository.Table.Where(x => x.OrderNumber == orderNumber)); @@ -125,7 +125,7 @@ where orderIds.Contains(o.Id) var orders = await _orderRepository.ToListAsync(query); //sort by passed identifiers return orderIds.Select(id => orders.FirstOrDefault(order => order.Id == id)) - .Where(order => order != null) + .OfType() .ToList(); } @@ -134,7 +134,7 @@ where orderIds.Contains(o.Id) ///
/// The order identifier /// Order - public virtual async Task GetOrderByGuid(Guid orderGuid) + public virtual async Task GetOrderByGuid(Guid orderGuid) { var query = from o in _orderRepository.Table where o.OrderGuid == orderGuid @@ -178,12 +178,12 @@ public virtual async Task> SearchOrders(string storeId = "", string vendorId = "", string customerId = "", string productId = "", string affiliateId = "", string warehouseId = "", string billingCountryId = "", string ownerId = "", string salesEmployeeId = "", - string paymentMethodSystemName = null, + string? paymentMethodSystemName = null, DateTime? createdFromUtc = null, DateTime? createdToUtc = null, int? os = null, PaymentStatus? ps = null, ShippingStatus? ss = null, - string billingEmail = null, string billingLastName = "", string orderGuid = null, - string orderCode = null, int pageIndex = 0, int pageSize = int.MaxValue, string orderTagId = "", - string purchaseOrderNumber = null, bool overdueOnly = false) + string? billingEmail = null, string billingLastName = "", string? orderGuid = null, + string? orderCode = null, int pageIndex = 0, int pageSize = int.MaxValue, string orderTagId = "", + string? purchaseOrderNumber = null, bool overdueOnly = false) { var queryModel = new GetOrderQuery { AffiliateId = affiliateId, @@ -314,7 +314,7 @@ public async Task CancelExpiredOrders(DateTime expirationDateUtc, CancellationTo var orderIds = orders.Select(o => o.Id).ToList(); var approvedRecently = orderIds.Count > 0 ? _orderApprovalRepository.Table - .Where(a => orderIds.Contains(a.OrderId) && a.Status == OrderApprovalStatus.Approved && + .Where(a => a.OrderId != null && orderIds.Contains(a.OrderId) && a.Status == OrderApprovalStatus.Approved && a.DecidedOnUtc >= expirationDateUtc) .Select(a => a.OrderId) .ToList() @@ -336,7 +336,7 @@ public async Task CancelExpiredOrders(DateTime expirationDateUtc, CancellationTo ///
/// Order identifier /// Order item - public virtual async Task GetOrderItemByGuid(Guid orderItemGuid) + public virtual async Task GetOrderItemByGuid(Guid orderItemGuid) { var query = from order in _orderRepository.Table from orderItem in order.OrderItems @@ -396,7 +396,7 @@ orderby orderNote.CreatedOnUtc descending ///
/// Order note identifier /// OrderNote - public virtual async Task GetOrderNote(string orderNoteId) + public virtual async Task GetOrderNote(string orderNoteId) { return await _orderNoteRepository.FirstOrDefaultAsync( _orderNoteRepository.Table.Where(x => x.Id == orderNoteId)); diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderStatusService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderStatusService.cs index 6d03b1e1c..058a248a0 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderStatusService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderStatusService.cs @@ -38,12 +38,12 @@ public virtual async Task> GetAll() return orderStatuses; } - public virtual async Task GetById(string id) + public virtual async Task GetById(string id) { return (await GetAll()).FirstOrDefault(x => x.Id == id); } - public virtual async Task GetByStatusId(int statusId) + public virtual async Task GetByStatusId(int statusId) { return (await GetAll()).FirstOrDefault(x => x.StatusId == statusId); } diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs index cc9e742a4..f4918ae33 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/OrderTagService.cs @@ -73,7 +73,7 @@ public virtual async Task> GetAllOrderTags() ///
/// Order's tag identifier /// Order's tag - public virtual Task GetOrderTagById(string orderTagId) + public virtual Task GetOrderTagById(string orderTagId) { return _orderTagRepository.GetByIdAsync(orderTagId); } @@ -83,7 +83,7 @@ public virtual Task GetOrderTagById(string orderTagId) ///
/// Order's tag name /// Order's tag - public virtual Task GetOrderTagByName(string name) + public virtual Task GetOrderTagByName(string name) { return _orderTagRepository.GetOneAsync(x => x.Name == name); } @@ -145,6 +145,9 @@ public virtual async Task AttachOrderTag(string orderTagId, string orderId) await _orderRepository.AddToCollectionField(orderId, x => x.OrderTags, orderTagId); var orderTag = await GetOrderTagById(orderTagId); + if (orderTag == null) + return; + //update product tag await _orderTagRepository.UpdateField(orderTagId, x => x.Count, orderTag.Count + 1); @@ -162,6 +165,9 @@ public virtual async Task DetachOrderTag(string orderTagId, string orderId) await _orderRepository.RemoveCollectionFieldItem(orderId, x => x.OrderTags, y => y == orderTagId); var orderTag = await GetOrderTagById(orderTagId); + if (orderTag == null) + return; + //update product tag await _orderTagRepository.UpdateField(orderTagId, x => x.Count, orderTag.Count - 1); diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentRuleProvider.cs b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentRuleProvider.cs index 6d2f870ce..d3cc74c3f 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentRuleProvider.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentRuleProvider.cs @@ -23,7 +23,7 @@ public RecurringPaymentRuleProvider(IRecurringPaymentService recurringPaymentSer _translationService = translationService; } - public string ConfigurationUrl => null; + public string? ConfigurationUrl => null; public string SystemName => "OrderPlacementRule.RecurringPayment"; public string FriendlyName => SystemName; public int Priority => 0; diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs index 1b39dcce7..1e305101a 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/RecurringPaymentService.cs @@ -28,12 +28,12 @@ public virtual async Task InsertRecurringPayment(RecurringPayment recurringPayme await mediator.EntityInserted(recurringPayment); } - public virtual async Task ClaimCycle(string recurringPaymentId, string providerReference, + public virtual async Task ClaimCycle(string recurringPaymentId, string? providerReference, string cycleReference, double amount, DateTime paidOnUtc, DateTime? nextPaymentDateUtc) { ArgumentException.ThrowIfNullOrEmpty(cycleReference); - RecurringPayment recurringPayment; + RecurringPayment? recurringPayment; RecurringPaymentCycle cycle; var completed = false; @@ -41,6 +41,8 @@ public virtual async Task ClaimCycle(string recurringPaymen await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) { recurringPayment = await repository.GetByIdAsync(recurringPaymentId); + if (recurringPayment == null) + return new RecurringCycleClaim { Outcome = RecurringReportOutcome.NotFound }; var refused = Refusal(recurringPayment, providerReference); if (refused == null && recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference)) refused = RecurringReportOutcome.Duplicate; @@ -87,16 +89,18 @@ public virtual async Task ClaimCycle(string recurringPaymen } public virtual async Task RecordFailure(string recurringPaymentId, - string providerReference, string cycleReference, string reason) + string? providerReference, string cycleReference, string? reason) { ArgumentException.ThrowIfNullOrEmpty(cycleReference); - RecurringPayment recurringPayment; + RecurringPayment? recurringPayment; bool enteredPastDue; await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) { recurringPayment = await repository.GetByIdAsync(recurringPaymentId); + if (recurringPayment == null) + return new RecurringReportResult { Outcome = RecurringReportOutcome.NotFound }; var refused = Refusal(recurringPayment, providerReference); //a failure that arrives after the cycle was paid is a late, out of order event if (refused == null && recurringPayment.Cycles.Any(x => x.ProviderReference == cycleReference)) @@ -131,14 +135,16 @@ public virtual async Task RecordFailure(string recurringP return new RecurringReportResult { Outcome = RecurringReportOutcome.Recorded, RecurringPayment = recurringPayment }; } - public virtual async Task RecordEnded(string recurringPaymentId, string providerReference) + public virtual async Task RecordEnded(string recurringPaymentId, string? providerReference) { - RecurringPayment recurringPayment; + RecurringPayment? recurringPayment; await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) { recurringPayment = await repository.GetByIdAsync(recurringPaymentId); //another subscription ending says nothing about the one this payment runs on + if (recurringPayment == null) + return new RecurringReportResult { Outcome = RecurringReportOutcome.NotFound }; var refused = Refusal(recurringPayment, providerReference); if (refused == null && recurringPayment.Status.HasEnded()) refused = RecurringReportOutcome.Ended; @@ -161,15 +167,17 @@ public virtual async Task RecordEnded(string recurringPay } public virtual async Task RecordProviderReference(string recurringPaymentId, - string providerReference) + string? providerReference) { ArgumentException.ThrowIfNullOrEmpty(providerReference); - RecurringPayment recurringPayment; + RecurringPayment? recurringPayment; await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) { recurringPayment = await repository.GetByIdAsync(recurringPaymentId); + if (recurringPayment == null) + return new RecurringReportResult { Outcome = RecurringReportOutcome.NotFound }; var refused = Refusal(recurringPayment, providerReference); if (refused == null && recurringPayment.ProviderReference == providerReference) refused = RecurringReportOutcome.Duplicate; @@ -186,19 +194,16 @@ public virtual async Task RecordProviderReference(string return new RecurringReportResult { Outcome = RecurringReportOutcome.Recorded, RecurringPayment = recurringPayment }; } - //why a report is refused whatever it reports, or null - private static RecurringReportOutcome? Refusal(RecurringPayment recurringPayment, string providerReference) + //why a report of a payment found is refused whatever it reports, or null + private static RecurringReportOutcome? Refusal(RecurringPayment recurringPayment, string? providerReference) { - if (recurringPayment == null) - return RecurringReportOutcome.NotFound; - return recurringPayment.HasOtherProviderReference(providerReference) ? RecurringReportOutcome.OtherReference : null; } //the first reference reported is the one the payment runs on, whichever report brings it - private static bool KeepFirstReference(RecurringPayment recurringPayment, string providerReference) + private static bool KeepFirstReference(RecurringPayment recurringPayment, string? providerReference) { if (!string.IsNullOrEmpty(recurringPayment.ProviderReference) || string.IsNullOrEmpty(providerReference)) return false; @@ -213,7 +218,7 @@ public virtual async Task Cancel(string recurringP ArgumentException.ThrowIfNullOrEmpty(cancelledBy); ArgumentNullException.ThrowIfNull(stopAtGateway); - RecurringPayment recurringPayment; + RecurringPayment? recurringPayment; var cancelled = false; await using (await resourceLock.Acquire([LockKey(recurringPaymentId)])) @@ -281,12 +286,12 @@ private static string LockKey(string recurringPaymentId) return $"{nameof(RecurringPayment)}:{recurringPaymentId}"; } - public virtual Task GetRecurringPaymentById(string id) + public virtual Task GetRecurringPaymentById(string id) { return repository.GetByIdAsync(id); } - public virtual Task GetRecurringPaymentByInitialOrderId(string initialOrderId) + public virtual Task GetRecurringPaymentByInitialOrderId(string initialOrderId) { return repository.GetOneAsync(x => x.InitialOrderId == initialOrderId); } diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs index fff4930d3..75e6451b6 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartService.cs @@ -56,7 +56,7 @@ public ShoppingCartService( /// Store identifier; pass null to load all records /// Shopping cart type; pass null to load all records /// Shopping Cart - public virtual async Task> GetShoppingCart(Customer customer, string storeId = null, + public virtual async Task> GetShoppingCart(Customer customer, string? storeId = null, params ShoppingCartType[] shoppingCartType) { ArgumentNullException.ThrowIfNull(customer); @@ -94,11 +94,11 @@ public virtual async Task> GetShoppingCart(Customer cust /// Rental end date /// /// Found shopping cart item - public virtual async Task FindShoppingCartItem(IList shoppingCart, + public virtual async Task FindShoppingCartItem(IList shoppingCart, ShoppingCartType shoppingCartType, string productId, - string warehouseId = null, - IList attributes = null, + string? warehouseId = null, + IList? attributes = null, double? customerEnteredPrice = null, DateTime? rentalStartDate = null, DateTime? rentalEndDate = null) @@ -110,14 +110,15 @@ public virtual async Task FindShoppingCartItem(IList FindShoppingCartItem(IList FindShoppingCartItem(IListDuration for reservation /// ShoppingCartValidatorOptions /// (warnings, shoppingCartItem) - public virtual async Task<(IList warnings, ShoppingCartItem shoppingCartItem)> AddToCart(Customer customer, - Language language, string productId, - ShoppingCartType shoppingCartType, string storeId, - string warehouseId = null, IList attributes = null, + public virtual async Task<(IList warnings, ShoppingCartItem? shoppingCartItem)> AddToCart(Customer customer, + Language language, string? productId, + ShoppingCartType shoppingCartType, string? storeId, + string? warehouseId = null, IList? attributes = null, double? customerEnteredPrice = null, DateTime? rentalStartDate = null, DateTime? rentalEndDate = null, int quantity = 1, bool automaticallyAddRequiredProductsIfEnabled = true, - string reservationId = "", string parameter = "", string duration = "", - ShoppingCartValidatorOptions validator = null) + string? reservationId = "", string? parameter = "", string? duration = "", + ShoppingCartValidatorOptions? validator = null) { ArgumentNullException.ThrowIfNull(customer); @@ -214,20 +215,20 @@ public virtual async Task FindShoppingCartItem(IList> UpdateShoppingCartItem(Customer custome if (quantity > 0) { var product = await _productService.GetProductById(shoppingCartItem.ProductId); + ArgumentNullException.ThrowIfNull(product); shoppingCartItem.Quantity = quantity; shoppingCartItem.WarehouseId = warehouseId; shoppingCartItem.Attributes = attributes; @@ -384,7 +386,9 @@ public virtual async Task DeleteShoppingCartItem(Customer customer, ShoppingCart if (resetCheckoutData) await _customerService.ResetCheckoutData(customer, shoppingCartItem.StoreId); //delete item - customer.ShoppingCartItems.Remove(customer.ShoppingCartItems.FirstOrDefault(x => x.Id == shoppingCartItem.Id)); + var item = customer.ShoppingCartItems.FirstOrDefault(x => x.Id == shoppingCartItem.Id); + if (item != null) + customer.ShoppingCartItems.Remove(item); await _customerService.DeleteShoppingCartItem(customer.Id, shoppingCartItem); //event notification diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartShippingService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartShippingService.cs index 9dac8c06d..0e35314f8 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartShippingService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartShippingService.cs @@ -162,16 +162,13 @@ public virtual async Task GetShoppingCartAdditionalShippingCharge(IList< public virtual async Task IsFreeShipping(IList cart, CalculationContext context) { var customer = context.Customer; - if (customer != null) - { - //check whether customer has a free shipping - if (customer.FreeShipping) - return true; + //check whether customer has a free shipping + if (customer.FreeShipping) + return true; - //check whether customer is in a customer group with free shipping applied - var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray()); - if (customerGroups.Any(customerGroup => customerGroup.FreeShipping)) return true; - } + //check whether customer is in a customer group with free shipping applied + var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray()); + if (customerGroups.Any(customerGroup => customerGroup.FreeShipping)) return true; var shoppingCartRequiresShipping = cart.RequiresShipping(); if (!shoppingCartRequiresShipping) @@ -265,11 +262,9 @@ public virtual async Task GetShoppingCartShippingTota if (isFreeShipping) return new ShoppingCartShippingTotal(0, taxRate, appliedDiscounts); - ShippingOption shippingOption = null; - if (customer != null) - shippingOption = - customer.GetUserFieldFromEntity(SystemCustomerFieldNames.SelectedShippingOption, - context.Store.Id); + var shippingOption = + customer.GetUserFieldFromEntity(SystemCustomerFieldNames.SelectedShippingOption, + context.Store.Id); if (shippingOption != null) { @@ -281,9 +276,7 @@ public virtual async Task GetShoppingCartShippingTota else { //use fixed rate (if possible) - Address shippingAddress = null; - if (customer != null) - shippingAddress = customer.ShippingAddress; + var shippingAddress = customer.ShippingAddress; var shippingRateMethods = await _shippingService.LoadActiveShippingRateCalculationProviders(context.Customer, diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartSubTotalService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartSubTotalService.cs index e52fb5c3b..26b993e68 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartSubTotalService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartSubTotalService.cs @@ -168,31 +168,28 @@ public virtual async Task GetShoppingCartSubTotal(IList>(SystemCustomerFieldNames.CheckoutAttributes, store.Id); + var attributeValues = await _checkoutAttributeParser.ParseCheckoutAttributeValue(checkoutAttributes); + foreach (var attributeValue in attributeValues) { - var checkoutAttributes = customer.GetUserFieldFromEntity>(SystemCustomerFieldNames.CheckoutAttributes, store.Id); - var attributeValues = await _checkoutAttributeParser.ParseCheckoutAttributeValue(checkoutAttributes); - foreach (var attributeValue in attributeValues) - { - var checkoutAttributePriceExclTax = await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, false, customer, store); - - var caExclTax = await _currencyService.ConvertFromPrimaryStoreCurrency(checkoutAttributePriceExclTax.checkoutPrice, - context.Currency); - var (checkoutPrice, taxRate) = await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, true, customer, store); - var caInclTax = await _currencyService.ConvertFromPrimaryStoreCurrency(checkoutPrice, - context.Currency); - - subTotalExclTaxWithoutDiscount += caExclTax; - subTotalInclTaxWithoutDiscount += caInclTax; - - //tax rates - var caTax = caInclTax - caExclTax; - if (!(taxRate > 0) || !(caTax > 0)) continue; - if (!taxRates.ContainsKey(taxRate)) - taxRates.Add(taxRate, caTax); - else - taxRates[taxRate] += caTax; - } + var checkoutAttributePriceExclTax = await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, false, customer, store); + + var caExclTax = await _currencyService.ConvertFromPrimaryStoreCurrency(checkoutAttributePriceExclTax.checkoutPrice, + context.Currency); + var (checkoutPrice, taxRate) = await _taxService.GetCheckoutAttributePrice(attributeValue.ca, attributeValue.cav, true, customer, store); + var caInclTax = await _currencyService.ConvertFromPrimaryStoreCurrency(checkoutPrice, + context.Currency); + + subTotalExclTaxWithoutDiscount += caExclTax; + subTotalInclTaxWithoutDiscount += caInclTax; + + //tax rates + var caTax = caInclTax - caExclTax; + if (!(taxRate > 0) || !(caTax > 0)) continue; + if (!taxRates.ContainsKey(taxRate)) + taxRates.Add(taxRate, caTax); + else + taxRates[taxRate] += caTax; } //subtotal without discount diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartTaxService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartTaxService.cs index 5650bef05..1832d1529 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartTaxService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartTaxService.cs @@ -76,11 +76,9 @@ public virtual async Task GetTaxTotal( var customer = context.Customer; var store = context.Store; - var paymentMethodSystemName = ""; - if (customer != null) - paymentMethodSystemName = customer.GetUserFieldFromEntity( - SystemCustomerFieldNames.SelectedPaymentMethod, - context.Store.Id); + var paymentMethodSystemName = customer.GetUserFieldFromEntity( + SystemCustomerFieldNames.SelectedPaymentMethod, + context.Store.Id) ?? ""; //order sub total (items + checkout attributes) double subTotalTaxTotal = 0; diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs index 24660dded..708f2d7c8 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/ShoppingCartValidator.cs @@ -176,7 +176,7 @@ await _mediator.ShoppingCartWarningsAdd(warnings, shoppingCart, checkoutAttribut public async Task> CheckCommonWarnings(Customer customer, IList currentCart, Product product, ShoppingCartType shoppingCartType, DateTime? rentalStartDate, DateTime? rentalEndDate, - int quantity, string reservationId, Language language) + int quantity, string? reservationId, Language language) { ArgumentNullException.ThrowIfNull(language); @@ -234,7 +234,7 @@ public virtual async Task> GetShoppingCartItemWarnings(Customer cu } public virtual async Task> GetRequiredProductWarnings(Customer customer, - ShoppingCartItem shoppingCartItem, Product product, string storeId, Language language) + ShoppingCartItem shoppingCartItem, Product product, string? storeId, Language language) { ArgumentNullException.ThrowIfNull(customer); ArgumentNullException.ThrowIfNull(product); diff --git a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs index 1a113c056..a0595de56 100644 --- a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentService.cs @@ -53,7 +53,7 @@ public PaymentService(PaymentSettings paymentSettings, /// Store ident /// Specified country /// Payment methods - public virtual async Task> LoadActivePaymentMethods(Customer customer = null, + public virtual async Task> LoadActivePaymentMethods(Customer? customer = null, string storeId = "", string filterByCountryId = "") { var pm = (await LoadAllPaymentMethods(customer, storeId, filterByCountryId)) @@ -70,7 +70,8 @@ public virtual async Task> LoadActivePaymentMethods(Cust for (var i = pm.Count - 1; i >= 0; i--) { var restrictedGroupIds =await GetRestrictedShippingIds(pm[i], storeId); - if (restrictedGroupIds.Contains(selectedShippingOption.Name)) pm.Remove(pm[i]); + if (selectedShippingOption.Name != null && restrictedGroupIds.Contains(selectedShippingOption.Name)) + pm.Remove(pm[i]); } return await Task.FromResult(pm); @@ -81,7 +82,7 @@ public virtual async Task> LoadActivePaymentMethods(Cust ///
/// System name /// Found payment provider - public virtual IPaymentProvider LoadPaymentMethodBySystemName(string systemName) + public virtual IPaymentProvider? LoadPaymentMethodBySystemName(string? systemName) { return _paymentProviders.FirstOrDefault( x => x.SystemName.Equals(systemName, StringComparison.OrdinalIgnoreCase)); @@ -94,7 +95,7 @@ public virtual IPaymentProvider LoadPaymentMethodBySystemName(string systemName) /// Customer /// Load records allowed only in a specified country; pass "" to load all records /// Payment providers - public virtual async Task> LoadAllPaymentMethods(Customer customer = null, string storeId = "", + public virtual async Task> LoadAllPaymentMethods(Customer? customer = null, string storeId = "", string filterByCountryId = "") { var paymentMethods = _paymentProviders @@ -289,7 +290,7 @@ public virtual async Task CanRePostRedirectPayment(PaymentTransaction paym /// Payment method system name /// Additional handling fee public virtual async Task GetAdditionalHandlingFee(IList cart, - string paymentMethodSystemName) + string? paymentMethodSystemName) { if (string.IsNullOrEmpty(paymentMethodSystemName)) return 0; @@ -311,7 +312,7 @@ public virtual async Task GetAdditionalHandlingFee(IList /// Payment method system name /// A value indicating whether capture is supported - public virtual async Task SupportCapture(string paymentMethodSystemName) + public virtual async Task SupportCapture(string? paymentMethodSystemName) { var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName); if (paymentMethod == null) @@ -340,7 +341,7 @@ public virtual async Task Capture(PaymentTransaction payme ///
/// Payment method system name /// A value indicating whether partial refund is supported - public virtual async Task SupportPartiallyRefund(string paymentMethodSystemName) + public virtual async Task SupportPartiallyRefund(string? paymentMethodSystemName) { var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName); if (paymentMethod == null) @@ -353,7 +354,7 @@ public virtual async Task SupportPartiallyRefund(string paymentMethodSyste ///
/// Payment method system name /// A value indicating whether refund is supported - public virtual async Task SupportRefund(string paymentMethodSystemName) + public virtual async Task SupportRefund(string? paymentMethodSystemName) { var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName); if (paymentMethod == null) @@ -381,7 +382,7 @@ public virtual async Task Refund(RefundPaymentRequest refun ///
/// Payment method system name /// A value indicating whether void is supported - public virtual async Task SupportVoid(string paymentMethodSystemName) + public virtual async Task SupportVoid(string? paymentMethodSystemName) { var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName); if (paymentMethod == null) diff --git a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionHistoryService.cs b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionHistoryService.cs index 8d3515635..65639a223 100644 --- a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionHistoryService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionHistoryService.cs @@ -14,9 +14,9 @@ public class PaymentTransactionHistoryService( IOrderService orderService, ICurrencyService currencyService) : IPaymentTransactionHistoryService { - public async Task Record(PaymentTransaction paymentTransaction, Order order, - PaymentTransactionEntryType entryType, double amount, string recordedBy, string reference = null, - string note = null) + public async Task Record(PaymentTransaction paymentTransaction, Order? order, + PaymentTransactionEntryType entryType, double amount, string? recordedBy, string? reference = null, + string? note = null) { ArgumentNullException.ThrowIfNull(paymentTransaction); @@ -54,7 +54,7 @@ public async Task> GetEntries(string paymentTrans /// The order note that records the same operation, e.g. "Payment of 1,250.00 EUR recorded by staff@shop.com. /// Reference: TR-881" ///
- private static string ToOrderNote(PaymentTransactionEntry entry, int decimals, string currencyCode) + private static string ToOrderNote(PaymentTransactionEntry entry, int decimals, string? currencyCode) { var note = new StringBuilder(); note.Append(CultureInfo.InvariantCulture, @@ -68,7 +68,7 @@ private static string ToOrderNote(PaymentTransactionEntry entry, int decimals, s return note.ToString(); } - private static string Clean(string value) + private static string? Clean(string? value) { return string.IsNullOrWhiteSpace(value) ? null : value.Trim(); } diff --git a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs index 6dbd80f95..96126a3ab 100644 --- a/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Payments/PaymentTransactionService.cs @@ -73,7 +73,7 @@ public virtual async Task DeletePaymentTransaction(PaymentTransaction paymentTra ///
/// The identifier /// PaymentTransaction - public virtual Task GetById(string id) + public virtual Task GetById(string id) { return _repositoryPaymentTransaction.GetByIdAsync(id); } @@ -94,7 +94,7 @@ public virtual async Task> GetByOrderCode(string order ///
/// The order guid /// PaymentTransaction - public virtual async Task GetOrderByGuid(Guid orderGuid) + public virtual async Task GetOrderByGuid(Guid orderGuid) { return await _repositoryPaymentTransaction.FirstOrDefaultAsync( _repositoryPaymentTransaction.Table.Where(x => x.OrderGuid == orderGuid)); diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs index fb39a8e6e..00663d9d6 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/DeliveryDateService.cs @@ -43,7 +43,7 @@ public DeliveryDateService( ///
/// The delivery date identifier /// Delivery date - public virtual Task GetDeliveryDateById(string deliveryDateId) + public virtual Task GetDeliveryDateById(string deliveryDateId) { var key = string.Format(CacheKey.DELIVERYDATE_BY_ID_KEY, deliveryDateId); return _cacheBase.GetAsync(key, () => _deliveryDateRepository.GetByIdAsync(deliveryDateId)); diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs index ad07eb4e5..d1a50f61c 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/PickupPointService.cs @@ -43,7 +43,7 @@ public PickupPointService( ///
/// The pickup point identifier /// Delivery date - public virtual Task GetPickupPointById(string pickupPointId) + public virtual Task GetPickupPointById(string? pickupPointId) { var key = string.Format(CacheKey.PICKUPPOINTS_BY_ID_KEY, pickupPointId); return _cacheBase.GetAsync(key, () => _pickupPointsRepository.GetByIdAsync(pickupPointId)); @@ -71,7 +71,7 @@ public virtual async Task> GetAllPickupPoints(string sto /// Gets all pickup points ///
/// Warehouses - public virtual async Task> LoadActivePickupPoints(string storeId = "") + public virtual async Task> LoadActivePickupPoints(string? storeId = "") { var pickupPoints = await GetAllPickupPoints(); return pickupPoints.Where(pp => pp.StoreId == storeId || string.IsNullOrEmpty(pp.StoreId)).ToList(); diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ReturnProviders/InStoreReturnProvider.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ReturnProviders/InStoreReturnProvider.cs index 758228521..1ef3f02a6 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/ReturnProviders/InStoreReturnProvider.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ReturnProviders/InStoreReturnProvider.cs @@ -46,7 +46,7 @@ public InStoreReturnProvider( public string ConfigurationUrl => ""; public IList LimitedToStores => new List(); public IList LimitedToGroups => new List(); - public IShipmentTracker ShipmentTracker => null; + public IShipmentTracker? ShipmentTracker => null; public async Task> GetReturnOptions(ReturnShippingRequest request) { diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ReturnProviders/ReturnProviderTexts.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ReturnProviders/ReturnProviderTexts.cs index 402001e87..755952d40 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/ReturnProviders/ReturnProviderTexts.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ReturnProviders/ReturnProviderTexts.cs @@ -19,13 +19,13 @@ internal class ReturnProviderTexts( IStoreService storeService, ILanguageService languageService, ICountryService countryService, - IVendorService vendorService = null) + IVendorService? vendorService = null) { /// /// Whether the address starts with who receives the parcel: the company, else the person's name, else the /// vendor whose address it is /// - public async Task Instructions(MerchandiseReturn merchandiseReturn, string resourceKey, Address address, + public async Task Instructions(MerchandiseReturn merchandiseReturn, string resourceKey, Address? address, bool withRecipient = false) { var order = await orderService.GetOrderById(merchandiseReturn.OrderId); @@ -42,42 +42,42 @@ public async Task Instructions(MerchandiseReturn merchandiseReturn, stri /// The address on one line, starting with who receives the parcel, as the instructions write it ///
/// The vendor the items go back to; empty for the store - public async Task AddressWithRecipient(Address address, string vendorId) + public async Task AddressWithRecipient(Address? address, string? vendorId) { return address == null ? "" : await OneLine(address, await Recipient(vendorId, address)); } - private Task OneLine(Address address, string recipient) + private Task OneLine(Address? address, string? recipient) { return address == null ? Task.FromResult("") : MerchandiseReturnShippingExtensions.AddressLine(countryService, address, recipient); } - private async Task Recipient(string vendorId, Address address) + private async Task Recipient(string? vendorId, Address address) { if (!string.IsNullOrWhiteSpace(address.Company)) return address.Company.Trim(); var name = string.Join(" ", - new[] { address.FirstName, address.LastName }.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim())); + new[] { address.FirstName, address.LastName }.Select(x => x?.Trim()).Where(x => !string.IsNullOrEmpty(x))); if (!string.IsNullOrEmpty(name) || string.IsNullOrEmpty(vendorId) || vendorService == null) return name; //a vendor's address often names no one: the parcel goes to the vendor when the address kept with the return //is the vendor's, not the store's it fell back to var vendor = await vendorService.GetVendorById(vendorId); - return IsAddressOf(vendor?.Address, address) ? vendor.Name?.Trim() : name; + return vendor != null && IsAddressOf(vendor.Address, address) ? vendor.Name?.Trim() : name; } - private static bool IsAddressOf(Address vendorAddress, Address address) + private static bool IsAddressOf(Address? vendorAddress, Address address) { return vendorAddress != null && !string.IsNullOrEmpty(address.Address1) && Same(vendorAddress.Address1, address.Address1) && Same(vendorAddress.CountryId, address.CountryId) && Same(vendorAddress.ZipPostalCode, address.ZipPostalCode); - static bool Same(string a, string b) + static bool Same(string? a, string? b) { return string.Equals(a?.Trim() ?? "", b?.Trim() ?? "", StringComparison.OrdinalIgnoreCase); } diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ReturnProviders/SendYourselfReturnProvider.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ReturnProviders/SendYourselfReturnProvider.cs index 0b88dc703..2fc957ee6 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/ReturnProviders/SendYourselfReturnProvider.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ReturnProviders/SendYourselfReturnProvider.cs @@ -48,7 +48,7 @@ public SendYourselfReturnProvider( public string ConfigurationUrl => ""; public IList LimitedToStores => new List(); public IList LimitedToGroups => new List(); - public IShipmentTracker ShipmentTracker => null; + public IShipmentTracker? ShipmentTracker => null; public async Task> GetReturnOptions(ReturnShippingRequest request) { diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ReturnShippingService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ReturnShippingService.cs index 4257839d5..5fb480b1f 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/ReturnShippingService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ReturnShippingService.cs @@ -21,7 +21,7 @@ public class ReturnShippingService( ICustomerService customerService, ILogger logger) : IReturnShippingService { - public async Task> LoadActiveProviders(Customer customer, string storeId) + public async Task> LoadActiveProviders(Customer? customer, string? storeId) { var settings = await settingService.LoadSetting(storeId); return LoadAllProviders(customer, storeId) @@ -30,13 +30,13 @@ public async Task> LoadActiveProviders(Customer c .ToList(); } - public IReturnShippingProvider LoadProviderBySystemName(string systemName) + public IReturnShippingProvider? LoadProviderBySystemName(string? systemName) { return returnShippingProviders.FirstOrDefault(x => string.Equals(x.SystemName, systemName, StringComparison.OrdinalIgnoreCase)); } - public IList LoadAllProviders(Customer customer = null, string storeId = "") + public IList LoadAllProviders(Customer? customer = null, string? storeId = "") { return returnShippingProviders .Where(x => x.IsAuthenticateStore(storeId) && x.IsAuthenticateGroup(customer)) @@ -61,7 +61,7 @@ public async Task> GetOffers(MerchandiseReturnSubmitR } public async Task Resolve(MerchandiseReturnSubmitRequest request, - ReturnShippingChoice choice) + ReturnShippingChoice? choice) { ArgumentNullException.ThrowIfNull(request); @@ -101,12 +101,12 @@ public async Task Resolve(MerchandiseReturnSubmitReque { var group = groups[i]; var option = chosen.Options[i]; - ReturnShippingValidationResult validation = null; + ReturnShippingValidationResult? validation = null; if (option.HasForm) try { validation = await chosen.Provider.ValidateForm(group.Request, option.Code, - choice.Form ?? new Dictionary()); + choice?.Form ?? new Dictionary()); } catch (Exception ex) { @@ -143,7 +143,7 @@ public async Task Resolve(MerchandiseReturnSubmitReque return resolution; } - public async Task
GetReturnAddress(string storeId, string vendorId) + public async Task GetReturnAddress(string? storeId, string vendorId) { //a copy: the address is kept with each return, and a change of the vendor or the settings must not reach it if (!string.IsNullOrEmpty(vendorId)) @@ -163,7 +163,7 @@ public async Task
GetReturnAddress(string storeId, string vendorId) /// /// The submitted items by vendor, grouped as the submit groups them into returns /// - private async Task> VendorGroups(MerchandiseReturnSubmitRequest request, Customer customer) + private async Task> VendorGroups(MerchandiseReturnSubmitRequest request, Customer? customer) { var items = request.Items.Where(x => x.Quantity > 0).ToList(); var vendorItems = request.Order.OrderItems @@ -199,7 +199,7 @@ private async Task> VendorGroups(MerchandiseReturnSubmitReque /// /// The options every vendor group is offered, with the option of each group in the order of the groups /// - private async Task> Offers(string storeId, IList groups, + private async Task> Offers(string? storeId, IList groups, IList providers) { if (providers.Count == 0) @@ -232,8 +232,8 @@ private async Task> Offers(string storeId, IList x.FirstOrDefault(option => option.Code == first.Code)) - .ToList(); - if (options.Any(x => x == null)) + .OfType().ToList(); + if (options.Count < groupOptions.Count) continue; offers.Add(new ProviderOffer(provider, options, new ReturnShippingOffer { @@ -265,7 +265,7 @@ private static bool CustomerPays(VendorGroup group, MerchandiseReturnFees fees) return MerchandiseReturnShippingExtensions.CustomerCost(1, fees, group.AnyFreeReason) > 0; } - private static Address Copy(Address address) + private static Address? Copy(Address? address) { if (address == null) return null; diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs index 33350d6ba..2e7b36d90 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ShipmentService.cs @@ -63,8 +63,8 @@ public virtual async Task> GetAllShipments(string storeId = string warehouseId = "", string shippingCountryId = "", int shippingStateId = 0, - string shippingCity = null, - string trackingNumber = null, + string? shippingCity = null, + string? trackingNumber = null, bool loadNotShipped = false, DateTime? createdFromUtc = null, DateTime? createdToUtc = null, int pageIndex = 0, int pageSize = int.MaxValue) @@ -75,7 +75,7 @@ public virtual async Task> GetAllShipments(string storeId = if (!string.IsNullOrEmpty(storeId)) query = query.Where(x => x.StoreId == storeId); if (!string.IsNullOrEmpty(vendorId)) query = query.Where(x => x.VendorId == vendorId); if (!string.IsNullOrEmpty(trackingNumber)) - query = query.Where(s => s.TrackingNumber.Contains(trackingNumber)); + query = query.Where(s => s.TrackingNumber != null && s.TrackingNumber.Contains(trackingNumber)); if (loadNotShipped) query = query.Where(s => !s.ShippedDateUtc.HasValue); @@ -117,7 +117,7 @@ public virtual async Task> GetShipmentsByOrder(string orderId) ///
/// Shipment identifier /// Shipment - public virtual Task GetShipmentById(string shipmentId) + public virtual Task GetShipmentById(string shipmentId) { return _shipmentRepository.GetByIdAsync(shipmentId); } @@ -210,7 +210,7 @@ orderby shipmentNote.CreatedOnUtc descending ///
/// Shipment note identifier /// shipmentNote - public virtual async Task GetShipmentNote(string shipmentNoteId) + public virtual async Task GetShipmentNote(string shipmentNoteId) { return await _shipmentNoteRepository.FirstOrDefaultAsync( _shipmentNoteRepository.Table.Where(x => x.Id == shipmentNoteId)); diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.cs index 8a07cb233..457c5b132 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingMethodService.cs @@ -58,7 +58,7 @@ public virtual async Task DeleteShippingMethod(ShippingMethod shippingMethod) ///
/// The shipping method identifier /// Shipping method - public virtual Task GetShippingMethodById(string shippingMethodId) + public virtual Task GetShippingMethodById(string shippingMethodId) { var key = string.Format(CacheKey.SHIPPINGMETHOD_BY_ID_KEY, shippingMethodId); return _cacheBase.GetAsync(key, () => _shippingMethodRepository.GetByIdAsync(shippingMethodId)); @@ -72,7 +72,7 @@ public virtual Task GetShippingMethodById(string shippingMethodI /// The store identifier to filter by /// Shipping methods public virtual async Task> GetAllShippingMethods(string filterByCountryId = "", - Customer customer = null, string storeId = "") + Customer? customer = null, string storeId = "") { var query = _shippingMethodRepository.Table; diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs index 96962436f..e8db6c191 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/ShippingService.cs @@ -58,7 +58,7 @@ public ShippingService( /// Cart /// Shipping rate methods public virtual async Task> LoadActiveShippingRateCalculationProviders( - Customer customer = null, string storeId = "", IList cart = null) + Customer? customer = null, string? storeId = "", IList? cart = null) { var shippingMethods = LoadAllShippingRateCalculationProviders(customer, storeId) .Where(provider => @@ -68,7 +68,7 @@ public virtual async Task> LoadActiveShi var availableShippingMethods = new List(); foreach (var sm in shippingMethods) - if (!await sm.HideShipmentMethods(cart)) + if (cart == null || !await sm.HideShipmentMethods(cart)) availableShippingMethods.Add(sm); return availableShippingMethods; } @@ -78,7 +78,7 @@ public virtual async Task> LoadActiveShi ///
/// System name /// Found Shipping rate method - public virtual IShippingRateCalculationProvider LoadShippingRateCalculationProviderBySystemName(string systemName) + public virtual IShippingRateCalculationProvider? LoadShippingRateCalculationProviderBySystemName(string systemName) { return _shippingRateCalculationProvider.FirstOrDefault(x => x.SystemName == systemName); } @@ -90,7 +90,7 @@ public virtual IShippingRateCalculationProvider LoadShippingRateCalculationProvi /// Store ident /// Shipping rate methods public virtual IList LoadAllShippingRateCalculationProviders( - Customer customer = null, string storeId = "") + Customer? customer = null, string? storeId = "") { return _shippingRateCalculationProvider .Where(x => @@ -112,7 +112,7 @@ public virtual IList LoadAllShippingRateCalcul /// Store /// Shipment packages (requests) public virtual async Task CreateShippingOptionRequests(Customer customer, - IList cart, Address shippingAddress, Store store) + IList cart, Address? shippingAddress, Store? store) { var request = new GetShippingOptionRequest { //store @@ -163,7 +163,7 @@ public virtual async Task CreateShippingOptionRequests public virtual async Task GetShippingOptions(Customer customer, IList cart, Address shippingAddress, string allowedShippingRateMethodSystemName = "", - Store store = null) + Store? store = null) { ArgumentNullException.ThrowIfNull(cart); diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseLocationService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseLocationService.cs index 6e9ab4d69..e868124cc 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseLocationService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseLocationService.cs @@ -10,12 +10,12 @@ namespace Grand.Business.Checkout.Services.Shipping; public class WarehouseLocationService(IRepository locationRepository, IMediator mediator) : IWarehouseLocationService { - public Task GetLocationById(string id) + public Task GetLocationById(string id) { return locationRepository.GetByIdAsync(id); } - public Task> GetLocations(IList warehouseIds = null, int pageIndex = 0, + public Task> GetLocations(IList? warehouseIds = null, int pageIndex = 0, int pageSize = int.MaxValue) { var query = locationRepository.Table; diff --git a/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs b/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs index 55eebb982..d88b0ef44 100644 --- a/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Shipping/WarehouseService.cs @@ -43,7 +43,7 @@ public WarehouseService( ///
/// The warehouse identifier /// Warehouse - public virtual Task GetWarehouseById(string warehouseId) + public virtual Task GetWarehouseById(string warehouseId) { var key = string.Format(CacheKey.WAREHOUSES_BY_ID_KEY, warehouseId); return _cacheBase.GetAsync(key, () => _warehouseRepository.GetByIdAsync(warehouseId)); diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartAuctionValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartAuctionValidator.cs index 85565c7b2..6041768e3 100644 --- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartAuctionValidator.cs +++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartAuctionValidator.cs @@ -10,7 +10,7 @@ namespace Grand.Business.Checkout.Validators; public record ShoppingCartAuctionValidatorRecord( Customer Customer, Product Product, - ShoppingCartItem ShoppingCartItem, + ShoppingCartItem? ShoppingCartItem, double Bid, Language Language); diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCheckoutAttributesValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCheckoutAttributesValidator.cs index 4b543f98d..6bd5ca6b4 100644 --- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCheckoutAttributesValidator.cs +++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCheckoutAttributesValidator.cs @@ -43,7 +43,7 @@ await checkoutAttributeService.GetAllCheckoutAttributes(CatalogAccess.For(value. { if (a1.Id != a2.Id) continue; var attributeValuesStr = value.CheckoutAttributes.Where(x => x.Key == a1.Id).Select(x => x.Value); - if (attributeValuesStr.Any(str1 => !string.IsNullOrEmpty(str1.Trim()))) + if (attributeValuesStr.Any(str1 => !string.IsNullOrWhiteSpace(str1))) { found = true; } diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCommonWarningsValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCommonWarningsValidator.cs index b3d481a60..cde74ec04 100644 --- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCommonWarningsValidator.cs +++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartCommonWarningsValidator.cs @@ -17,7 +17,7 @@ public record ShoppingCartCommonWarningsValidatorRecord( DateTime? RentalStartDate, DateTime? RentalEndDate, int Quantity, - string ReservationId, + string? ReservationId, Language Language); public class ShoppingCartCommonWarningsValidator : AbstractValidator diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartItemAttributeValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartItemAttributeValidator.cs index b0f3b5f9a..bca71dac0 100644 --- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartItemAttributeValidator.cs +++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartItemAttributeValidator.cs @@ -72,7 +72,7 @@ value with { var productAttribute = await productAttributeService.GetProductAttributeById(productAttributeMapping .ProductAttributeId); - var attributeName = productAttribute.Name; + var attributeName = productAttribute?.Name; var attributeValueName = attributeValue.Name; warnings.Add(string.Format( translationService.GetResource("ShoppingCart.AssociatedAttributeWarning", value.Language.Id), @@ -204,7 +204,7 @@ where attributeValuesStr.Any(str1 => !string.IsNullOrEmpty(str1.Trim())) var productAttribute = await _productAttributeService.GetProductAttributeById(pam.ProductAttributeId); warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.TextboxMinimumLength", value.Language.Id), - productAttribute.Name, pam.ValidationMinLength.Value)); + productAttribute?.Name, pam.ValidationMinLength.Value)); } } @@ -220,7 +220,7 @@ where attributeValuesStr.Any(str1 => !string.IsNullOrEmpty(str1.Trim())) if (pam.ValidationMaxLength.Value >= enteredTextLength) continue; var productAttribute = await _productAttributeService.GetProductAttributeById(pam.ProductAttributeId); warnings.Add(string.Format(_translationService.GetResource("ShoppingCart.TextboxMaximumLength", value.Language.Id), - productAttribute.Name, pam.ValidationMaxLength.Value)); + productAttribute?.Name, pam.ValidationMaxLength.Value)); } } diff --git a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartRequiredProductValidator.cs b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartRequiredProductValidator.cs index fdf6a45f7..14d18ff72 100644 --- a/src/Business/Grand.Business.Checkout/Validators/ShoppingCartRequiredProductValidator.cs +++ b/src/Business/Grand.Business.Checkout/Validators/ShoppingCartRequiredProductValidator.cs @@ -10,7 +10,7 @@ namespace Grand.Business.Checkout.Validators; public record ShoppingCartRequiredProductValidatorRecord( Customer Customer, - string StoreId, + string? StoreId, Product Product, ShoppingCartItem ShoppingCartItem, Language Language); diff --git a/src/Business/Grand.Business.Cms/Events/BlogPostDeletedEventHandler.cs b/src/Business/Grand.Business.Cms/Events/BlogPostDeletedEventHandler.cs index e1261c80f..00a083410 100644 --- a/src/Business/Grand.Business.Cms/Events/BlogPostDeletedEventHandler.cs +++ b/src/Business/Grand.Business.Cms/Events/BlogPostDeletedEventHandler.cs @@ -16,7 +16,9 @@ public BlogPostDeletedEventHandler(ISlugService slugService) public async Task Handle(EntityDeleted notification, CancellationToken cancellationToken) { + //a post saved without a slug has no url to delete var urlToDelete = await _slugService.GetBySlug(notification.Entity.SeName); - await _slugService.DeleteEntityUrl(urlToDelete); + if (urlToDelete != null) + await _slugService.DeleteEntityUrl(urlToDelete); } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Cms/Grand.Business.Cms.csproj b/src/Business/Grand.Business.Cms/Grand.Business.Cms.csproj index 2ac20c3e9..4076c6016 100644 --- a/src/Business/Grand.Business.Cms/Grand.Business.Cms.csproj +++ b/src/Business/Grand.Business.Cms/Grand.Business.Cms.csproj @@ -7,4 +7,7 @@ + + enable + diff --git a/src/Business/Grand.Business.Cms/Services/BlogService.cs b/src/Business/Grand.Business.Cms/Services/BlogService.cs index dd95dcb50..f95ad91ca 100644 --- a/src/Business/Grand.Business.Cms/Services/BlogService.cs +++ b/src/Business/Grand.Business.Cms/Services/BlogService.cs @@ -50,7 +50,7 @@ public BlogService(IRepository blogPostRepository, ///
/// Blog post identifier /// Blog post - public virtual Task GetBlogPostById(string blogPostId) + public virtual Task GetBlogPostById(string blogPostId) { return _blogPostRepository.GetByIdAsync(blogPostId); } @@ -70,7 +70,7 @@ public virtual Task GetBlogPostById(string blogPostId) /// Blog posts public virtual async Task> GetAllBlogPosts(string storeId, DateTime? dateFrom = null, DateTime? dateTo = null, - int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false, string tag = null, + int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false, string? tag = null, string blogPostName = "", string categoryId = "") { var query = await BuildBlogPostQuery(storeId, dateFrom, dateTo, showHidden, blogPostName, categoryId); @@ -130,7 +130,7 @@ private async Task> BuildBlogPostQuery(string storeId, Date /// A value indicating whether to show hidden records /// Blog posts public virtual async Task> GetAllBlogPostsByTag(string storeId, - string tag = "", + string? tag = "", int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false) { tag = tag?.Trim(); @@ -162,7 +162,7 @@ public virtual async Task> GetAllBlogPostTags(string storeId, foreach (var tag in tags) { var foundBlogPostTag = - blogPostTags.FirstOrDefault(bpt => bpt.Name.Equals(tag, StringComparison.OrdinalIgnoreCase)); + blogPostTags.FirstOrDefault(bpt => string.Equals(bpt.Name, tag, StringComparison.OrdinalIgnoreCase)); if (foundBlogPostTag == null) { foundBlogPostTag = new BlogPostTag { @@ -244,7 +244,7 @@ orderby c.CreatedOnUtc ///
/// Blog comment identifier /// Blog comment - public virtual Task GetBlogCommentById(string blogCommentId) + public virtual Task GetBlogCommentById(string blogCommentId) { return _blogCommentRepository.GetByIdAsync(blogCommentId); } @@ -275,7 +275,7 @@ where commentIds.Contains(bc.Id) var comments = query.ToList(); //sort by passed identifiers var sortedComments = commentIds.Select(id => comments.FirstOrDefault(comment => comment.Id == id)) - .Where(comment => comment != null) + .OfType() .ToList(); return await Task.FromResult(sortedComments); @@ -309,7 +309,7 @@ public virtual async Task DeleteBlogComment(BlogComment blogComment) ///
/// Blog category id /// - public virtual Task GetBlogCategoryById(string blogCategoryId) + public virtual Task GetBlogCategoryById(string blogCategoryId) { return _blogCategoryRepository.GetByIdAsync(blogCategoryId); } @@ -330,7 +330,7 @@ public virtual async Task> GetBlogCategoryByPostId(string bl ///
/// Blog category se-name /// - public virtual async Task GetBlogCategoryBySeName(string blogCategorySeName) + public virtual async Task GetBlogCategoryBySeName(string blogCategorySeName) { ArgumentNullException.ThrowIfNullOrEmpty(blogCategorySeName); @@ -407,7 +407,7 @@ public virtual async Task DeleteBlogCategory(BlogCategory blogCategory) ///
/// id /// Blog product - public virtual Task GetBlogProductById(string id) + public virtual Task GetBlogProductById(string id) { return _blogProductRepository.GetByIdAsync(id); } diff --git a/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs b/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs index a2cde7678..fc211bedb 100644 --- a/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs +++ b/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs @@ -50,7 +50,7 @@ private IQueryable ApplyStandardFilter(IQueryable query, CatalogAccess } //null group ids skip the group filter, an empty store id the store filter - private IQueryable ApplyStandardFilter(IQueryable query, string[] allowedCustomerGroupsIds, + private IQueryable ApplyStandardFilter(IQueryable query, string[]? allowedCustomerGroupsIds, string storeId) where T : BaseEntity, IGroupLinkEntity, IStoreLinkEntity { if (allowedCustomerGroupsIds != null && !_accessControlConfig.IgnoreAcl) @@ -118,7 +118,7 @@ public virtual async Task UpdateKnowledgebaseCategory(KnowledgebaseCategory kc) ///
/// /// knowledge base category - public virtual async Task GetKnowledgebaseCategory(string id) + public virtual async Task GetKnowledgebaseCategory(string id) { return await _knowledgebaseCategoryRepository.GetOneAsync(x => x.Id == id); } @@ -128,7 +128,7 @@ public virtual async Task GetKnowledgebaseCategory(string ///
/// /// knowledge base category - public virtual async Task GetPublicKnowledgebaseCategory(string id, CatalogAccess access) + public virtual async Task GetPublicKnowledgebaseCategory(string id, CatalogAccess access) { var key = GetCacheKey(CacheKey.KNOWLEDGEBASE_CATEGORY_BY_ID, access, id); @@ -172,7 +172,7 @@ public virtual async Task> GetKnowledgebaseCategorie ///
/// /// knowledge base article - public virtual Task GetKnowledgebaseArticle(string id) + public virtual Task GetKnowledgebaseArticle(string id) { return _knowledgebaseArticleRepository.GetByIdAsync(id); } @@ -298,7 +298,7 @@ public virtual async Task> GetPublicKnowledgebaseArti /// Gets knowledge base article if it is published etc /// /// knowledge base article - public virtual async Task GetPublicKnowledgebaseArticle(string id, CatalogAccess access) + public virtual async Task GetPublicKnowledgebaseArticle(string id, CatalogAccess access) { var key = GetCacheKey(CacheKey.ARTICLE_BY_ID, access, id); @@ -355,7 +355,7 @@ public virtual async Task> GetPublicKnowledgebaseArti query = query.Where(p => p.Locales.Any(x => x.LocaleValue != null && x.LocaleValue.ToLower().Contains(keyword.ToLower())) - || p.Name.ToLower().Contains(keyword.ToLower()) || p.Content.ToLower().Contains(keyword.ToLower())); + || p.Name.ToLower().Contains(keyword.ToLower()) || p.Content != null && p.Content.ToLower().Contains(keyword.ToLower())); query = ApplyStandardFilter(query, access); query = query.OrderBy(x => x.DisplayOrder); @@ -381,7 +381,7 @@ public virtual async Task> GetPublicKnowledgebaseCat query = query.Where(p => p.Locales.Any(x => x.LocaleValue != null && x.LocaleValue.ToLower().Contains(keyword.ToLower())) - || p.Name.ToLower().Contains(keyword.ToLower()) || p.Description.ToLower().Contains(keyword.ToLower())); + || p.Name.ToLower().Contains(keyword.ToLower()) || p.Description != null && p.Description.ToLower().Contains(keyword.ToLower())); query = ApplyStandardFilter(query, access); query = query.OrderBy(x => x.DisplayOrder); @@ -452,7 +452,7 @@ public virtual async Task> GetRelatedKnowledgeb .ToDictionary(x => x.Id); //keep the order the articles were related in; ids of deleted articles are skipped - var toReturn = article.RelatedArticles.Select(related.GetValueOrDefault).Where(x => x != null); + var toReturn = article.RelatedArticles.Select(related.GetValueOrDefault).OfType(); return new PagedList(toReturn, pageIndex, pageSize); } @@ -505,7 +505,7 @@ orderby c.CreatedOnUtc /// /// Article identifier /// Article comment - public virtual Task GetArticleCommentById(string articleId) + public virtual Task GetArticleCommentById(string articleId) { return _articleCommentRepository.GetByIdAsync(articleId); } @@ -525,7 +525,7 @@ where commentIds.Contains(bc.Id) var comments = query.ToList(); //sort by passed identifiers var sortedComments = commentIds.Select(id => comments.FirstOrDefault(x => x.Id == id)) - .Where(comment => comment != null) + .OfType() .ToList(); return await Task.FromResult(sortedComments); diff --git a/src/Business/Grand.Business.Cms/Services/NewsService.cs b/src/Business/Grand.Business.Cms/Services/NewsService.cs index 028b5cb46..e8f498d8c 100644 --- a/src/Business/Grand.Business.Cms/Services/NewsService.cs +++ b/src/Business/Grand.Business.Cms/Services/NewsService.cs @@ -43,7 +43,7 @@ public NewsService(IRepository newsItemRepository, /// /// The news identifier /// News - public virtual Task GetNewsById(string newsId) + public virtual Task GetNewsById(string newsId) { return _newsItemRepository.GetByIdAsync(newsId); } diff --git a/src/Business/Grand.Business.Cms/Services/PageLayoutService.cs b/src/Business/Grand.Business.Cms/Services/PageLayoutService.cs index 9a2d67e29..d88e845e3 100644 --- a/src/Business/Grand.Business.Cms/Services/PageLayoutService.cs +++ b/src/Business/Grand.Business.Cms/Services/PageLayoutService.cs @@ -63,7 +63,7 @@ orderby pt.DisplayOrder /// /// Page layout identifier /// Page layout - public virtual Task GetPageLayoutById(string pageLayoutId) + public virtual Task GetPageLayoutById(string pageLayoutId) { var key = string.Format(CacheKey.PAGE_LAYOUT_BY_ID_KEY, pageLayoutId); return _cacheBase.GetAsync(key, () => _pageLayoutRepository.GetByIdAsync(pageLayoutId)); diff --git a/src/Business/Grand.Business.Cms/Services/PageService.cs b/src/Business/Grand.Business.Cms/Services/PageService.cs index ea987c097..8332d2b13 100644 --- a/src/Business/Grand.Business.Cms/Services/PageService.cs +++ b/src/Business/Grand.Business.Cms/Services/PageService.cs @@ -50,7 +50,7 @@ public PageService(IRepository pageRepository, /// /// The page identifier /// Page - public virtual Task GetPageById(string pageId) + public virtual Task GetPageById(string pageId) { var key = string.Format(CacheKey.PAGES_BY_ID_KEY, pageId); return _cacheBase.GetAsync(key, () => _pageRepository.GetByIdAsync(pageId)); @@ -64,7 +64,7 @@ public virtual Task GetPageById(string pageId) /// /// The page a store overrode this system name with, if it has one; otherwise the page shared by every store /// - public virtual async Task GetPageBySystemName(string systemName, string storeId) + public virtual async Task GetPageBySystemName(string systemName, string storeId) { if (string.IsNullOrEmpty(systemName)) return null; @@ -75,7 +75,7 @@ public virtual async Task GetPageBySystemName(string systemName, string st var query = from p in _pageRepository.Table select p; - query = query.Where(t => t.SystemName.ToLower() == systemName.ToLower()); + query = query.Where(t => t.SystemName != null && t.SystemName.ToLower() == systemName.ToLower()); query = query.OrderBy(t => t.Id); IEnumerable pages = await _pageRepository.ToListAsync(query); if (!string.IsNullOrEmpty(storeId)) @@ -100,7 +100,7 @@ public virtual async Task> GetAllPages(CatalogAccess access) var storeId = access.StoreId; var ignoreAcl = access.ShowHidden || _accessControlConfig.IgnoreAcl; - var allowedCustomerGroupsIds = ignoreAcl ? Array.Empty() : access.Customer.GetCustomerGroupIds(); + var allowedCustomerGroupsIds = ignoreAcl || access.ShowHidden ? Array.Empty() : access.Customer.GetCustomerGroupIds(); var key = string.Format(CacheKey.PAGES_ALL_KEY, storeId, access.ShowHidden, string.Join(",", allowedCustomerGroupsIds)); return await _cacheBase.GetAsync(key, async () => diff --git a/src/Business/Grand.Business.Cms/Services/RobotsTxtService.cs b/src/Business/Grand.Business.Cms/Services/RobotsTxtService.cs index a9a08f2af..29459613c 100644 --- a/src/Business/Grand.Business.Cms/Services/RobotsTxtService.cs +++ b/src/Business/Grand.Business.Cms/Services/RobotsTxtService.cs @@ -36,7 +36,7 @@ public RobotsTxtService( /// /// /// - public virtual async Task GetRobotsTxt(string storeId = "") + public virtual async Task GetRobotsTxt(string storeId = "") { var key = string.Format(CacheKey.ROBOTS_BY_STORE, storeId); diff --git a/src/Business/Grand.Business.Cms/Services/WidgetService.cs b/src/Business/Grand.Business.Cms/Services/WidgetService.cs index c82fd63ab..2c98c5357 100644 --- a/src/Business/Grand.Business.Cms/Services/WidgetService.cs +++ b/src/Business/Grand.Business.Cms/Services/WidgetService.cs @@ -40,7 +40,7 @@ public WidgetService( /// Store ident /// Customer /// Widgets - public virtual IList LoadActiveWidgets(string storeId = "", Customer customer = null) + public virtual IList LoadActiveWidgets(string storeId = "", Customer? customer = null) { return LoadAllWidgets(storeId, customer) .Where(x => @@ -56,7 +56,7 @@ public virtual IList LoadActiveWidgets(string storeId = "", Cus /// Customer /// Widgets public virtual async Task> LoadActiveWidgetsByWidgetZone(string widgetZone, - string storeId = "", Customer customer = null) + string storeId = "", Customer? customer = null) { if (string.IsNullOrWhiteSpace(widgetZone)) return new List(); @@ -78,7 +78,7 @@ public virtual async Task> LoadActiveWidgetsByWidgetZone( /// /// System name /// Found widget - public virtual IWidgetProvider LoadWidgetBySystemName(string systemName) + public virtual IWidgetProvider? LoadWidgetBySystemName(string systemName) { return _widgetProviders.FirstOrDefault(x => x.SystemName.Equals(systemName, StringComparison.OrdinalIgnoreCase)); @@ -90,7 +90,7 @@ public virtual IWidgetProvider LoadWidgetBySystemName(string systemName) /// Store ident /// Customer /// Widgets - public virtual IList LoadAllWidgets(string storeId = "", Customer customer = null) + public virtual IList LoadAllWidgets(string storeId = "", Customer? customer = null) { return _widgetProviders .Where(x => diff --git a/src/Business/Grand.Business.Common/Grand.Business.Common.csproj b/src/Business/Grand.Business.Common/Grand.Business.Common.csproj index 033289d5e..81f9cec45 100644 --- a/src/Business/Grand.Business.Common/Grand.Business.Common.csproj +++ b/src/Business/Grand.Business.Common/Grand.Business.Common.csproj @@ -15,4 +15,7 @@ + + enable + diff --git a/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeParser.cs b/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeParser.cs index b472de2d3..d7c38bd27 100644 --- a/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeParser.cs +++ b/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeParser.cs @@ -121,7 +121,7 @@ public virtual async Task> GetAttributeWarnings(IList x.Key == a1.Id).Select(x => x.Value); - if (valuesStr.Any(str1 => !string.IsNullOrEmpty(str1.Trim()))) found = true; + if (valuesStr.Any(str1 => !string.IsNullOrEmpty(str1?.Trim()))) found = true; } //if not found @@ -141,8 +141,8 @@ public virtual async Task> GetAttributeWarnings(IListA value indicating whether to encode (HTML) values /// Attributes public virtual async Task FormatAttributes( - Language language, - IList customAttributes, + Language? language, + IList? customAttributes, string separator = "
", bool htmlEncode = true) { @@ -167,7 +167,7 @@ public virtual async Task FormatAttributes( case AttributeControlType.MultilineTextbox: { //multiline text box - var attributeName = attribute.GetTranslation(a => a.Name, language.Id); + var attributeName = attribute.GetTranslation(a => a.Name, language?.Id); //encode (if required) if (htmlEncode) attributeName = WebUtility.HtmlEncode(attributeName); @@ -181,7 +181,7 @@ public virtual async Task FormatAttributes( default: { //other attributes (text box, datepicker) - formattedAttribute = $"{attribute.GetTranslation(a => a.Name, language.Id)}: {valueStr}"; + formattedAttribute = $"{attribute.GetTranslation(a => a.Name, language?.Id)}: {valueStr}"; //encode (if required) if (htmlEncode) formattedAttribute = WebUtility.HtmlEncode(formattedAttribute); @@ -195,7 +195,7 @@ public virtual async Task FormatAttributes( var attributeValue = attribute.AddressAttributeValues.FirstOrDefault(x => x.Id == attributeValueId); if (attributeValue != null) formattedAttribute = - $"{attribute.GetTranslation(a => a.Name, language.Id)}: {attributeValue.GetTranslation(a => a.Name, language.Id)}"; + $"{attribute.GetTranslation(a => a.Name, language?.Id)}: {attributeValue.GetTranslation(a => a.Name, language?.Id)}"; //encode (if required) if (htmlEncode) formattedAttribute = WebUtility.HtmlEncode(formattedAttribute); diff --git a/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeService.cs b/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeService.cs index 47fbaa045..b81205870 100644 --- a/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeService.cs +++ b/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeService.cs @@ -88,7 +88,7 @@ public virtual async Task> GetAllAddressAttributes(strin /// /// Address attribute identifier /// Address attribute - public virtual async Task GetAddressAttributeById(string addressAttributeId) + public virtual async Task GetAddressAttributeById(string? addressAttributeId) { if (string.IsNullOrEmpty(addressAttributeId)) return null; @@ -146,6 +146,7 @@ public virtual async Task DeleteAddressAttribute(AddressAttribute addressAttribu public virtual async Task InsertAddressAttributeValue(AddressAttributeValue addressAttributeValue) { ArgumentNullException.ThrowIfNull(addressAttributeValue); + ArgumentException.ThrowIfNullOrEmpty(addressAttributeValue.AddressAttributeId); await _addressAttributeRepository.AddToCollectionField(addressAttributeValue.AddressAttributeId, x => x.AddressAttributeValues, addressAttributeValue); @@ -161,6 +162,7 @@ await _addressAttributeRepository.AddToCollectionField(addressAttributeValue.Add public virtual async Task UpdateAddressAttributeValue(AddressAttributeValue addressAttributeValue) { ArgumentNullException.ThrowIfNull(addressAttributeValue); + ArgumentException.ThrowIfNullOrEmpty(addressAttributeValue.AddressAttributeId); await _addressAttributeRepository.UpdateCollectionFieldItem(addressAttributeValue.AddressAttributeId, x => x.AddressAttributeValues, z => z.Id == addressAttributeValue.Id, addressAttributeValue); @@ -175,6 +177,7 @@ public virtual async Task UpdateAddressAttributeValue(AddressAttributeValue addr public virtual async Task DeleteAddressAttributeValue(AddressAttributeValue addressAttributeValue) { ArgumentNullException.ThrowIfNull(addressAttributeValue); + ArgumentException.ThrowIfNullOrEmpty(addressAttributeValue.AddressAttributeId); await _addressAttributeRepository.RemoveCollectionFieldItem(addressAttributeValue.AddressAttributeId, x => x.AddressAttributeValues, z => z.Id == addressAttributeValue.Id); diff --git a/src/Business/Grand.Business.Common/Services/Audit/AuditService.cs b/src/Business/Grand.Business.Common/Services/Audit/AuditService.cs index 4d2f8050b..ea5df943e 100644 --- a/src/Business/Grand.Business.Common/Services/Audit/AuditService.cs +++ b/src/Business/Grand.Business.Common/Services/Audit/AuditService.cs @@ -28,7 +28,7 @@ public Task> GetEntries(AuditEntrySearch search, int page return repository.PagedAsync(Query(search), pageIndex, pageSize); } - public Task GetById(string id) + public Task GetById(string id) { return repository.GetByIdAsync(id); } @@ -130,14 +130,14 @@ private IQueryable Query(AuditEntrySearch search) if (types.Count == 1) query = query.Where(x => x.EntityType == types[0]); else if (types.Count > 1) - query = query.Where(x => types.Contains(x.EntityType)); + query = query.Where(x => x.EntityType != null && types.Contains(x.EntityType)); if (!string.IsNullOrEmpty(search.EntityId)) query = query.Where(x => x.EntityId == search.EntityId); } if (search.EntityNames is { Count: > 0 }) { var names = search.EntityNames.ToList(); - query = query.Where(x => names.Contains(x.EntityName)); + query = query.Where(x => x.EntityName != null && names.Contains(x.EntityName)); } if (!string.IsNullOrEmpty(search.StoreId)) diff --git a/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs b/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs index c8f2a725a..9abafded4 100644 --- a/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs +++ b/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs @@ -50,7 +50,7 @@ private static string StoreSettingsKey(string storeId) /// /// Gets the settings of a store and the global ones, read with one query and cached together /// - private Task GetStoreSettings(string storeId) + private Task GetStoreSettings(string? storeId) { storeId ??= ""; return _cacheBase.GetAsync(StoreSettingsKey(storeId), async () => @@ -65,7 +65,8 @@ private IQueryable StoreSettingsQuery(string storeId) private static ISettings CreateSettings(StoreSettings storeSettings, Type type) { return storeSettings.Find(type.Name.ToLowerInvariant(), type) as ISettings ?? - Activator.CreateInstance(type) as ISettings; + Activator.CreateInstance(type) as ISettings ?? + throw new ArgumentException($"{type.Name} is not a settings class", nameof(type)); } /// @@ -74,11 +75,11 @@ private static ISettings CreateSettings(StoreSettings storeSettings, Type type) private sealed class StoreSettings { private readonly ILookup _rows; - private readonly ConcurrentDictionary<(string name, Type type), object> _values = new(); + private readonly ConcurrentDictionary<(string name, Type type), object?> _values = new(); public StoreSettings(IEnumerable rows, string storeId) { - _rows = rows.ToLookup(x => x.Name); + _rows = rows.ToLookup(x => x.Name ?? string.Empty); StoreId = storeId ?? ""; } @@ -87,14 +88,14 @@ public StoreSettings(IEnumerable rows, string storeId) /// /// Gets the value of a setting - the row of the store wins over the global one - or null when there is neither /// - public object Find(string name, Type type) + public object? Find(string name, Type type) { return _values.GetOrAdd((name, type), _ => { var rows = _rows[name]; var setting = rows.FirstOrDefault(x => x.StoreId == StoreId) ?? rows.FirstOrDefault(x => string.IsNullOrEmpty(x.StoreId)); - return setting != null ? JsonSerializer.Deserialize(setting.Metadata, type) : null; + return setting?.Metadata != null ? JsonSerializer.Deserialize(setting.Metadata, type) : null; }); } } @@ -107,7 +108,7 @@ public object Find(string name, Type type) private readonly ICacheBase _cacheBase; //the settings read without the cache, kept for the rest of this scope - private StoreSettings _uncachedStoreSettings; + private StoreSettings? _uncachedStoreSettings; #endregion @@ -165,7 +166,7 @@ public virtual async Task DeleteSetting(Setting setting) /// /// Setting identifier /// Setting - public virtual Task GetSettingById(string settingId) + public virtual Task GetSettingById(string settingId) { return _settingRepository.GetByIdAsync(settingId); } @@ -179,7 +180,7 @@ public virtual Task GetSettingById(string settingId) /// Default value /// Store identifier /// Setting value - public virtual async Task GetSettingByKey(string key, T defaultValue = default, string storeId = "") + public virtual async Task GetSettingByKey(string key, T? defaultValue = default, string storeId = "") { if (string.IsNullOrEmpty(key)) return defaultValue; @@ -237,7 +238,7 @@ public virtual IList GetAllSettings() /// /// Type /// Store identifier for which settings should be loaded - public virtual async Task LoadSetting(string storeId = "") where T : ISettings, new() + public virtual async Task LoadSetting(string? storeId = "") where T : ISettings, new() { return (T)CreateSettings(await GetStoreSettings(storeId), typeof(T)); } @@ -256,13 +257,13 @@ public virtual Task LoadStoreSettings(string storeId) /// /// Type /// Store identifier for which settings should be loaded - public virtual ISettings LoadSetting(Type type, string storeId = "") + public virtual ISettings LoadSetting(Type type, string? storeId = "") { //called by the container, which cannot wait for a query: LoadStoreSettings reads the store settings ahead //when the store context is set. Without them - a scope with no store context, or the cache cleared //meanwhile - they are read here once and kept for the other settings this scope resolves storeId ??= ""; - if (_cacheBase.TryGet(StoreSettingsKey(storeId), out StoreSettings storeSettings)) + if (_cacheBase.TryGet(StoreSettingsKey(storeId), out var storeSettings)) return CreateSettings(storeSettings, type); if (_uncachedStoreSettings?.StoreId != storeId) diff --git a/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs b/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs index e30261081..f8541da3c 100644 --- a/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs +++ b/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs @@ -118,7 +118,7 @@ public virtual async Task> GetAllCountriesForShipping(string lang /// /// Country identifier /// Country - public virtual async Task GetCountryById(string countryId) + public virtual async Task GetCountryById(string? countryId) { if (string.IsNullOrEmpty(countryId)) return null; @@ -143,7 +143,7 @@ where countryIds.Contains(c.Id) var countries = await _countryRepository.ToListAsync(query); //sort by passed identifiers return countryIds.Select(id => countries.FirstOrDefault(country => country.Id == id)) - .Where(country => country != null) + .OfType() .ToList(); } @@ -152,7 +152,7 @@ where countryIds.Contains(c.Id) /// /// Country two letter ISO code /// Country - public virtual async Task GetCountryByTwoLetterIsoCode(string twoLetterIsoCode) + public virtual async Task GetCountryByTwoLetterIsoCode(string twoLetterIsoCode) { var key = string.Format(CacheKey.COUNTRIES_BY_TWOLETTER, twoLetterIsoCode); return await _cacheBase.GetAsync(key, async () => @@ -166,7 +166,7 @@ public virtual async Task GetCountryByTwoLetterIsoCode(string twoLetter /// /// Country three letter ISO code /// Country - public virtual async Task GetCountryByThreeLetterIsoCode(string threeLetterIsoCode) + public virtual async Task GetCountryByThreeLetterIsoCode(string threeLetterIsoCode) { var key = string.Format(CacheKey.COUNTRIES_BY_THREELETTER, threeLetterIsoCode); return await _cacheBase.GetAsync(key, async () => @@ -226,7 +226,7 @@ public virtual async Task DeleteCountry(Country country) /// Country identifier /// Language identifier. /// States - public virtual async Task> GetStateProvincesByCountryId(string countryId, + public virtual async Task?> GetStateProvincesByCountryId(string countryId, string languageId = "") { if (string.IsNullOrEmpty(countryId)) @@ -297,7 +297,8 @@ public virtual async Task DeleteStateProvince(StateProvince stateProvince, strin ArgumentNullException.ThrowIfNull(country); var state = country.StateProvinces.FirstOrDefault(x => x.Id == stateProvince.Id); - country.StateProvinces.Remove(state); + if (state != null) + country.StateProvinces.Remove(state); await UpdateCountry(country); } diff --git a/src/Business/Grand.Business.Common/Services/Directory/CurrencyService.cs b/src/Business/Grand.Business.Common/Services/Directory/CurrencyService.cs index 39a7c27d3..92528d38a 100644 --- a/src/Business/Grand.Business.Common/Services/Directory/CurrencyService.cs +++ b/src/Business/Grand.Business.Common/Services/Directory/CurrencyService.cs @@ -47,8 +47,8 @@ public CurrencyService(ICacheBase cacheBase, private readonly ICacheBase _cacheBase; private readonly IMediator _mediator; private readonly CurrencySettings _currencySettings; - private Currency _primaryCurrency; - private Currency _primaryExchangeRateCurrency; + private Currency? _primaryCurrency; + private Currency? _primaryExchangeRateCurrency; #endregion @@ -59,7 +59,7 @@ public CurrencyService(ICacheBase cacheBase, /// /// Currency identifier /// Currency - public virtual Task GetCurrencyById(string currencyId) + public virtual Task GetCurrencyById(string? currencyId) { var key = string.Format(CacheKey.CURRENCIES_BY_ID_KEY, currencyId); return _cacheBase.GetAsync(key, () => _currencyRepository.GetByIdAsync(currencyId)); @@ -69,7 +69,7 @@ public virtual Task GetCurrencyById(string currencyId) /// Gets primary store currency /// /// Currency - public async Task GetPrimaryStoreCurrency() + public async Task GetPrimaryStoreCurrency() { return _primaryCurrency ??= await GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId); } @@ -78,7 +78,7 @@ public async Task GetPrimaryStoreCurrency() /// Gets primary exchange currency /// /// Currency - public async Task GetPrimaryExchangeRateCurrency() + public async Task GetPrimaryExchangeRateCurrency() { return _primaryExchangeRateCurrency ??= await GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId); } @@ -88,7 +88,7 @@ public async Task GetPrimaryExchangeRateCurrency() /// /// Currency code /// Currency - public virtual async Task GetCurrencyByCode(string currencyCode) + public virtual async Task GetCurrencyByCode(string? currencyCode) { if (string.IsNullOrEmpty(currencyCode)) return null; @@ -266,7 +266,8 @@ public virtual async Task ConvertToPrimaryStoreCurrency(double amount, C { ArgumentNullException.ThrowIfNull(sourceCurrencyCode); - var primaryStoreCurrency = await GetPrimaryStoreCurrency(); + var primaryStoreCurrency = await GetPrimaryStoreCurrency() ?? + throw new GrandException("The primary store currency is not set"); var result = await ConvertCurrency(amount, sourceCurrencyCode, primaryStoreCurrency); return result; @@ -278,12 +279,14 @@ public virtual async Task ConvertToPrimaryStoreCurrency(double amount, C /// Amount /// Target currency code /// Converted value - public virtual async Task ConvertFromPrimaryStoreCurrency(double amount, Currency targetCurrencyCode) + public virtual async Task ConvertFromPrimaryStoreCurrency(double amount, Currency? targetCurrencyCode) { if (targetCurrencyCode == null) return amount; - var result = await ConvertCurrency(amount, await GetPrimaryStoreCurrency(), targetCurrencyCode); + var primaryStoreCurrency = await GetPrimaryStoreCurrency() ?? + throw new GrandException("The primary store currency is not set"); + var result = await ConvertCurrency(amount, primaryStoreCurrency, targetCurrencyCode); return result; } diff --git a/src/Business/Grand.Business.Common/Services/Directory/DateTimeService.cs b/src/Business/Grand.Business.Common/Services/Directory/DateTimeService.cs index ee24d86fd..8daf7bc83 100644 --- a/src/Business/Grand.Business.Common/Services/Directory/DateTimeService.cs +++ b/src/Business/Grand.Business.Common/Services/Directory/DateTimeService.cs @@ -11,7 +11,7 @@ namespace Grand.Business.Common.Services.Directory; public class DateTimeService : IDateTimeService { private readonly DateTimeSettings _dateTimeSettings; - private TimeZoneInfo _timeZoneInfo; + private TimeZoneInfo? _timeZoneInfo; /// /// Ctor diff --git a/src/Business/Grand.Business.Common/Services/Directory/ExchangeRateService.cs b/src/Business/Grand.Business.Common/Services/Directory/ExchangeRateService.cs index 889ae2dd9..943afefd6 100644 --- a/src/Business/Grand.Business.Common/Services/Directory/ExchangeRateService.cs +++ b/src/Business/Grand.Business.Common/Services/Directory/ExchangeRateService.cs @@ -37,7 +37,7 @@ public virtual Task> GetCurrencyLiveRates(string exchangeRat /// Load active exchange rate provider /// /// Active exchange rate provider - public virtual IExchangeRateProvider LoadActiveExchangeRateProvider() + public virtual IExchangeRateProvider? LoadActiveExchangeRateProvider() { var exchangeRateProvider = LoadExchangeRateProviderBySystemName(_currencySettings.ActiveExchangeRateProviderSystemName) ?? @@ -50,7 +50,7 @@ public virtual IExchangeRateProvider LoadActiveExchangeRateProvider() /// /// System name /// Found exchange rate provider - public virtual IExchangeRateProvider LoadExchangeRateProviderBySystemName(string systemName) + public virtual IExchangeRateProvider? LoadExchangeRateProviderBySystemName(string? systemName) { return _exchangeRateProvider.FirstOrDefault(x => x.SystemName == systemName); } diff --git a/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs b/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs index 2df14e2d6..86fe4febd 100644 --- a/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs +++ b/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs @@ -30,10 +30,10 @@ public GroupService(IRepository customerGroupRepository, /// /// Customer group identifier /// Customer group - public virtual Task GetCustomerGroupById(string customerGroupId) + public virtual Task GetCustomerGroupById(string customerGroupId) { if (string.IsNullOrWhiteSpace(customerGroupId)) - return Task.FromResult(null); + return Task.FromResult(null); var key = string.Format(CacheKey.CUSTOMERGROUPS_BY_KEY, customerGroupId); return _cacheBase.GetAsync(key, () => _customerGroupRepository.GetByIdAsync(customerGroupId)); @@ -44,7 +44,7 @@ public virtual Task GetCustomerGroupById(string customerGroupId) /// /// Customer group system name /// Customer group - public virtual async Task GetCustomerGroupBySystemName(string systemName) + public virtual async Task GetCustomerGroupBySystemName(string systemName) { var key = string.Format(CacheKey.CUSTOMERGROUPS_BY_SYSTEMNAME_KEY, systemName); return await _cacheBase.GetAsync(key, async () => diff --git a/src/Business/Grand.Business.Common/Services/Directory/HistoryService.cs b/src/Business/Grand.Business.Common/Services/Directory/HistoryService.cs index 30db6b0dc..75a37aa4e 100644 --- a/src/Business/Grand.Business.Common/Services/Directory/HistoryService.cs +++ b/src/Business/Grand.Business.Common/Services/Directory/HistoryService.cs @@ -31,8 +31,8 @@ public virtual async Task> GetHistoryForEntity(BaseEntity entity) wh ArgumentNullException.ThrowIfNull(entity); var history = await _historyRepository.ToListAsync(_historyRepository.Table - .Where(x => x.Object.Id == entity.Id).Select(x => (T)x.Object)); - return history; + .Where(x => x.Object != null && x.Object.Id == entity.Id).Select(x => x.Object)); + return history.OfType().ToList(); } public virtual async Task> GetHistoryObjectForEntity(BaseEntity entity) @@ -40,7 +40,7 @@ public virtual async Task> GetHistoryObjectForEntity(BaseEn ArgumentNullException.ThrowIfNull(entity); var history = await _historyRepository.ToListAsync( - _historyRepository.Table.Where(x => x.Object.Id == entity.Id)); + _historyRepository.Table.Where(x => x.Object != null && x.Object.Id == entity.Id)); return history; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Common/Services/ExportImport/CountryImportDataObject.cs b/src/Business/Grand.Business.Common/Services/ExportImport/CountryImportDataObject.cs index 31fcb51e7..dd7b7757a 100644 --- a/src/Business/Grand.Business.Common/Services/ExportImport/CountryImportDataObject.cs +++ b/src/Business/Grand.Business.Common/Services/ExportImport/CountryImportDataObject.cs @@ -25,12 +25,15 @@ public async Task Execute(IEnumerable data, CancellationToken private async Task Import(CountryStatesDto countryStatesDtoDto) { + //a state needs a name, as it does in the admin panel + if (string.IsNullOrEmpty(countryStatesDtoDto.Country) || string.IsNullOrEmpty(countryStatesDtoDto.StateProvinceName)) + return; var country = await _countryService.GetCountryByTwoLetterIsoCode(countryStatesDtoDto.Country); if (country == null) return; var state = country.StateProvinces.FirstOrDefault(x => - x.Abbreviation.Equals(countryStatesDtoDto.Abbreviation, StringComparison.OrdinalIgnoreCase)); + string.Equals(x.Abbreviation, countryStatesDtoDto.Abbreviation, StringComparison.OrdinalIgnoreCase)); if (state != null) { state.Name = countryStatesDtoDto.StateProvinceName; diff --git a/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs b/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs index ef152bb78..23f2f2223 100644 --- a/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs +++ b/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs @@ -7,8 +7,8 @@ namespace Grand.Business.Common.Services.ExportImport; public class ExcelExportProvider : IExportProvider { - private MemoryStream _stream; - private IWorkbook _xlPackage; + private MemoryStream? _stream; + private IWorkbook? _xlPackage; public virtual byte[] ExportToByte(PropertyByName[] properties, IEnumerable itemsToExport) { @@ -46,6 +46,8 @@ public virtual IExportProvider BuilderExportToByte(PropertyByName[] proper public virtual byte[] BuilderExportToByte() { + if (_xlPackage == null || _stream == null) + throw new InvalidOperationException("Nothing was added to the export"); _xlPackage.Write(_stream, false); return _stream.ToArray(); } @@ -74,7 +76,7 @@ private static void WriteToXlsx(PropertyByName[] properties, ISheet sheet, var row = sheet.CreateRow(idrow); foreach (var prop in properties) { - var cellValue = prop.GetProperty(items)?.ToString(); + var cellValue = prop.GetProperty?.Invoke(items)?.ToString(); if (cellValue is { Length: >= 32767 }) // 32767 is the max char size of an excel cell cellValue = cellValue[..32767]; //Truncate the content to max size. row.CreateCell(prop.PropertyOrderPosition).SetCellValue(cellValue); diff --git a/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs b/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs index d76335465..d340e8ee2 100644 --- a/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs +++ b/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs @@ -75,7 +75,7 @@ public virtual async Task> GetAllLanguages(bool showHidden = fal /// /// Language identifier /// Language - public virtual Task GetLanguageById(string languageId) + public virtual Task GetLanguageById(string? languageId) { var key = string.Format(CacheKey.LANGUAGES_BY_ID_KEY, languageId); return _cacheBase.GetAsync(key, () => _languageRepository.GetByIdAsync(languageId)); @@ -86,7 +86,7 @@ public virtual Task GetLanguageById(string languageId) /// /// Language code /// Language - public virtual async Task GetLanguageByCode(string languageCode) + public virtual async Task GetLanguageByCode(string languageCode) { ArgumentNullException.ThrowIfNullOrEmpty(languageCode); diff --git a/src/Business/Grand.Business.Common/Services/Localization/PluginTranslateResource.cs b/src/Business/Grand.Business.Common/Services/Localization/PluginTranslateResource.cs index b80c32043..77baf7f96 100644 --- a/src/Business/Grand.Business.Common/Services/Localization/PluginTranslateResource.cs +++ b/src/Business/Grand.Business.Common/Services/Localization/PluginTranslateResource.cs @@ -12,7 +12,7 @@ public class PluginTranslateResource(ITranslationService translationService, ILa /// Value /// Area /// Language culture code. If null or empty, then a resource will be added for all languages - public virtual async Task AddOrUpdatePluginTranslateResource(string name, string value, TranslationResourceArea area = TranslationResourceArea.Common, string languageCulture = null) + public virtual async Task AddOrUpdatePluginTranslateResource(string name, string value, TranslationResourceArea area = TranslationResourceArea.Common, string? languageCulture = null) { if (!string.IsNullOrEmpty(name)) name = name.ToLowerInvariant(); diff --git a/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs b/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs index 01f5d7ac1..6a4038ba6 100644 --- a/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs +++ b/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs @@ -47,7 +47,7 @@ public TranslationService( /// /// Translate resource identifier /// Translate resource - public virtual Task GetTranslateResourceById(string translateResourceId) + public virtual Task GetTranslateResourceById(string translateResourceId) { return _translationRepository.GetByIdAsync(translateResourceId); } @@ -58,7 +58,7 @@ public virtual Task GetTranslateResourceById(string transla /// A string representing a name /// Language identifier /// Translate resource - public virtual async Task GetTranslateResourceByName(string name, string languageId) + public virtual async Task GetTranslateResourceByName(string name, string languageId) { var query = from lsr in _translationRepository.Table orderby lsr.Name @@ -86,7 +86,7 @@ public virtual async Task InsertTranslateResource(TranslationResource translateR { ArgumentNullException.ThrowIfNull(translateResource); - translateResource.Name = translateResource.Name.ToLowerInvariant(); + translateResource.Name = translateResource.Name?.ToLowerInvariant(); await _translationRepository.InsertAsync(translateResource); await RefreshCachedResources(translateResource.LanguageId); @@ -103,7 +103,7 @@ public virtual async Task UpdateTranslateResource(TranslationResource translateR { ArgumentNullException.ThrowIfNull(translateResource); - translateResource.Name = translateResource.Name.ToLowerInvariant(); + translateResource.Name = translateResource.Name?.ToLowerInvariant(); await _translationRepository.UpdateAsync(translateResource); //cache @@ -142,9 +142,11 @@ public virtual async Task DeleteTranslateResource(TranslationResource translateR /// found and default value is set to empty string /// /// A string representing the requested resource string. - public virtual string GetResource(string name, string languageId, string defaultValue = "", + public virtual string GetResource(string name, string? languageId, string defaultValue = "", bool returnEmptyIfNotFound = false) { + //a record without a language (an order placed before it was stored) reads the untranslated text + languageId ??= string.Empty; name ??= string.Empty; name = name.Trim().ToLowerInvariant(); @@ -155,7 +157,7 @@ public virtual string GetResource(string name, string languageId, string default if (!string.IsNullOrEmpty(defaultValue)) result = defaultValue; else if (!returnEmptyIfNotFound) result = name; - return result; + return result ?? string.Empty; } /// @@ -274,7 +276,7 @@ await _translationRepository.InsertAsync(new TranslationResource { await RefreshCachedResources(language.Id); } - private string GetOrAddToStaticCache(string languageId, string name) + private string? GetOrAddToStaticCache(string languageId, string name) { if (_cachedResources.TryGetValue(languageId, out var languageResources)) { @@ -288,8 +290,12 @@ private string GetOrAddToStaticCache(string languageId, string name) return result; } - private Task RefreshCachedResources(string languageId) + private Task RefreshCachedResources(string? languageId) { + //a resource without a language belongs to no cached dictionary + if (languageId == null) + return Task.CompletedTask; + if (_cachedResources.ContainsKey(languageId)) _cachedResources.TryRemove(languageId, out _); _cachedResources.TryAdd(languageId, CreateLanguageResourcesDictionary(languageId)); @@ -299,10 +305,10 @@ private Task RefreshCachedResources(string languageId) private Dictionary CreateLanguageResourcesDictionary(string languageId) { return GetAllResources(languageId) - .GroupBy(r => r.Name) + .GroupBy(r => r.Name ?? string.Empty) .ToDictionary( g => g.Key, - g => g.First().Value); + g => g.First().Value ?? string.Empty); } #endregion diff --git a/src/Business/Grand.Business.Common/Services/Pdf/PdfComposer.cs b/src/Business/Grand.Business.Common/Services/Pdf/PdfComposer.cs index 900669957..ac5ad2177 100644 --- a/src/Business/Grand.Business.Common/Services/Pdf/PdfComposer.cs +++ b/src/Business/Grand.Business.Common/Services/Pdf/PdfComposer.cs @@ -33,9 +33,11 @@ internal sealed class PdfComposer : IDisposable private readonly Dictionary<(bool Bold, int Rune), bool> _glyphs = new(); private readonly Dictionary _images = new(ReferenceEqualityComparer.Instance); - private PdfPageBuilder _page; + private PdfPageBuilder? _page; + + private PdfPageBuilder Page => _page ?? throw new InvalidOperationException("NewPage has not been called"); private double _y; - private string _footerText; + private string? _footerText; private IReadOnlyList _footer = []; //a right-aligned image narrows the text beside it down to this y @@ -60,7 +62,7 @@ public void Dispose() /// /// Starts a new page. The footer is repeated on the pages a table or text overflows to. /// - public void NewPage(string footer = null) + public void NewPage(string? footer = null) { _page = _builder.AddPage(PageWidth, PageHeight); _y = PageHeight - Margin; @@ -77,7 +79,7 @@ public void Space(double height) _y -= height; } - public void Text(string text, double size = 10, bool bold = false, PdfAlign align = PdfAlign.Left, + public void Text(string? text, double size = 10, bool bold = false, PdfAlign align = PdfAlign.Left, byte gray = 0) { if (string.IsNullOrWhiteSpace(text)) return; @@ -98,9 +100,9 @@ public void Text(string text, double size = 10, bool bold = false, PdfAlign alig public void HorizontalRule(byte gray = 0, double width = 0.5) { ClearImage(); - _page.SetStrokeColor(gray, gray, gray); - _page.DrawLine(new PdfPoint(Margin, _y), new PdfPoint(PageWidth - Margin, _y), width); - _page.ResetColor(); + Page.SetStrokeColor(gray, gray, gray); + Page.DrawLine(new PdfPoint(Margin, _y), new PdfPoint(PageWidth - Margin, _y), width); + Page.ResetColor(); } /// @@ -118,9 +120,9 @@ public void Image(byte[] png, double maxWidth, double maxHeight, PdfAlign align) var rectangle = new PdfRectangle(x, _y - h, x + w, _y); //the image is written into the document once and every later page refers to it if (_images.TryGetValue(png, out var added)) - _page.AddImage(added, rectangle); + Page.AddImage(added, rectangle); else - _images[png] = _page.AddPng(png, rectangle); + _images[png] = Page.AddPng(png, rectangle); if (align != PdfAlign.Right) return; _asideBottom = _y - h; @@ -142,7 +144,7 @@ public void ClearImage() /// the page moves to the next one, repeating the header; a row taller than a whole page is split /// between its lines. /// - public void Table(IReadOnlyList columns, IReadOnlyList header, + public void Table(IReadOnlyList columns, IReadOnlyList? header, IEnumerable> rows, double size = 10, bool rowLines = true) { ClearImage(); @@ -248,14 +250,14 @@ public static bool CanEmbedPng(byte[] png) } } - private void NewTablePage(IReadOnlyList columns, double[] widths, IReadOnlyList header, + private void NewTablePage(IReadOnlyList columns, double[] widths, IReadOnlyList? header, double size) { NewPage(_footerText); if (header != null) DrawHeader(columns, widths, header, size); } - private static double HeaderHeight(IReadOnlyList header, double size) + private static double HeaderHeight(IReadOnlyList? header, double size) { return header == null ? 0 : size * LineSpacing + 2 * CellPadding; } @@ -265,10 +267,10 @@ private void DrawHeader(IReadOnlyList columns, double[] widths, IRead { var height = HeaderHeight(header, size); EnsureSpace(height); - _page.SetStrokeColor(128, 128, 128); - _page.SetTextAndFillColor(128, 128, 128); - _page.DrawRectangle(new PdfPoint(Margin, _y - height), ContentWidth, height, 0.5, true); - _page.ResetColor(); + Page.SetStrokeColor(128, 128, 128); + Page.SetTextAndFillColor(128, 128, 128); + Page.DrawRectangle(new PdfPoint(Margin, _y - height), ContentWidth, height, 0.5, true); + Page.ResetColor(); var x = Margin; for (var i = 0; i < columns.Count; i++) @@ -301,22 +303,22 @@ private void EnsureSpace(double height) /// /// Draws one already wrapped line with its top at . /// - private void DrawLine(string text, double size, PdfDocumentBuilder.AddedFont font, double x, double top, + private void DrawLine(string? text, double size, PdfDocumentBuilder.AddedFont font, double x, double top, double width, PdfAlign align, byte gray) { if (string.IsNullOrEmpty(text)) return; if (align == PdfAlign.Right) x += width - Measure(text, size, font); - if (gray != 0) _page.SetTextAndFillColor(gray, gray, gray); - _page.AddText(text, size, new PdfPoint(x, top - size), font); - if (gray != 0) _page.ResetColor(); + if (gray != 0) Page.SetTextAndFillColor(gray, gray, gray); + Page.AddText(text, size, new PdfPoint(x, top - size), font); + if (gray != 0) Page.ResetColor(); } /// /// Breaks text into lines, giving the width of the n-th line. Each word is /// measured once and a line is as wide as its words and the spaces between them. /// - private List Wrap(string text, double size, PdfDocumentBuilder.AddedFont font, Func width) + private List Wrap(string? text, double size, PdfDocumentBuilder.AddedFont font, Func width) { var lines = new List(); if (string.IsNullOrEmpty(text)) return lines; @@ -360,7 +362,7 @@ private List Wrap(string text, double size, PdfDocumentBuilder.AddedFont private (string Tail, double Width) BreakWord(string word, double size, PdfDocumentBuilder.AddedFont font, Func width, List lines) { - var letters = _page.MeasureText(word, size, new PdfPoint(0, 0), font); + var letters = Page.MeasureText(word, size, new PdfPoint(0, 0), font); //one letter per rune; charEnds[i] is where rune i ends in the string var charEnds = new List(word.Length); foreach (var rune in word.EnumerateRunes()) @@ -385,7 +387,7 @@ private List Wrap(string text, double size, PdfDocumentBuilder.AddedFont private double Measure(string text, double size, PdfDocumentBuilder.AddedFont font) { if (string.IsNullOrEmpty(text)) return 0; - var letters = _page.MeasureText(text, size, new PdfPoint(0, 0), font); + var letters = Page.MeasureText(text, size, new PdfPoint(0, 0), font); return letters.Count == 0 ? 0 : letters[^1].EndBaseLine.X; } @@ -409,7 +411,7 @@ private string Supported(string text, PdfDocumentBuilder.AddedFont font) { try { - _page.MeasureText(rune.ToString(), 10, new PdfPoint(0, 0), font); + Page.MeasureText(rune.ToString(), 10, new PdfPoint(0, 0), font); supported = true; } catch (InvalidOperationException) @@ -457,13 +459,13 @@ internal enum PdfAlign internal sealed record PdfColumn(double Weight, PdfAlign Align = PdfAlign.Left); -internal sealed record PdfLine(string Text, bool Bold = false, bool Small = false); +internal sealed record PdfLine(string? Text, bool Bold = false, bool Small = false); internal sealed record PdfCell(IReadOnlyList Lines) { public static readonly PdfCell Empty = new([]); - public static PdfCell Of(string text, bool bold = false) + public static PdfCell Of(string? text, bool bold = false) { return new PdfCell([new PdfLine(text ?? string.Empty, bold)]); } diff --git a/src/Business/Grand.Business.Common/Services/Pdf/PdfHtmlText.cs b/src/Business/Grand.Business.Common/Services/Pdf/PdfHtmlText.cs index 66e4c3d7b..898a10a58 100644 --- a/src/Business/Grand.Business.Common/Services/Pdf/PdfHtmlText.cs +++ b/src/Business/Grand.Business.Common/Services/Pdf/PdfHtmlText.cs @@ -9,7 +9,7 @@ namespace Grand.Business.Common.Services.Pdf; /// internal static partial class PdfHtmlText { - public static string ToPlainText(string html) + public static string ToPlainText(string? html) { if (string.IsNullOrWhiteSpace(html)) return string.Empty; diff --git a/src/Business/Grand.Business.Common/Services/Pdf/PdfService.cs b/src/Business/Grand.Business.Common/Services/Pdf/PdfService.cs index 575c71ef6..75027524b 100644 --- a/src/Business/Grand.Business.Common/Services/Pdf/PdfService.cs +++ b/src/Business/Grand.Business.Common/Services/Pdf/PdfService.cs @@ -79,7 +79,7 @@ public PdfService( _logger = logger; } - public async Task PrintOrdersToPdf(Stream stream, IList orders, string languageId = "", + public async Task PrintOrdersToPdf(Stream stream, IList orders, string? languageId = "", string vendorId = "", CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(stream); @@ -87,7 +87,7 @@ public async Task PrintOrdersToPdf(Stream stream, IList orders, string la using var pdf = new PdfComposer(); //orders of several stores can be printed together; each store's logo is loaded once - var logos = new Dictionary(); + var logos = new Dictionary(); foreach (var order in orders) { cancellationToken.ThrowIfCancellationRequested(); @@ -99,7 +99,7 @@ public async Task PrintOrdersToPdf(Stream stream, IList orders, string la await stream.WriteAsync(pdf.Build(), cancellationToken); } - public async Task PrintPackagingSlipsToPdf(Stream stream, IList shipments, string languageId = "", + public async Task PrintPackagingSlipsToPdf(Stream stream, IList shipments, string? languageId = "", CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(stream); @@ -117,7 +117,7 @@ public async Task PrintPackagingSlipsToPdf(Stream stream, IList shipme await stream.WriteAsync(pdf.Build(), cancellationToken); } - public async Task SaveOrderToBinary(Order order, string languageId, string vendorId = "") + public async Task SaveOrderToBinary(Order order, string? languageId, string vendorId = "") { ArgumentNullException.ThrowIfNull(order); @@ -136,9 +136,10 @@ public async Task SaveOrderToBinary(Order order, string languageId, stri return download.Id; } - private async Task ComposeOrder(PdfComposer pdf, Order order, string vendorId, Dictionary logos) + private async Task ComposeOrder(PdfComposer pdf, Order order, string vendorId, Dictionary logos) { - var lang = order.CustomerLanguageId; + //an order without a language prints the untranslated texts + var lang = order.CustomerLanguageId ?? string.Empty; var limitByVendor = !string.IsNullOrEmpty(vendorId); var priceIncludesTax = order.CustomerTaxDisplayTypeId == TaxDisplayType.IncludingTax; var store = await _storeService.GetStoreById(order.StoreId); @@ -244,7 +245,7 @@ private List> VendorTotals(Order order, IList return totals; } - private static IReadOnlyList TotalRow(Order order, string label, double amount, bool bold = false) + private static IReadOnlyList TotalRow(Order order, string? label, double amount, bool bold = false) { return [PdfCell.Empty, PdfCell.Of(label, bold), PdfCell.Of(Money(order, amount), bold)]; } @@ -253,7 +254,7 @@ private async Task>> Totals(Order order, bool priceI { var totals = new List>(); - void Add(string label, double amount, bool bold = false) + void Add(string? label, double amount, bool bold = false) { totals.Add(TotalRow(order, label, amount, bold)); } @@ -290,7 +291,8 @@ private async Task ComposePackagingSlip(PdfComposer pdf, Shipment shipment) var order = await _orderService.GetOrderById(shipment.OrderId); if (order == null) return; - var lang = order.CustomerLanguageId; + //an order without a language prints the untranslated texts + var lang = order.CustomerLanguageId ?? string.Empty; var store = await _storeService.GetStoreById(order.StoreId); var pdfSettings = await _settingService.LoadSetting(order.StoreId); @@ -342,7 +344,7 @@ private async Task ComposePackagingSlip(PdfComposer pdf, Shipment shipment) } public async Task PrintMerchandiseReturnToPdf(Stream stream, MerchandiseReturn merchandiseReturn, Order order, - string languageId = "", CancellationToken cancellationToken = default) + string? languageId = "", CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(stream); ArgumentNullException.ThrowIfNull(merchandiseReturn); @@ -361,8 +363,9 @@ await ComposeMerchandiseReturn(pdf, merchandiseReturn, order, /// The return, the order it came from, the items with their reasons, and how and where they are sent back /// private async Task ComposeMerchandiseReturn(PdfComposer pdf, MerchandiseReturn merchandiseReturn, Order order, - string lang) + string? lang) { + lang ??= string.Empty; var store = await _storeService.GetStoreById(order.StoreId); pdf.NewPage(); @@ -435,7 +438,7 @@ private async Task ComposeMerchandiseReturn(PdfComposer pdf, MerchandiseReturn m } private async Task AddressCell(Address address, string resourcePrefix, string titleKey, string lang, - string closingLine, IEnumerable extraLines = null) + string? closingLine, IEnumerable? extraLines = null) { var lines = new List { new(_translationService.GetResource(titleKey, lang), true) }; if (!string.IsNullOrEmpty(address.Company)) @@ -462,7 +465,7 @@ private async Task AddressCell(Address address, string resourcePrefix, /// Loads the PDF logo as PNG, the one raster format the composer embeds. Pictures are usually stored as /// WebP, so anything else is converted. A logo that cannot be read is left out rather than failing the PDF. /// - private async Task LoadLogo(string logoPictureId) + private async Task LoadLogo(string logoPictureId) { if (string.IsNullOrEmpty(logoPictureId)) return null; try @@ -499,7 +502,7 @@ private IEnumerable PaymentTermsLines(Order order, string lang) yield return Format("PDFInvoice.PaymentDueDate", lang, order.PaymentDueDateUtc.Value.ToString("yyyy-MM-dd")); } - private string Format(string resourceKey, string lang, object value) + private string Format(string resourceKey, string? lang, object? value) { return string.Format(_translationService.GetResource(resourceKey, lang), value); } diff --git a/src/Business/Grand.Business.Common/Services/Security/AclService.cs b/src/Business/Grand.Business.Common/Services/Security/AclService.cs index 771622c55..87c91d679 100644 --- a/src/Business/Grand.Business.Common/Services/Security/AclService.cs +++ b/src/Business/Grand.Business.Common/Services/Security/AclService.cs @@ -61,7 +61,7 @@ public virtual bool Authorize(T entity, Customer customer) where T : BaseEnti /// Entity /// Store identifier /// true - authorized; otherwise, false - public virtual bool Authorize(T entity, string storeId) where T : BaseEntity, IStoreLinkEntity + public virtual bool Authorize(T entity, string? storeId) where T : BaseEntity, IStoreLinkEntity { if (entity == null) return false; diff --git a/src/Business/Grand.Business.Common/Services/Security/EncryptionService.cs b/src/Business/Grand.Business.Common/Services/Security/EncryptionService.cs index 704ff8b79..5a05d36d2 100644 --- a/src/Business/Grand.Business.Common/Services/Security/EncryptionService.cs +++ b/src/Business/Grand.Business.Common/Services/Security/EncryptionService.cs @@ -1,6 +1,7 @@ using Grand.Business.Core.Interfaces.Common.Security; using Grand.Domain.Customers; using Grand.Infrastructure.Configuration; +using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; namespace Grand.Business.Common.Services.Security; @@ -14,7 +15,7 @@ public class EncryptionService : IEncryptionService private readonly SecurityConfig _securityConfig; - public EncryptionService(SecurityConfig securityConfig = null) + public EncryptionService(SecurityConfig? securityConfig = null) { _securityConfig = securityConfig ?? new SecurityConfig(); } @@ -46,7 +47,7 @@ public virtual string CreateSaltKey(int size) /// Salk key /// /// Password hash - public virtual string CreatePasswordHash(string password, string saltKey, + public virtual string CreatePasswordHash(string password, string? saltKey, HashedPasswordFormat passwordFormat = HashedPasswordFormat.SHA1) { var saltAndPassword = string.Concat(password, saltKey); @@ -70,7 +71,7 @@ public virtual string CreatePasswordHash(string password, string saltKey, /// Text to encrypt /// Encryption private key /// Encrypted text - public virtual string EncryptText(string plainText, string privateKey) + public virtual string EncryptText(string plainText, string? privateKey) { if (string.IsNullOrEmpty(plainText)) return plainText; @@ -93,7 +94,7 @@ public virtual string EncryptText(string plainText, string privateKey) /// Text to decrypt /// Encryption private key /// Decrypted text - public virtual string DecryptText(string cipherText, string encryptionPrivateKey) + public virtual string? DecryptText(string cipherText, string encryptionPrivateKey) { if (string.IsNullOrEmpty(cipherText)) return cipherText; @@ -126,8 +127,8 @@ public virtual string HashPassword(string password) Pbkdf2Prefix, "1", iterations.ToString(), Convert.ToBase64String(salt), Convert.ToBase64String(hash)); } - public virtual bool VerifyPassword(string enteredPassword, PasswordFormat passwordFormat, string storedPassword, - string storedSalt, HashedPasswordFormat legacyHashedFormat) + public virtual bool VerifyPassword(string enteredPassword, PasswordFormat passwordFormat, string? storedPassword, + string? storedSalt, HashedPasswordFormat legacyHashedFormat) { if (enteredPassword == null || storedPassword == null) return false; @@ -148,7 +149,7 @@ public virtual bool VerifyPassword(string enteredPassword, PasswordFormat passwo } } - public virtual bool PasswordHashNeedsUpgrade(PasswordFormat passwordFormat, string storedPassword) + public virtual bool PasswordHashNeedsUpgrade(PasswordFormat passwordFormat, string? storedPassword) { //up to date only if it is a PBKDF2 hash whose embedded cost meets the currently configured iteration count; //everything else (Clear/Encrypted, legacy SHA, or a weaker/unparseable PBKDF2 hash) is upgraded on next login @@ -164,7 +165,7 @@ public virtual bool IsHashedPassword(string storedPassword) return IsPbkdf2Hash(storedPassword); } - private static bool IsPbkdf2Hash(string storedPassword) + private static bool IsPbkdf2Hash([NotNullWhen(true)] string? storedPassword) { return storedPassword != null && storedPassword.StartsWith(Pbkdf2Prefix + "$", StringComparison.Ordinal); } @@ -223,7 +224,7 @@ private static byte[] EncryptTextToMemory(string data, byte[] key, byte[] iv) return ms.ToArray(); } - private static string DecryptTextFromMemory(byte[] data, byte[] key, byte[] iv) + private static string? DecryptTextFromMemory(byte[] data, byte[] key, byte[] iv) { using var ms = new MemoryStream(data); using var cs = new CryptoStream(ms, TripleDES.Create().CreateDecryptor(key, iv), CryptoStreamMode.Read); diff --git a/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs b/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs index 98e058cb5..76f495b0d 100644 --- a/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs +++ b/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs @@ -96,7 +96,7 @@ public virtual async Task DeletePermission(Permission permission) /// /// Permission identifier /// Permission - public virtual Task GetPermissionById(string permissionId) + public virtual Task GetPermissionById(string permissionId) { return _permissionRepository.GetByIdAsync(permissionId); } @@ -106,10 +106,10 @@ public virtual Task GetPermissionById(string permissionId) /// /// Permission system name /// Permission - public virtual async Task GetPermissionBySystemName(string systemName) + public virtual async Task GetPermissionBySystemName(string systemName) { if (string.IsNullOrWhiteSpace(systemName)) - return await Task.FromResult(null); + return await Task.FromResult(null); var query = from pr in _permissionRepository.Table where pr.SystemName == systemName @@ -179,7 +179,7 @@ public virtual async Task Authorize(Permission permission, Customer custom /// Permission system name /// Customer /// true - authorized; otherwise, false - public virtual async Task Authorize(string permissionSystemName, Customer customer) + public virtual async Task Authorize(string? permissionSystemName, Customer customer) { if (string.IsNullOrEmpty(permissionSystemName)) return false; diff --git a/src/Business/Grand.Business.Common/Services/Seo/SeNameService.cs b/src/Business/Grand.Business.Common/Services/Seo/SeNameService.cs index ee249f850..3aa3c65e0 100644 --- a/src/Business/Grand.Business.Common/Services/Seo/SeNameService.cs +++ b/src/Business/Grand.Business.Common/Services/Seo/SeNameService.cs @@ -13,7 +13,7 @@ namespace Grand.Business.Common.Services.Seo; public class SeNameService(ISlugService slugService, ILanguageService languageService, SeoSettings seoSettings) : ISeNameService { - public async Task ValidateSeName(T entity, string seName, string name, bool ensureNotEmpty) where T : BaseEntity, ISlugEntity + public async Task ValidateSeName(T entity, string? seName, string? name, bool ensureNotEmpty) where T : BaseEntity, ISlugEntity { ArgumentNullException.ThrowIfNull(entity); @@ -40,12 +40,11 @@ public async Task ValidateSeName(T entity, string seName, string name { var entityUrl = await slugService.GetBySlug(tempSeName); var reserved1 = entityUrl != null && !(entityUrl.EntityId == entity.Id && - entityUrl.EntityName.Equals(entityName, - StringComparison.OrdinalIgnoreCase)); + string.Equals(entityUrl.EntityName, entityName, StringComparison.OrdinalIgnoreCase)); var reserved2 = seoSettings.ReservedEntityUrlSlugs?.Contains(tempSeName, StringComparer.OrdinalIgnoreCase) ?? false; var reserved3 = (await languageService.GetAllLanguages(true)).Any(language => - language.UniqueSeoCode.Equals(tempSeName, StringComparison.OrdinalIgnoreCase)); + string.Equals(language.UniqueSeoCode, tempSeName, StringComparison.OrdinalIgnoreCase)); if (!reserved1 && !reserved2 && !reserved3) break; @@ -134,8 +133,9 @@ public async Task SaveSeName(T entity) where T : BaseEntity, ISlugEntity //save translation entities foreach (var locale in translationEntity.Locales .Where(x => x.LocaleKey == nameof(ISlugEntity.SeName) - && !x.LocaleValue.Equals(entity.SeName, StringComparison.InvariantCulture))) + && !string.Equals(x.LocaleValue, entity.SeName, StringComparison.InvariantCulture))) { + if (locale.LanguageId == null) continue; await slugService.SaveSlug(entity, locale.LocaleValue, locale.LanguageId); } } @@ -146,7 +146,7 @@ private static bool HasProperty(Type obj, string propertyName) return obj.GetProperty(propertyName) != null; } - private string GetSeName(string name) + private string? GetSeName(string? name) { return SeoExtensions.GenerateSlug(name, seoSettings.ConvertNonWesternChars, seoSettings.AllowUnicodeCharsInUrls, seoSettings.AllowSlashChar, seoSettings.SeoCharConversion); diff --git a/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs b/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs index 5a9563c49..09c36f287 100644 --- a/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs +++ b/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs @@ -45,7 +45,7 @@ public SlugService(ICacheBase cacheBase, /// /// URL Entity identifier /// URL Entity - public virtual Task GetEntityUrlById(string urlEntityId) + public virtual Task GetEntityUrlById(string urlEntityId) { return _urlEntityRepository.GetByIdAsync(urlEntityId); } @@ -98,7 +98,7 @@ public virtual async Task DeleteEntityUrl(EntityUrl urlEntity) /// /// Slug /// Found URL Entity - public virtual async Task GetBySlug(string slug) + public virtual async Task GetBySlug(string? slug) { if (string.IsNullOrEmpty(slug)) return null; @@ -117,7 +117,7 @@ orderby ur.IsActive /// /// Slug /// Found URL Entity - public virtual async Task GetBySlugCached(string slug) + public virtual async Task GetBySlugCached(string slug) { if (string.IsNullOrEmpty(slug)) return null; @@ -149,7 +149,7 @@ public virtual async Task> GetAllEntityUrl(string slug = " select p; if (!string.IsNullOrWhiteSpace(slug)) - query = query.Where(ur => ur.Slug.Contains(slug.ToLowerInvariant())); + query = query.Where(ur => ur.Slug != null && ur.Slug.Contains(slug.ToLowerInvariant())); if (active.HasValue) query = query.Where(ur => ur.IsActive == active.Value); @@ -189,7 +189,7 @@ public virtual async Task GetActiveSlug(string entityId, string entityNa /// Entity /// Slug /// Language ID - public virtual async Task SaveSlug(T entity, string slug, string languageId) + public virtual async Task SaveSlug(T entity, string? slug, string languageId) where T : BaseEntity, ISlugEntity { ArgumentNullException.ThrowIfNull(entity); @@ -213,7 +213,7 @@ public virtual async Task SaveSlug(T entity, string slug, string languageId) { //find in non-active records with the specified slug var nonActiveRecordWithSpecifiedSlug = allUrlEntity - .FirstOrDefault(x => x.Slug.Equals(slug, StringComparison.OrdinalIgnoreCase) && !x.IsActive); + .FirstOrDefault(x => string.Equals(x.Slug, slug, StringComparison.OrdinalIgnoreCase) && !x.IsActive); if (nonActiveRecordWithSpecifiedSlug != null) { //mark non-active record as active @@ -241,11 +241,11 @@ public virtual async Task SaveSlug(T entity, string slug, string languageId) } if (activeUrlEntity != null && !string.IsNullOrWhiteSpace(slug)) - if (!activeUrlEntity.Slug.Equals(slug, StringComparison.OrdinalIgnoreCase)) + if (!string.Equals(activeUrlEntity.Slug, slug, StringComparison.OrdinalIgnoreCase)) { //find in non-active records with the specified slug var nonActiveRecordWithSpecifiedSlug = allUrlEntity - .FirstOrDefault(x => x.Slug.Equals(slug, StringComparison.OrdinalIgnoreCase) && !x.IsActive); + .FirstOrDefault(x => string.Equals(x.Slug, slug, StringComparison.OrdinalIgnoreCase) && !x.IsActive); if (nonActiveRecordWithSpecifiedSlug != null) { nonActiveRecordWithSpecifiedSlug.IsActive = true; diff --git a/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs b/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs index 01d6d1070..da4b22ae1 100644 --- a/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs +++ b/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs @@ -61,7 +61,7 @@ public virtual async Task> GetAllStores() /// /// Store identifier /// Store - public virtual Task GetStoreById(string storeId) + public virtual Task GetStoreById(string? storeId) { var key = string.Format(CacheKey.STORES_BY_ID_KEY, storeId); return _cacheBase.GetAsync(key, () => _storeRepository.GetByIdAsync(storeId)); diff --git a/src/Business/Grand.Business.Common/Utilities/PowerExcelExtensions.cs b/src/Business/Grand.Business.Common/Utilities/PowerExcelExtensions.cs index 33ace3521..07f09a9cf 100644 --- a/src/Business/Grand.Business.Common/Utilities/PowerExcelExtensions.cs +++ b/src/Business/Grand.Business.Common/Utilities/PowerExcelExtensions.cs @@ -24,9 +24,9 @@ internal static Type ConvertToNullableType(this Type type) return type; } - internal static object GetPropertyValue(ColumnInfo columnInfo, object o, object val, ICell cell) + internal static object? GetPropertyValue(ColumnInfo columnInfo, object? o, object? val, ICell cell) { - object v; + object? v; if (columnInfo.SetProp != null) v = columnInfo.SetProp(o, val, cell); else if (columnInfo.IsNullable && (val == null || val is string { Length: 0 }) && @@ -38,15 +38,15 @@ internal static object GetPropertyValue(ColumnInfo columnInfo, object o, object v = Guid.Parse(g); else if (val is string es && columnInfo.PropertyType.IsEnum) v = ParseEnum(columnInfo.PropertyType, es); - else if (val is string && columnInfo.PropertyType == typeof(byte[])) - v = Encoding.UTF8.GetBytes(val as string); + else if (val is string bytesText && columnInfo.PropertyType == typeof(byte[])) + v = Encoding.UTF8.GetBytes(bytesText); else v = Convert.ChangeType(val, columnInfo.PropertyType, CultureInfo.InvariantCulture); return v; } - private static object ParseEnum(Type t, string s) + private static object? ParseEnum(Type t, string s) { var name = Enum.GetNames(t).FirstOrDefault(n => n.Equals(s, StringComparison.OrdinalIgnoreCase)); return name == null ? Activator.CreateInstance(t) : Enum.Parse(t, name); @@ -59,7 +59,7 @@ private static object ParseEnum(Type t, string s) /// The object whose property to set. /// The value. /// The cell where the value originates from. - internal static void SetProperty(ColumnInfo columnInfo, object o, object val, ICell cell) + internal static void SetProperty(ColumnInfo columnInfo, object o, object? val, ICell cell) { var v = GetPropertyValue(columnInfo, o, val, cell); columnInfo.Property.SetValue(o, v, null); diff --git a/src/Business/Grand.Business.Common/Utilities/PowerExcelMapper.cs b/src/Business/Grand.Business.Common/Utilities/PowerExcelMapper.cs index 817accabc..e256c1faf 100644 --- a/src/Business/Grand.Business.Common/Utilities/PowerExcelMapper.cs +++ b/src/Business/Grand.Business.Common/Utilities/PowerExcelMapper.cs @@ -12,7 +12,7 @@ public class PowerExcelMapper : ExcelMapper private readonly Dictionary> ObjectFactories = new(); private Dictionary> Objects { get; } = new(); - private IWorkbook Workbook { get; set; } + private IWorkbook? Workbook { get; set; } private static async Task ReadAsync(Stream stream, CancellationToken cancellationToken) { @@ -22,7 +22,7 @@ private static async Task ReadAsync(Stream stream, CancellationToken can } public async Task> FetchAsync(Stream stream, int sheetIndex = 0, - Func valueParser = null, CancellationToken cancellationToken = default) + Func? valueParser = null, CancellationToken cancellationToken = default) { using var ms = await ReadAsync(stream, cancellationToken); ms.Position = 0; @@ -30,19 +30,19 @@ public async Task> FetchAsync(Stream stream, int sheetIndex = } public IEnumerable Fetch(Stream stream, Type type, int sheetIndex, - Func valueParser = null) + Func? valueParser = null) { Workbook = WorkbookFactory.Create(stream); return Fetch(type, sheetIndex, valueParser); } - public IEnumerable Fetch(Type type, int sheetIndex = 0, Func valueParser = null) + public IEnumerable Fetch(Type type, int sheetIndex = 0, Func? valueParser = null) { - var sheet = Workbook.GetSheetAt(sheetIndex); + var sheet = (Workbook ?? throw new InvalidOperationException("No workbook has been read")).GetSheetAt(sheetIndex); return Fetch(sheet, type, valueParser); } - private IEnumerable Fetch(ISheet sheet, Type type, Func valueParser = null) + private IEnumerable Fetch(ISheet sheet, Type type, Func? valueParser = null) { var firstRowNumber = HeaderRowNumber; @@ -76,7 +76,7 @@ private IEnumerable Fetch(ISheet sheet, Type type, Func if ((!HeaderRow || i != HeaderRowNumber) && (!SkipBlankRows || row.Cells.Any(c => !IsCellBlank(c)))) { var o = MapCells(type, valueParser, typeMapper, firstRowCells, ref objInstanceIdx, row, - new HashSet { type }); + type != null ? new HashSet { type } : new HashSet()); yield return o; } } @@ -91,12 +91,12 @@ private static bool IsCellBlank(ICell cell) }; } - private object MapCells(Type type, Func valueParser, TypeMapper typeMapper, + private object? MapCells(Type? type, Func? valueParser, TypeMapper typeMapper, IEnumerable cells, ref int objInstanceIdx, IRow row, ISet callChain) { var sheet = row.Sheet; var i = row.RowNum; - List<(ColumnInfo Col, object CellValue, ICell Cell, int ColumnIndex)> initValues = new(); + List<(ColumnInfo Col, object? CellValue, ICell? Cell, int ColumnIndex)> initValues = new(); var columns = cells .Select(c => (Index: c.ColumnIndex, Columns: GetColumnInfo(typeMapper, c) @@ -111,7 +111,7 @@ private object MapCells(Type type, Func valueParser, Typ if (cell != null && (!SkipBlankCells || !IsCellBlank(cell))) foreach (var ci in columnInfos) { - object cellValue; + object? cellValue; try { @@ -153,7 +153,7 @@ private object MapCells(Type type, Func valueParser, Typ initValues.Add((ci, subObject, null, -1)); } - object o; + object? o; if (type == null) { @@ -170,7 +170,7 @@ private object MapCells(Type type, Func valueParser, Typ if (typeMapper.ConstructorParams.TryGetValue(initVal.Col.Property.Name, out var parm)) try { - object v; + object? v; if (initVal.Cell != null) v = PowerExcelExtensions.GetPropertyValue(initVal.Col, null, initVal.CellValue, @@ -237,7 +237,7 @@ private object MapCells(Type type, Func valueParser, Typ return o; } - private static object GetDefault(Type t) + private static object? GetDefault(Type t) { return t.GetTypeInfo().IsValueType ? Activator.CreateInstance(t) : null; } @@ -269,7 +269,7 @@ private List GetColumnInfo(TypeMapper typeMapper, ICell cell) return new List(); } - private object GetCellValue(ICell cell, ColumnInfo targetColumn) + private object? GetCellValue(ICell cell, ColumnInfo targetColumn) { var formulaResult = cell.CellType == CellType.Formula && (targetColumn.PropertyType != typeof(string) || targetColumn.FormulaResult); diff --git a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddRequiredProductsCommand.cs b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddRequiredProductsCommand.cs index 9ea738baf..5299c70c3 100644 --- a/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddRequiredProductsCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Checkout/Orders/AddRequiredProductsCommand.cs @@ -11,7 +11,7 @@ public class AddRequiredProductsCommand : IRequest public required Customer Customer { get; set; } public ShoppingCartType ShoppingCartType { get; set; } public required Product Product { get; set; } - public required string StoreId { get; set; } + public required string? StoreId { get; set; } /// /// Language the cart warnings are written in diff --git a/src/Business/Grand.Business.Core/Commands/Messages/Common/InsertContactUsCommand.cs b/src/Business/Grand.Business.Core/Commands/Messages/Common/InsertContactUsCommand.cs index 95338eedc..c0a28110f 100644 --- a/src/Business/Grand.Business.Core/Commands/Messages/Common/InsertContactUsCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Messages/Common/InsertContactUsCommand.cs @@ -8,10 +8,10 @@ public class InsertContactUsCommand : IRequest public string? CustomerId { get; set; } public string? StoreId { get; set; } public string? VendorId { get; set; } - public string? Email { get; set; } - public string? FullName { get; set; } + public required string Email { get; set; } + public required string FullName { get; set; } public string? Subject { get; set; } - public string? Enquiry { get; set; } + public required string Enquiry { get; set; } public string? RemoteIpAddress { get; set; } public string? ContactAttributeDescription { get; set; } public IList? ContactAttributes { get; set; } diff --git a/src/Business/Grand.Business.Core/Commands/Messages/Common/OrderNotificationCommand.cs b/src/Business/Grand.Business.Core/Commands/Messages/Common/OrderNotificationCommand.cs index 427ca0fd5..f55959ab2 100644 --- a/src/Business/Grand.Business.Core/Commands/Messages/Common/OrderNotificationCommand.cs +++ b/src/Business/Grand.Business.Core/Commands/Messages/Common/OrderNotificationCommand.cs @@ -12,7 +12,7 @@ public class OrderNotificationCommand : IRequest /// /// Customer the order was placed for /// - public required Customer Customer { get; set; } + public required Customer? Customer { get; set; } /// /// Staff member who placed the order while impersonating the customer, if any diff --git a/src/Business/Grand.Business.Core/Events/Customers/CustomerRegisteredEvent.cs b/src/Business/Grand.Business.Core/Events/Customers/CustomerRegisteredEvent.cs index 9f98eae66..0d92add30 100644 --- a/src/Business/Grand.Business.Core/Events/Customers/CustomerRegisteredEvent.cs +++ b/src/Business/Grand.Business.Core/Events/Customers/CustomerRegisteredEvent.cs @@ -9,7 +9,7 @@ namespace Grand.Business.Core.Events.Customers; /// public class CustomerRegisteredEvent : INotification { - public CustomerRegisteredEvent(Customer customer, Language language) + public CustomerRegisteredEvent(Customer customer, Language? language) { Customer = customer; Language = language; @@ -27,5 +27,5 @@ public Customer Customer { /// Working language of the request the customer registered through; null when the account was registered /// without one (from an access token) /// - public Language Language { get; } + public Language? Language { get; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Extensions/LanguageServiceExtensions.cs b/src/Business/Grand.Business.Core/Extensions/LanguageServiceExtensions.cs index cbcde2f0c..0edddb77b 100644 --- a/src/Business/Grand.Business.Core/Extensions/LanguageServiceExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/LanguageServiceExtensions.cs @@ -16,7 +16,7 @@ public static class LanguageServiceExtensions /// Store whose languages are the fallback; null for all stores /// The language, or null when no language exists at all public static async Task GetLanguageOrStoreDefault(this ILanguageService languageService, - string languageId, Store store) + string? languageId, Store? store) { if (!string.IsNullOrEmpty(languageId)) { diff --git a/src/Business/Grand.Business.Core/Extensions/MerchandiseReturnShippingExtensions.cs b/src/Business/Grand.Business.Core/Extensions/MerchandiseReturnShippingExtensions.cs index a3519bd1b..4f42c686a 100644 --- a/src/Business/Grand.Business.Core/Extensions/MerchandiseReturnShippingExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/MerchandiseReturnShippingExtensions.cs @@ -52,7 +52,7 @@ public static bool CustomerRetriesLabel(this MerchandiseReturn merchandiseReturn /// name, a recipient), the street, the zip code with the city, the country; empty parts are left out /// public static async Task AddressLine(ICountryService countryService, string? address1, - string? zipPostalCode, string? city, string? countryId, params string[] leading) + string? zipPostalCode, string? city, string? countryId, params string?[] leading) { var country = string.IsNullOrEmpty(countryId) ? null : await countryService.GetCountryById(countryId); var zipAndCity = string.Join(" ", new[] { zipPostalCode, city }.Where(x => !string.IsNullOrEmpty(x))); @@ -64,7 +64,7 @@ public static async Task AddressLine(ICountryService countryService, str /// An address on one line, as every text and page of a merchandise return writes it; no address gives the /// leading parts alone /// - public static Task AddressLine(ICountryService countryService, Address? address, params string[] leading) + public static Task AddressLine(ICountryService countryService, Address? address, params string?[] leading) { return AddressLine(countryService, address?.Address1, address?.ZipPostalCode, address?.City, address?.CountryId, leading); diff --git a/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs b/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs index b187b6128..05f82d036 100644 --- a/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/PaymentExtensions.cs @@ -49,7 +49,7 @@ public static bool IsPaymentMethodActive(this IPaymentProvider paymentMethod, /// Payment method, or null when it is no longer installed /// Order /// Payment method name - public static string? GetPaymentMethodName(this IPaymentProvider paymentMethod, Order order) + public static string? GetPaymentMethodName(this IPaymentProvider? paymentMethod, Order order) { ArgumentNullException.ThrowIfNull(order); diff --git a/src/Business/Grand.Business.Core/Extensions/RecurringPaymentExtensions.cs b/src/Business/Grand.Business.Core/Extensions/RecurringPaymentExtensions.cs index 526878712..2ed2a922c 100644 --- a/src/Business/Grand.Business.Core/Extensions/RecurringPaymentExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/RecurringPaymentExtensions.cs @@ -17,7 +17,7 @@ public static bool HasEnded(this RecurringPaymentStatus status) /// Whether a gateway report names another reference than the one the recurring payment runs on, for example a /// second subscription started for the same order. False while either reference is unknown /// - public static bool HasOtherProviderReference(this RecurringPayment recurringPayment, string providerReference) + public static bool HasOtherProviderReference(this RecurringPayment recurringPayment, string? providerReference) { return !string.IsNullOrEmpty(recurringPayment.ProviderReference) && !string.IsNullOrEmpty(providerReference) && recurringPayment.ProviderReference != providerReference; diff --git a/src/Business/Grand.Business.Core/Extensions/RoundingHelper.cs b/src/Business/Grand.Business.Core/Extensions/RoundingHelper.cs index 1fd0f70b7..dd7a43d46 100644 --- a/src/Business/Grand.Business.Core/Extensions/RoundingHelper.cs +++ b/src/Business/Grand.Business.Core/Extensions/RoundingHelper.cs @@ -10,7 +10,7 @@ public static class RoundingHelper /// Value to round /// Currency /// Rounded value - public static double RoundPrice(double value, Currency currency) + public static double RoundPrice(double value, Currency? currency) { return currency != null ? value.Round(currency.NumberDecimal, currency.RoundingTypeId, currency.MidpointRoundId) diff --git a/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs b/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs index 6f1ee5abd..f24b008d6 100644 --- a/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs +++ b/src/Business/Grand.Business.Core/Extensions/TranslateExtensions.cs @@ -20,7 +20,7 @@ public static class TranslateExtensions /// A value indicating whether to return default value (if translation is not found) /// Translation property public static string? GetTranslation(this T entity, - Expression> keySelector, string languageId, + Expression> keySelector, string? languageId, bool returnDefaultValue = true) where T : ParentEntity, ITranslationEntity { diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalAuthenticationService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalAuthenticationService.cs index e012ec8fb..f8b2295fd 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalAuthenticationService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalAuthenticationService.cs @@ -40,7 +40,7 @@ Task Authenticate(ExternalAuthParam parameters, Customer cus /// /// External authentication parameters /// Customer - Task GetCustomer(ExternalAuthParam parameters); + Task GetCustomer(ExternalAuthParam parameters); Task> GetExternalIdentifiers(Customer customer); @@ -66,7 +66,7 @@ Task Authenticate(ExternalAuthParam parameters, Customer cus /// /// System name /// Found external authentication method - IExternalAuthenticationProvider LoadAuthenticationProviderBySystemName(string systemName); + IExternalAuthenticationProvider? LoadAuthenticationProviderBySystemName(string systemName); /// /// Load all external authentication providers independently from status diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IJwtBearerAuthenticationService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IJwtBearerAuthenticationService.cs index d77f06a05..0343f4bc7 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IJwtBearerAuthenticationService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IJwtBearerAuthenticationService.cs @@ -15,5 +15,5 @@ public interface IJwtBearerAuthenticationService /// Get error message /// /// - Task ErrorMessage(); + Task ErrorMessage(); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IJwtBearerCustomerAuthenticationService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IJwtBearerCustomerAuthenticationService.cs index bbec785dc..8a1b473f8 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IJwtBearerCustomerAuthenticationService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IJwtBearerCustomerAuthenticationService.cs @@ -5,5 +5,5 @@ namespace Grand.Business.Core.Interfaces.Authentication; public interface IJwtBearerCustomerAuthenticationService { Task Valid(ClaimsPrincipal principal); - Task ErrorMessage(); + Task ErrorMessage(); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcLinkService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcLinkService.cs index 77a9e29e7..8ac53d215 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcLinkService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcLinkService.cs @@ -31,7 +31,7 @@ public interface IOidcLinkService /// OidcResourceServer:Authority /// The provider the links were made with (empty before the first use) /// Stored OpenID Connect links -public sealed record OidcLinkState(string ConfiguredAuthority, string LinkedAuthority, long LinkCount) +public sealed record OidcLinkState(string? ConfiguredAuthority, string? LinkedAuthority, long LinkCount) { /// Links exist and their provider differs from the configured one, or was never recorded public bool ProviderChanged => LinkCount > 0 && @@ -44,8 +44,8 @@ public sealed record OidcLinkState(string ConfiguredAuthority, string LinkedAuth public static class OidcAuthority { /// Authorities compared without a trailing slash and without regard to case - public static bool SameProvider(string a, string b) => + public static bool SameProvider(string? a, string? b) => string.Equals(Normalize(a), Normalize(b), StringComparison.OrdinalIgnoreCase); - public static string Normalize(string authority) => (authority ?? "").Trim().TrimEnd('/'); + public static string Normalize(string? authority) => (authority ?? "").Trim().TrimEnd('/'); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcSessionService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcSessionService.cs index aec229e1f..116839ea5 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcSessionService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcSessionService.cs @@ -11,7 +11,7 @@ public interface IOidcSessionService /// Records a new session and returns its id; the refresh token is kept (protected) only for a back-office account. /// Null when a back-office account brings no refresh token: such a session could never be revalidated /// - Task Start(Customer customer, string subject, string sid, string refreshToken, string storeId); + Task Start(Customer customer, string subject, string sid, string refreshToken, string storeId); /// /// The session may continue: not ended, of this customer, and for a back-office account within the idle and diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcTokenRevocationService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcTokenRevocationService.cs index 692e515b8..904669fe6 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcTokenRevocationService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcTokenRevocationService.cs @@ -7,7 +7,7 @@ namespace Grand.Business.Core.Interfaces.Authentication; public interface IOidcTokenRevocationService { /// Tokens of the subject issued until now are refused - Task RevokeTokens(string subject); + Task RevokeTokens(string? subject); /// The token of the subject issued at is refused Task IsRevoked(string subject, DateTime issuedUtc); diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IRefreshTokenService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IRefreshTokenService.cs index 30c75ccde..47a3f1e2c 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IRefreshTokenService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IRefreshTokenService.cs @@ -8,6 +8,6 @@ public interface IRefreshTokenService { string GenerateRefreshToken(); Task SaveRefreshTokenToCustomer(Customer customer, string refreshToken); - Task GetCustomerRefreshToken(Customer customer); + Task GetCustomerRefreshToken(Customer customer); ClaimsPrincipal GetPrincipalFromToken(string token); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/ISMSVerificationService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/ISMSVerificationService.cs index 275f89ebe..a1f6bc00b 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/ISMSVerificationService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/ISMSVerificationService.cs @@ -6,6 +6,6 @@ namespace Grand.Business.Core.Interfaces.Authentication; public interface ISMSVerificationService { - Task Authenticate(string secretKey, string token, Customer customer); + Task Authenticate(string? secretKey, string? token, Customer customer); Task GenerateCode(string secretKey, Customer customer, Language language); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/ITwoFactorAuthenticationService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/ITwoFactorAuthenticationService.cs index 9f65d828f..b7fdb4976 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/ITwoFactorAuthenticationService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/ITwoFactorAuthenticationService.cs @@ -7,7 +7,7 @@ namespace Grand.Business.Core.Interfaces.Authentication; public interface ITwoFactorAuthenticationService { - Task AuthenticateTwoFactor(string secretKey, string token, Customer customer, + Task AuthenticateTwoFactor(string? secretKey, string? token, Customer customer, TwoFactorAuthenticationType twoFactorAuthenticationType); /// The store whose company name the authenticator app shows as the issuer diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandLayoutService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandLayoutService.cs index ac029a7f3..3a1061704 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandLayoutService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandLayoutService.cs @@ -15,7 +15,7 @@ public interface IBrandLayoutService /// /// Brand layout id /// Brand layout - Task GetBrandLayoutById(string brandLayoutId); + Task GetBrandLayoutById(string brandLayoutId); /// /// Inserts a new brand layout diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandService.cs index b19bb291a..08ba72110 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandService.cs @@ -27,7 +27,7 @@ Task> GetAllBrands(string brandName, /// /// Brand identifier /// Brand - Task GetBrandById(string brandId); + Task GetBrandById(string brandId); /// /// Inserts a new brand diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Categories/ICategoryLayoutService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Categories/ICategoryLayoutService.cs index aadf6a767..9db22c3ab 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Categories/ICategoryLayoutService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Categories/ICategoryLayoutService.cs @@ -15,7 +15,7 @@ public interface ICategoryLayoutService /// /// Category layout id /// Category layout - Task GetCategoryLayoutById(string categoryLayoutId); + Task GetCategoryLayoutById(string categoryLayoutId); /// /// Inserts new category layout diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Categories/ICategoryService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Categories/ICategoryService.cs index fbb1760ea..4a53326d9 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Categories/ICategoryService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Categories/ICategoryService.cs @@ -16,7 +16,7 @@ public interface ICategoryService /// Page index /// Page size /// Categories - Task> GetAllCategories(string parentId, string categoryName, CatalogAccess access, + Task> GetAllCategories(string? parentId, string categoryName, CatalogAccess access, int pageIndex = 0, int pageSize = int.MaxValue); /// @@ -64,7 +64,7 @@ Task> GetAllCategoriesByParentCategoryId(CatalogAccess access, s /// Category /// Whose view of the categories to return, and the store whose limitations apply /// Category breadcrumb - Task> GetCategoryBreadCrumb(Category category, CatalogAccess access); + Task> GetCategoryBreadCrumb(Category? category, CatalogAccess access); /// /// Get category breadcrumb @@ -73,7 +73,7 @@ Task> GetAllCategoriesByParentCategoryId(CatalogAccess access, s /// All categories /// Whose view of the categories to return, and the store whose limitations apply /// Category breadcrumb - IList GetCategoryBreadCrumb(Category category, IList allCategories, CatalogAccess access); + IList GetCategoryBreadCrumb(Category? category, IList allCategories, CatalogAccess access); /// /// Get formatted category breadcrumb @@ -82,7 +82,7 @@ Task> GetAllCategoriesByParentCategoryId(CatalogAccess access, s /// Separator /// Language id for localization /// Formatted breadcrumb - Task GetFormattedBreadCrumb(Category category, string separator = ">>", string languageId = ""); + Task GetFormattedBreadCrumb(Category category, string separator = ">>", string languageId = ""); /// /// Get formatted category breadcrumb @@ -92,7 +92,7 @@ Task> GetAllCategoriesByParentCategoryId(CatalogAccess access, s /// Separator /// Language id for localization /// Formatted breadcrumb - string GetFormattedBreadCrumb(Category category, + string? GetFormattedBreadCrumb(Category category, IList allCategories, string separator = ">>", string languageId = ""); /// @@ -106,7 +106,7 @@ string GetFormattedBreadCrumb(Category category, /// /// Category identifier /// Category - Task GetCategoryById(string categoryId); + Task GetCategoryById(string? categoryId); /// /// Inserts the new category diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Collections/ICollectionLayoutService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Collections/ICollectionLayoutService.cs index bd7eb70d2..db852d63a 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Collections/ICollectionLayoutService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Collections/ICollectionLayoutService.cs @@ -15,7 +15,7 @@ public interface ICollectionLayoutService /// /// Collection layout id /// Collection layout - Task GetCollectionLayoutById(string collectionLayoutId); + Task GetCollectionLayoutById(string collectionLayoutId); /// /// Inserts a new collection layout diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Collections/ICollectionService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Collections/ICollectionService.cs index e21220c81..c288eacfe 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Collections/ICollectionService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Collections/ICollectionService.cs @@ -34,7 +34,7 @@ Task> GetAllCollections(string collectionName, /// /// Collection identifier /// Collection - Task GetCollectionById(string collectionId); + Task GetCollectionById(string? collectionId); /// /// Inserts a new collection diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/IMeasureService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/IMeasureService.cs index bf0cfab22..44303da67 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/IMeasureService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/IMeasureService.cs @@ -12,14 +12,14 @@ public interface IMeasureService /// /// Measure dimension identifier /// Measure dimension - Task GetMeasureDimensionById(string measureDimensionId); + Task GetMeasureDimensionById(string measureDimensionId); /// /// Gets a measure dimension by system keyword /// /// The system keyword /// Measure dimension - Task GetMeasureDimensionBySystemKeyword(string systemKeyword); + Task GetMeasureDimensionBySystemKeyword(string systemKeyword); /// /// Gets all measure dimensions @@ -80,14 +80,14 @@ Task ConvertFromPrimaryMeasureDimension(double value, /// /// Measure weight identifier /// Measure weight - Task GetMeasureWeightById(string measureWeightId); + Task GetMeasureWeightById(string measureWeightId); /// /// Gets a measure weight by system keyword /// /// The system keyword /// Measure weight - Task GetMeasureWeightBySystemKeyword(string systemKeyword); + Task GetMeasureWeightBySystemKeyword(string systemKeyword); /// /// Gets all measure weights @@ -146,7 +146,7 @@ Task ConvertFromPrimaryMeasureWeight(double value, /// /// Measure unit identifier /// Measure dimension - Task GetMeasureUnitById(string measureUnitId); + Task GetMeasureUnitById(string measureUnitId); /// /// Gets all measure units diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/ISearchTermService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/ISearchTermService.cs index 95a517629..b4a179c84 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/ISearchTermService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Directory/ISearchTermService.cs @@ -20,7 +20,7 @@ public interface ISearchTermService /// /// Search term identifier /// Search term - Task GetSearchTermById(string searchTermId); + Task GetSearchTermById(string searchTermId); /// /// Gets a search term record by keyword @@ -28,7 +28,7 @@ public interface ISearchTermService /// Search term keyword /// Store identifier /// Search term - Task GetSearchTermByKeyword(string keyword, string storeId); + Task GetSearchTermByKeyword(string keyword, string storeId); /// /// Gets a search term statistics diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountAmountProvider.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountAmountProvider.cs index 05568ac00..e44463945 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountAmountProvider.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountAmountProvider.cs @@ -7,5 +7,5 @@ namespace Grand.Business.Core.Interfaces.Catalog.Discounts; public interface IDiscountAmountProvider : IProvider { - Task DiscountAmount(Discount discount, Customer customer, Product product, double amount); + Task DiscountAmount(Discount discount, Customer customer, Product? product, double amount); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountProviderLoader.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountProviderLoader.cs index 42458c445..22f07e88c 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountProviderLoader.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountProviderLoader.cs @@ -7,7 +7,7 @@ public interface IDiscountProviderLoader /// /// Rule system name /// Discount provider - IDiscountProvider LoadDiscountProviderByRuleSystemName(string ruleSystemName); + IDiscountProvider? LoadDiscountProviderByRuleSystemName(string? ruleSystemName); /// /// Loads all available discount providers @@ -27,5 +27,5 @@ public interface IDiscountProviderLoader /// /// /// - IDiscountAmountProvider LoadDiscountAmountProviderBySystemName(string systemName); + IDiscountAmountProvider? LoadDiscountAmountProviderBySystemName(string? systemName); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountService.cs index 52dd2515b..1196d4db3 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountService.cs @@ -17,7 +17,7 @@ public interface IDiscountService /// /// Discount id /// Discount - Task GetDiscountById(string discountId); + Task GetDiscountById(string? discountId); /// /// Gets active discounts by context @@ -57,14 +57,14 @@ Task> GetDiscountsQuery(DiscountType? discountType, string store /// CouponCode /// A value that indicates if it should shows hidden records /// Discount - Task GetDiscountByCouponCode(string couponCode, bool showHidden = false); + Task GetDiscountByCouponCode(string couponCode, bool showHidden = false); /// /// Gets a discount usage history item /// /// Discount usage history item id /// Discount usage history - Task GetDiscountUsageHistoryById(string discountUsageHistoryId); + Task GetDiscountUsageHistoryById(string discountUsageHistoryId); /// /// Inserts discount usage history item @@ -113,14 +113,14 @@ Task> GetAllCouponCodesByDiscountId(string discountId /// /// /// - Task GetDiscountCodeById(string id); + Task GetDiscountCodeById(string id); /// /// Gets the discount code by code /// /// /// - Task GetDiscountCodeByCode(string couponCode); + Task GetDiscountCodeByCode(string couponCode); /// /// Deletes discount code diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IInventoryDocumentService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IInventoryDocumentService.cs index d2f875e46..5f6805dde 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IInventoryDocumentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IInventoryDocumentService.cs @@ -34,10 +34,10 @@ public sealed record InventoryDocumentSearch /// The warehouse the goods are received to; empty while the draft names none public sealed record ReturnReceiptSummary( string Id, - string Number, + string? Number, InventoryDocumentStatus Status, - string StoreId, - string WarehouseId); + string? StoreId, + string? WarehouseId); /// /// The return receipts of a merchandise return, posted or draft, oldest first @@ -56,12 +56,12 @@ public sealed record MerchandiseReturnReceipts( /// /// What a merchandise return gives back of a product and no return receipt takes in yet /// -public sealed record ReturnReceiptLeft(string ReturnItemId, string ProductId, int Quantity); +public sealed record ReturnReceiptLeft(string ReturnItemId, string? ProductId, int Quantity); /// /// The units of a merchandise return item the posted return receipts put back on stock, and those they wrote off /// -public sealed record ReturnItemInspected(string ReturnItemId, int Restocked, int Scrapped); +public sealed record ReturnItemInspected(string? ReturnItemId, int Restocked, int Scrapped); /// /// What the staff found when the goods came back: how many units of a product of a return item are scrapped, @@ -75,7 +75,7 @@ public sealed record ReturnReceiptInspection(string ReturnItemId, string Product /// public interface IInventoryDocumentService { - Task GetById(string id); + Task GetById(string id); Task> Search(InventoryDocumentSearch search, int pageIndex = 0, int pageSize = int.MaxValue); @@ -112,7 +112,7 @@ Task> Search(InventoryDocumentSearch search, int p /// Only products of these brands; empty for all /// Who creates it /// The draft, or null and the keys of the errors - Task<(InventoryDocument Document, IList Errors)> CreateStockCount(string warehouseId, + Task<(InventoryDocument? Document, IList Errors)> CreateStockCount(string warehouseId, IList categoryIds, IList brandIds, string customerId); /// @@ -123,7 +123,7 @@ Task> Search(InventoryDocumentSearch search, int p /// The units scrapped of each item and product; the rest is restocked. An entry naming what is not left to /// receive, named twice, or scrapping less than none or more than is left refuses the whole receipt /// - Task<(InventoryDocument Document, IList Errors)> CreateReturnReceipt(string merchandiseReturnId, + Task<(InventoryDocument? Document, IList Errors)> CreateReturnReceipt(string merchandiseReturnId, string customerId, IList? inspection = null); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IInventoryJournalService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IInventoryJournalService.cs index b68cdf864..dac2a53b2 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IInventoryJournalService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IInventoryJournalService.cs @@ -16,8 +16,8 @@ namespace Grand.Business.Core.Interfaces.Catalog.Inventory; /// false when the date is before the bucket's history starts public sealed record StockAtDateRow( string ProductId, - string ProductName, - string Sku, + string? ProductName, + string? Sku, string CombinationId, IList Attributes, int Stock, diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IProductUnitService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IProductUnitService.cs index 5a17bbc48..b4ad8244c 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IProductUnitService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Inventory/IProductUnitService.cs @@ -14,7 +14,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Inventory; /// The quantity the batch holds in the warehouse /// The quantity proposed from it public sealed record BatchAllocation( - string Number, + string? Number, DateTime? ExpiryDateUtc, BatchExpiryStatus? Status, int Available, @@ -23,7 +23,7 @@ public sealed record BatchAllocation( /// /// Why the units of a shipment item cannot be shipped /// -public sealed record ShipmentUnitError(string ShipmentItemId, string ProductName, string ErrorKey); +public sealed record ShipmentUnitError(string ShipmentItemId, string? ProductName, string ErrorKey); /// /// A batch or serial number a shipment item shipped, as its customer is told about it @@ -34,11 +34,11 @@ public sealed record ShipmentUnitError(string ShipmentItemId, string ProductName /// The batch's expiry date /// What the store tells the customer about the unit; empty when its record is gone public sealed record ShippedUnitView( - string Number, + string? Number, bool IsSerialNumber, int Quantity, DateTime? ExpiryDateUtc, - string CustomerComment); + string? CustomerComment); /// /// The filter of the batch and serial number screens; an empty field filters nothing @@ -82,8 +82,8 @@ public sealed record UnitSearch /// public sealed record ExpiringBatch( ProductBatch Batch, - string ProductName, - string Sku, + string? ProductName, + string? Sku, string WarehouseName, BatchExpiryStatus Status); @@ -91,12 +91,12 @@ public sealed record ExpiringBatch( /// A shipment that shipped units of a batch: who received them, and the store of their order /// public sealed record BatchRecipient( - string ShipmentId, + string? ShipmentId, int ShipmentNumber, - string OrderId, + string? OrderId, int OrderNumber, - string CustomerId, - string CustomerEmail, + string? CustomerId, + string? CustomerEmail, int Quantity, DateTime ShippedOnUtc, string? StoreId = null); @@ -168,9 +168,9 @@ Task> SearchSerialNumbers(UnitSearch search, int Task> SearchBatches(UnitSearch search, int pageIndex = 0, int pageSize = int.MaxValue); - Task GetSerialNumber(string id); + Task GetSerialNumber(string id); - Task GetBatch(string id); + Task GetBatch(string id); /// /// Saves what the back office tells about the batch: its location, supplier, dates and comments; never its @@ -242,5 +242,5 @@ Task> History(ProductSerialNumber serialNumber, ILi /// The product as stored /// The product as it is to be saved /// The key of the error, or null - Task TrackingChangeRefused(Product stored, Product changed); + Task TrackingChangeRefused(Product stored, Product changed); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPriceFormatter.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPriceFormatter.cs index de287f089..61cae4846 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPriceFormatter.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPriceFormatter.cs @@ -10,7 +10,7 @@ public interface IPriceFormatter /// Price /// Target currency /// Price - string FormatPrice(double price, Currency targetCurrency); + string FormatPrice(double price, Currency? targetCurrency); /// /// Formats a tax rate diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPricingService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPricingService.cs index d95aacf1d..df6051166 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPricingService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Prices/IPricingService.cs @@ -24,7 +24,7 @@ public interface IPricingService /// A value indicating whether include discounts or not for final price computation /// Shopping cart item quantity /// Final price - Task<(double finalPrice, double discountAmount, List appliedDiscounts, TierPrice preferredTierPrice)> + Task<(double finalPrice, double discountAmount, List appliedDiscounts, TierPrice? preferredTierPrice)> GetFinalPrice( Product product, Customer customer, @@ -47,7 +47,7 @@ public interface IPricingService /// Rental period start date (for rental products) /// Rental period end date (for rental products) /// Final price - Task<(double finalPrice, double discountAmount, List appliedDiscounts, TierPrice preferredTierPrice)> + Task<(double finalPrice, double discountAmount, List appliedDiscounts, TierPrice? preferredTierPrice)> GetFinalPrice(Product product, Customer customer, Store store, diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IAuctionService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IAuctionService.cs index 6b20b51c1..71fd654ba 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IAuctionService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IAuctionService.cs @@ -52,14 +52,14 @@ public interface IAuctionService /// /// Id /// Bid - Task GetBid(string id); + Task GetBid(string id); /// /// Get latest bid for product Id /// /// productId /// Bid - Task GetLatestBid(string productId); + Task GetLatestBid(string productId); /// /// Updates highest bid @@ -67,7 +67,7 @@ public interface IAuctionService /// /// /// - Task UpdateHighestBid(Product product, double bid, string bidder); + Task UpdateHighestBid(Product product, double bid, string? bidder); /// /// Updates auction ended diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ICustomerGroupProductService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ICustomerGroupProductService.cs index 83587b40d..bd9b5f7cc 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ICustomerGroupProductService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ICustomerGroupProductService.cs @@ -17,14 +17,14 @@ public interface ICustomerGroupProductService /// Customer group id /// Product id /// Customer group product - Task GetCustomerGroupProduct(string customerGroupId, string productId); + Task GetCustomerGroupProduct(string customerGroupId, string productId); /// /// Gets customer groups product /// /// id /// Customer group product - Task GetCustomerGroupProductById(string id); + Task GetCustomerGroupProductById(string id); /// /// Inserts a customer group product diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IInventoryManageService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IInventoryManageService.cs index e650d996e..20cd8fe7f 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IInventoryManageService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IInventoryManageService.cs @@ -23,7 +23,7 @@ public interface IInventoryManageService /// Attributes /// Warehouse ident Task AdjustReserved(Product product, int quantityToChange, IList? attributes = null, - string warehouseId = ""); + string? warehouseId = ""); /// @@ -42,7 +42,7 @@ Task AdjustReserved(Product product, int quantityToChange, IListAttributes /// Warehouse ident /// False when the stock is short; nothing is reserved then - Task TryReserve(Product product, int quantity, IList attributes, string warehouseId); + Task TryReserve(Product product, int quantity, IList attributes, string? warehouseId); /// /// Gives back a quantity reserved for an order that was never placed; the low-stock action the reservation @@ -52,7 +52,7 @@ Task AdjustReserved(Product product, int quantityToChange, IListQuantity to give back /// Attributes /// Warehouse ident - Task CancelReservation(Product product, int quantity, IList attributes, string warehouseId); + Task CancelReservation(Product product, int quantity, IList attributes, string? warehouseId); /// /// Reverse booked inventory diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IOutOfStockSubscriptionService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IOutOfStockSubscriptionService.cs index cbf8b2372..f20528780 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IOutOfStockSubscriptionService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IOutOfStockSubscriptionService.cs @@ -29,7 +29,7 @@ Task> GetAllSubscriptionsByCustomerId(string /// Store identifier /// Warehouse identifier /// Subscriptions - Task FindSubscription(string customerId, string productId, + Task FindSubscription(string customerId, string productId, IList attributes, string storeId, string warehouseId); /// @@ -37,7 +37,7 @@ Task FindSubscription(string customerId, string productI /// /// Subscription identifier /// Subscription - Task GetSubscriptionById(string subscriptionId); + Task GetSubscriptionById(string subscriptionId); /// /// Inserts subscription diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductAttributeFormatter.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductAttributeFormatter.cs index 4fc6842b8..426e4e2c7 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductAttributeFormatter.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductAttributeFormatter.cs @@ -28,7 +28,7 @@ public interface IProductAttributeFormatter /// Show in admin /// Attributes Task FormatAttributes(Product product, IList customAttributes, - CalculationContext context, Language language, DomainHost host, + CalculationContext? context, Language? language, DomainHost host, string separator = "
", bool htmlEncode = true, bool renderPrices = true, bool renderProductAttributes = true, bool renderGiftVoucherAttributes = true, bool allowHyperlinks = true, bool showInAdmin = false); diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductAttributeService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductAttributeService.cs index 4d5518b24..764385553 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductAttributeService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductAttributeService.cs @@ -30,7 +30,7 @@ public interface IProductAttributeService ///
/// Product attribute identifier /// Product attribute - Task GetProductAttributeById(string productAttributeId); + Task GetProductAttributeById(string? productAttributeId); /// /// Inserts a product attribute diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductCourseService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductCourseService.cs index f3201973a..9405e3b00 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductCourseService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductCourseService.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Core.Interfaces.Catalog.Products; public interface IProductCourseService { - Task GetProductByCourseId(string courseId); - Task GetCourseByProductId(string productId); + Task GetProductByCourseId(string courseId); + Task GetCourseByProductId(string productId); Task UpdateCourseOnProduct(string productId, string courseId); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductLayoutService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductLayoutService.cs index a8c34c8d3..1427978f6 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductLayoutService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductLayoutService.cs @@ -18,7 +18,7 @@ public interface IProductLayoutService /// /// Product layout identifier /// Product layout - Task GetProductLayoutById(string productLayoutId); + Task GetProductLayoutById(string productLayoutId); /// /// Inserts product layout diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs index ce53a6e09..fdd01cbbd 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReservationService.cs @@ -44,7 +44,7 @@ Task> GetProductReservationsByProductId(string pr /// /// Product Id /// Product reservation - Task GetProductReservation(string id); + Task GetProductReservation(string? id); /// /// Adds customer reservations helper @@ -69,7 +69,7 @@ Task> GetProductReservationsByProductId(string pr /// /// /// CustomerReservationsHelper - Task GetCustomerReservationsHelperById(string id); + Task GetCustomerReservationsHelperById(string id); /// /// Gets customer reservations helpers diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReviewService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReviewService.cs index fc403db5d..5edc989f7 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReviewService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductReviewService.cs @@ -39,9 +39,9 @@ public interface IProductReviewService /// /// /// Reviews - Task> GetAllProductReviews(string customerId, bool? approved = null, + Task> GetAllProductReviews(string? customerId, bool? approved = null, DateTime? fromUtc = null, DateTime? toUtc = null, - string? message = null, string storeId = "", string productId = "", int pageIndex = 0, + string? message = null, string? storeId = "", string productId = "", int pageIndex = 0, int pageSize = int.MaxValue); /// @@ -49,5 +49,5 @@ Task> GetAllProductReviews(string customerId, bool? ap /// /// Product review identifier /// Product review - Task GetProductReviewById(string productReviewId); + Task GetProductReviewById(string productReviewId); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductService.cs index ccc854d33..0c4616ee6 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductService.cs @@ -32,14 +32,14 @@ public interface IProductService /// Product identifier /// get data from db (not from cache) /// Product - Task GetProductById(string productId, bool fromDb = false); + Task GetProductById(string? productId, bool fromDb = false); /// /// Gets product from product or product deleted /// /// Product identifier /// Product - Task GetProductByIdIncludeArch(string productId); + Task GetProductByIdIncludeArch(string? productId); /// /// Gets products by identifier @@ -217,7 +217,7 @@ Task> GetAssociatedProducts(string parentGroupedProductId, Catalo /// /// SKU /// Product - Task GetProductBySku(string sku); + Task GetProductBySku(string? sku); #endregion diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductTagService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductTagService.cs index f4f9ff096..d3d07b0b8 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductTagService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IProductTagService.cs @@ -18,21 +18,21 @@ public interface IProductTagService /// /// Product tag identifier /// Product tag - Task GetProductTagById(string productTagId); + Task GetProductTagById(string productTagId); /// /// Gets product tag by name /// /// Product tag name /// Product tag - Task GetProductTagByName(string name); + Task GetProductTagByName(string name); /// /// Gets product tag by se-name /// /// Product tag se-name /// Product tag - Task GetProductTagBySeName(string sename); + Task GetProductTagBySeName(string sename); /// /// Inserts a product tag diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ISpecificationAttributeService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ISpecificationAttributeService.cs index ab06990aa..6577e016b 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ISpecificationAttributeService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ISpecificationAttributeService.cs @@ -15,14 +15,14 @@ public interface ISpecificationAttributeService /// /// The specification attribute identifier /// Specification attribute - Task GetSpecificationAttributeById(string specificationAttributeId); + Task GetSpecificationAttributeById(string specificationAttributeId); /// /// Gets a specification attribute by se-name /// /// Se-name /// Specification attribute - Task GetSpecificationAttributeBySeName(string sename); + Task GetSpecificationAttributeBySeName(string sename); /// /// Gets specification attributes @@ -60,7 +60,7 @@ public interface ISpecificationAttributeService /// /// The specification attribute option /// Specification attribute option - Task GetSpecificationAttributeByOptionId(string specificationAttributeOption); + Task GetSpecificationAttributeByOptionId(string specificationAttributeOption); /// /// Deletes a specification attribute option diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IStockQuantityService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IStockQuantityService.cs index ed80c399b..be6996adc 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IStockQuantityService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/IStockQuantityService.cs @@ -9,23 +9,23 @@ public interface IStockQuantityService { int GetTotalStockQuantity(Product product, bool useReservedQuantity = true, - string warehouseId = "", bool total = false); + string? warehouseId = "", bool total = false); int GetTotalStockQuantityForCombination(Product product, ProductAttributeCombination combination, - bool useReservedQuantity = true, string warehouseId = ""); + bool useReservedQuantity = true, string? warehouseId = ""); /// /// Whether the stock covers the quantity, by the rule the shopping cart and the order placement share; a /// bundle is checked by its products /// - StockCheck CheckStock(Product product, int quantity, IList? attributes, string warehouseId); + StockCheck CheckStock(Product product, int quantity, IList? attributes, string? warehouseId); - (string resource, object? arg0) FormatStockMessage(Product product, string warehouseId, + (string resource, object? arg0) FormatStockMessage(Product product, string? warehouseId, IList attributes); /// /// The stock message together with the availability it describes - one answer, so the /// text a customer reads and the state given to search engines cannot disagree /// - StockStatus GetStockStatus(Product product, string warehouseId, IList attributes); + StockStatus GetStockStatus(Product product, string? warehouseId, IList attributes); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxCategoryService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxCategoryService.cs index d7659084e..447e9fa6f 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxCategoryService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxCategoryService.cs @@ -19,7 +19,7 @@ public interface ITaxCategoryService /// /// Tax category identifier /// Tax category - Task GetTaxCategoryById(string taxCategoryId); + Task GetTaxCategoryById(string taxCategoryId); /// /// Inserts a tax category diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxService.cs index d146017bd..0ce63278c 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/ITaxService.cs @@ -18,14 +18,14 @@ public interface ITaxService /// Customer whose groups limit the fallback providers /// Store whose providers are the fallback /// Active tax provider - ITaxProvider LoadActiveTaxProvider(Customer customer, string storeId); + ITaxProvider? LoadActiveTaxProvider(Customer customer, string? storeId); /// /// Load tax provider by system name /// /// System name /// Found tax provider - ITaxProvider LoadTaxProviderBySystemName(string systemName); + ITaxProvider? LoadTaxProviderBySystemName(string systemName); /// /// Load all tax providers @@ -33,7 +33,7 @@ public interface ITaxService /// Customer /// Store ident /// Tax providers - IList LoadAllTaxProviders(Customer? customer = null, string storeId = ""); + IList LoadAllTaxProviders(Customer? customer = null, string? storeId = ""); /// @@ -124,7 +124,7 @@ bool priceIncludesTax /// Product /// Customer /// A value indicating whether a product is tax exempt - Task IsTaxExempt(Product product, Customer customer); + Task IsTaxExempt(Product? product, Customer? customer); /// /// Gets a value indicating whether EU VAT exempt (the European Union Value Added Tax) diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/IVatService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/IVatService.cs index b3f39eb79..39fa1999a 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/IVatService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Tax/IVatService.cs @@ -10,7 +10,7 @@ public interface IVatService /// /// Two letter ISO code of a country and VAT number (e.g. GB 111 1111 111) /// VAT Number status - Task<(VatNumberStatus status, string name, string address, Exception exception)> GetVatNumberStatus( + Task<(VatNumberStatus status, string? name, string? address, Exception? exception)> GetVatNumberStatus( string fullVatNumber); /// @@ -19,7 +19,7 @@ public interface IVatService /// Two letter ISO code of a country /// VAT number /// VAT Number status - Task<(VatNumberStatus status, string name, string address, Exception exception)> GetVatNumberStatus( + Task<(VatNumberStatus status, string? name, string? address, Exception? exception)> GetVatNumberStatus( string twoLetterIsoCode, string vatNumber); @@ -29,7 +29,7 @@ public interface IVatService /// Two letter ISO code of a country /// VAT number /// VAT number status - Task<(VatNumberStatus status, string name, string address, Exception exception)> DoVatCheck(string twoLetterIsoCode, + Task<(VatNumberStatus status, string? name, string? address, Exception? exception)> DoVatCheck(string twoLetterIsoCode, string vatNumber); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeFormatter.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeFormatter.cs index b16bdab2c..4500b2499 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeFormatter.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeFormatter.cs @@ -22,7 +22,7 @@ public interface ICheckoutAttributeFormatter /// A value indicating whether to render prices /// A value indicating whether to HTML hyperlink tags could be rendered (if required) /// Attributes - Task FormatAttributes(IList customAttributes, + Task FormatAttributes(IList? customAttributes, CalculationContext context, Language language, DomainHost host, diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeParser.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeParser.cs index 7e66cf76f..94e2bbcd3 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeParser.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeParser.cs @@ -28,7 +28,7 @@ public interface ICheckoutAttributeParser /// Attributes /// Checkout attribute values with checkout attribute Task> ParseCheckoutAttributeValue( - IList customAttributes); + IList? customAttributes); /// /// Adds an attribute diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeService.cs index abf28f5e5..d03dfd754 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/CheckoutAttributes/ICheckoutAttributeService.cs @@ -24,7 +24,7 @@ Task> GetAllCheckoutAttributes(CatalogAccess access, /// /// Checkout attribute identifier /// Checkout attribute - Task GetCheckoutAttributeById(string checkoutAttributeId); + Task GetCheckoutAttributeById(string? checkoutAttributeId); /// /// Inserts a checkout attribute diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/GiftVouchers/IGiftVoucherService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/GiftVouchers/IGiftVoucherService.cs index 1effa4f0c..84d35ff70 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/GiftVouchers/IGiftVoucherService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/GiftVouchers/IGiftVoucherService.cs @@ -13,7 +13,7 @@ public interface IGiftVoucherService /// /// Gift voucher identifier /// Gift voucher entry - Task GetGiftVoucherById(string giftVoucherId); + Task GetGiftVoucherById(string? giftVoucherId); /// /// Gets all gift vouchers diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/ILoyaltyPointsService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/ILoyaltyPointsService.cs index 447e03409..27ccf9716 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/ILoyaltyPointsService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/ILoyaltyPointsService.cs @@ -13,7 +13,7 @@ public interface ILoyaltyPointsService /// Customer identifier /// Store identifier; pass /// Balance - Task GetLoyaltyPointsBalance(string customerId, string storeId); + Task GetLoyaltyPointsBalance(string customerId, string? storeId); /// /// Add loyalty points history record @@ -24,7 +24,7 @@ public interface ILoyaltyPointsService /// Message /// the order for which points were redeemed as a payment /// Used amount - Task AddLoyaltyPointsHistory(string customerId, int points, string storeId, + Task AddLoyaltyPointsHistory(string customerId, int points, string? storeId, string message = "", string usedWithOrderId = "", double usedAmount = 0); @@ -38,7 +38,7 @@ Task AddLoyaltyPointsHistory(string customerId, int points /// the order for which points are redeemed as a payment /// Used amount /// The history record, or null when the balance is short - Task TryRedeemLoyaltyPoints(string customerId, int points, string storeId, + Task TryRedeemLoyaltyPoints(string customerId, int points, string? storeId, string message, string usedWithOrderId, double usedAmount); /// @@ -48,6 +48,6 @@ Task TryRedeemLoyaltyPoints(string customerId, int points, /// Store ident /// A value indicating whether to show for all store(filter by current store if possible) /// Loyalty point history records - Task> GetLoyaltyPointsHistory(string customerId = "", string storeId = "", + Task> GetLoyaltyPointsHistory(string customerId = "", string? storeId = "", bool showAll = false); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnLabelService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnLabelService.cs index 9629e636a..781f5ccdd 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnLabelService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnLabelService.cs @@ -15,7 +15,7 @@ public interface IMerchandiseReturnLabelService /// note for the staff, and is not an error of the call /// /// null when done or there is nothing to do, else a key of MerchandiseReturnErrors - Task CreateLabel(string merchandiseReturnId); + Task CreateLabel(string merchandiseReturnId); /// /// Cancels a created label once the return is rejected or cancelled; best effort: a label the provider did @@ -34,6 +34,6 @@ public interface IMerchandiseReturnLabelService /// number typed in while the staff marked the return received /// /// null when saved, else a key of MerchandiseReturnErrors (ShippingChangeNotAllowed when not allowed) - Task UpdateShipping(string merchandiseReturnId, Action apply, + Task UpdateShipping(string merchandiseReturnId, Action apply, Func? allowed = null); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnRefundService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnRefundService.cs index 6cc9f6dc4..387a7ddaa 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnRefundService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnRefundService.cs @@ -39,7 +39,7 @@ public interface IMerchandiseReturnRefundService /// Whether the money was given back outside the payment provider /// Who refunded, as the staff notes name them; null for the system /// null when refunded, else a key of MerchandiseReturnErrors - Task Refund(string merchandiseReturnId, double amount, bool offline, string? refundedBy = null); + Task Refund(string merchandiseReturnId, double amount, bool offline, string? refundedBy = null); /// /// Records what the staff found when they checked the payment of a refund that waits for it: the money went @@ -49,5 +49,5 @@ public interface IMerchandiseReturnRefundService /// Whether the money went back /// Who checked, as the staff notes name them; null for the system /// null when recorded, else a key of MerchandiseReturnErrors - Task ResolveRefund(string merchandiseReturnId, bool wentBack, string? checkedBy = null); + Task ResolveRefund(string merchandiseReturnId, bool wentBack, string? checkedBy = null); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnService.cs index 281d31259..52e4020af 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnService.cs @@ -13,7 +13,7 @@ public interface IMerchandiseReturnService /// /// Merchandise return identifier /// Merchandise return - Task GetMerchandiseReturnById(string merchandiseReturnId); + Task GetMerchandiseReturnById(string? merchandiseReturnId); /// /// Gets a merchandise return @@ -21,7 +21,7 @@ public interface IMerchandiseReturnService /// Merchandise return number /// t /// Merchandise return - Task GetMerchandiseReturnById(int id); + Task GetMerchandiseReturnById(int id); /// /// Search merchandise returns @@ -78,14 +78,14 @@ Task> SearchMerchandiseReturns(string storeId = "" /// /// Store identifier; empty to load all entries /// Merchandise return actions - Task> GetAllMerchandiseReturnActions(string storeId = ""); + Task> GetAllMerchandiseReturnActions(string? storeId = ""); /// /// Gets a merchandise return action /// /// Merchandise return action identifier /// Merchandise return action - Task GetMerchandiseReturnActionById(string merchandiseReturnActionId); + Task GetMerchandiseReturnActionById(string merchandiseReturnActionId); /// /// Inserts a merchandise return action @@ -110,14 +110,14 @@ Task> SearchMerchandiseReturns(string storeId = "" /// /// Store identifier; empty to load all entries /// Merchandise return reasons - Task> GetAllMerchandiseReturnReasons(string storeId = ""); + Task> GetAllMerchandiseReturnReasons(string? storeId = ""); /// /// Gets a merchandise return reasons /// /// Merchandise return reason identifier /// Merchandise return reasons - Task GetMerchandiseReturnReasonById(string merchandiseReturnReasonId); + Task GetMerchandiseReturnReasonById(string merchandiseReturnReasonId); /// /// Inserts a merchandise return reasons @@ -163,7 +163,7 @@ Task> SearchMerchandiseReturns(string storeId = "" /// /// Merchandise return note identifier /// MerchandiseReturnNote - Task GetMerchandiseReturnNote(string merchandiseReturnNoteId); + Task GetMerchandiseReturnNote(string merchandiseReturnNoteId); #endregion } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnWorkflowService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnWorkflowService.cs index fdd28ecf6..2e1d7bca9 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnWorkflowService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnWorkflowService.cs @@ -31,7 +31,7 @@ public interface IMerchandiseReturnWorkflowService /// The new status /// A note shown to the customer with the change, e.g. why the return was rejected /// Who changed it, as the staff note names them (e.g. the e-mail); null for the system - Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus status, string? customerNote = null, + Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus status, string? customerNote = null, string? changedBy = null); /// @@ -45,8 +45,8 @@ Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus st /// Checked on the return as stored, under the lock: when it says no, nothing is saved, e.g. a customer's cancel /// of a return the staff accepted since the page was loaded (StatusChangeNotAllowed) /// - Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus status, string customerNote, - string changedBy, Func allowed); + Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus status, string? customerNote, + string? changedBy, Func allowed); /// /// Changes the status as the overload with allowed does @@ -60,18 +60,18 @@ Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus st /// The caller can post no return receipt (the vendor panel has no inventory documents): Received is allowed /// where a receipt would take the goods in /// - Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus status, string customerNote, - string changedBy, Func allowed, bool withoutReturnReceipts); + Task ChangeStatus(string merchandiseReturnId, MerchandiseReturnStatus status, string? customerNote, + string? changedBy, Func allowed, bool withoutReturnReceipts); /// /// Saves the fields set by apply; the status stays as stored, it changes only through ChangeStatus /// - Task Update(string merchandiseReturnId, Action apply); + Task Update(string merchandiseReturnId, Action apply); /// /// Deletes the merchandise return /// - Task Delete(string merchandiseReturnId); + Task Delete(string merchandiseReturnId); /// /// A return receipt of the return was posted: a pending or accepted return becomes received, any other one diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderApprovalService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderApprovalService.cs index 028db0cc9..0fd1f8b95 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderApprovalService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderApprovalService.cs @@ -14,14 +14,14 @@ public interface IOrderApprovalService /// Approval identifier /// Identifier of the company owner the approval must belong to /// Approval; null when it does not exist or belongs to another company - Task GetById(string id, string companyOwnerId); + Task GetById(string id, string companyOwnerId); /// /// Gets the approval request of an order /// /// Order identifier /// Approval; null when the order has none - Task GetByOrderId(string orderId); + Task GetByOrderId(string orderId); /// /// Gets the company's requests in the store, pending first and then the newest @@ -70,5 +70,5 @@ Task Close(OrderApproval approval, OrderApprovalStatus status, string? dec /// Gets a value indicating whether the payment method may be used for an order that needs an approval /// /// Payment method system name - bool IsPaymentMethodAllowed(string paymentMethodSystemName); + bool IsPaymentMethodAllowed(string? paymentMethodSystemName); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderPlacementService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderPlacementService.cs index d79434905..41fbcf490 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderPlacementService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderPlacementService.cs @@ -18,5 +18,5 @@ public interface IOrderPlacementService /// Chosen payment method; null until the buyer has chosen one /// Cancellation token, passed on to every rule Task Evaluate(IList cart, CalculationContext calculation, - Language language, string paymentMethodSystemName, CancellationToken cancellationToken = default); + Language language, string? paymentMethodSystemName, CancellationToken cancellationToken = default); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderService.cs index abacd735c..7146248b3 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderService.cs @@ -17,7 +17,7 @@ public interface IOrderService /// /// Order item identifier /// Order item - Task GetOrderItemByGuid(Guid orderItemGuid); + Task GetOrderItemByGuid(Guid orderItemGuid); #endregion @@ -28,21 +28,21 @@ public interface IOrderService /// /// The order identifier /// Order - Task GetOrderById(string orderId); + Task GetOrderById(string? orderId); /// /// Gets an order /// /// The order item identifier /// Order - Task GetOrderByOrderItemId(string orderItemId); + Task GetOrderByOrderItemId(string orderItemId); /// /// Gets an order /// /// The order number /// Order - Task GetOrderByNumber(int orderNumber); + Task GetOrderByNumber(int orderNumber); /// /// Gets orders by code @@ -63,7 +63,7 @@ public interface IOrderService /// /// The order identifier /// Order - Task GetOrderByGuid(Guid orderGuid); + Task GetOrderByGuid(Guid orderGuid); /// /// Search orders @@ -160,7 +160,7 @@ Task> SearchOrders(string storeId = "", /// /// Order note identifier /// OrderNote - Task GetOrderNote(string orderNoteId); + Task GetOrderNote(string orderNoteId); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderStatusService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderStatusService.cs index e526c6014..b2017acdf 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderStatusService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderStatusService.cs @@ -5,8 +5,8 @@ namespace Grand.Business.Core.Interfaces.Checkout.Orders; public interface IOrderStatusService { Task> GetAll(); - Task GetById(string id); - Task GetByStatusId(int statusId); + Task GetById(string id); + Task GetByStatusId(int statusId); Task Insert(OrderStatus orderStatus); Task Update(OrderStatus orderStatus); Task Delete(OrderStatus orderStatus); diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderTagService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderTagService.cs index 0b9ab7aca..aa81773ce 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderTagService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IOrderTagService.cs @@ -18,14 +18,14 @@ public interface IOrderTagService /// /// order's tag identifier /// order's tag - Task GetOrderTagById(string orderTagId); + Task GetOrderTagById(string orderTagId); /// /// Gets order tag by name /// /// order tag name /// order tag - Task GetOrderTagByName(string name); + Task GetOrderTagByName(string name); /// /// Inserts a order tag diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs index 616c8346e..46dce749e 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IRecurringPaymentService.cs @@ -21,7 +21,7 @@ public interface IRecurringPaymentService /// another provider reference than the one the recurring payment runs on). The first reported reference is /// recorded /// - Task ClaimCycle(string recurringPaymentId, string providerReference, string cycleReference, + Task ClaimCycle(string recurringPaymentId, string? providerReference, string cycleReference, double amount, DateTime paidOnUtc, DateTime? nextPaymentDateUtc); /// @@ -31,22 +31,22 @@ Task ClaimCycle(string recurringPaymentId, string providerR /// whose missing reference is still recorded so the gateway can be stopped. The first reported reference is /// recorded /// - Task RecordFailure(string recurringPaymentId, string providerReference, - string cycleReference, string reason); + Task RecordFailure(string recurringPaymentId, string? providerReference, + string cycleReference, string? reason); /// /// Cancels a recurring payment the provider reports as ended at the gateway, under the same lock. Nothing is /// recorded for an unknown recurring payment, another provider reference than the one the recurring payment /// runs on, or one that is Cancelled or Completed. The first reported reference is recorded /// - Task RecordEnded(string recurringPaymentId, string providerReference); + Task RecordEnded(string recurringPaymentId, string? providerReference); /// /// Records the gateway's reference as soon as the provider learns it (at checkout), under the same lock, so a /// cancel made before the first paid cycle stops the gateway. A reference recorded already is kept: the /// outcome is Duplicate for the same one and OtherReference for another /// - Task RecordProviderReference(string recurringPaymentId, string providerReference); + Task RecordProviderReference(string recurringPaymentId, string? providerReference); /// /// Cancels a recurring payment, writing it under the same lock on a fresh read. Unless it is Pending without a @@ -60,12 +60,12 @@ Task Cancel(string recurringPaymentId, string canc /// /// Gets a recurring payment /// - Task GetRecurringPaymentById(string id); + Task GetRecurringPaymentById(string id); /// /// Gets the recurring payment of the order the customer placed; null when the order is not recurring /// - Task GetRecurringPaymentByInitialOrderId(string initialOrderId); + Task GetRecurringPaymentByInitialOrderId(string initialOrderId); /// /// Gets a customer's recurring payments in a store, newest first; nothing for an empty customer or store diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartService.cs index 36d27a8d8..d6a989d8d 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartService.cs @@ -33,7 +33,7 @@ Task> GetShoppingCart(Customer customer, string? storeId /// Rental start date /// Rental end date /// Found shopping cart item - Task FindShoppingCartItem(IList shoppingCart, + Task FindShoppingCartItem(IList shoppingCart, ShoppingCartType shoppingCartType, string productId, string? warehouseId = null, @@ -62,14 +62,14 @@ Task FindShoppingCartItem(IList shoppingCart /// Duration for reservation /// ShoppingCartValidatorOptions /// (warnings, shoppingCartItem) - Task<(IList warnings, ShoppingCartItem shoppingCartItem)> AddToCart(Customer customer, Language language, - string productId, ShoppingCartType shoppingCartType, string storeId, string? warehouseId = null, + Task<(IList warnings, ShoppingCartItem? shoppingCartItem)> AddToCart(Customer customer, Language language, + string? productId, ShoppingCartType shoppingCartType, string? storeId, string? warehouseId = null, IList? attributes = null, double? customerEnteredPrice = null, DateTime? rentalStartDate = null, DateTime? rentalEndDate = null, int quantity = 1, - bool automaticallyAddRequiredProductsIfEnabled = true, string reservationId = "", string parameter = "", - string duration = "", + bool automaticallyAddRequiredProductsIfEnabled = true, string? reservationId = "", string? parameter = "", + string? duration = "", ShoppingCartValidatorOptions? validator = null); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartValidator.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartValidator.cs index 8e6b3df2a..960bfef01 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartValidator.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IShoppingCartValidator.cs @@ -117,7 +117,7 @@ Task> GetInventoryProductWarnings(Customer customer, Product produ /// Warnings Task> CheckCommonWarnings(Customer customer, IList currentCart, Product product, ShoppingCartType shoppingCartType, DateTime? rentalStartDate, DateTime? rentalEndDate, int quantity, - string reservationId, Language language); + string? reservationId, Language language); /// /// Validates required products (products which require some other products to be added to the cart) @@ -130,5 +130,5 @@ Task> CheckCommonWarnings(Customer customer, IListWarnings Task> GetRequiredProductWarnings(Customer customer, ShoppingCartItem shoppingCartItem, Product product, - string storeId, Language language); + string? storeId, Language language); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs index dff03e661..6bb9173ac 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentService.cs @@ -26,7 +26,7 @@ Task> LoadActivePaymentMethods(Customer? customer = null /// /// System name /// Found payment provider - IPaymentProvider LoadPaymentMethodBySystemName(string systemName); + IPaymentProvider? LoadPaymentMethodBySystemName(string? systemName); /// /// Load all payment providers @@ -103,14 +103,14 @@ Task> LoadAllPaymentMethods(Customer? customer = null, s /// Shopping cart /// Payment method system name /// Additional handling fee - Task GetAdditionalHandlingFee(IList cart, string paymentMethodSystemName); + Task GetAdditionalHandlingFee(IList cart, string? paymentMethodSystemName); /// /// Gets a value indicating whether capture is supported by payment method /// /// Payment method system name /// A value indicating whether capture is supported - Task SupportCapture(string paymentMethodSystemName); + Task SupportCapture(string? paymentMethodSystemName); /// /// Captures payment @@ -124,14 +124,14 @@ Task> LoadAllPaymentMethods(Customer? customer = null, s /// /// Payment method system name /// A value indicating whether partial refund is supported - Task SupportPartiallyRefund(string paymentMethodSystemName); + Task SupportPartiallyRefund(string? paymentMethodSystemName); /// /// Gets a value indicating whether refund is supported by payment method /// /// Payment method system name /// A value indicating whether refund is supported - Task SupportRefund(string paymentMethodSystemName); + Task SupportRefund(string? paymentMethodSystemName); /// /// Refunds a payment @@ -145,7 +145,7 @@ Task> LoadAllPaymentMethods(Customer? customer = null, s /// /// Payment method system name /// A value indicating whether void is supported - Task SupportVoid(string paymentMethodSystemName); + Task SupportVoid(string? paymentMethodSystemName); /// /// Gets a value indicating whether recurring payments are supported by payment method diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentTransactionHistoryService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentTransactionHistoryService.cs index 81f4b0d8b..d2b864434 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentTransactionHistoryService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentTransactionHistoryService.cs @@ -19,8 +19,8 @@ public interface IPaymentTransactionHistoryService /// A staff e-mail or a payment method system name /// The bank transfer title, receipt or gateway number the money can be matched with /// Anything else the staff want to keep with it - Task Record(PaymentTransaction paymentTransaction, Order order, - PaymentTransactionEntryType entryType, double amount, string recordedBy, string? reference = null, + Task Record(PaymentTransaction paymentTransaction, Order? order, + PaymentTransactionEntryType entryType, double amount, string? recordedBy, string? reference = null, string? note = null); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentTransactionService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentTransactionService.cs index d35d63a52..d53f875ad 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentTransactionService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Payments/IPaymentTransactionService.cs @@ -29,7 +29,7 @@ public interface IPaymentTransactionService /// /// The identifier /// PaymentTransaction - Task GetById(string id); + Task GetById(string id); /// /// Gets an payment transactions for order Ident @@ -43,7 +43,7 @@ public interface IPaymentTransactionService /// /// The order guid /// PaymentTransaction - Task GetOrderByGuid(Guid orderGuid); + Task GetOrderByGuid(Guid orderGuid); /// /// Get an payment transactions by authorization transaction ID and payment method system name diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IDeliveryDateService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IDeliveryDateService.cs index 94e6162d0..fb9946b0d 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IDeliveryDateService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IDeliveryDateService.cs @@ -10,7 +10,7 @@ public interface IDeliveryDateService /// /// The delivery date identifier /// Delivery date - Task GetDeliveryDateById(string deliveryDateId); + Task GetDeliveryDateById(string deliveryDateId); /// /// Gets all delivery dates diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IPickupPointService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IPickupPointService.cs index 1d1aadea9..3860dc3e3 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IPickupPointService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IPickupPointService.cs @@ -10,7 +10,7 @@ public interface IPickupPointService /// /// The pickup point identifier /// PickupPoint - Task GetPickupPointById(string pickupPointId); + Task GetPickupPointById(string? pickupPointId); /// /// Gets all pickup points @@ -25,7 +25,7 @@ public interface IPickupPointService /// Gets active pickup points /// /// PickupPoints - Task> LoadActivePickupPoints(string storeId = ""); + Task> LoadActivePickupPoints(string? storeId = ""); /// /// Inserts a pickupPoint diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IReturnShippingProvider.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IReturnShippingProvider.cs index a752cc07d..f21b8ceeb 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IReturnShippingProvider.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IReturnShippingProvider.cs @@ -52,5 +52,5 @@ Task ValidateForm(ReturnShippingRequest request, /// /// Gets a shipment tracker; null when the provider tracks nothing /// - IShipmentTracker ShipmentTracker { get; } + IShipmentTracker? ShipmentTracker { get; } } diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IReturnShippingService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IReturnShippingService.cs index 1ad8e794d..6dd04bba5 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IReturnShippingService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IReturnShippingService.cs @@ -17,7 +17,7 @@ public interface IReturnShippingService /// /// Loads a provider by system name /// - IReturnShippingProvider LoadProviderBySystemName(string systemName); + IReturnShippingProvider? LoadProviderBySystemName(string? systemName); /// /// Loads the providers allowed in the store and for the customer, active or not, by priority @@ -34,10 +34,10 @@ public interface IReturnShippingService /// Validates the choice for every vendor of the submitted items; the keys of ByVendor are those of the returns /// a submit creates /// - Task Resolve(MerchandiseReturnSubmitRequest request, ReturnShippingChoice choice); + Task Resolve(MerchandiseReturnSubmitRequest request, ReturnShippingChoice? choice); /// /// Gets the address the items of a vendor (empty for the store) are sent back to /// - Task
GetReturnAddress(string storeId, string vendorId); + Task GetReturnAddress(string storeId, string vendorId); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShipmentService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShipmentService.cs index f04f341c0..79c619761 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShipmentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShipmentService.cs @@ -50,7 +50,7 @@ Task> GetAllShipments(string storeId = "", string vendorId ///
/// Shipment identifier /// Shipment - Task GetShipmentById(string shipmentId); + Task GetShipmentById(string shipmentId); /// /// Inserts a shipment @@ -97,7 +97,7 @@ Task> GetAllShipments(string storeId = "", string vendorId /// /// Shipment note identifier /// ShipmentNote - Task GetShipmentNote(string shipmentNoteId); + Task GetShipmentNote(string shipmentNoteId); #endregion } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingMethodService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingMethodService.cs index c571bb9ff..74cbda998 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingMethodService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingMethodService.cs @@ -10,7 +10,7 @@ public interface IShippingMethodService ///
/// The shipping method identifier /// Shipping method - Task GetShippingMethodById(string shippingMethodId); + Task GetShippingMethodById(string shippingMethodId); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingService.cs index 37e0c7d9d..55653bda8 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IShippingService.cs @@ -19,14 +19,14 @@ public interface IShippingService /// Cart /// Shipping rate methods Task> LoadActiveShippingRateCalculationProviders(Customer? customer = null, - string storeId = "", IList? cart = null); + string? storeId = "", IList? cart = null); /// /// Load Shipping rate provider by system name /// /// System name /// Found Shipping rate provider - IShippingRateCalculationProvider LoadShippingRateCalculationProviderBySystemName(string systemName); + IShippingRateCalculationProvider? LoadShippingRateCalculationProviderBySystemName(string systemName); /// /// Load all Shipping rate providers @@ -35,7 +35,7 @@ Task> LoadActiveShippingRateCalculationP /// Store ident /// Shipping rate providers IList LoadAllShippingRateCalculationProviders(Customer? customer = null, - string storeId = ""); + string? storeId = ""); /// /// Create shipment packages (requests) from shopping cart @@ -46,7 +46,7 @@ IList LoadAllShippingRateCalculationProviders( /// Store /// Shipment packages Task CreateShippingOptionRequests(Customer customer, - IList cart, Address shippingAddress, Store store); + IList cart, Address? shippingAddress, Store? store); /// /// Gets available shipping options diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IWarehouseLocationService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IWarehouseLocationService.cs index eae81669a..8df6eac82 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IWarehouseLocationService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IWarehouseLocationService.cs @@ -8,7 +8,7 @@ namespace Grand.Business.Core.Interfaces.Checkout.Shipping; /// public interface IWarehouseLocationService { - Task GetLocationById(string id); + Task GetLocationById(string id); /// /// The locations of the warehouses by display order and code diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IWarehouseService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IWarehouseService.cs index a47591d94..9059b0860 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IWarehouseService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Shipping/IWarehouseService.cs @@ -10,7 +10,7 @@ public interface IWarehouseService /// /// The warehouse identifier /// Warehouse - Task GetWarehouseById(string warehouseId); + Task GetWarehouseById(string warehouseId); /// /// Gets all warehouses diff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IBlogService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IBlogService.cs index e3853807d..cacd8594a 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Cms/IBlogService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IBlogService.cs @@ -13,7 +13,7 @@ public interface IBlogService /// /// Blog post identifier /// Blog post - Task GetBlogPostById(string blogPostId); + Task GetBlogPostById(string blogPostId); /// /// Gets all blog posts @@ -85,7 +85,7 @@ Task> GetAllBlogPostsByTag(string storeId, /// /// Blog comment identifier /// Blog comment - Task GetBlogCommentById(string blogCommentId); + Task GetBlogCommentById(string blogCommentId); Task> GetBlogCommentsByBlogPostId(string blogPostId); @@ -102,7 +102,7 @@ Task> GetAllBlogPostsByTag(string storeId, /// /// Blog category id /// - Task GetBlogCategoryById(string blogCategoryId); + Task GetBlogCategoryById(string blogCategoryId); /// /// Get categories by post id @@ -116,7 +116,7 @@ Task> GetAllBlogPostsByTag(string storeId, /// /// Blog category se name /// - Task GetBlogCategoryBySeName(string blogCategorySeName); + Task GetBlogCategoryBySeName(string blogCategorySeName); /// /// Get all blog categories @@ -147,7 +147,7 @@ Task> GetAllBlogPostsByTag(string storeId, /// /// id /// Blog product - Task GetBlogProductById(string id); + Task GetBlogProductById(string id); /// /// Insert an blog product diff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IKnowledgebaseService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IKnowledgebaseService.cs index 40585cb5b..a9363eb2e 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Cms/IKnowledgebaseService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IKnowledgebaseService.cs @@ -11,7 +11,7 @@ public interface IKnowledgebaseService /// /// /// knowledge base category - Task GetKnowledgebaseCategory(string id); + Task GetKnowledgebaseCategory(string id); /// /// Gets public knowledge base category @@ -19,7 +19,7 @@ public interface IKnowledgebaseService /// /// Whose view: the customer's groups and the store limit the result /// knowledge base category - Task GetPublicKnowledgebaseCategory(string id, CatalogAccess access); + Task GetPublicKnowledgebaseCategory(string id, CatalogAccess access); /// /// Gets knowledge base categories @@ -57,7 +57,7 @@ public interface IKnowledgebaseService /// /// /// knowledge base article - Task GetKnowledgebaseArticle(string id); + Task GetKnowledgebaseArticle(string id); /// /// Gets public knowledge base article @@ -65,7 +65,7 @@ public interface IKnowledgebaseService /// /// Whose view: the customer's groups and the store limit the result /// knowledge base article - Task GetPublicKnowledgebaseArticle(string id, CatalogAccess access); + Task GetPublicKnowledgebaseArticle(string id, CatalogAccess access); /// /// Gets every knowledge base article, unpublished and group- or store-limited ones included diff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/INewsService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/INewsService.cs index cd70a511c..a61fb06b5 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Cms/INewsService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Cms/INewsService.cs @@ -14,7 +14,7 @@ public interface INewsService /// /// The news identifier /// News - Task GetNewsById(string newsId); + Task GetNewsById(string newsId); /// /// Gets all news diff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IPageLayoutService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IPageLayoutService.cs index 7f4b6edb1..c09ffbb35 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Cms/IPageLayoutService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IPageLayoutService.cs @@ -18,7 +18,7 @@ public interface IPageLayoutService /// /// Page layout identifier /// Page layout - Task GetPageLayoutById(string pageLayoutId); + Task GetPageLayoutById(string pageLayoutId); /// /// Inserts page layout diff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IPageService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IPageService.cs index 36e04e0fa..aa14146f8 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Cms/IPageService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IPageService.cs @@ -13,7 +13,7 @@ public interface IPageService /// /// The page identifier /// Page - Task GetPageById(string pageId); + Task GetPageById(string pageId); /// /// Gets a page @@ -21,7 +21,7 @@ public interface IPageService /// The page system name /// Store identifier; pass 0 to ignore filtering by store and load the first one /// Page - Task GetPageBySystemName(string systemName, string storeId); + Task GetPageBySystemName(string systemName, string storeId); /// /// Gets all pages diff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IRobotsTxtService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IRobotsTxtService.cs index a77701aab..9161c791e 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Cms/IRobotsTxtService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IRobotsTxtService.cs @@ -9,7 +9,7 @@ public interface IRobotsTxtService /// /// Store identifier /// RobotsTxt - Task GetRobotsTxt(string storeId = ""); + Task GetRobotsTxt(string storeId = ""); /// /// Insert a RobotsTxt diff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IWidgetService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IWidgetService.cs index 6b69ffc07..c1c49ff13 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Cms/IWidgetService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IWidgetService.cs @@ -30,7 +30,7 @@ Task> LoadActiveWidgetsByWidgetZone(string widgetZone, st /// /// System name /// Found widget - IWidgetProvider LoadWidgetBySystemName(string systemName); + IWidgetProvider? LoadWidgetBySystemName(string systemName); /// /// Load all widgets diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Addresses/IAddressAttributeParser.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Addresses/IAddressAttributeParser.cs index 27a1f0415..bd5513a58 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Addresses/IAddressAttributeParser.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Addresses/IAddressAttributeParser.cs @@ -56,8 +56,8 @@ IList AddAddressAttribute(IList customAttribut /// A value indicating whether to encode (HTML) values /// Attributes Task FormatAttributes( - Language language, - IList customAttributes, + Language? language, + IList? customAttributes, string separator = "
", bool htmlEncode = true); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Addresses/IAddressAttributeService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Addresses/IAddressAttributeService.cs index 4dfc6ed12..5c3b714f2 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Addresses/IAddressAttributeService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Addresses/IAddressAttributeService.cs @@ -25,7 +25,7 @@ public interface IAddressAttributeService ///
/// Address attribute identifier /// Address attribute - Task GetAddressAttributeById(string addressAttributeId); + Task GetAddressAttributeById(string? addressAttributeId); /// /// Inserts an address attribute diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Audit/IAuditService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Audit/IAuditService.cs index 5182a792a..260b35551 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Audit/IAuditService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Audit/IAuditService.cs @@ -14,7 +14,7 @@ public interface IAuditService /// Task> GetEntries(AuditEntrySearch search, int pageIndex = 0, int pageSize = int.MaxValue); - Task GetById(string id); + Task GetById(string id); /// /// Yields every entry matching the search, newest first, a page at a time (for exports) diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Configuration/ISettingService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Configuration/ISettingService.cs index e63c92ca5..29962fb48 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Configuration/ISettingService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Configuration/ISettingService.cs @@ -31,7 +31,7 @@ public interface ISettingService /// /// Setting ident /// Setting - Task GetSettingById(string settingId); + Task GetSettingById(string settingId); /// /// Get setting value by key @@ -63,7 +63,7 @@ public interface ISettingService /// /// Type /// Store identifier for which settings should be loaded - Task LoadSetting(string storeId = "") where T : ISettings, new(); + Task LoadSetting(string? storeId = "") where T : ISettings, new(); /// /// Reads the settings of a store, and the global ones, into the cache, so that settings resolved from the container need no query @@ -77,7 +77,7 @@ public interface ISettingService /// /// /// - ISettings LoadSetting(Type type, string storeId = ""); + ISettings LoadSetting(Type type, string? storeId = ""); /// /// Save settings object diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/ICountryService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/ICountryService.cs index d9ab048a5..889799b35 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/ICountryService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/ICountryService.cs @@ -41,7 +41,7 @@ Task> GetAllCountriesForShipping(string languageId = "", string s /// /// Country identifier /// Country - Task GetCountryById(string countryId); + Task GetCountryById(string? countryId); /// /// Get countries by identifiers @@ -55,14 +55,14 @@ Task> GetAllCountriesForShipping(string languageId = "", string s /// /// Country two letter ISO code /// Country - Task GetCountryByTwoLetterIsoCode(string twoLetterIsoCode); + Task GetCountryByTwoLetterIsoCode(string twoLetterIsoCode); /// /// Gets a country by three letter ISO code /// /// Country three letter ISO code /// Country - Task GetCountryByThreeLetterIsoCode(string threeLetterIsoCode); + Task GetCountryByThreeLetterIsoCode(string threeLetterIsoCode); /// /// Inserts a country @@ -90,7 +90,7 @@ Task> GetAllCountriesForShipping(string languageId = "", string s /// Country identifier /// Language identifier. /// States - Task> GetStateProvincesByCountryId(string countryId, string languageId = ""); + Task?> GetStateProvincesByCountryId(string countryId, string languageId = ""); /// /// Inserts a state/province diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/ICurrencyService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/ICurrencyService.cs index e3454264b..6da04a69d 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/ICurrencyService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/ICurrencyService.cs @@ -12,26 +12,26 @@ public interface ICurrencyService /// /// Currency identifier /// Currency - Task GetCurrencyById(string currencyId); + Task GetCurrencyById(string? currencyId); /// /// Gets primary store currency /// /// Currency - Task GetPrimaryStoreCurrency(); + Task GetPrimaryStoreCurrency(); /// /// Gets primary exchange currency /// /// Currency - Task GetPrimaryExchangeRateCurrency(); + Task GetPrimaryExchangeRateCurrency(); /// /// Gets a currency by code /// /// Currency code /// Currency - Task GetCurrencyByCode(string currencyCode); + Task GetCurrencyByCode(string? currencyCode); /// /// Gets all currencies @@ -106,5 +106,5 @@ public interface ICurrencyService /// Amount /// Target currency code /// Converted value - Task ConvertFromPrimaryStoreCurrency(double amount, Currency targetCurrencyCode); + Task ConvertFromPrimaryStoreCurrency(double amount, Currency? targetCurrencyCode); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IExchangeRateService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IExchangeRateService.cs index 65468ff07..4f6234004 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IExchangeRateService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IExchangeRateService.cs @@ -18,14 +18,14 @@ Task> GetCurrencyLiveRates(string exchangeRateCurrencyCode, /// Load active exchange rate provider /// /// Active exchange rate provider - IExchangeRateProvider LoadActiveExchangeRateProvider(); + IExchangeRateProvider? LoadActiveExchangeRateProvider(); /// /// Load exchange rate provider by system name /// /// System name /// Found exchange rate provider - IExchangeRateProvider LoadExchangeRateProviderBySystemName(string systemName); + IExchangeRateProvider? LoadExchangeRateProviderBySystemName(string? systemName); /// /// Load all exchange rate providers diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IGroupService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IGroupService.cs index c527bc52f..d2bde1e21 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IGroupService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IGroupService.cs @@ -91,14 +91,14 @@ Task IsInCustomerGroup(Customer customer, /// /// Customer group identifier /// Customer group - Task GetCustomerGroupById(string customerGroupId); + Task GetCustomerGroupById(string customerGroupId); /// /// Gets a customer group /// /// Customer group system name /// Customer group - Task GetCustomerGroupBySystemName(string systemName); + Task GetCustomerGroupBySystemName(string systemName); /// /// Gets all customer groups diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Localization/ILanguageService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Localization/ILanguageService.cs index a10744904..519fed131 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Localization/ILanguageService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Localization/ILanguageService.cs @@ -20,14 +20,14 @@ public interface ILanguageService /// /// Language identifier /// Language - Task GetLanguageById(string languageId); + Task GetLanguageById(string? languageId); /// /// Gets a language /// /// Language code /// Language - Task GetLanguageByCode(string languageCode); + Task GetLanguageByCode(string languageCode); /// /// Inserts a language diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Localization/ITranslationService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Localization/ITranslationService.cs index c6fdb0f57..167fe8df9 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Localization/ITranslationService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Localization/ITranslationService.cs @@ -12,7 +12,7 @@ public interface ITranslationService /// /// Translate resource identifier /// Translate resource - Task GetTranslateResourceById(string translateResourceId); + Task GetTranslateResourceById(string translateResourceId); /// /// Gets a translate resource @@ -20,7 +20,7 @@ public interface ITranslationService /// A string representing a resource name /// Language identifier /// Translate resource - Task GetTranslateResourceByName(string name, string languageId); + Task GetTranslateResourceByName(string name, string languageId); /// /// Gets all translate resources by language identifier @@ -58,7 +58,7 @@ public interface ITranslationService /// found and default value is set to empty string /// /// A string representing the requested resource string. - string GetResource(string resourceKey, string languageId, string defaultValue = "", + string GetResource(string resourceKey, string? languageId, string defaultValue = "", bool returnEmptyIfNotFound = false); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Pdf/IPdfService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Pdf/IPdfService.cs index 67dc7855c..97f6204c0 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Pdf/IPdfService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Pdf/IPdfService.cs @@ -18,7 +18,7 @@ public interface IPdfService /// be printed /// /// A download ident - Task SaveOrderToBinary(Order order, string languageId, string vendorId = ""); + Task SaveOrderToBinary(Order order, string? languageId, string vendorId = ""); /// /// Print orders to PDF @@ -31,7 +31,7 @@ public interface IPdfService /// be printed /// /// Stops the work before the PDF is generated - Task PrintOrdersToPdf(Stream stream, IList orders, string languageId = "", string vendorId = "", + Task PrintOrdersToPdf(Stream stream, IList orders, string? languageId = "", string vendorId = "", CancellationToken cancellationToken = default); /// @@ -41,7 +41,7 @@ Task PrintOrdersToPdf(Stream stream, IList orders, string languageId = "" /// Shipments /// Language identifier; 0 to use a language used when placing an order /// Stops the work before the PDF is generated - Task PrintPackagingSlipsToPdf(Stream stream, IList shipments, string languageId = "", + Task PrintPackagingSlipsToPdf(Stream stream, IList shipments, string? languageId = "", CancellationToken cancellationToken = default); /// @@ -54,5 +54,5 @@ Task PrintPackagingSlipsToPdf(Stream stream, IList shipments, string l /// Language identifier; empty to use the language the order was placed in /// Stops the work before the PDF is generated Task PrintMerchandiseReturnToPdf(Stream stream, MerchandiseReturn merchandiseReturn, Order order, - string languageId = "", CancellationToken cancellationToken = default); + string? languageId = "", CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Security/IAclService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Security/IAclService.cs index e5b55fbbf..7141d81df 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Security/IAclService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Security/IAclService.cs @@ -26,5 +26,5 @@ public interface IAclService /// Entity /// Store identifier /// true - authorized; otherwise, false - bool Authorize(T entity, string storeId) where T : BaseEntity, IStoreLinkEntity; + bool Authorize(T entity, string? storeId) where T : BaseEntity, IStoreLinkEntity; } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Security/IEncryptionService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Security/IEncryptionService.cs index a5888d3d0..b4f1a9133 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Security/IEncryptionService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Security/IEncryptionService.cs @@ -41,14 +41,14 @@ string CreatePasswordHash(string password, string saltKey, /// Stored salt (Customer.PasswordSalt); ignored for PBKDF2 /// Hash algorithm used by legacy SHA hashes (global setting) /// True when the password matches - bool VerifyPassword(string enteredPassword, PasswordFormat passwordFormat, string storedPassword, - string storedSalt, HashedPasswordFormat legacyHashedFormat); + bool VerifyPassword(string enteredPassword, PasswordFormat passwordFormat, string? storedPassword, + string? storedSalt, HashedPasswordFormat legacyHashedFormat); /// /// Indicates whether a stored credential uses a weak/legacy format (Clear, Encrypted or a non-PBKDF2 hash) /// and should be transparently re-hashed to the modern format after the next successful authentication. /// - bool PasswordHashNeedsUpgrade(PasswordFormat passwordFormat, string storedPassword); + bool PasswordHashNeedsUpgrade(PasswordFormat passwordFormat, string? storedPassword); /// /// Returns true when the stored value is the modern self-describing (PBKDF2) hash produced by @@ -74,5 +74,5 @@ bool VerifyPassword(string enteredPassword, PasswordFormat passwordFormat, strin /// Text to decrypt /// Encryption private key /// Decrypted text - string DecryptText(string cipherText, string encryptionPrivateKey); + string? DecryptText(string cipherText, string encryptionPrivateKey); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Security/IPermissionService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Security/IPermissionService.cs index 508b66d16..26b939f4c 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Security/IPermissionService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Security/IPermissionService.cs @@ -13,14 +13,14 @@ public interface IPermissionService /// /// Permission identifier /// Permission - Task GetPermissionById(string permissionId); + Task GetPermissionById(string permissionId); /// /// Gets a permission /// /// Permission system name /// Permission - Task GetPermissionBySystemName(string systemName); + Task GetPermissionBySystemName(string systemName); /// /// Gets all permissions diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Seo/ISeNameService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Seo/ISeNameService.cs index 9bbf66ad6..24bfe7f2b 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Seo/ISeNameService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Seo/ISeNameService.cs @@ -8,7 +8,7 @@ namespace Grand.Business.Core.Interfaces.Common.Seo; public interface ISeNameService { - Task ValidateSeName(T entity, string seName, string name, bool ensureNotEmpty) where T : BaseEntity, ISlugEntity; + Task ValidateSeName(T entity, string? seName, string? name, bool ensureNotEmpty) where T : BaseEntity, ISlugEntity; Task> TranslationSeNameProperties(IList list, TE entity, Expression> keySelector) where T : ILocalizedModelLocal where TE : BaseEntity, ISlugEntity; Task SaveSeName(T entity) where T : BaseEntity, ISlugEntity; diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Seo/ISlugService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Seo/ISlugService.cs index 6272aba36..0c32d044c 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Seo/ISlugService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Seo/ISlugService.cs @@ -13,7 +13,7 @@ public interface ISlugService /// /// URL entity identifier /// URL Entity - Task GetEntityUrlById(string urlEntityId); + Task GetEntityUrlById(string urlEntityId); /// /// Inserts an URL Entity @@ -38,14 +38,14 @@ public interface ISlugService /// /// Slug /// Found URL Entity - Task GetBySlug(string slug); + Task GetBySlug(string? slug); /// /// Find URL Entity (cached version). /// /// Slug /// Found URL Entity - Task GetBySlugCached(string slug); + Task GetBySlugCached(string slug); /// /// Gets all URL Entity @@ -74,5 +74,5 @@ Task> GetAllEntityUrl(string slug = "", bool? active = nul /// Entity /// Slug /// Language ID - Task SaveSlug(T entity, string slug, string languageId) where T : BaseEntity, ISlugEntity; + Task SaveSlug(T entity, string? slug, string languageId) where T : BaseEntity, ISlugEntity; } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Stores/IStoreService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Stores/IStoreService.cs index bfc2da2ac..4a0849706 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Stores/IStoreService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Stores/IStoreService.cs @@ -20,7 +20,7 @@ public interface IStoreService /// /// Store identifier /// Store - Task GetStoreById(string storeId); + Task GetStoreById(string? storeId); /// /// Inserts a store diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/IAffiliateService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/IAffiliateService.cs index 8642bec76..168fb3a73 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Customers/IAffiliateService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Customers/IAffiliateService.cs @@ -13,14 +13,14 @@ public interface IAffiliateService /// /// Affiliate identifier /// Affiliate - Task GetAffiliateById(string affiliateId); + Task GetAffiliateById(string affiliateId); /// /// Gets an affiliate by url name /// /// Friendly url name /// Affiliate - Task GetAffiliateByFriendlyUrlName(string friendlyUrlName); + Task GetAffiliateByFriendlyUrlName(string friendlyUrlName); /// /// Gets all affiliates diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerAttributeService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerAttributeService.cs index c94fd1ef3..e72821112 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerAttributeService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerAttributeService.cs @@ -25,7 +25,7 @@ public interface ICustomerAttributeService /// /// Customer attribute identifier /// Customer attribute - Task GetCustomerAttributeById(string customerAttributeId); + Task GetCustomerAttributeById(string? customerAttributeId); /// /// Inserts a customer attribute diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerNoteService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerNoteService.cs index 044d68425..f13854350 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerNoteService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerNoteService.cs @@ -11,7 +11,7 @@ public interface ICustomerNoteService /// /// Note identifier /// CustomerNote - Task GetCustomerNote(string id); + Task GetCustomerNote(string id); /// /// Insert an customer note diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs index 319bad2c7..065c4bd27 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs @@ -90,7 +90,7 @@ Task GetCountOnlineShoppingCart(DateTime lastActivityFromUtc, string storeI /// /// Customer identifier /// A customer - Task GetCustomerById(string customerId); + Task GetCustomerById(string? customerId); /// /// Get customers by identifiers @@ -104,7 +104,7 @@ Task GetCountOnlineShoppingCart(DateTime lastActivityFromUtc, string storeI /// /// Customer GUID /// A customer - Task GetCustomerByGuid(Guid customerGuid); + Task GetCustomerByGuid(Guid customerGuid); /// /// Get customer by email. @@ -114,14 +114,14 @@ Task GetCountOnlineShoppingCart(DateTime lastActivityFromUtc, string storeI /// Email /// Store identifier (optional) /// Customer - Task GetCustomerByEmail(string email, string storeId = ""); + Task GetCustomerByEmail(string email, string storeId = ""); /// /// Get customer by system group /// /// System name /// Customer - Task GetCustomerBySystemName(string systemName); + Task GetCustomerBySystemName(string systemName); /// /// Get customer by username. @@ -131,7 +131,7 @@ Task GetCountOnlineShoppingCart(DateTime lastActivityFromUtc, string storeI /// Username /// Store identifier (optional) /// Customer - Task GetCustomerByUsername(string username, string storeId = ""); + Task GetCustomerByUsername(string username, string storeId = ""); /// /// Insert a guest customer @@ -160,7 +160,7 @@ Task GetCountOnlineShoppingCart(DateTime lastActivityFromUtc, string storeI /// /// /// - Task UpdateUserField(Customer customer, string key, TPropType value, string storeId = ""); + Task UpdateUserField(Customer customer, string key, TPropType value, string? storeId = ""); /// /// Delete a customer @@ -184,7 +184,7 @@ Task UpdateCustomerField(Customer customer, /// Customer ident /// /// - Task UpdateCustomerField(string customerId, + Task UpdateCustomerField(string? customerId, Expression> expression, T value); /// @@ -233,7 +233,7 @@ Task UpdateCustomerField(string customerId, /// A value indicating whether to clear "Use loyalty points" flag /// A value indicating whether to clear selected shipping method /// A value indicating whether to clear selected payment method - Task ResetCheckoutData(Customer customer, string storeId, + Task ResetCheckoutData(Customer customer, string? storeId, bool clearCouponCodes = false, bool clearCheckoutAttributes = false, bool clearLoyaltyPoints = true, bool clearShipping = true, bool clearPayment = true); diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ISalesEmployeeService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ISalesEmployeeService.cs index b8a585adf..512d4db9b 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Customers/ISalesEmployeeService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ISalesEmployeeService.cs @@ -9,7 +9,7 @@ public interface ISalesEmployeeService /// /// The sales employee identifier /// SalesEmployee - Task GetSalesEmployeeById(string salesEmployeeId); + Task GetSalesEmployeeById(string salesEmployeeId); /// /// Gets all sales employees diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/IUserApiService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/IUserApiService.cs index df4a9cea8..59ec4f3d1 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Customers/IUserApiService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Customers/IUserApiService.cs @@ -10,13 +10,13 @@ public interface IUserApiService /// Get user api by id /// /// id - Task GetUserById(string id); + Task GetUserById(string id); /// /// Get user api by email /// /// email - Task GetUserByEmail(string email); + Task GetUserByEmail(string email); /// /// Insert user api diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/IVendorService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/IVendorService.cs index dfca4ad35..a65a22534 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Customers/IVendorService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Customers/IVendorService.cs @@ -13,7 +13,7 @@ public interface IVendorService /// /// Vendor identifier /// Vendor - Task GetVendorById(string vendorId); + Task GetVendorById(string vendorId); /// /// Gets all vendors @@ -51,7 +51,7 @@ Task> GetAllVendors(string name = "", /// The vendor identifier /// The vendor note identifier /// Vendor note - Task GetVendorNoteById(string vendorId, string vendorNoteId); + Task GetVendorNoteById(string vendorId, string vendorNoteId); /// /// Insert a vendor note @@ -115,7 +115,7 @@ Task> GetAllVendorReviews(string customerId, bool? appr /// /// Vendor review identifier /// Vendor review - Task GetVendorReviewById(string vendorReviewId); + Task GetVendorReviewById(string vendorReviewId); /// /// Deletes a vendor review diff --git a/src/Business/Grand.Business.Core/Interfaces/ExportImport/IRowImport.cs b/src/Business/Grand.Business.Core/Interfaces/ExportImport/IRowImport.cs index 8c773fc6f..cd3303b52 100644 --- a/src/Business/Grand.Business.Core/Interfaces/ExportImport/IRowImport.cs +++ b/src/Business/Grand.Business.Core/Interfaces/ExportImport/IRowImport.cs @@ -16,7 +16,7 @@ public sealed record ImportRowResult(int Row, ImportRowStatus Status, string Id, public const string NotProcessedError = "Not processed: the batch time limit was reached; send these rows again."; /// A row the import did not reach because its cancellation token fired; nothing was written for it - public static ImportRowResult NotProcessed(int row, string id, string key) + public static ImportRowResult NotProcessed(int row, string? id, string key) { return new ImportRowResult(row, ImportRowStatus.Rejected, id ?? "", key, [NotProcessedError], []); } @@ -25,7 +25,7 @@ public static ImportRowResult NotProcessed(int row, string id, string key) "The row failed while it was being saved and may be partly written; the error is in the log. Send the row again."; /// A row that threw; the batch went on with the next row - public static ImportRowResult Failed(int row, string id, string key) + public static ImportRowResult Failed(int row, string? id, string key) { return new ImportRowResult(row, ImportRowStatus.Rejected, id ?? "", key, [FailedError], []); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Campaigns/ICampaignService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Campaigns/ICampaignService.cs index 2cb3d104b..2c63ad656 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Campaigns/ICampaignService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Campaigns/ICampaignService.cs @@ -37,7 +37,7 @@ public interface ICampaignService /// /// Campaign identifier /// Campaign - Task GetCampaignById(string campaignId); + Task GetCampaignById(string campaignId); /// /// Gets all campaigns diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactAttributeService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactAttributeService.cs index 66a0b8c26..92707a8c2 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactAttributeService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactAttributeService.cs @@ -28,7 +28,7 @@ public interface IContactAttributeService /// /// Contact attribute identifier /// Contact attribute - Task GetContactAttributeById(string contactAttributeId); + Task GetContactAttributeById(string? contactAttributeId); /// /// Inserts a Contact attribute diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactUsService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactUsService.cs index 91ecf944f..65d2741b6 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactUsService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Contacts/IContactUsService.cs @@ -40,7 +40,7 @@ Task> GetAllContactUs(DateTime? fromUtc = null, DateTime? /// /// ContactUs item identifier /// ContactUs item - Task GetContactUsById(string contactUsId); + Task GetContactUsById(string contactUsId); /// /// Inserts a contactus item diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseActionService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseActionService.cs index 45b8db5f2..03d2ec982 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseActionService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseActionService.cs @@ -4,8 +4,8 @@ namespace Grand.Business.Core.Interfaces.Marketing.Courses; public interface ICourseActionService { - Task GetById(string id); - Task GetCourseAction(string customerId, string lessonId); + Task GetById(string id); + Task GetCourseAction(string customerId, string lessonId); Task CustomerLessonCompleted(string customerId, string lessonId); Task Update(CourseAction courseAction); Task InsertAsync(CourseAction courseAction); diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseLessonService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseLessonService.cs index 81a8a7616..79030ac92 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseLessonService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseLessonService.cs @@ -4,7 +4,7 @@ namespace Grand.Business.Core.Interfaces.Marketing.Courses; public interface ICourseLessonService { - Task GetById(string id); + Task GetById(string id); Task> GetByCourseId(string courseId); Task Update(CourseLesson courseLesson); Task Insert(CourseLesson courseLesson); diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseLevelService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseLevelService.cs index 8f1eb79fb..8c61cae93 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseLevelService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseLevelService.cs @@ -4,7 +4,7 @@ namespace Grand.Business.Core.Interfaces.Marketing.Courses; public interface ICourseLevelService { - Task GetById(string id); + Task GetById(string id); Task> GetAll(); Task Update(CourseLevel courseLevel); Task Insert(CourseLevel courseLevel); diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseService.cs index 641ab598f..2074b8927 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseService.cs @@ -6,7 +6,7 @@ namespace Grand.Business.Core.Interfaces.Marketing.Courses; public interface ICourseService { - Task GetById(string id); + Task GetById(string id); Task> GetAll(int pageIndex = 0, int pageSize = int.MaxValue); Task> GetByCustomer(Customer customer, string storeId); Task Update(Course course); diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseSubjectService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseSubjectService.cs index 18c39651f..1dff40afa 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseSubjectService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Courses/ICourseSubjectService.cs @@ -4,7 +4,7 @@ namespace Grand.Business.Core.Interfaces.Marketing.Courses; public interface ICourseSubjectService { - Task GetById(string id); + Task GetById(string id); Task> GetByCourseId(string courseId); Task Update(CourseSubject courseSubject); Task Insert(CourseSubject courseSubject); diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Customers/ICustomerProductService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Customers/ICustomerProductService.cs index f272b0594..4792563e8 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Customers/ICustomerProductService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Customers/ICustomerProductService.cs @@ -15,7 +15,7 @@ public interface ICustomerProductService /// /// Identifier /// Customer product price - Task GetCustomerProductPriceById(string id); + Task GetCustomerProductPriceById(string id); /// /// Gets a price @@ -30,7 +30,7 @@ public interface ICustomerProductService /// /// Identifier /// Customer product - Task GetCustomerProduct(string id); + Task GetCustomerProduct(string id); /// /// Gets a customer product @@ -38,7 +38,7 @@ public interface ICustomerProductService /// Customer Identifier /// Product Identifier /// Customer product - Task GetCustomerProduct(string customerId, string productId); + Task GetCustomerProduct(string customerId, string productId); /// /// Inserts a customer product price diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Customers/ICustomerTagService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Customers/ICustomerTagService.cs index 53881c1e3..575ea3bcf 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Customers/ICustomerTagService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Customers/ICustomerTagService.cs @@ -32,14 +32,14 @@ Task> GetCustomersByTag(string customerTagId = "", int page /// /// Customer tag identifier /// Product tag - Task GetCustomerTagById(string customerTagId); + Task GetCustomerTagById(string customerTagId); /// /// Gets customer tag by name /// /// Customer tag name /// Customer tag - Task GetCustomerTagByName(string name); + Task GetCustomerTagByName(string name); /// /// Gets customer tags search by name @@ -90,14 +90,14 @@ Task> GetCustomersByTag(string customerTagId = "", int page /// Customer tag id /// Product id /// Customer tag product - Task GetCustomerTagProduct(string customerTagId, string productId); + Task GetCustomerTagProduct(string customerTagId, string productId); /// /// Gets customer tag product /// /// id /// Customer tag product - Task GetCustomerTagProductById(string id); + Task GetCustomerTagProductById(string id); /// /// Inserts a customer tag product diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Documents/IDocumentService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Documents/IDocumentService.cs index 8f0a6c0a0..280dd9432 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Documents/IDocumentService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Documents/IDocumentService.cs @@ -11,7 +11,7 @@ public interface IDocumentService /// /// document identifier /// Document - Task GetById(string id); + Task GetById(string id); /// /// Gets all documents diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Documents/IDocumentTypeService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Documents/IDocumentTypeService.cs index bd72f3e72..85c3b5a74 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Documents/IDocumentTypeService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Documents/IDocumentTypeService.cs @@ -9,7 +9,7 @@ public interface IDocumentTypeService /// /// document type identifier /// Document type - Task GetById(string id); + Task GetById(string id); /// /// Gets all document types diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.cs index 73e890174..6ddc7caec 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.cs @@ -37,14 +37,14 @@ Task DeleteNewsLetterSubscription(NewsLetterSubscription newsLetterSubscription, /// /// The newsletter subscription identifier /// NewsLetter subscription - Task GetNewsLetterSubscriptionById(string newsLetterSubscriptionId); + Task GetNewsLetterSubscriptionById(string newsLetterSubscriptionId); /// /// Gets a newsletter subscription by newsletter subscription GUID /// /// The newsletter subscription GUID /// NewsLetter subscription - Task GetNewsLetterSubscriptionByGuid(Guid newsLetterSubscriptionGuid); + Task GetNewsLetterSubscriptionByGuid(Guid newsLetterSubscriptionGuid); /// /// Gets a newsletter subscription by email and store ID @@ -52,7 +52,7 @@ Task DeleteNewsLetterSubscription(NewsLetterSubscription newsLetterSubscription, /// The newsletter subscription email /// Store identifier /// NewsLetter subscription - Task GetNewsLetterSubscriptionByEmailAndStoreId(string email, string storeId); + Task GetNewsLetterSubscriptionByEmailAndStoreId(string email, string storeId); /// @@ -60,7 +60,7 @@ Task DeleteNewsLetterSubscription(NewsLetterSubscription newsLetterSubscription, /// /// Customer identifier /// NewsLetter subscription - Task GetNewsLetterSubscriptionByCustomerId(string customerId); + Task GetNewsLetterSubscriptionByCustomerId(string customerId); /// /// Gets the newsletter subscription list diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsletterCategoryService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsletterCategoryService.cs index e9b3c61d6..1fd4113f9 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsletterCategoryService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsletterCategoryService.cs @@ -27,7 +27,7 @@ public interface INewsletterCategoryService /// /// newsletter category /// NewsletterCategory - Task GetNewsletterCategoryById(string id); + Task GetNewsletterCategoryById(string id); /// /// Gets all newsletter categories diff --git a/src/Business/Grand.Business.Core/Interfaces/Marketing/PushNotifications/IPushNotificationsService.cs b/src/Business/Grand.Business.Core/Interfaces/Marketing/PushNotifications/IPushNotificationsService.cs index 58c5f797a..1ada140ce 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Marketing/PushNotifications/IPushNotificationsService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Marketing/PushNotifications/IPushNotificationsService.cs @@ -21,7 +21,7 @@ public interface IPushNotificationsService /// Gets push receiver /// /// - Task GetPushReceiverByCustomerId(string customerId); + Task GetPushReceiverByCustomerId(string customerId); /// /// Gets all push receivers @@ -32,7 +32,7 @@ public interface IPushNotificationsService /// Gets all push receivers /// /// - Task GetPushReceiver(string id); + Task GetPushReceiver(string id); /// /// Gets number of customers that accepted push notifications permission popup diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/ICatalogMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/ICatalogMessageProviderService.cs index ee8a12694..832c7adb3 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/ICatalogMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/ICatalogMessageProviderService.cs @@ -21,7 +21,7 @@ public interface ICatalogMessageProviderService /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendProductEmailAFriendMessage(Customer customer, Store store, string languageId, + Task SendProductEmailAFriendMessage(Customer customer, Store store, string? languageId, Product product, string customerEmail, string friendsEmail, string personalMessage, DomainHost? host = null); /// @@ -37,7 +37,7 @@ Task SendProductEmailAFriendMessage(Customer customer, Store store, string /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendWishlistEmailAFriendMessage(Customer customer, Store store, string languageId, + Task SendWishlistEmailAFriendMessage(Customer customer, Store store, string? languageId, string customerEmail, string friendsEmail, string personalMessage, DomainHost? host = null); /// @@ -47,7 +47,7 @@ Task SendWishlistEmailAFriendMessage(Customer customer, Store store, string /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendProductQuestionMessage(Customer customer, Store store, string languageId, + Task SendProductQuestionMessage(Customer customer, Store store, string? languageId, Product product, string customerEmail, string fullName, string phone, string message, string ipaddress, DomainHost? host = null); @@ -62,7 +62,7 @@ Task SendProductQuestionMessage(Customer customer, Store store, string lang /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendProductReviewMessage(Product product, ProductReview productReview, Store store, string languageId, + Task SendProductReviewMessage(Product product, ProductReview productReview, Store store, string? languageId, DomainHost? host = null); /// @@ -71,13 +71,13 @@ Task SendProductReviewMessage(Product product, ProductReview productReview, /// Product /// Message language identifier /// Queued email identifier - Task SendQuantityBelowStoreOwnerMessage(Product product, string languageId); + Task SendQuantityBelowStoreOwnerMessage(Product product, string? languageId); /// /// Sends the store owner the batches of the store that became expiring or expired /// /// Queued email identifier; 0 without the message template - Task SendBatchesExpiringStoreOwnerMessage(Store store, IList batches, string languageId); + Task SendBatchesExpiringStoreOwnerMessage(Store store, IList batches, string? languageId); /// /// Sends a "quantity below" notification to a store owner @@ -87,7 +87,7 @@ Task SendProductReviewMessage(Product product, ProductReview productReview, /// Message language identifier /// Queued email identifier Task SendQuantityBelowStoreOwnerMessage(Product product, ProductAttributeCombination combination, - string languageId); + string? languageId); /// /// Sends a 'Back in stock' notification message to a customer @@ -98,7 +98,7 @@ Task SendQuantityBelowStoreOwnerMessage(Product product, ProductAttributeCo /// Message language identifier /// Queued email identifier Task SendBackInStockMessage(Customer customer, Product product, OutOfStockSubscription subscription, - string languageId); + string? languageId); /// /// Sends auction ended notification to a customer (winner) @@ -107,7 +107,7 @@ Task SendBackInStockMessage(Customer customer, Product product, OutOfStockS /// Message language identifier /// Bid /// Queued email identifier - Task SendAuctionWinEndedCustomerMessage(Product product, string languageId, Bid bid); + Task SendAuctionWinEndedCustomerMessage(Product product, string? languageId, Bid bid); /// /// Sends auction ended notification to a customer (loser) @@ -116,7 +116,7 @@ Task SendBackInStockMessage(Customer customer, Product product, OutOfStockS /// Message language identifier /// /// Queued email identifier - Task SendAuctionEndedLostCustomerMessage(Product product, string languageId, Bid bid); + Task SendAuctionEndedLostCustomerMessage(Product product, string? languageId, Bid bid); /// /// Sends auction ended notification to a customer (loser - bin) @@ -126,7 +126,7 @@ Task SendBackInStockMessage(Customer customer, Product product, OutOfStockS /// Message language identifier /// Store identifier /// Queued email identifier - Task SendAuctionEndedBinCustomerMessage(Product product, string customerId, string languageId, string storeId); + Task SendAuctionEndedBinCustomerMessage(Product product, string? customerId, string? languageId, string? storeId); /// /// Sends auction ended notification to a store owner @@ -135,7 +135,7 @@ Task SendBackInStockMessage(Customer customer, Product product, OutOfStockS /// Auction /// Bid /// Queued email identifier - Task SendAuctionEndedStoreOwnerMessage(Product product, string languageId, Bid bid); + Task SendAuctionEndedStoreOwnerMessage(Product product, string? languageId, Bid bid); /// /// Send outbid notification to a customer @@ -144,5 +144,5 @@ Task SendBackInStockMessage(Customer customer, Product product, OutOfStockS /// Product /// Bid /// Queued email identifier - Task SendOutBidCustomerMessage(Product product, string languageId, Bid bid); + Task SendOutBidCustomerMessage(Product product, string? languageId, Bid bid); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/ICmsMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/ICmsMessageProviderService.cs index 9fb5f2054..6eea124e2 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/ICmsMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/ICmsMessageProviderService.cs @@ -14,7 +14,7 @@ public interface ICmsMessageProviderService /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendBlogCommentMessage(BlogPost blogPost, BlogComment blogComment, string languageId, + Task SendBlogCommentMessage(BlogPost blogPost, BlogComment blogComment, string? languageId, DomainHost? host = null); /// @@ -28,7 +28,7 @@ Task SendBlogCommentMessage(BlogPost blogPost, BlogComment blogComment, str /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendArticleCommentMessage(KnowledgebaseArticle article, KnowledgebaseArticleComment articleComment, - string languageId, DomainHost? host = null); + string? languageId, DomainHost? host = null); /// /// Sends a news comment notification message to a store owner @@ -40,6 +40,6 @@ Task SendArticleCommentMessage(KnowledgebaseArticle article, KnowledgebaseA /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendNewsCommentMessage(NewsItem newsItem, NewsComment newsComment, string languageId, + Task SendNewsCommentMessage(NewsItem newsItem, NewsComment newsComment, string? languageId, DomainHost? host = null); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/ICustomerMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/ICustomerMessageProviderService.cs index 57959b1bd..774097fea 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/ICustomerMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/ICustomerMessageProviderService.cs @@ -17,7 +17,7 @@ public interface ICustomerMessageProviderService /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendCustomerRegisteredMessage(Customer customer, Store store, string languageId, DomainHost? host = null); + Task SendCustomerRegisteredMessage(Customer customer, Store store, string? languageId, DomainHost? host = null); /// /// Sends a welcome message to a customer @@ -29,7 +29,7 @@ public interface ICustomerMessageProviderService /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendCustomerWelcomeMessage(Customer customer, Store store, string languageId, DomainHost? host = null); + Task SendCustomerWelcomeMessage(Customer customer, Store store, string? languageId, DomainHost? host = null); /// /// Sends an email validation message to a customer @@ -41,7 +41,7 @@ public interface ICustomerMessageProviderService /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendCustomerEmailValidationMessage(Customer customer, Store store, string languageId, + Task SendCustomerEmailValidationMessage(Customer customer, Store store, string? languageId, DomainHost? host = null); /// @@ -54,7 +54,7 @@ Task SendCustomerEmailValidationMessage(Customer customer, Store store, str /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendCustomerPasswordRecoveryMessage(Customer customer, Store store, string languageId, + Task SendCustomerPasswordRecoveryMessage(Customer customer, Store store, string? languageId, DomainHost? host = null); /// @@ -65,7 +65,7 @@ Task SendCustomerPasswordRecoveryMessage(Customer customer, Store store, st /// Store /// Message language identifier /// Queued email identifier - Task SendNewCustomerNoteMessage(CustomerNote customerNote, Customer customer, Store store, string languageId); + Task SendNewCustomerNoteMessage(CustomerNote customerNote, Customer customer, Store store, string? languageId); /// /// Send an email token validation message to a customer @@ -77,7 +77,7 @@ Task SendCustomerPasswordRecoveryMessage(Customer customer, Store store, st /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendCustomerEmailTokenValidationMessage(Customer customer, Store store, string languageId, + Task SendCustomerEmailTokenValidationMessage(Customer customer, Store store, string? languageId, DomainHost? host = null); /// @@ -89,7 +89,7 @@ Task SendCustomerEmailTokenValidationMessage(Customer customer, Store store /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendCustomerDeleteStoreOwnerMessage(Customer customer, string languageId, DomainHost? host = null); + Task SendCustomerDeleteStoreOwnerMessage(Customer customer, string? languageId, DomainHost? host = null); /// /// Sends "contact us" message @@ -108,7 +108,7 @@ Task SendCustomerEmailTokenValidationMessage(Customer customer, Store store /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendContactUsMessage(Customer customer, Store store, string languageId, string senderEmail, + Task SendContactUsMessage(Customer customer, Store store, string? languageId, string senderEmail, string senderName, string subject, string body, string attrInfo, IList customAttributes, string ipaddress, DomainHost? host = null); @@ -125,7 +125,7 @@ Task SendContactUsMessage(Customer customer, Store store, string languageId /// /// Queued email identifier Task SendOrderApprovalRequestedMessage(OrderApproval approval, Customer buyer, Customer approver, - Store store, string languageId, DomainHost? host = null); + Store store, string? languageId, DomainHost? host = null); /// /// Sends an 'Order approval decided' message to the buyer @@ -139,7 +139,7 @@ Task SendOrderApprovalRequestedMessage(OrderApproval approval, Customer buy /// /// Queued email identifier Task SendOrderApprovalDecidedMessage(OrderApproval approval, Customer buyer, Store store, - string languageId, DomainHost? host = null); + string? languageId, DomainHost? host = null); /// /// Sends an 'Order approval decided' message to the given address, for a buyer who has none of their own @@ -154,7 +154,7 @@ Task SendOrderApprovalDecidedMessage(OrderApproval approval, Customer buyer /// Recipient /// Queued email identifier Task SendOrderApprovalDecidedMessage(OrderApproval approval, Customer buyer, Store store, - string languageId, DomainHost host, string toEmail); + string? languageId, DomainHost? host, string toEmail); /// /// Sends an 'Order approval requested' message to the store, when the store decides the request @@ -167,6 +167,6 @@ Task SendOrderApprovalDecidedMessage(OrderApproval approval, Customer buyer /// The back office panel the recipient works in /// Message language identifier /// Queued email identifier - Task SendOrderApprovalStaffMessage(OrderApproval approval, Customer buyer, Store store, string toEmail, - string toName, string panelArea, string languageId); + Task SendOrderApprovalStaffMessage(OrderApproval approval, Customer buyer, Store store, string? toEmail, + string? toName, string panelArea, string? languageId); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailAccountService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailAccountService.cs index 00fbf3cda..6dafb0d98 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailAccountService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailAccountService.cs @@ -28,7 +28,7 @@ public interface IEmailAccountService /// /// The email account identifier /// Email account - Task GetEmailAccountById(string emailAccountId); + Task GetEmailAccountById(string? emailAccountId); /// /// Gets all email accounts, optionally filtered by store, with pagination support. diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailSender.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailSender.cs index ca6d65c49..8efacb8bc 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailSender.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IEmailSender.cs @@ -32,7 +32,7 @@ public interface IEmailSender /// not cancelled: the server may already have accepted it /// Task SendEmail(EmailAccount emailAccount, string subject, string body, - string fromAddress, string fromName, string toAddress, string toName, + string fromAddress, string? fromName, string toAddress, string? toName, string? replyToAddress = null, string? replyToName = null, IEnumerable? bcc = null, IEnumerable? cc = null, string? attachmentFilePath = null, string? attachmentFileName = null, diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IMerchandiseReturnMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IMerchandiseReturnMessageProviderService.cs index 445eb1972..7965f4055 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/IMerchandiseReturnMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IMerchandiseReturnMessageProviderService.cs @@ -16,7 +16,7 @@ public interface IMerchandiseReturnMessageProviderService /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendNewMerchandiseReturnStoreOwnerMessage(MerchandiseReturn merchandiseReturn, Order order, - string languageId, DomainHost? host = null); + string? languageId, DomainHost? host = null); /// /// Sends the customer the message of the status the merchandise return reached (accepted, received, rejected, @@ -29,7 +29,7 @@ Task SendNewMerchandiseReturnStoreOwnerMessage(MerchandiseReturn merchandis /// The note shown to the customer with the change, e.g. why the return was rejected /// Queued email identifier Task SendMerchandiseReturnStatusChangedCustomerMessage(MerchandiseReturn merchandiseReturn, Order order, - string languageId, string? statusNote = null); + string? languageId, string? statusNote = null); /// /// Sends 'New Merchandise Return' message to a customer @@ -42,7 +42,7 @@ Task SendMerchandiseReturnStatusChangedCustomerMessage(MerchandiseReturn me /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendNewMerchandiseReturnCustomerMessage(MerchandiseReturn merchandiseReturn, Order order, - string languageId, DomainHost? host = null); + string? languageId, DomainHost? host = null); /// /// Sends a new merchandise return note added notification to a customer @@ -66,5 +66,5 @@ Task SendNewMerchandiseReturnNoteAddedCustomerMessage(MerchandiseReturn mer /// /// Queued email identifier Task SendNewMerchandiseReturnNoteAddedStoreOwnerMessage(MerchandiseReturn merchandiseReturn, - MerchandiseReturnNote merchandiseReturnNote, Order order, string languageId, DomainHost? host = null); + MerchandiseReturnNote merchandiseReturnNote, Order order, string? languageId, DomainHost? host = null); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageLookupService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageLookupService.cs index bd035377f..a815ca583 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageLookupService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageLookupService.cs @@ -12,12 +12,12 @@ public interface IMessageLookupService /// /// Gets the store by identifier, or the first store when it does not exist /// - Task GetStore(string storeId); + Task GetStore(string? storeId); /// /// Gets an active message template by name, or null when it is missing or inactive /// - Task GetMessageTemplate(string messageTemplateName, string storeId); + Task GetMessageTemplate(string messageTemplateName, string? storeId); /// /// Gets the email account of the message template, falling back to the default and then to any account @@ -27,5 +27,5 @@ public interface IMessageLookupService /// /// Gets the language if published, else a published language of the store, else any language /// - Task EnsureLanguageIsActive(string languageId, string storeId); + Task EnsureLanguageIsActive(string? languageId, string storeId); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageProviderService.cs index 682e52af5..42daa299f 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageProviderService.cs @@ -27,11 +27,11 @@ public interface IMessageProviderService /// Download of the invoice; the queued email owns it and deletes it with itself /// Queued email identifier Task SendNotification(MessageTemplate messageTemplate, - EmailAccount emailAccount, string languageId, LiquidObject liquidObject, - string toEmailAddress, string toName, + EmailAccount emailAccount, string? languageId, LiquidObject liquidObject, + string? toEmailAddress, string? toName, string? attachmentFilePath = null, string? attachmentFileName = null, IEnumerable? attachedDownloads = null, string? replyToEmailAddress = null, string? replyToName = null, string? fromEmail = null, string? fromName = null, string? subject = null, - Reference reference = Reference.None, string objectId = "", string? invoiceDownloadId = null); + Reference reference = Reference.None, string? objectId = "", string? invoiceDownloadId = null); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageTemplateService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageTemplateService.cs index c107e3104..af408b0de 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageTemplateService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IMessageTemplateService.cs @@ -31,7 +31,7 @@ public interface IMessageTemplateService /// /// Message template identifier /// Message template - Task GetMessageTemplateById(string messageTemplateId); + Task GetMessageTemplateById(string messageTemplateId); /// /// Gets a message template by name @@ -39,7 +39,7 @@ public interface IMessageTemplateService /// Message template name /// Store identifier /// Message template - Task GetMessageTemplateByName(string messageTemplateName, string storeId); + Task GetMessageTemplateByName(string messageTemplateName, string? storeId); /// /// Gets all message templates diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/INewsletterMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/INewsletterMessageProviderService.cs index 0ae2f5936..2b8cd2cfc 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/INewsletterMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/INewsletterMessageProviderService.cs @@ -15,7 +15,7 @@ public interface INewsletterMessageProviderService /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendNewsLetterSubscriptionActivationMessage(NewsLetterSubscription subscription, - string languageId, DomainHost? host = null); + string? languageId, DomainHost? host = null); /// /// Sends a newsletter subscription deactivation message @@ -27,5 +27,5 @@ Task SendNewsLetterSubscriptionActivationMessage(NewsLetterSubscription sub /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendNewsLetterSubscriptionDeactivationMessage(NewsLetterSubscription subscription, - string languageId, DomainHost? host = null); + string? languageId, DomainHost? host = null); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IOrderMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IOrderMessageProviderService.cs index bc1ca26f7..37181af76 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/IOrderMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IOrderMessageProviderService.cs @@ -19,7 +19,7 @@ public interface IOrderMessageProviderService /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendOrderPlacedVendorMessage(Order order, Customer customer, Vendor vendor, string languageId, + Task SendOrderPlacedVendorMessage(Order order, Customer? customer, Vendor vendor, string? languageId, DomainHost? host = null); /// @@ -32,7 +32,7 @@ Task SendOrderPlacedVendorMessage(Order order, Customer customer, Vendor ve /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendOrderPlacedStoreOwnerMessage(Order order, Customer customer, string languageId, + Task SendOrderPlacedStoreOwnerMessage(Order order, Customer? customer, string? languageId, DomainHost? host = null); /// @@ -42,7 +42,7 @@ Task SendOrderPlacedStoreOwnerMessage(Order order, Customer customer, strin /// Customer instance /// Message language identifier /// Queued email identifier - Task SendOrderPaidStoreOwnerMessage(Order order, Customer customer, string languageId); + Task SendOrderPaidStoreOwnerMessage(Order order, Customer? customer, string? languageId); /// /// Sends an order paid notification to a customer @@ -54,7 +54,7 @@ Task SendOrderPlacedStoreOwnerMessage(Order order, Customer customer, strin /// Download of the invoice to attach. The queued email takes ownership of it; it is deleted when no email is queued /// /// Queued email identifier - Task SendOrderPaidCustomerMessage(Order order, Customer customer, string languageId, + Task SendOrderPaidCustomerMessage(Order order, Customer? customer, string? languageId, string? invoiceDownloadId = null); /// @@ -64,7 +64,7 @@ Task SendOrderPaidCustomerMessage(Order order, Customer customer, string la /// Vendor instance /// Message language identifier /// Queued email identifier - Task SendOrderPaidVendorMessage(Order order, Vendor vendor, string languageId); + Task SendOrderPaidVendorMessage(Order order, Vendor vendor, string? languageId); /// /// Sends an order placed notification to a customer @@ -79,7 +79,7 @@ Task SendOrderPaidCustomerMessage(Order order, Customer customer, string la /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendOrderPlacedCustomerMessage(Order order, Customer customer, string languageId, + Task SendOrderPlacedCustomerMessage(Order order, Customer? customer, string? languageId, string? invoiceDownloadId = null, DomainHost? host = null); /// @@ -108,7 +108,7 @@ Task SendOrderPlacedCustomerMessage(Order order, Customer customer, string /// Download of the invoice to attach. The queued email takes ownership of it; it is deleted when no email is queued /// /// Queued email identifier - Task SendOrderCompletedCustomerMessage(Order order, Customer customer, string languageId, + Task SendOrderCompletedCustomerMessage(Order order, Customer? customer, string? languageId, string? invoiceDownloadId = null); /// @@ -118,7 +118,7 @@ Task SendOrderCompletedCustomerMessage(Order order, Customer customer, stri /// Customer instance /// Message language identifier /// Queued email identifier - Task SendOrderCancelledCustomerMessage(Order order, Customer customer, string languageId); + Task SendOrderCancelledCustomerMessage(Order order, Customer? customer, string? languageId); /// /// Sends an order cancelled notification to a store owner @@ -127,7 +127,7 @@ Task SendOrderCompletedCustomerMessage(Order order, Customer customer, stri /// Customer instance /// Message language identifier /// Queued email identifier - Task SendOrderCancelledStoreOwnerMessage(Order order, Customer customer, string languageId); + Task SendOrderCancelledStoreOwnerMessage(Order order, Customer? customer, string? languageId); /// /// Sends an order cancel notification to a vendor @@ -136,7 +136,7 @@ Task SendOrderCompletedCustomerMessage(Order order, Customer customer, stri /// Vendor instance /// Message language identifier /// Queued email identifier - Task SendOrderCancelledVendorMessage(Order order, Vendor vendor, string languageId); + Task SendOrderCancelledVendorMessage(Order order, Vendor vendor, string? languageId); /// /// Sends an order refunded notification to a store owner @@ -145,7 +145,7 @@ Task SendOrderCompletedCustomerMessage(Order order, Customer customer, stri /// Amount refunded /// Message language identifier /// Queued email identifier - Task SendOrderRefundedStoreOwnerMessage(Order order, double refundedAmount, string languageId); + Task SendOrderRefundedStoreOwnerMessage(Order order, double refundedAmount, string? languageId); /// /// Sends an order refunded notification to a customer @@ -154,7 +154,7 @@ Task SendOrderCompletedCustomerMessage(Order order, Customer customer, stri /// Amount refunded /// Message language identifier /// Queued email identifier - Task SendOrderRefundedCustomerMessage(Order order, double refundedAmount, string languageId); + Task SendOrderRefundedCustomerMessage(Order order, double refundedAmount, string? languageId); /// /// Reminds a customer that the payment of an order bought on credit falls due @@ -163,7 +163,7 @@ Task SendOrderCompletedCustomerMessage(Order order, Customer customer, stri /// Customer /// Message language identifier /// Queued email identifier - Task SendPaymentDueReminderCustomerMessage(Order order, Customer customer, string languageId); + Task SendPaymentDueReminderCustomerMessage(Order order, Customer? customer, string? languageId); /// /// Tells a customer that the payment of an order bought on credit is overdue @@ -172,7 +172,7 @@ Task SendOrderCompletedCustomerMessage(Order order, Customer customer, stri /// Customer /// Message language identifier /// Queued email identifier - Task SendPaymentOverdueCustomerMessage(Order order, Customer customer, string languageId); + Task SendPaymentOverdueCustomerMessage(Order order, Customer? customer, string? languageId); /// /// Sends a new order note added notification to a customer @@ -192,7 +192,7 @@ Task SendOrderCompletedCustomerMessage(Order order, Customer customer, stri /// Order /// Message language identifier /// Queued email identifier - Task SendGiftVoucherMessage(GiftVoucher giftVoucher, Order order, string languageId); + Task SendGiftVoucherMessage(GiftVoucher giftVoucher, Order order, string? languageId); /// /// Sends the e-mail address of an order placed without an account the link that opens the order diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IQueuedEmailService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IQueuedEmailService.cs index 261588d9f..966d5d176 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/IQueuedEmailService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IQueuedEmailService.cs @@ -28,7 +28,7 @@ public interface IQueuedEmailService /// /// Download identifier of the invoice /// Download identifier of the copy; null when there is no invoice to copy - Task CopyInvoiceDownload(string invoiceDownloadId); + Task CopyInvoiceDownload(string invoiceDownloadId); /// /// Deleted a customer emails and their invoices @@ -47,7 +47,7 @@ public interface IQueuedEmailService /// /// Queued email identifier /// Queued email - Task GetQueuedEmailById(string queuedEmailId); + Task GetQueuedEmailById(string queuedEmailId); /// /// Get queued emails by identifiers diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IRecurringPaymentMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IRecurringPaymentMessageProviderService.cs index 6f784fc41..8af8e222c 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/IRecurringPaymentMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IRecurringPaymentMessageProviderService.cs @@ -17,7 +17,7 @@ public interface IRecurringPaymentMessageProviderService /// Message language identifier /// Queued email identifier; 0 when nothing was queued Task SendRecurringPaymentCancelledCustomerMessage(RecurringPayment recurringPayment, Order initialOrder, - Customer customer, string languageId); + Customer? customer, string? languageId); /// /// Sends a 'Recurring payment cancelled' message to the store owner @@ -28,7 +28,7 @@ Task SendRecurringPaymentCancelledCustomerMessage(RecurringPayment recurrin /// Message language identifier /// Queued email identifier; 0 when nothing was queued Task SendRecurringPaymentCancelledStoreOwnerMessage(RecurringPayment recurringPayment, Order initialOrder, - Customer customer, string languageId); + Customer? customer, string? languageId); /// /// Sends a 'Recurring payment failed' message to the customer @@ -39,7 +39,7 @@ Task SendRecurringPaymentCancelledStoreOwnerMessage(RecurringPayment recurr /// Message language identifier /// Queued email identifier; 0 when nothing was queued Task SendRecurringPaymentFailedCustomerMessage(RecurringPayment recurringPayment, Order initialOrder, - Customer customer, string languageId); + Customer? customer, string? languageId); /// /// Sends a 'Recurring payment failed' message to the store owner @@ -50,5 +50,5 @@ Task SendRecurringPaymentFailedCustomerMessage(RecurringPayment recurringPa /// Message language identifier /// Queued email identifier; 0 when nothing was queued Task SendRecurringPaymentFailedStoreOwnerMessage(RecurringPayment recurringPayment, Order initialOrder, - Customer customer, string languageId); + Customer? customer, string? languageId); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IVendorMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IVendorMessageProviderService.cs index 89ea61c5e..9cc11009f 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/IVendorMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IVendorMessageProviderService.cs @@ -19,7 +19,7 @@ public interface IVendorMessageProviderService /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// Task SendNewVendorAccountApplyStoreOwnerMessage(Customer customer, Vendor vendor, Store store, - string languageId, DomainHost? host = null); + string? languageId, DomainHost? host = null); /// /// Sends 'Vendor information change' message to a store owner @@ -28,7 +28,7 @@ Task SendNewVendorAccountApplyStoreOwnerMessage(Customer customer, Vendor v /// Store /// Message language identifier /// Queued email identifier - Task SendVendorInformationChangeMessage(Vendor vendor, Store store, string languageId); + Task SendVendorInformationChangeMessage(Vendor vendor, Store store, string? languageId); /// /// Sends a vendor review notification message to a store owner @@ -40,7 +40,7 @@ Task SendNewVendorAccountApplyStoreOwnerMessage(Customer customer, Vendor v /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendVendorReviewMessage(VendorReview vendorReview, Store store, string languageId, + Task SendVendorReviewMessage(VendorReview vendorReview, Store store, string? languageId, DomainHost? host = null); /// @@ -59,6 +59,6 @@ Task SendVendorReviewMessage(VendorReview vendorReview, Store store, string /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - Task SendContactVendorMessage(Customer customer, Store store, Vendor vendor, string languageId, + Task SendContactVendorMessage(Customer customer, Store store, Vendor vendor, string? languageId, string senderEmail, string senderName, string subject, string body, string ipaddress, DomainHost? host = null); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Storage/IDownloadService.cs b/src/Business/Grand.Business.Core/Interfaces/Storage/IDownloadService.cs index dba3222bd..470d61c83 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Storage/IDownloadService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Storage/IDownloadService.cs @@ -12,14 +12,14 @@ public interface IDownloadService /// /// Download identifier /// Download - Task GetDownloadById(string downloadId); + Task GetDownloadById(string downloadId); /// /// Gets a download by GUID /// /// Download GUID /// Download - Task GetDownloadByGuid(Guid downloadGuid); + Task GetDownloadByGuid(Guid downloadGuid); /// /// Inserts a download @@ -43,5 +43,5 @@ public interface IDownloadService /// Deletes a download by identifier, without loading its file. Does nothing when it no longer exists /// /// Download identifier - Task DeleteDownloadById(string downloadId); + Task DeleteDownloadById(string? downloadId); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Storage/IFileStore.cs b/src/Business/Grand.Business.Core/Interfaces/Storage/IFileStore.cs index b744a15da..45801f1e1 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Storage/IFileStore.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Storage/IFileStore.cs @@ -1,6 +1,7 @@ //Source https://github.com/OrchardCMS/OrchardCore/tree/dev/src/OrchardCore using Microsoft.Extensions.FileProviders.Physical; +using System.Diagnostics.CodeAnalysis; namespace Grand.Business.Core.Interfaces.Storage; @@ -14,7 +15,7 @@ public interface IFileStore /// /// The path within the file store. /// A object representing the file, or null if the file does not exist. - Task GetFileInfo(string path); + Task GetFileInfo(string path); /// /// Retrieves information about the given directory within the file store. @@ -24,7 +25,7 @@ public interface IFileStore /// A object representing the directory, or null if the directory does not /// exist. /// - IFileStoreEntry GetDirectoryInfo(string path); + IFileStoreEntry? GetDirectoryInfo(string path); /// /// Retrieves information about the given directory within the file store. @@ -33,7 +34,7 @@ public interface IFileStore /// A object representing the directory, or null if the directory does /// not exist. /// - Task GetPhysicalDirectoryInfo(string directoryPath); + Task GetPhysicalDirectoryInfo(string directoryPath); /// /// Enumerates the content (files and directories) in a given directory within the file store. @@ -158,10 +159,11 @@ public static class IFileStoreExtensions /// The . /// The path parts to combine. /// The full combined path. - public static string? Combine(this IFileStore fileStore, params ReadOnlySpan paths) + public static string Combine(this IFileStore fileStore, params ReadOnlySpan paths) { + //nothing to combine; a null or empty part is skipped the same way below if (paths.Length == 0) - return null; + return string.Empty; List normalizedParts = []; foreach (var path in paths) @@ -185,7 +187,8 @@ public static class IFileStoreExtensions /// Backslash is converted to forward slash and any leading or trailing slashes /// are removed. /// - public static string? NormalizePath(this IFileStore fileStore, string path) + [return: NotNullIfNotNull(nameof(path))] + public static string? NormalizePath(this IFileStore fileStore, string? path) { return path?.Replace('\\', '/').Trim('/', ' '); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Storage/IFileStoreEntry.cs b/src/Business/Grand.Business.Core/Interfaces/Storage/IFileStoreEntry.cs index 0f102dd54..3d8199b21 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Storage/IFileStoreEntry.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Storage/IFileStoreEntry.cs @@ -22,7 +22,7 @@ public interface IFileStoreEntry /// /// Gets the full path of the file store entry's containing directory within the file store. /// - string PhysicalPath { get; } + string? PhysicalPath { get; } /// /// Gets the length of the file (0 if the file story entry is a directory). diff --git a/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs b/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs index 9c176ab08..1d2f5ad28 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs @@ -15,7 +15,7 @@ public interface IPictureService /// /// Picture /// Picture binary - Task LoadPictureBinary(Picture picture); + Task LoadPictureBinary(Picture picture); /// /// Gets the loaded picture binary depending on picture storage settings @@ -23,14 +23,14 @@ public interface IPictureService /// Picture /// Load from database; otherwise, from file system /// Picture binary - Task LoadPictureBinary(Picture picture, bool fromDb); + Task LoadPictureBinary(Picture picture, bool fromDb); /// /// Get picture SEO friendly name /// /// Name /// Result - string GetPictureSeName(string name); + string? GetPictureSeName(string? name); /// /// Gets the default picture URL @@ -38,7 +38,7 @@ public interface IPictureService /// The target picture size (longest side) /// Store location URL; null to use determine the current store location automatically /// Picture URL - Task GetDefaultPictureUrl(int targetSize = 0, string? storeLocation = null); + Task GetDefaultPictureUrl(int targetSize = 0, string? storeLocation = null); /// /// Get a picture URL @@ -48,7 +48,7 @@ public interface IPictureService /// A value indicating whether the default picture is shown /// Store location URL; null to use determine the current store location automatically /// Picture URL - Task GetPictureUrl(string pictureId, + Task GetPictureUrl(string pictureId, int targetSize = 0, bool showDefaultPicture = true, string? storeLocation = null); @@ -61,7 +61,7 @@ Task GetPictureUrl(string pictureId, /// A value indicating whether the default picture is shown /// Store location URL; null to use determine the current store location automatically /// Picture URL - Task GetPictureUrl(Picture picture, + Task GetPictureUrl(Picture picture, int targetSize = 0, bool showDefaultPicture = true, string? storeLocation = null); @@ -73,14 +73,14 @@ Task GetPictureUrl(Picture picture, /// The target picture size (longest side) /// A value indicating whether the default picture is shown /// - Task GetThumbPhysicalPath(Picture picture, int targetSize = 0, bool showDefaultPicture = true); + Task GetThumbPhysicalPath(Picture? picture, int targetSize = 0, bool showDefaultPicture = true); /// /// Gets a picture /// /// Picture identifier /// Picture - Task GetPictureById(string pictureId); + Task GetPictureById(string pictureId); /// /// Deletes a picture @@ -128,7 +128,7 @@ Task GetPictureUrl(Picture picture, /// Object id for reference /// A value indicating whether to validated provided picture binary /// Picture - Task InsertPicture(byte[] pictureBinary, string mimeType, string seoFilename, + Task InsertPicture(byte[] pictureBinary, string mimeType, string? seoFilename, string? altAttribute = null, string? titleAttribute = null, bool isNew = true, Reference reference = Reference.None, string objectId = "", bool validateBinary = false); @@ -146,7 +146,7 @@ Task InsertPicture(byte[] pictureBinary, string mimeType, string seoFil /// A value indicating whether the picture is new /// A value indicating whether to validated provided picture binary /// Picture - Task UpdatePicture(string pictureId, byte[] pictureBinary, string mimeType, + Task UpdatePicture(string pictureId, byte[] pictureBinary, string mimeType, string seoFilename, string? altAttribute = null, string? titleAttribute = null, string? style = null, string? extraField = null, bool isNew = true, bool validateBinary = true); diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetDiscountAmountProvider.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetDiscountAmountProvider.cs index 49c02d34b..a8a47ee03 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetDiscountAmountProvider.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetDiscountAmountProvider.cs @@ -9,6 +9,6 @@ namespace Grand.Business.Core.Queries.Catalog; public record GetDiscountAmountProvider( Discount Discount, Customer Customer, - Product Product, + Product? Product, Currency Currency, double Amount) : IRequest; \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetProductArchByIdQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetProductArchByIdQuery.cs index a5d9a52a3..3a54c7231 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetProductArchByIdQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetProductArchByIdQuery.cs @@ -3,7 +3,7 @@ namespace Grand.Business.Core.Queries.Catalog; -public class GetProductArchByIdQuery : IRequest +public class GetProductArchByIdQuery : IRequest { public required string Id { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetSearchProductsQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetSearchProductsQuery.cs index 6e3815017..b961375a8 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetSearchProductsQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetSearchProductsQuery.cs @@ -8,7 +8,7 @@ namespace Grand.Business.Core.Queries.Catalog; public class GetSearchProductsQuery : IRequest<(IPagedList products, IList filterableSpecificationAttributeOptionIds)> { - public required Customer Customer { get; set; } + public required Customer? Customer { get; set; } /// /// Customer groups the ACL filter uses instead of the groups of ; diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetSitemapProductsQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetSitemapProductsQuery.cs index 7c3f48238..730bb9567 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetSitemapProductsQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetSitemapProductsQuery.cs @@ -25,4 +25,4 @@ public class GetSitemapProductsQuery : IRequest> /// /// Search engine name in the requested language, or the default one /// The first product picture; null when the product has none -public record SitemapProduct(string Id, string SeName, string PictureId, DateTime UpdatedOnUtc); +public record SitemapProduct(string Id, string? SeName, string? PictureId, DateTime UpdatedOnUtc); diff --git a/src/Business/Grand.Business.Core/Queries/Catalog/GetVendorByIdQuery.cs b/src/Business/Grand.Business.Core/Queries/Catalog/GetVendorByIdQuery.cs index 379679800..4a1a31043 100644 --- a/src/Business/Grand.Business.Core/Queries/Catalog/GetVendorByIdQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Catalog/GetVendorByIdQuery.cs @@ -3,7 +3,7 @@ namespace Grand.Business.Core.Queries.Catalog; -public class GetVendorByIdQuery : IRequest +public class GetVendorByIdQuery : IRequest { public string? Id { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPickupPointById.cs b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPickupPointById.cs index 847de2b2c..57c09fd6a 100644 --- a/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPickupPointById.cs +++ b/src/Business/Grand.Business.Core/Queries/Checkout/Orders/GetPickupPointById.cs @@ -3,7 +3,7 @@ namespace Grand.Business.Core.Queries.Checkout.Orders; -public class GetPickupPointById : IRequest +public class GetPickupPointById : IRequest { public required string Id { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Customers/GetGroupBySystemNameQuery.cs b/src/Business/Grand.Business.Core/Queries/Customers/GetGroupBySystemNameQuery.cs index 077d92ac0..a6340ba45 100644 --- a/src/Business/Grand.Business.Core/Queries/Customers/GetGroupBySystemNameQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Customers/GetGroupBySystemNameQuery.cs @@ -3,7 +3,7 @@ namespace Grand.Business.Core.Queries.Customers; -public class GetGroupBySystemNameQuery : IRequest +public class GetGroupBySystemNameQuery : IRequest { public string SystemName { get; set; } = ""; } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Messages/GetCustomerByIdQuery.cs b/src/Business/Grand.Business.Core/Queries/Messages/GetCustomerByIdQuery.cs index e4db4e4f0..22935b65b 100644 --- a/src/Business/Grand.Business.Core/Queries/Messages/GetCustomerByIdQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Messages/GetCustomerByIdQuery.cs @@ -3,7 +3,7 @@ namespace Grand.Business.Core.Queries.Messages; -public class GetCustomerByIdQuery : IRequest +public class GetCustomerByIdQuery : IRequest { public string? Id { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Messages/GetProductByIdQuery.cs b/src/Business/Grand.Business.Core/Queries/Messages/GetProductByIdQuery.cs index 9b0c2e031..ca47c7d38 100644 --- a/src/Business/Grand.Business.Core/Queries/Messages/GetProductByIdQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Messages/GetProductByIdQuery.cs @@ -3,7 +3,7 @@ namespace Grand.Business.Core.Queries.Messages; -public class GetProductByIdQuery : IRequest +public class GetProductByIdQuery : IRequest { public string? Id { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Queries/Messages/GetVendorByIdQuery.cs b/src/Business/Grand.Business.Core/Queries/Messages/GetVendorByIdQuery.cs index 135dd8d4c..b1ed3a93a 100644 --- a/src/Business/Grand.Business.Core/Queries/Messages/GetVendorByIdQuery.cs +++ b/src/Business/Grand.Business.Core/Queries/Messages/GetVendorByIdQuery.cs @@ -3,7 +3,7 @@ namespace Grand.Business.Core.Queries.Messages; -public class GetVendorByIdQuery : IRequest +public class GetVendorByIdQuery : IRequest { public string? Id { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthParam.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthParam.cs index 68a75aca1..269038848 100644 --- a/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthParam.cs +++ b/src/Business/Grand.Business.Core/Utilities/Authentication/ExternalAuthParam.cs @@ -10,12 +10,12 @@ public class ExternalAuthParam /// /// Gets or sets the external authentication provider's system name /// - public string? ProviderSystemName { get; set; } + public required string ProviderSystemName { get; set; } /// /// Gets or sets user id /// - public string? Identifier { get; set; } + public required string Identifier { get; set; } /// /// Gets or sets user name diff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/OidcCustomerResult.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/OidcCustomerResult.cs index 99bd5f547..6acf6f5cd 100644 --- a/src/Business/Grand.Business.Core/Utilities/Authentication/OidcCustomerResult.cs +++ b/src/Business/Grand.Business.Core/Utilities/Authentication/OidcCustomerResult.cs @@ -1,4 +1,5 @@ using Grand.Domain.Customers; +using System.Diagnostics.CodeAnalysis; namespace Grand.Business.Core.Utilities.Authentication; @@ -20,6 +21,7 @@ private OidcCustomerResult(Customer? customer, OidcFailureKind? failure, string? /// Fixed, token-independent text safe for error_description public string? Description { get; } + [MemberNotNullWhen(true, nameof(Customer))] public bool Succeeded => Customer != null; public static OidcCustomerResult Success(Customer customer) => new(customer, null, null); diff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/ScimResults.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/ScimResults.cs index c69b1b2a9..a623a3f66 100644 --- a/src/Business/Grand.Business.Core/Utilities/Authentication/ScimResults.cs +++ b/src/Business/Grand.Business.Core/Utilities/Authentication/ScimResults.cs @@ -17,16 +17,16 @@ public enum ScimOutcome /// The attributes of a SCIM user that GrandNode keeps public record ScimUserData(string UserName, string ExternalId, string Email, string GivenName, string FamilyName, bool Active); -public record ScimGroupRef(string Id, string DisplayName); +public record ScimGroupRef(string Id, string? DisplayName); /// A SCIM user as the endpoint returns it (id = customer id) public record ScimUserView( string Id, - string ExternalId, - string UserName, - string Email, - string GivenName, - string FamilyName, + string? ExternalId, + string? UserName, + string? Email, + string? GivenName, + string? FamilyName, bool Active, IList Groups, DateTime Created, @@ -40,8 +40,8 @@ public record ScimGroupData(string DisplayName, string ExternalId, IList public record ScimGroupView( string Id, - string DisplayName, - string ExternalId, + string? DisplayName, + string? ExternalId, IList MemberIds, DateTime Created, DateTime? LastModified); @@ -54,8 +54,8 @@ public record ScimPage(IList Items, int Total); /// A group received from the identity provider and the role an administrator mapped to it public record ScimGroupMapping( string GroupId, - string DisplayName, + string? DisplayName, int MemberCount, - string CustomerGroupId, - string StaffStoreId, - string VendorId); + string? CustomerGroupId, + string? StaffStoreId, + string? VendorId); diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/StockBuckets.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/StockBuckets.cs index 782d65933..20abc719d 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/StockBuckets.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/StockBuckets.cs @@ -125,7 +125,7 @@ public static Expression> KeptIn(string warehouseId) /// of its batches and serial numbers: a product kept in one warehouse has all its stock there, whatever /// warehouse a shipment or order item names /// - public static string UnitWarehouse(Product product, string warehouseId) + public static string UnitWarehouse(Product product, string? warehouseId) { ArgumentNullException.ThrowIfNull(product); @@ -136,7 +136,7 @@ public static string UnitWarehouse(Product product, string warehouseId) /// The product is kept in one warehouse other than this one, so its stock is not booked here; a product naming /// no warehouse is booked anywhere /// - public static bool KeptElsewhere(Product product, string warehouseId) + public static bool KeptElsewhere(Product product, string? warehouseId) { ArgumentNullException.ThrowIfNull(product); diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/StockChange.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/StockChange.cs index 8f161087a..eacfb83e8 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/StockChange.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/StockChange.cs @@ -13,10 +13,10 @@ namespace Grand.Business.Core.Utilities.Catalog; /// who caused it; empty for the system /// the comment of the entry public sealed record StockSource( - string ObjectType = "", - string ObjectId = "", - string PositionId = "", - string Reference = "", + string? ObjectType = "", + string? ObjectId = "", + string? PositionId = "", + string? Reference = "", string CustomerId = "", string Comment = ""); @@ -31,7 +31,7 @@ public sealed record StockSource( /// the source the journal entry names public sealed record StockChange( IList Attributes, - string WarehouseId, + string? WarehouseId, int Quantity, bool SetTo, InventoryMovementType MovementType, diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/UnitNumbers.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/UnitNumbers.cs index c5fdc5ca1..5515cb55c 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/UnitNumbers.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/UnitNumbers.cs @@ -10,7 +10,7 @@ public static class UnitNumbers /// /// What two numbers are compared by: trimmed and upper-cased /// - public static string Key(string number) + public static string Key(string? number) { return number?.Trim().ToUpperInvariant() ?? ""; } diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/AppliedGiftVoucher.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/AppliedGiftVoucher.cs index 8f0ae1ba4..2bc03348f 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/AppliedGiftVoucher.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/AppliedGiftVoucher.cs @@ -15,5 +15,5 @@ public class AppliedGiftVoucher /// /// Gets the gift voucher /// - public GiftVoucher? GiftVoucher { get; set; } + public required GiftVoucher GiftVoucher { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/CheckoutClaim.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/CheckoutClaim.cs index cbc54a6bd..a67b3d63d 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/CheckoutClaim.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/CheckoutClaim.cs @@ -13,11 +13,11 @@ public class CheckoutClaim /// /// The identifier the order is inserted with /// - public string? OrderId { get; init; } + public required string OrderId { get; init; } - public string? OrderCode { get; init; } - public string? CustomerId { get; init; } - public string? StoreId { get; init; } + public required string OrderCode { get; init; } + public required string CustomerId { get; init; } + public required string StoreId { get; init; } /// /// Everything the order spends was taken; when false, nothing is held @@ -33,4 +33,4 @@ public class CheckoutClaim /// /// A quantity reserved for one cart line /// -public record ClaimedStock(Product Product, int Quantity, IList Attributes, string WarehouseId); +public record ClaimedStock(Product Product, int Quantity, IList Attributes, string? WarehouseId); diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/MerchandiseReturnSubmitRequest.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/MerchandiseReturnSubmitRequest.cs index dd085e3fa..3c4d9072d 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/MerchandiseReturnSubmitRequest.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/MerchandiseReturnSubmitRequest.cs @@ -8,7 +8,7 @@ namespace Grand.Business.Core.Utilities.Checkout; /// public class MerchandiseReturnSubmitRequest { - public Order? Order { get; set; } + public required Order Order { get; set; } public string? StoreId { get; set; } public string? CustomerId { get; set; } public string? OwnerId { get; set; } diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/OrderPlacementContext.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/OrderPlacementContext.cs index 2f76c9006..b106d93c1 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/OrderPlacementContext.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/OrderPlacementContext.cs @@ -12,7 +12,7 @@ public class OrderPlacementContext private Task? _total; public OrderPlacementContext(IList cart, CalculationContext calculation, Language language, - string paymentMethodSystemName, Func> getTotal) + string? paymentMethodSystemName, Func> getTotal) { Cart = cart; Calculation = calculation; @@ -39,7 +39,7 @@ public OrderPlacementContext(IList cart, CalculationContext ca /// /// Gets the chosen payment method; null until the buyer has chosen one /// - public string PaymentMethodSystemName { get; } + public string? PaymentMethodSystemName { get; } /// /// Gets the order total in the primary store currency; null until shipping is chosen. diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/OrderPlacementRuleResult.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/OrderPlacementRuleResult.cs index d4d370296..e6d61accc 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/OrderPlacementRuleResult.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/OrderPlacementRuleResult.cs @@ -13,7 +13,7 @@ public static OrderPlacementRuleResult Allow() return new OrderPlacementRuleResult(OrderPlacementDecision.Allow, null); } - public static OrderPlacementRuleResult RequireApproval(string reason) + public static OrderPlacementRuleResult RequireApproval(string? reason) { return new OrderPlacementRuleResult(OrderPlacementDecision.RequireApproval, reason); } @@ -23,7 +23,7 @@ public static OrderPlacementRuleResult RequireStoreApproval(string reason) return new OrderPlacementRuleResult(OrderPlacementDecision.RequireApproval, reason, true); } - public static OrderPlacementRuleResult Block(string reason) + public static OrderPlacementRuleResult Block(string? reason) { return new OrderPlacementRuleResult(OrderPlacementDecision.Block, reason); } diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainer.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainer.cs index d5e2488c9..b3d272658 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainer.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/PlaceOrderContainer.cs @@ -22,23 +22,26 @@ public class PlaceOrderContainer /// /// Customer, store, working currency and tax display the order totals are calculated for /// - public CalculationContext? Context { get; set; } + public required CalculationContext Context { get; set; } - public Customer? Customer { get; set; } - public Store? Store { get; set; } - public Language? Language { get; set; } + public required Customer Customer { get; set; } + public required Store Store { get; set; } + + //set by PreparePlaceOrderDetails, the one place a container is filled, before anything reads it + public Language Language { get; set; } = null!; /// /// Language of the request placing the order, used for the attribute descriptions /// - public Language? WorkingLanguage { get; set; } + public required Language WorkingLanguage { get; set; } /// /// Store address used for file download links in the attribute descriptions /// - public DomainHost? Host { get; set; } + public required DomainHost Host { get; set; } - public Currency? Currency { get; set; } + //set by PreparePlaceOrderDetails, the one place a container is filled, before anything reads it + public Currency Currency { get; set; } = null!; public string? AffiliateId { get; set; } public TaxDisplayType TaxDisplayType { get; set; } public double CurrencyRate { get; set; } diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/PurchaseOrderNumberRules.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/PurchaseOrderNumberRules.cs index 491cd56e3..46461863b 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/PurchaseOrderNumberRules.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/PurchaseOrderNumberRules.cs @@ -18,7 +18,7 @@ public static class PurchaseOrderNumberRules /// /// Number entered by the buyer /// Purchase order number mode - public static string? Normalize(string value, PurchaseOrderNumberMode mode) + public static string? Normalize(string? value, PurchaseOrderNumberMode mode) { if (mode == PurchaseOrderNumberMode.Disabled || string.IsNullOrWhiteSpace(value)) return null; @@ -32,7 +32,7 @@ public static class PurchaseOrderNumberRules /// Number returned by /// Purchase order number mode /// Resource key of the error; null when the number is valid - public static string? Validate(string normalized, PurchaseOrderNumberMode mode) + public static string? Validate(string? normalized, PurchaseOrderNumberMode mode) { if (normalized == null) return mode == PurchaseOrderNumberMode.Required ? "Checkout.PurchaseOrderNumber.Required" : null; diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/RefundPaymentRequest.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/RefundPaymentRequest.cs index 25b4a7b1e..0d2b34ca6 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/RefundPaymentRequest.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/RefundPaymentRequest.cs @@ -10,7 +10,7 @@ public class RefundPaymentRequest /// /// Gets or sets an payment transaction /// - public PaymentTransaction? PaymentTransaction { get; set; } + public required PaymentTransaction PaymentTransaction { get; set; } /// /// Gets or sets an amount diff --git a/src/Business/Grand.Business.Core/Utilities/Checkout/ReturnShipping.cs b/src/Business/Grand.Business.Core/Utilities/Checkout/ReturnShipping.cs index e73d44eaf..b4da47c6c 100644 --- a/src/Business/Grand.Business.Core/Utilities/Checkout/ReturnShipping.cs +++ b/src/Business/Grand.Business.Core/Utilities/Checkout/ReturnShipping.cs @@ -9,14 +9,14 @@ namespace Grand.Business.Core.Utilities.Checkout; /// public class ReturnShippingRequest { - public Order? Order { get; set; } + public required Order Order { get; set; } public Customer? Customer { get; set; } public string? StoreId { get; set; } /// /// The vendor the items are sent back to; empty for the store /// - public string? VendorId { get; set; } + public required string VendorId { get; set; } public IList<(OrderItem OrderItem, int Quantity)> Items { get; set; } = []; @@ -34,7 +34,7 @@ public class ReturnShippingRequest /// public class ReturnShippingOption { - public string? Code { get; set; } + public required string Code { get; set; } public string? Name { get; set; } public string? Description { get; set; } diff --git a/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyByName.cs b/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyByName.cs index 57d19e897..9ba97002a 100644 --- a/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyByName.cs +++ b/src/Business/Grand.Business.Core/Utilities/ExportImport/PropertyByName.cs @@ -11,7 +11,7 @@ public class PropertyByName /// /// Property name /// Feature property access - public PropertyByName(string propertyName, Func? func = null) + public PropertyByName(string propertyName, Func? func = null) { PropertyName = propertyName; GetProperty = func; @@ -27,7 +27,7 @@ public PropertyByName(string propertyName, Func? func = null) /// /// Feature property access /// - public Func? GetProperty { get; private set; } + public Func? GetProperty { get; private set; } /// /// Property name diff --git a/src/Business/Grand.Business.Core/Utilities/Messages/CampaignRecipient.cs b/src/Business/Grand.Business.Core/Utilities/Messages/CampaignRecipient.cs index 254b4a07e..9b47048e1 100644 --- a/src/Business/Grand.Business.Core/Utilities/Messages/CampaignRecipient.cs +++ b/src/Business/Grand.Business.Core/Utilities/Messages/CampaignRecipient.cs @@ -40,7 +40,7 @@ public sealed record CampaignRecipient /// /// Currency the shopping cart prices are rendered in /// - public Currency? Currency { get; init; } + public required Currency Currency { get; init; } /// /// Whether the shopping cart prices include tax diff --git a/src/Business/Grand.Business.Customers/Commands/Handlers/ActiveVendorCommandHandler.cs b/src/Business/Grand.Business.Customers/Commands/Handlers/ActiveVendorCommandHandler.cs index 65ca6515a..43ef2fd65 100644 --- a/src/Business/Grand.Business.Customers/Commands/Handlers/ActiveVendorCommandHandler.cs +++ b/src/Business/Grand.Business.Customers/Commands/Handlers/ActiveVendorCommandHandler.cs @@ -28,6 +28,8 @@ public ActiveVendorCommandHandler( public async Task Handle(ActiveVendorCommand request, CancellationToken cancellationToken) { + ArgumentNullException.ThrowIfNull(request.Vendor); + //update vendor - set active request.Vendor.Active = request.Active; await _vendorService.UpdateVendor(request.Vendor); diff --git a/src/Business/Grand.Business.Customers/Grand.Business.Customers.csproj b/src/Business/Grand.Business.Customers/Grand.Business.Customers.csproj index 4a9089b3c..f1e2f27a6 100644 --- a/src/Business/Grand.Business.Customers/Grand.Business.Customers.csproj +++ b/src/Business/Grand.Business.Customers/Grand.Business.Customers.csproj @@ -7,4 +7,7 @@ + + enable + diff --git a/src/Business/Grand.Business.Customers/Queries/Handlers/GetCustomerQueryHandler.cs b/src/Business/Grand.Business.Customers/Queries/Handlers/GetCustomerQueryHandler.cs index 32900adf3..d758601b8 100644 --- a/src/Business/Grand.Business.Customers/Queries/Handlers/GetCustomerQueryHandler.cs +++ b/src/Business/Grand.Business.Customers/Queries/Handlers/GetCustomerQueryHandler.cs @@ -91,19 +91,19 @@ public async Task> Handle(GetCustomerQuery request, Cancell } else { - var propName = GetName(request.OrderBySelector); + var propName = GetName(request.OrderBySelector) ?? + throw new ArgumentException("OrderBySelector selects no property", nameof(request)); query = OrderingHelper(query, propName); } return await _customerRepository.PagedAsync(query, request.PageIndex, request.PageSize, cancellationToken); } - private static string GetName(Expression> exp) + private static string? GetName(Expression> exp) { if (exp.Body is MemberExpression body) return body.Member.Name; var expBody = (UnaryExpression)exp.Body; - body = expBody.Operand as MemberExpression; - return body?.Member.Name; + return (expBody.Operand as MemberExpression)?.Member.Name; } private static IOrderedQueryable OrderingHelper(IQueryable source, string propertyName) diff --git a/src/Business/Grand.Business.Customers/Queries/Handlers/GetGroupBySystemNameQueryHandler.cs b/src/Business/Grand.Business.Customers/Queries/Handlers/GetGroupBySystemNameQueryHandler.cs index e370eaa87..b62216152 100644 --- a/src/Business/Grand.Business.Customers/Queries/Handlers/GetGroupBySystemNameQueryHandler.cs +++ b/src/Business/Grand.Business.Customers/Queries/Handlers/GetGroupBySystemNameQueryHandler.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Customers.Queries.Handlers; -public class GetGroupBySystemNameQueryHandler : IRequestHandler +public class GetGroupBySystemNameQueryHandler : IRequestHandler { private readonly IGroupService _groupService; @@ -14,7 +14,7 @@ public GetGroupBySystemNameQueryHandler(IGroupService groupService) _groupService = groupService; } - public async Task Handle(GetGroupBySystemNameQuery request, CancellationToken cancellationToken) + public async Task Handle(GetGroupBySystemNameQuery request, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNullOrEmpty(request.SystemName); diff --git a/src/Business/Grand.Business.Customers/Services/AffiliateService.cs b/src/Business/Grand.Business.Customers/Services/AffiliateService.cs index fc8845635..869385dfa 100644 --- a/src/Business/Grand.Business.Customers/Services/AffiliateService.cs +++ b/src/Business/Grand.Business.Customers/Services/AffiliateService.cs @@ -47,7 +47,7 @@ public AffiliateService(IRepository affiliateRepository, /// /// Affiliate identifier /// Affiliate - public virtual Task GetAffiliateById(string affiliateId) + public virtual Task GetAffiliateById(string affiliateId) { return _affiliateRepository.GetByIdAsync(affiliateId); } @@ -57,7 +57,7 @@ public virtual Task GetAffiliateById(string affiliateId) /// /// Friendly url name /// Affiliate - public virtual async Task GetAffiliateByFriendlyUrlName(string friendlyUrlName) + public virtual async Task GetAffiliateByFriendlyUrlName(string friendlyUrlName) { var query = from a in _affiliateRepository.Table where a.FriendlyUrlName != null && a.FriendlyUrlName.Contains(friendlyUrlName.ToLowerInvariant()) @@ -70,8 +70,8 @@ public virtual async Task GetAffiliateByFriendlyUrlName(string friend /// Gets all affiliates /// /// Affiliates - public virtual async Task> GetAllAffiliates(string friendlyUrlName = null, - string firstName = null, string lastName = null, + public virtual async Task> GetAllAffiliates(string? friendlyUrlName = null, + string? firstName = null, string? lastName = null, bool loadOnlyWithOrders = false, DateTime? ordersCreatedFromUtc = null, DateTime? ordersCreatedToUtc = null, int pageIndex = 0, int pageSize = int.MaxValue, @@ -85,10 +85,10 @@ public virtual async Task> GetAllAffiliates(string friendl a.FriendlyUrlName != null && a.FriendlyUrlName.Contains(friendlyUrlName.ToLowerInvariant())); if (!string.IsNullOrWhiteSpace(firstName)) query = query.Where(a => - a.Address.FirstName != null && a.Address.FirstName.ToLower().Contains(firstName.ToLower())); + a.Address != null && a.Address.FirstName != null && a.Address.FirstName.ToLower().Contains(firstName.ToLower())); if (!string.IsNullOrWhiteSpace(lastName)) query = query.Where(a => - a.Address.LastName != null && a.Address.LastName.ToLower().Contains(lastName.ToLower())); + a.Address != null && a.Address.LastName != null && a.Address.LastName.ToLower().Contains(lastName.ToLower())); if (!showHidden) query = query.Where(a => a.Active); diff --git a/src/Business/Grand.Business.Customers/Services/CustomerAttributeParser.cs b/src/Business/Grand.Business.Customers/Services/CustomerAttributeParser.cs index 421d34401..ef17fc9f0 100644 --- a/src/Business/Grand.Business.Customers/Services/CustomerAttributeParser.cs +++ b/src/Business/Grand.Business.Customers/Services/CustomerAttributeParser.cs @@ -125,7 +125,7 @@ public virtual async Task> GetAttributeWarnings(IList x.Key == a1.Id).Select(x => x.Value); - if (valuesStr.Any(str1 => !string.IsNullOrEmpty(str1.Trim()))) found = true; + if (valuesStr.Any(str1 => !string.IsNullOrEmpty(str1?.Trim()))) found = true; } //if not found diff --git a/src/Business/Grand.Business.Customers/Services/CustomerAttributeService.cs b/src/Business/Grand.Business.Customers/Services/CustomerAttributeService.cs index 2d246f7f9..d5acb902b 100644 --- a/src/Business/Grand.Business.Customers/Services/CustomerAttributeService.cs +++ b/src/Business/Grand.Business.Customers/Services/CustomerAttributeService.cs @@ -88,7 +88,7 @@ public virtual async Task> GetAllCustomerAttributes(str /// /// Customer attribute identifier /// Customer attribute - public virtual Task GetCustomerAttributeById(string customerAttributeId) + public virtual Task GetCustomerAttributeById(string? customerAttributeId) { var key = string.Format(CacheKey.CUSTOMERATTRIBUTES_BY_ID_KEY, customerAttributeId); return _cacheBase.GetAsync(key, () => _customerAttributeRepository.GetByIdAsync(customerAttributeId)); @@ -145,7 +145,8 @@ public virtual async Task InsertCustomerAttributeValue(CustomerAttributeValue cu { ArgumentNullException.ThrowIfNull(customerAttributeValue); - var ca = await _customerAttributeRepository.GetByIdAsync(customerAttributeValue.CustomerAttributeId); + var ca = await _customerAttributeRepository.GetByIdAsync(customerAttributeValue.CustomerAttributeId) ?? + throw new ArgumentException("The value names no customer attribute", nameof(customerAttributeValue)); ca.CustomerAttributeValues.Add(customerAttributeValue); await _customerAttributeRepository.UpdateAsync(ca); @@ -162,9 +163,11 @@ public virtual async Task UpdateCustomerAttributeValue(CustomerAttributeValue cu { ArgumentNullException.ThrowIfNull(customerAttributeValue); - var ca = await _customerAttributeRepository.GetByIdAsync(customerAttributeValue.CustomerAttributeId); - ca.CustomerAttributeValues.Remove( - ca.CustomerAttributeValues.FirstOrDefault(c => c.Id == customerAttributeValue.Id)); + var ca = await _customerAttributeRepository.GetByIdAsync(customerAttributeValue.CustomerAttributeId) ?? + throw new ArgumentException("The value names no customer attribute", nameof(customerAttributeValue)); + var existing = ca.CustomerAttributeValues.FirstOrDefault(c => c.Id == customerAttributeValue.Id); + if (existing != null) + ca.CustomerAttributeValues.Remove(existing); ca.CustomerAttributeValues.Add(customerAttributeValue); await _customerAttributeRepository.UpdateAsync(ca); @@ -181,9 +184,11 @@ public virtual async Task DeleteCustomerAttributeValue(CustomerAttributeValue cu { ArgumentNullException.ThrowIfNull(customerAttributeValue); - var ca = await _customerAttributeRepository.GetByIdAsync(customerAttributeValue.CustomerAttributeId); - ca.CustomerAttributeValues.Remove( - ca.CustomerAttributeValues.FirstOrDefault(c => c.Id == customerAttributeValue.Id)); + var ca = await _customerAttributeRepository.GetByIdAsync(customerAttributeValue.CustomerAttributeId) ?? + throw new ArgumentException("The value names no customer attribute", nameof(customerAttributeValue)); + var existing = ca.CustomerAttributeValues.FirstOrDefault(c => c.Id == customerAttributeValue.Id); + if (existing != null) + ca.CustomerAttributeValues.Remove(existing); await _customerAttributeRepository.UpdateAsync(ca); //event notification diff --git a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs index f7c3bbce6..bd919e810 100644 --- a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs +++ b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs @@ -91,6 +91,9 @@ public virtual async Task LoginCustomer(string usernameOrE var customer = _customerSettings.UsernamesEnabled ? await _customerService.GetCustomerByUsername(usernameOrEmail, storeId) : await _customerService.GetCustomerByEmail(usernameOrEmail, storeId); + //the login validators refuse an unknown account first; answered like a wrong password all the same + if (customer == null) + return CustomerLoginResults.WrongPassword; var isValid = _encryptionService.VerifyPassword(password, customer.PasswordFormatId, customer.Password, customer.PasswordSalt, _customerSettings.HashedPasswordFormat); @@ -185,7 +188,7 @@ public virtual async Task RegisterCustomer(RegistrationRequest request) //remove from 'Guests' role var guestGroup = await _groupService.GetCustomerGroupBySystemName(SystemCustomerGroupNames.Guests); var guestExists = request.Customer.Groups.FirstOrDefault(cr => cr == guestGroup?.Id); - if (guestExists != null) + if (guestGroup != null && guestExists != null) { request.Customer.Groups.Remove(guestGroup.Id); await _customerService.DeleteCustomerGroupInCustomer(guestGroup, request.Customer.Id); @@ -203,7 +206,8 @@ public virtual async Task ChangePassword(ChangePasswordRequest request, string s { ArgumentNullException.ThrowIfNull(request); - var customer = await _customerService.GetCustomerByEmail(request.Email, storeId); + var customer = await _customerService.GetCustomerByEmail(request.Email, storeId) ?? + throw new ArgumentNullException(nameof(request), "No customer has the e-mail"); await ChangePassword(customer, request.PasswordFormat, request.NewPassword); } diff --git a/src/Business/Grand.Business.Customers/Services/CustomerNoteService.cs b/src/Business/Grand.Business.Customers/Services/CustomerNoteService.cs index 78649179b..f5f2bcc52 100644 --- a/src/Business/Grand.Business.Customers/Services/CustomerNoteService.cs +++ b/src/Business/Grand.Business.Customers/Services/CustomerNoteService.cs @@ -25,10 +25,10 @@ public CustomerNoteService(IRepository customerNoteRepository, /// /// Note identifier /// CustomerNote - public virtual Task GetCustomerNote(string id) + public virtual Task GetCustomerNote(string id) { return string.IsNullOrWhiteSpace(id) - ? Task.FromResult(null) + ? Task.FromResult(null) : _customerNoteRepository.GetByIdAsync(id); } diff --git a/src/Business/Grand.Business.Customers/Services/CustomerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerService.cs index a953a0abe..7a002e7c7 100644 --- a/src/Business/Grand.Business.Customers/Services/CustomerService.cs +++ b/src/Business/Grand.Business.Customers/Services/CustomerService.cs @@ -85,13 +85,13 @@ public CustomerService( public virtual async Task> GetAllCustomers(DateTime? createdFromUtc = null, DateTime? createdToUtc = null, string affiliateId = "", string vendorId = "", string storeId = "", string ownerId = "", - string salesEmployeeId = "", string[] customerGroupIds = null, string[] customerTagIds = null, - string email = null, string username = null, - string firstName = null, string lastName = null, - string company = null, string phone = null, string zipPostalCode = null, + string salesEmployeeId = "", string[]? customerGroupIds = null, string[]? customerTagIds = null, + string? email = null, string? username = null, + string? firstName = null, string? lastName = null, + string? company = null, string? phone = null, string? zipPostalCode = null, bool loadOnlyWithShoppingCart = false, ShoppingCartType? sct = null, - int pageIndex = 0, int pageSize = 2147483647, Expression> orderBySelector = null, - string[] excludedCustomerGroupIds = null, bool excludeVendorAndStaffAccounts = false) + int pageIndex = 0, int pageSize = 2147483647, Expression>? orderBySelector = null, + string[]? excludedCustomerGroupIds = null, bool excludeVendorAndStaffAccounts = false) { var queryModel = new GetCustomerQuery { CreatedFromUtc = createdFromUtc, @@ -188,10 +188,10 @@ public virtual async Task GetCountOnlineShoppingCart(DateTime lastActivityF /// /// Customer identifier /// A customer - public virtual Task GetCustomerById(string customerId) + public virtual Task GetCustomerById(string? customerId) { return string.IsNullOrWhiteSpace(customerId) - ? Task.FromResult(null) + ? Task.FromResult(null) : _customerRepository.GetByIdAsync(customerId); } @@ -211,7 +211,7 @@ where customerIds.Contains(c.Id) var customers = query.ToList(); //sort by passed identifiers var sortedCustomers = customerIds.Select(id => customers.FirstOrDefault(customer => customer.Id == id)) - .Where(customer => customer != null) + .OfType() .ToList(); return await Task.FromResult(sortedCustomers); @@ -222,7 +222,7 @@ where customerIds.Contains(c.Id) /// /// Customer GUID /// A customer - public virtual async Task GetCustomerByGuid(Guid customerGuid) + public virtual async Task GetCustomerByGuid(Guid customerGuid) { return await _customerRepository.GetOneAsync(x => x.CustomerGuid == customerGuid); } @@ -232,7 +232,7 @@ public virtual async Task GetCustomerByGuid(Guid customerGuid) /// /// Email /// Customer - public virtual async Task GetCustomerByEmail(string email, string storeId = "") + public virtual async Task GetCustomerByEmail(string email, string storeId = "") { if (string.IsNullOrWhiteSpace(email)) return null; @@ -268,10 +268,10 @@ public virtual async Task GetCustomerByEmail(string email, string stor /// /// System name /// Customer - public virtual Task GetCustomerBySystemName(string systemName) + public virtual Task GetCustomerBySystemName(string systemName) { if (string.IsNullOrWhiteSpace(systemName)) - return Task.FromResult(null); + return Task.FromResult(null); var key = string.Format(CacheKey.CUSTOMER_BY_SYSTEMNAME_BY_KEY, systemName); @@ -283,7 +283,7 @@ public virtual Task GetCustomerBySystemName(string systemName) /// /// Username /// Customer - public virtual async Task GetCustomerByUsername(string username, string storeId = "") + public virtual async Task GetCustomerByUsername(string username, string storeId = "") { if (string.IsNullOrWhiteSpace(username)) return null; @@ -377,7 +377,7 @@ public virtual async Task UpdateCustomerField(Customer customer, /// Customer ident /// Expression /// value - public virtual async Task UpdateCustomerField(string customerId, + public virtual async Task UpdateCustomerField(string? customerId, Expression> expression, T value) { ArgumentNullException.ThrowIfNullOrEmpty(customerId); @@ -422,14 +422,14 @@ public virtual async Task UpdateCustomer(Customer customer) /// Key /// Value /// Store identifier; pass "" if this attribute will be available for all stores - public virtual async Task UpdateUserField(Customer customer, string key, TPropType value, string storeId = "") + public virtual async Task UpdateUserField(Customer customer, string key, TPropType? value, string? storeId = "") { ArgumentNullException.ThrowIfNull(customer); ArgumentNullException.ThrowIfNull(key); var props = customer.UserFields.Where(x => string.IsNullOrEmpty(storeId) || x.StoreId == storeId); - var prop = props.FirstOrDefault(ga => ga.Key.Equals(key, StringComparison.OrdinalIgnoreCase)); //should be culture invariant + var prop = props.FirstOrDefault(ga => string.Equals(ga.Key, key, StringComparison.OrdinalIgnoreCase)); //should be culture invariant var valueStr = CommonHelper.To(value); @@ -623,7 +623,7 @@ public virtual async Task UpdateContributions(Customer customer) /// A value indicating whether to clear "Use loyalty points" flag /// A value indicating whether to clear selected shipping method /// A value indicating whether to clear selected payment method - public virtual async Task ResetCheckoutData(Customer customer, string storeId, + public virtual async Task ResetCheckoutData(Customer customer, string? storeId, bool clearCouponCodes = false, bool clearCheckoutAttributes = false, bool clearLoyaltyPoints = true, bool clearShipping = true, bool clearPayment = true) { diff --git a/src/Business/Grand.Business.Customers/Services/SalesEmployeeService.cs b/src/Business/Grand.Business.Customers/Services/SalesEmployeeService.cs index be13e5dcd..5a15d880e 100644 --- a/src/Business/Grand.Business.Customers/Services/SalesEmployeeService.cs +++ b/src/Business/Grand.Business.Customers/Services/SalesEmployeeService.cs @@ -25,7 +25,7 @@ public SalesEmployeeService( /// /// The sales employee identifier /// SalesEmployee - public virtual Task GetSalesEmployeeById(string salesEmployeeId) + public virtual Task GetSalesEmployeeById(string salesEmployeeId) { var key = string.Format(CacheKey.SALESEMPLOYEE_BY_ID_KEY, salesEmployeeId); return _cacheBase.GetAsync(key, () => _salesEmployeeRepository.GetByIdAsync(salesEmployeeId)); diff --git a/src/Business/Grand.Business.Customers/Services/UserApiService.cs b/src/Business/Grand.Business.Customers/Services/UserApiService.cs index 09461d9d9..64260e111 100644 --- a/src/Business/Grand.Business.Customers/Services/UserApiService.cs +++ b/src/Business/Grand.Business.Customers/Services/UserApiService.cs @@ -21,7 +21,7 @@ public UserApiService(IRepository userRepository, IMediator mediator) /// Get user api by id /// /// id - public virtual Task GetUserById(string id) + public virtual Task GetUserById(string id) { return _userRepository.GetByIdAsync(id); } @@ -30,7 +30,7 @@ public virtual Task GetUserById(string id) /// Get user api by email /// /// email - public virtual async Task GetUserByEmail(string email) + public virtual async Task GetUserByEmail(string email) { return await _userRepository.FirstOrDefaultAsync( _userRepository.Table.Where(x => x.Email == email.ToLowerInvariant())); diff --git a/src/Business/Grand.Business.Customers/Services/VendorService.cs b/src/Business/Grand.Business.Customers/Services/VendorService.cs index 1434eb726..c710b4836 100644 --- a/src/Business/Grand.Business.Customers/Services/VendorService.cs +++ b/src/Business/Grand.Business.Customers/Services/VendorService.cs @@ -50,7 +50,7 @@ public VendorService(IRepository vendorRepository, IRepository /// Vendor identifier /// Vendor - public virtual async Task GetVendorById(string vendorId) + public virtual async Task GetVendorById(string vendorId) { var key = string.Format(CacheKey.VENDOR_BY_ID_KEY, vendorId); return await _cacheBase.GetAsync(key, () => _vendorRepository.GetByIdAsync(vendorId)); @@ -126,7 +126,7 @@ public virtual async Task DeleteVendor(Vendor vendor) /// Vendor ident /// The vendor note identifier /// Vendor note - public virtual async Task GetVendorNoteById(string vendorId, string vendorNoteId) + public virtual async Task GetVendorNoteById(string vendorId, string vendorNoteId) { if (string.IsNullOrEmpty(vendorNoteId)) return null; @@ -194,7 +194,7 @@ where c.AppliedDiscounts.Any(x => x == discountId) /// Reviews public virtual async Task> GetAllVendorReviews(string customerId, bool? approved, DateTime? fromUtc = null, DateTime? toUtc = null, - string message = null, string vendorId = "", int pageIndex = 0, int pageSize = int.MaxValue) + string? message = null, string vendorId = "", int pageIndex = 0, int pageSize = int.MaxValue) { var query = from p in _vendorReviewRepository.Table select p; @@ -308,7 +308,7 @@ public virtual async Task DeleteVendorReview(VendorReview vendorReview) /// /// Vendor review identifier /// Vendor review - public virtual Task GetVendorReviewById(string vendorReviewId) + public virtual Task GetVendorReviewById(string vendorReviewId) { return _vendorReviewRepository.GetByIdAsync(vendorReviewId); } @@ -322,7 +322,7 @@ public virtual Task GetVendorReviewById(string vendorReviewId) /// Vendors public virtual async Task> SearchVendors( string vendorId = "", - string keywords = null) + string? keywords = null) { //vendors var query = from p in _vendorRepository.Table diff --git a/src/Business/Grand.Business.Marketing/Grand.Business.Marketing.csproj b/src/Business/Grand.Business.Marketing/Grand.Business.Marketing.csproj index 2ac20c3e9..4076c6016 100644 --- a/src/Business/Grand.Business.Marketing/Grand.Business.Marketing.csproj +++ b/src/Business/Grand.Business.Marketing/Grand.Business.Marketing.csproj @@ -7,4 +7,7 @@ + + enable + diff --git a/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs b/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs index 1fb226b79..2b52121a5 100644 --- a/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Campaigns/CampaignService.cs @@ -13,6 +13,7 @@ using Grand.Domain.Tax; using Grand.Infrastructure.Extensions; using Grand.Mediator; +using Grand.SharedKernel; namespace Grand.Business.Marketing.Services.Campaigns; @@ -87,7 +88,7 @@ public virtual async Task DeleteCampaign(Campaign campaign) /// /// Campaign identifier /// Campaign - public virtual Task GetCampaignById(string campaignId) + public virtual Task GetCampaignById(string campaignId) { return campaignRepository.GetByIdAsync(campaignId); } @@ -190,7 +191,7 @@ from customers in joined //tags if (campaign.CustomerTags.Count > 0) foreach (var item in campaign.CustomerTags) - query = query.Where(x => x.CustomerTags.Contains(item)); + query = query.Where(x => x.CustomerTags != null && x.CustomerTags.Contains(item)); //roles if (campaign.CustomerGroups.Count > 0) foreach (var item in campaign.CustomerGroups) @@ -198,7 +199,7 @@ from customers in joined //categories news if (campaign.NewsletterCategories.Count > 0) foreach (var item in campaign.NewsletterCategories) - query = query.Where(x => x.NewsletterCategories.Contains(item)); + query = query.Where(x => x.NewsletterCategories != null && x.NewsletterCategories.Contains(item)); model = await newsLetterSubscriptionRepository.PagedAsync( query.Select(x => new NewsLetterSubscription { CustomerId = x.CustomerId, Email = x.Email, @@ -239,18 +240,21 @@ public virtual async Task SendCampaign(Campaign campaign, EmailAccount emai var totalEmailsSent = 0; var language = await languageService.GetLanguageById(campaign.LanguageId) ?? - (await languageService.GetAllLanguages()).FirstOrDefault(); + (await languageService.GetAllLanguages()).FirstOrDefault() ?? + throw new GrandException("No language is configured to send the campaign in"); var store = await storeService.GetStoreById(campaign.StoreId) ?? - (await storeService.GetAllStores()).FirstOrDefault(); + (await storeService.GetAllStores()).FirstOrDefault() ?? + throw new GrandException("No store is configured to send the campaign from"); foreach (var subscription in subscriptions) { - Customer customer = null; + Customer? customer = null; if (!string.IsNullOrEmpty(subscription.CustomerId)) customer = await customerRepository.GetByIdAsync(subscription.CustomerId); - customer ??= customerRepository.Table.FirstOrDefault(x => x.Email == subscription.Email.ToLowerInvariant()); + if (subscription.Email != null) + customer ??= customerRepository.Table.FirstOrDefault(x => x.Email == subscription.Email.ToLowerInvariant()); //ignore deleted or inactive customers when sending newsletter campaigns if (customer != null && (!customer.Active || customer.Deleted)) @@ -302,10 +306,12 @@ public virtual async Task SendCampaign(Campaign campaign, EmailAccount emailAcco ArgumentNullException.ThrowIfNull(emailAccount); var language = await languageService.GetLanguageById(campaign.LanguageId) ?? - (await languageService.GetAllLanguages()).FirstOrDefault(); + (await languageService.GetAllLanguages()).FirstOrDefault() ?? + throw new GrandException("No language is configured to send the campaign in"); var store = await storeService.GetStoreById(campaign.StoreId) ?? - (await storeService.GetAllStores()).FirstOrDefault(); + (await storeService.GetAllStores()).FirstOrDefault() ?? + throw new GrandException("No store is configured to send the campaign from"); var customer = customerRepository.Table.FirstOrDefault(x => x.Email == email.ToLowerInvariant()); var (subject, body) = await campaignMessageRenderer.Render(campaign, new CampaignRecipient { @@ -319,16 +325,17 @@ await emailSender.SendEmail(emailAccount, subject, body, emailAccount.Email, ema private class CampaignCustomerHelp { - public string CustomerId { get; set; } - public string CustomerEmail { get; set; } - public string Email { get; set; } + public string? CustomerId { get; set; } + public string? CustomerEmail { get; set; } + //projected from NewsLetterSubscription.Email, which every subscription has + public string Email { get; set; } = null!; public DateTime CreatedOnUtc { get; set; } public DateTime LastActivityDateUtc { get; set; } public DateTime? LastPurchaseDateUtc { get; set; } public bool HasShoppingCartItems { get; set; } public bool IsHasOrders { get; } - public ICollection CustomerTags { get; set; } - public ICollection NewsletterCategories { get; set; } + public ICollection? CustomerTags { get; set; } + public ICollection? NewsletterCategories { get; set; } public ICollection CustomerGroups { get; set; } = new List(); public Guid NewsLetterSubscriptionGuid { get; set; } } diff --git a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs index 86aa0c73b..1651abe82 100644 --- a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs +++ b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeParser.cs @@ -209,7 +209,7 @@ public virtual async Task FormatAttributes( if (allowHyperlinks) { var textPrompt = attribute.GetTranslation(a => a.TextPrompt, language.Id); - if (host != null) + if (host?.Url != null) { var downloadLink = $"{host.Url.TrimEnd('/')}/download/getfileupload/?downloadId={downloadGuid}"; diff --git a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs index a01026644..a1b122493 100644 --- a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactAttributeService.cs @@ -71,7 +71,7 @@ public virtual async Task> GetAllContactAttributes(Catal ArgumentNullException.ThrowIfNull(access); var applyAcl = !access.ShowHidden && !_accessControlConfig.IgnoreAcl; - var allowedCustomerGroupsIds = applyAcl ? access.Customer.GetCustomerGroupIds() : []; + var allowedCustomerGroupsIds = applyAcl && !access.ShowHidden ? access.Customer.GetCustomerGroupIds() : []; var key = string.Format(CacheKey.CONTACTATTRIBUTES_ALL_KEY, access.StoreId, access.ShowHidden, string.Join(",", allowedCustomerGroupsIds)); return await _cacheBase.GetAsync(key, async () => @@ -100,7 +100,7 @@ public virtual async Task> GetAllContactAttributes(Catal /// /// Contact attribute identifier /// Contact attribute - public virtual Task GetContactAttributeById(string contactAttributeId) + public virtual Task GetContactAttributeById(string? contactAttributeId) { var key = string.Format(CacheKey.CONTACTATTRIBUTES_BY_ID_KEY, contactAttributeId); return _cacheBase.GetAsync(key, () => _contactAttributeRepository.GetByIdAsync(contactAttributeId)); diff --git a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs index dc858f5d1..ec4ac2e9a 100644 --- a/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Contacts/ContactUsService.cs @@ -88,7 +88,7 @@ public virtual async Task> GetAllContactUs(DateTime? fromU /// /// ContactUs item identifier /// ContactUs item - public virtual Task GetContactUsById(string contactUsId) + public virtual Task GetContactUsById(string contactUsId) { return _contactusRepository.GetByIdAsync(contactUsId); } diff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseActionService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseActionService.cs index 5f6159f6a..26294ecad 100644 --- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseActionService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseActionService.cs @@ -17,12 +17,12 @@ public CourseActionService(IRepository courseActionRepository, IMe _mediator = mediator; } - public virtual Task GetById(string id) + public virtual Task GetById(string id) { return _courseActionRepository.GetByIdAsync(id); } - public virtual async Task GetCourseAction(string customerId, string lessonId) + public virtual async Task GetCourseAction(string customerId, string lessonId) { var query = from a in _courseActionRepository.Table where a.CustomerId == customerId && a.LessonId == lessonId diff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs index 77cde4aab..47f089b31 100644 --- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseLessonService.cs @@ -38,7 +38,7 @@ public virtual async Task> GetByCourseId(string courseId) return await _courseLessonRepository.ToListAsync(query); } - public virtual Task GetById(string id) + public virtual Task GetById(string id) { return _courseLessonRepository.GetByIdAsync(id); } diff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseLevelService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseLevelService.cs index fb3e0f89f..2f7d93fba 100644 --- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseLevelService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseLevelService.cs @@ -36,7 +36,7 @@ orderby l.DisplayOrder return await _courseLevelRepository.ToListAsync(query); } - public virtual Task GetById(string id) + public virtual Task GetById(string id) { return _courseLevelRepository.GetByIdAsync(id); } diff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs index d7761566b..3937a6f05 100644 --- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseService.cs @@ -90,7 +90,7 @@ public virtual async Task> GetByCustomer(Customer customer, string return await Task.FromResult(q1.Concat(q2).ToList()); } - public virtual Task GetById(string id) + public virtual Task GetById(string id) { return _courseRepository.GetByIdAsync(id); } diff --git a/src/Business/Grand.Business.Marketing/Services/Courses/CourseSubjectService.cs b/src/Business/Grand.Business.Marketing/Services/Courses/CourseSubjectService.cs index 0b1d585ce..63b30bdb1 100644 --- a/src/Business/Grand.Business.Marketing/Services/Courses/CourseSubjectService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Courses/CourseSubjectService.cs @@ -39,7 +39,7 @@ orderby c.DisplayOrder return await _courseSubjectRepository.ToListAsync(query); } - public virtual Task GetById(string id) + public virtual Task GetById(string id) { return _courseSubjectRepository.GetByIdAsync(id); } diff --git a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs index e1c384d60..91e21b0cd 100644 --- a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerProductService.cs @@ -39,7 +39,7 @@ public CustomerProductService( /// /// Identifier /// Customer product price - public virtual Task GetCustomerProductPriceById(string id) + public virtual Task GetCustomerProductPriceById(string id) { return _customerProductPriceRepository.GetByIdAsync(id); } @@ -61,9 +61,8 @@ public virtual Task GetCustomerProductPriceById(string id) return pp == null ? (null, false) : (pp, true); }); - if (!productPrice.Item2) - return null; - return productPrice.pp.Price; + //no price stored for the customer: pp is null exactly when Item2 is false + return productPrice.pp?.Price; } /// @@ -126,7 +125,7 @@ public virtual async Task> GetProductsPriceByCu /// /// Identifier /// Customer product - public virtual async Task GetCustomerProduct(string id) + public virtual async Task GetCustomerProduct(string id) { return await _customerProductRepository.GetByIdAsync(id); } @@ -137,7 +136,7 @@ public virtual async Task GetCustomerProduct(string id) /// Customer Identifier /// Product Identifier /// Customer product - public virtual async Task GetCustomerProduct(string customerId, string productId) + public virtual async Task GetCustomerProduct(string customerId, string productId) { var query = from pp in _customerProductRepository.Table where pp.CustomerId == customerId && pp.ProductId == productId diff --git a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs index 92ea6d673..5b2a15c2c 100644 --- a/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Customers/CustomerTagService.cs @@ -80,7 +80,7 @@ public virtual async Task> GetAllCustomerTags() /// /// Customer tag identifier /// Customer tag - public virtual Task GetCustomerTagById(string customerTagId) + public virtual Task GetCustomerTagById(string customerTagId) { return _customerTagRepository.GetByIdAsync(customerTagId); } @@ -90,7 +90,7 @@ public virtual Task GetCustomerTagById(string customerTagId) /// /// Customer tag name /// Customer tag - public virtual async Task GetCustomerTagByName(string name) + public virtual async Task GetCustomerTagByName(string name) { var query = from pt in _customerTagRepository.Table where pt.Name == name @@ -205,7 +205,7 @@ orderby cr.DisplayOrder /// Customer tag id /// Product id /// Customer tag product - public virtual async Task GetCustomerTagProduct(string customerTagId, string productId) + public virtual async Task GetCustomerTagProduct(string customerTagId, string productId) { var query = from cr in _customerTagProductRepository.Table where cr.CustomerTagId == customerTagId && cr.ProductId == productId @@ -219,7 +219,7 @@ orderby cr.DisplayOrder /// /// id /// Customer tag product - public virtual Task GetCustomerTagProductById(string id) + public virtual Task GetCustomerTagProductById(string id) { return _customerTagProductRepository.GetByIdAsync(id); } diff --git a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs index 41d769a6e..ebc040b11 100644 --- a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentService.cs @@ -65,7 +65,7 @@ public virtual async Task> GetAll(string name = "", string } - public virtual Task GetById(string id) + public virtual Task GetById(string id) { return _documentRepository.GetByIdAsync(id); } diff --git a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentTypeService.cs b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentTypeService.cs index 780416493..5572abfa1 100644 --- a/src/Business/Grand.Business.Marketing/Services/Documents/DocumentTypeService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Documents/DocumentTypeService.cs @@ -35,7 +35,7 @@ orderby t.DisplayOrder return await _documentTypeRepository.ToListAsync(query); } - public virtual Task GetById(string id) + public virtual Task GetById(string id) { return _documentTypeRepository.GetByIdAsync(id); } diff --git a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs index 852911480..76a3bb8ae 100644 --- a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsLetterSubscriptionService.cs @@ -39,9 +39,10 @@ public NewsLetterSubscriptionService( /// The email. /// if set to true [is subscribe]. /// if set to true [publish subscription events]. - private async Task PublishSubscriptionEvent(string email, bool isSubscribe, bool publishSubscriptionEvents) + private async Task PublishSubscriptionEvent(string? email, bool isSubscribe, bool publishSubscriptionEvents) { - if (publishSubscriptionEvents) + //a subscription without an e-mail has nobody to announce + if (publishSubscriptionEvents && email != null) { if (isSubscribe) await _mediator.PublishNewsletterSubscribe(email); @@ -151,7 +152,7 @@ public virtual async Task DeleteNewsLetterSubscription(NewsLetterSubscription ne /// /// The newsletter subscription identifier /// NewsLetter subscription - public virtual Task GetNewsLetterSubscriptionById(string newsLetterSubscriptionId) + public virtual Task GetNewsLetterSubscriptionById(string newsLetterSubscriptionId) { return _subscriptionRepository.GetByIdAsync(newsLetterSubscriptionId); } @@ -161,7 +162,7 @@ public virtual Task GetNewsLetterSubscriptionById(string /// /// The newsletter subscription GUID /// NewsLetter subscription - public virtual async Task GetNewsLetterSubscriptionByGuid(Guid newsLetterSubscriptionGuid) + public virtual async Task GetNewsLetterSubscriptionByGuid(Guid newsLetterSubscriptionGuid) { if (newsLetterSubscriptionGuid == Guid.Empty) return null; @@ -178,7 +179,7 @@ public virtual async Task GetNewsLetterSubscriptionByGui /// The newsletter subscription email /// Store identifier /// NewsLetter subscription - public virtual async Task GetNewsLetterSubscriptionByEmailAndStoreId(string email, + public virtual async Task GetNewsLetterSubscriptionByEmailAndStoreId(string email, string storeId) { if (!CommonHelper.IsValidEmail(email)) @@ -198,7 +199,7 @@ where nls.Email.ToLower() == email.ToLower() && nls.StoreId == storeId /// /// Customer identifier /// NewsLetter subscription - public virtual async Task GetNewsLetterSubscriptionByCustomerId(string customerId) + public virtual async Task GetNewsLetterSubscriptionByCustomerId(string customerId) { if (string.IsNullOrEmpty(customerId)) return null; @@ -220,8 +221,8 @@ public virtual async Task GetNewsLetterSubscriptionByCus /// Page index /// Page size /// NewsLetterSubscription entities - public virtual async Task> GetAllNewsLetterSubscriptions(string email = null, - string storeId = "", bool? isActive = null, string[] categoryIds = null, + public virtual async Task> GetAllNewsLetterSubscriptions(string? email = null, + string storeId = "", bool? isActive = null, string[]? categoryIds = null, int pageIndex = 0, int pageSize = int.MaxValue) { //do not filter by customer group @@ -279,7 +280,7 @@ public virtual async Task ImportNewsletterSubscribersFromTxt(Stream stream, { var count = 0; using var reader = new StreamReader(stream); - string line; + string? line; while ((line = await reader.ReadLineAsync()) is not null) { if (string.IsNullOrWhiteSpace(line)) diff --git a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsletterCategoryService.cs b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsletterCategoryService.cs index e2bf4d66e..5aba43914 100644 --- a/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsletterCategoryService.cs +++ b/src/Business/Grand.Business.Marketing/Services/Newsletters/NewsletterCategoryService.cs @@ -74,7 +74,7 @@ public virtual async Task DeleteNewsletterCategory(NewsletterCategory newsletter /// /// newsletter category /// NewsletterCategory - public virtual Task GetNewsletterCategoryById(string id) + public virtual Task GetNewsletterCategoryById(string id) { return _newsletterCategoryRepository.GetByIdAsync(id); } diff --git a/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs b/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs index 29d94fd1b..7a1de8343 100644 --- a/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs +++ b/src/Business/Grand.Business.Marketing/Services/PushNotifications/PushNotificationsService.cs @@ -62,7 +62,7 @@ public virtual async Task DeletePushReceiver(PushRegistration registration) /// Gets push receiver /// /// - public virtual async Task GetPushReceiverByCustomerId(string customerId) + public virtual async Task GetPushReceiverByCustomerId(string customerId) { return await _pushRegistrationRepository.FirstOrDefaultAsync( _pushRegistrationRepository.Table.Where(x => x.CustomerId == customerId)); @@ -145,7 +145,7 @@ public virtual async Task> GetPushReceivers(int pag /// Cancels the request to the push service /// Bool indicating whether message was sent successfully and string result to display public virtual async Task<(bool, string)> SendPushNotification(string title, string text, string pictureUrl, - string clickUrl, List registrationIds = null, CancellationToken cancellationToken = default) + string clickUrl, List? registrationIds = null, CancellationToken cancellationToken = default) { List ids; if (registrationIds != null && registrationIds.Any()) @@ -156,7 +156,7 @@ public virtual async Task> GetPushReceivers(int pag { var receivers = await GetAllowedPushReceivers(); if (!receivers.Any()) return (false, "Admin.PushNotifications.Error.NoReceivers"); - ids = receivers.Select(x => x.Token).Distinct().ToList(); + ids = receivers.Select(x => x.Token).OfType().Distinct().ToList(); } var numberOfReceivers = 0; @@ -239,7 +239,7 @@ await InsertPushMessage(new PushMessage { string customerId, string clickUrl, CancellationToken cancellationToken = default) { var receiver = await GetPushReceiverByCustomerId(customerId); - if (receiver == null) return (false, "Admin.PushNotifications.Error.NoReceivers"); + if (receiver?.Token == null) return (false, "Admin.PushNotifications.Error.NoReceivers"); return await SendPushNotification(title, text, pictureUrl, clickUrl, [receiver.Token], cancellationToken); } @@ -248,7 +248,7 @@ await InsertPushMessage(new PushMessage { /// Gets all push receivers /// /// Ident - public virtual Task GetPushReceiver(string id) + public virtual Task GetPushReceiver(string id) { return _pushRegistrationRepository.GetByIdAsync(id); } diff --git a/src/Business/Grand.Business.Marketing/Utilities/JsonResponse.cs b/src/Business/Grand.Business.Marketing/Utilities/JsonResponse.cs index f035c96db..2d2746990 100644 --- a/src/Business/Grand.Business.Marketing/Utilities/JsonResponse.cs +++ b/src/Business/Grand.Business.Marketing/Utilities/JsonResponse.cs @@ -6,10 +6,10 @@ public class JsonResponse public int success { get; set; } public int failure { get; set; } public int canonical_ids { get; set; } - public Message[] results { get; set; } + public Message[]? results { get; set; } } public class Message { - public string message_id { get; set; } + public string? message_id { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/Commands/Handlers/Catalog/SendNotificationsToSubscribersCommandHandler.cs b/src/Business/Grand.Business.Messages/Commands/Handlers/Catalog/SendNotificationsToSubscribersCommandHandler.cs index 3410a1c71..e3bae984f 100644 --- a/src/Business/Grand.Business.Messages/Commands/Handlers/Catalog/SendNotificationsToSubscribersCommandHandler.cs +++ b/src/Business/Grand.Business.Messages/Commands/Handlers/Catalog/SendNotificationsToSubscribersCommandHandler.cs @@ -59,7 +59,7 @@ await _catalogMessageProviderService.SendBackInStockMessage(customer, request.Pr /// for multi-warehouse products; for single-warehouse products it retains the legacy all-records behavior. /// Subscriptions private async Task> GetAllSubscriptionsByProductId(Product product, - IList attributes, string warehouseId) + IList? attributes, string? warehouseId) { var query = _outOfStockSubscriptionRepository.Table .Where(biss => biss.ProductId == product.Id) diff --git a/src/Business/Grand.Business.Messages/Commands/Handlers/Common/InsertContactUsCommandHandler.cs b/src/Business/Grand.Business.Messages/Commands/Handlers/Common/InsertContactUsCommandHandler.cs index ce4fc9a93..bd405eb98 100644 --- a/src/Business/Grand.Business.Messages/Commands/Handlers/Common/InsertContactUsCommandHandler.cs +++ b/src/Business/Grand.Business.Messages/Commands/Handlers/Common/InsertContactUsCommandHandler.cs @@ -26,7 +26,7 @@ public async Task Handle(InsertContactUsCommand request, CancellationToken Subject = request.Subject, Enquiry = request.Enquiry, EmailAccountId = request.EmailAccountId, - Attributes = request.ContactAttributes, + Attributes = request.ContactAttributes ?? [], ContactAttributeDescription = request.ContactAttributeDescription, IpAddress = request.RemoteIpAddress }; diff --git a/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetAuctionTokensCommandHandler.cs b/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetAuctionTokensCommandHandler.cs index d4f654157..f503518c3 100644 --- a/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetAuctionTokensCommandHandler.cs +++ b/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetAuctionTokensCommandHandler.cs @@ -28,9 +28,9 @@ public async Task Handle(GetAuctionTokensCommand request, Cancel var liquidAuctions = new LiquidAuctions(request.Product, request.Bid); var defaultCurrency = await _currencyService.GetPrimaryStoreCurrency(); liquidAuctions.Price = _priceFormatter.FormatPrice(request.Bid.Amount, defaultCurrency); - liquidAuctions.EndTime = _dateTimeService - .ConvertToUserTime(request.Product.AvailableEndDateTimeUtc.Value, DateTimeKind.Utc) - .ToString(CultureInfo.InvariantCulture); + liquidAuctions.EndTime = request.Product.AvailableEndDateTimeUtc is { } endTime + ? _dateTimeService.ConvertToUserTime(endTime, DateTimeKind.Utc).ToString(CultureInfo.InvariantCulture) + : ""; return liquidAuctions; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetMerchandiseReturnTokensCommandHandler.cs b/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetMerchandiseReturnTokensCommandHandler.cs index 0bddbbd97..c5acdaf62 100644 --- a/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetMerchandiseReturnTokensCommandHandler.cs +++ b/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetMerchandiseReturnTokensCommandHandler.cs @@ -41,19 +41,19 @@ public async Task Handle(GetMerchandiseReturnTokensComm var liquidMerchandiseReturn = new LiquidMerchandiseReturn(request.MerchandiseReturn, request.Store, request.Host, request.Order, request.MerchandiseReturnNote); - var country = await _countryService.GetCountryById(request.MerchandiseReturn.PickupAddress.CountryId); + var country = await _countryService.GetCountryById(request.MerchandiseReturn.PickupAddress?.CountryId); liquidMerchandiseReturn.Status = request.MerchandiseReturn.MerchandiseReturnStatus.ToString(); liquidMerchandiseReturn.PickupAddressStateProvince = - !string.IsNullOrEmpty(request.MerchandiseReturn.PickupAddress.StateProvinceId) + !string.IsNullOrEmpty(request.MerchandiseReturn.PickupAddress?.StateProvinceId) ? country?.StateProvinces - .FirstOrDefault(x => x.Id == request.MerchandiseReturn.PickupAddress.StateProvinceId) + .FirstOrDefault(x => x.Id == request.MerchandiseReturn.PickupAddress?.StateProvinceId) ?.GetTranslation(x => x.Name, request.Language.Id) : ""; liquidMerchandiseReturn.PickupAddressCountry = - !string.IsNullOrEmpty(request.MerchandiseReturn.PickupAddress.CountryId) + !string.IsNullOrEmpty(request.MerchandiseReturn.PickupAddress?.CountryId) ? country?.GetTranslation(x => x.Name, request.Language.Id) : ""; diff --git a/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetOrderApprovalTokensCommandHandler.cs b/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetOrderApprovalTokensCommandHandler.cs index 0067ff0d4..7ffeb49f8 100644 --- a/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetOrderApprovalTokensCommandHandler.cs +++ b/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetOrderApprovalTokensCommandHandler.cs @@ -55,7 +55,7 @@ public async Task Handle(GetOrderApprovalTokensCommand requ return liquidOrderApproval; } - private static string BuyerName(Customer buyer, Address billingAddress) + private static string BuyerName(Customer buyer, Address? billingAddress) { var name = buyer.GetFullName(); return string.IsNullOrWhiteSpace(name) @@ -63,7 +63,7 @@ private static string BuyerName(Customer buyer, Address billingAddress) : name; } - private static string Encode(string value) + private static string Encode(string? value) { return WebUtility.HtmlEncode(value ?? string.Empty); } diff --git a/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetOrderTokensCommandHandler.cs b/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetOrderTokensCommandHandler.cs index ea6cb1190..554893ee1 100644 --- a/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetOrderTokensCommandHandler.cs +++ b/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetOrderTokensCommandHandler.cs @@ -62,7 +62,7 @@ public async Task Handle(GetOrderTokensCommand request, Cancellatio var currency = await _currencyService.GetCurrencyByCode(request.Order.CustomerCurrencyCode); //the message's store, not the current one: a scheduled task or another store's admin sends it too. //The store tokens read the same store, so one e-mail never mixes the settings of two stores - var taxSettings = await _settingService.LoadSetting(request.Store?.Id); + var taxSettings = await _settingService.LoadSetting(request.Store.Id); var liquidOrder = new LiquidOrder(request.Order, request.Customer, language, currency, request.Store, request.Host, request.OrderNote, request.Vendor); diff --git a/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetRecurringPaymentTokensCommandHandler.cs b/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetRecurringPaymentTokensCommandHandler.cs index 9d6851fd7..43c279cf7 100644 --- a/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetRecurringPaymentTokensCommandHandler.cs +++ b/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetRecurringPaymentTokensCommandHandler.cs @@ -34,7 +34,7 @@ public Task Handle(GetRecurringPaymentTokensCommand requ return Task.FromResult(liquidRecurringPayment); } - private static string Encode(string value) + private static string Encode(string? value) { return WebUtility.HtmlEncode(value ?? string.Empty); } diff --git a/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetShoppingCartTokensCommandHandler.cs b/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetShoppingCartTokensCommandHandler.cs index 6f994cbda..62af84a2e 100644 --- a/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetShoppingCartTokensCommandHandler.cs +++ b/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetShoppingCartTokensCommandHandler.cs @@ -43,8 +43,8 @@ async Task ProductList() pictureUrl = await _pictureService.GetPictureUrl( product.ProductPictures.OrderByDescending(p => p.IsDefault) .ThenBy(p => p.DisplayOrder) - .FirstOrDefault()?.PictureId, 100, - storeLocation: request.Context.Store.Url); + .FirstOrDefault()?.PictureId ?? "", 100, + storeLocation: request.Context.Store.Url) ?? ""; //attributes if (item.Attributes != null && item.Attributes.Any()) diff --git a/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetStoreTokensCommandHandler.cs b/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetStoreTokensCommandHandler.cs index 3781ff77a..65694f7be 100644 --- a/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetStoreTokensCommandHandler.cs +++ b/src/Business/Grand.Business.Messages/Commands/Handlers/Messages/GetStoreTokensCommandHandler.cs @@ -19,7 +19,7 @@ public async Task Handle(GetStoreTokensCommand request, Cancellatio { //the message's store, not the current one: a scheduled task or another store's admin sends it too var storeInformationSettings = - await _settingService.LoadSetting(request.Store?.Id); + await _settingService.LoadSetting(request.Store.Id); return new LiquidStore(request.Store, request.Language, request.EmailAccount) { TwitterLink = storeInformationSettings.TwitterLink, FacebookLink = storeInformationSettings.FacebookLink, diff --git a/src/Business/Grand.Business.Messages/Commands/Tokens/GetAttributeCombinationTokensCommand.cs b/src/Business/Grand.Business.Messages/Commands/Tokens/GetAttributeCombinationTokensCommand.cs index 35e8fe910..e79c3664d 100644 --- a/src/Business/Grand.Business.Messages/Commands/Tokens/GetAttributeCombinationTokensCommand.cs +++ b/src/Business/Grand.Business.Messages/Commands/Tokens/GetAttributeCombinationTokensCommand.cs @@ -8,8 +8,8 @@ namespace Grand.Business.Messages.Commands.Tokens; public class GetAttributeCombinationTokensCommand : IRequest { - public Product Product { get; set; } - public ProductAttributeCombination Combination { get; set; } - public Language Language { get; set; } - public DomainHost Host { get; set; } + public required Product Product { get; set; } + public required ProductAttributeCombination Combination { get; set; } + public required Language Language { get; set; } + public required DomainHost Host { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/Commands/Tokens/GetAuctionTokensCommand.cs b/src/Business/Grand.Business.Messages/Commands/Tokens/GetAuctionTokensCommand.cs index eb2e8a08b..d453ab29c 100644 --- a/src/Business/Grand.Business.Messages/Commands/Tokens/GetAuctionTokensCommand.cs +++ b/src/Business/Grand.Business.Messages/Commands/Tokens/GetAuctionTokensCommand.cs @@ -6,6 +6,6 @@ namespace Grand.Business.Messages.Commands.Tokens; public class GetAuctionTokensCommand : IRequest { - public Product Product { get; set; } - public Bid Bid { get; set; } + public required Product Product { get; set; } + public required Bid Bid { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/Commands/Tokens/GetGiftVoucherTokensCommand.cs b/src/Business/Grand.Business.Messages/Commands/Tokens/GetGiftVoucherTokensCommand.cs index e1e6d09f4..911febff2 100644 --- a/src/Business/Grand.Business.Messages/Commands/Tokens/GetGiftVoucherTokensCommand.cs +++ b/src/Business/Grand.Business.Messages/Commands/Tokens/GetGiftVoucherTokensCommand.cs @@ -7,6 +7,6 @@ namespace Grand.Business.Messages.Commands.Tokens; public class GetGiftVoucherTokensCommand : IRequest { - public GiftVoucher GiftVoucher { get; set; } - public Language Language { get; set; } + public required GiftVoucher GiftVoucher { get; set; } + public Language? Language { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/Commands/Tokens/GetMerchandiseReturnTokensCommand.cs b/src/Business/Grand.Business.Messages/Commands/Tokens/GetMerchandiseReturnTokensCommand.cs index 92f1340cb..be27c669d 100644 --- a/src/Business/Grand.Business.Messages/Commands/Tokens/GetMerchandiseReturnTokensCommand.cs +++ b/src/Business/Grand.Business.Messages/Commands/Tokens/GetMerchandiseReturnTokensCommand.cs @@ -8,13 +8,13 @@ namespace Grand.Business.Messages.Commands.Tokens; public class GetMerchandiseReturnTokensCommand : IRequest { - public MerchandiseReturn MerchandiseReturn { get; set; } - public Store Store { get; set; } - public Order Order { get; set; } - public DomainHost Host { get; set; } - public Language Language { get; set; } - public MerchandiseReturnNote MerchandiseReturnNote { get; set; } = null; + public required MerchandiseReturn MerchandiseReturn { get; set; } + public required Store Store { get; set; } + public required Order Order { get; set; } + public required DomainHost Host { get; set; } + public required Language Language { get; set; } + public MerchandiseReturnNote? MerchandiseReturnNote { get; set; } = null; //the note shown to the customer with the status change, e.g. why the return was rejected - public string StatusNote { get; set; } + public string? StatusNote { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/Commands/Tokens/GetOrderApprovalTokensCommand.cs b/src/Business/Grand.Business.Messages/Commands/Tokens/GetOrderApprovalTokensCommand.cs index 8d7c282a2..5bdaa7f9a 100644 --- a/src/Business/Grand.Business.Messages/Commands/Tokens/GetOrderApprovalTokensCommand.cs +++ b/src/Business/Grand.Business.Messages/Commands/Tokens/GetOrderApprovalTokensCommand.cs @@ -9,14 +9,14 @@ namespace Grand.Business.Messages.Commands.Tokens; public class GetOrderApprovalTokensCommand : IRequest { - public OrderApproval Approval { get; set; } - public Customer Buyer { get; set; } - public Store Store { get; set; } - public DomainHost Host { get; set; } - public Language Language { get; set; } + public required OrderApproval Approval { get; set; } + public required Customer Buyer { get; set; } + public required Store Store { get; set; } + public DomainHost? Host { get; set; } + public required Language Language { get; set; } /// /// The back office panel the recipient works in; empty for a message to the buyer /// - public string PanelArea { get; set; } + public string? PanelArea { get; set; } } diff --git a/src/Business/Grand.Business.Messages/Commands/Tokens/GetOrderTokensCommand.cs b/src/Business/Grand.Business.Messages/Commands/Tokens/GetOrderTokensCommand.cs index e1331e5e7..e0265882b 100644 --- a/src/Business/Grand.Business.Messages/Commands/Tokens/GetOrderTokensCommand.cs +++ b/src/Business/Grand.Business.Messages/Commands/Tokens/GetOrderTokensCommand.cs @@ -9,11 +9,11 @@ namespace Grand.Business.Messages.Commands.Tokens; public class GetOrderTokensCommand : IRequest { - public Order Order { get; set; } - public Customer Customer { get; set; } - public Store Store { get; set; } - public DomainHost Host { get; set; } - public OrderNote OrderNote { get; set; } = null; - public Vendor Vendor { get; set; } = null; + public required Order Order { get; set; } + public Customer? Customer { get; set; } + public required Store Store { get; set; } + public required DomainHost Host { get; set; } + public OrderNote? OrderNote { get; set; } = null; + public Vendor? Vendor { get; set; } = null; public double RefundedAmount { get; set; } = 0; } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/Commands/Tokens/GetRecurringPaymentTokensCommand.cs b/src/Business/Grand.Business.Messages/Commands/Tokens/GetRecurringPaymentTokensCommand.cs index 2df989c05..9251462d4 100644 --- a/src/Business/Grand.Business.Messages/Commands/Tokens/GetRecurringPaymentTokensCommand.cs +++ b/src/Business/Grand.Business.Messages/Commands/Tokens/GetRecurringPaymentTokensCommand.cs @@ -7,6 +7,6 @@ namespace Grand.Business.Messages.Commands.Tokens; public class GetRecurringPaymentTokensCommand : IRequest { - public RecurringPayment RecurringPayment { get; set; } - public Language Language { get; set; } + public required RecurringPayment RecurringPayment { get; set; } + public required Language Language { get; set; } } diff --git a/src/Business/Grand.Business.Messages/Commands/Tokens/GetShipmentTokensCommand.cs b/src/Business/Grand.Business.Messages/Commands/Tokens/GetShipmentTokensCommand.cs index a9b3b78ec..904ece05e 100644 --- a/src/Business/Grand.Business.Messages/Commands/Tokens/GetShipmentTokensCommand.cs +++ b/src/Business/Grand.Business.Messages/Commands/Tokens/GetShipmentTokensCommand.cs @@ -9,9 +9,9 @@ namespace Grand.Business.Messages.Commands.Tokens; public class GetShipmentTokensCommand : IRequest { - public Shipment Shipment { get; set; } - public Order Order { get; set; } - public Store Store { get; set; } - public DomainHost Host { get; set; } - public Language Language { get; set; } + public required Shipment Shipment { get; set; } + public required Order Order { get; set; } + public required Store Store { get; set; } + public required DomainHost Host { get; set; } + public required Language Language { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/Commands/Tokens/GetShoppingCartTokensCommand.cs b/src/Business/Grand.Business.Messages/Commands/Tokens/GetShoppingCartTokensCommand.cs index 3b48d9d61..5f72d6e44 100644 --- a/src/Business/Grand.Business.Messages/Commands/Tokens/GetShoppingCartTokensCommand.cs +++ b/src/Business/Grand.Business.Messages/Commands/Tokens/GetShoppingCartTokensCommand.cs @@ -8,7 +8,7 @@ namespace Grand.Business.Messages.Commands.Tokens; public class GetShoppingCartTokensCommand : IRequest { - public CalculationContext Context { get; set; } - public DomainHost Host { get; set; } - public Language Language { get; set; } + public required CalculationContext Context { get; set; } + public required DomainHost Host { get; set; } + public required Language Language { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/Commands/Tokens/GetStoreTokensCommand.cs b/src/Business/Grand.Business.Messages/Commands/Tokens/GetStoreTokensCommand.cs index 2e67949d0..2ccc42020 100644 --- a/src/Business/Grand.Business.Messages/Commands/Tokens/GetStoreTokensCommand.cs +++ b/src/Business/Grand.Business.Messages/Commands/Tokens/GetStoreTokensCommand.cs @@ -8,7 +8,7 @@ namespace Grand.Business.Messages.Commands.Tokens; public class GetStoreTokensCommand : IRequest { - public Store Store { get; set; } - public Language Language { get; set; } - public EmailAccount EmailAccount { get; set; } + public required Store Store { get; set; } + public required Language Language { get; set; } + public required EmailAccount EmailAccount { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/Commands/Tokens/GetVendorTokensCommand.cs b/src/Business/Grand.Business.Messages/Commands/Tokens/GetVendorTokensCommand.cs index 5cc969273..acb58ad64 100644 --- a/src/Business/Grand.Business.Messages/Commands/Tokens/GetVendorTokensCommand.cs +++ b/src/Business/Grand.Business.Messages/Commands/Tokens/GetVendorTokensCommand.cs @@ -7,6 +7,6 @@ namespace Grand.Business.Messages.Commands.Tokens; public class GetVendorTokensCommand : IRequest { - public Vendor Vendor { get; set; } - public Language Language { get; set; } + public required Vendor Vendor { get; set; } + public required Language Language { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidAttributeCombination.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidAttributeCombination.cs index 213b3b90e..f5cb70063 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidAttributeCombination.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidAttributeCombination.cs @@ -13,9 +13,9 @@ public LiquidAttributeCombination(ProductAttributeCombination combination) AdditionalTokens = new Dictionary(); } - public string Formatted { get; set; } + public string? Formatted { get; set; } - public string SKU { get; set; } + public string? SKU { get; set; } public string StockQuantity => _combination.StockQuantity.ToString(); diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidAuctions.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidAuctions.cs index eb29ca96a..3619c8aad 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidAuctions.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidAuctions.cs @@ -5,10 +5,10 @@ namespace Grand.Business.Messages.DotLiquidDrops; public class LiquidAuctions : Drop { - private readonly Bid _bid; + private readonly Bid? _bid; private readonly Product _product; - public LiquidAuctions(Product product, Bid bid = null) + public LiquidAuctions(Product product, Bid? bid = null) { _product = product; _bid = bid; @@ -16,13 +16,13 @@ public LiquidAuctions(Product product, Bid bid = null) AdditionalTokens = new Dictionary(); } - public string ProductName => _product.Name; + public string? ProductName => _product.Name; - public string Price { get; set; } + public string? Price { get; set; } - public string EndTime { get; set; } + public string? EndTime { get; set; } - public string ProductSeName => _product.SeName; + public string? ProductSeName => _product.SeName; public IDictionary AdditionalTokens { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidBlogComment.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidBlogComment.cs index 88c882339..d82c7ab68 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidBlogComment.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidBlogComment.cs @@ -10,7 +10,7 @@ public class LiquidBlogComment : Drop { private readonly BlogComment _blogComment; private readonly BlogPost _blogPost; - private readonly DomainHost _host; + private readonly DomainHost? _host; private readonly Language _language; private readonly Store _store; @@ -30,11 +30,11 @@ public LiquidBlogComment(BlogComment blogComment, BlogPost blogPost, Store store AdditionalTokens = new Dictionary(); } - public string BlogPostTitle => _blogPost.Title; + public string? BlogPostTitle => _blogPost.Title; public string BlogPostURL => $"{url}/{_blogPost.SeName}"; - public string BlogPostCommentText => WebUtility.HtmlEncode(_blogComment?.CommentText); + public string? BlogPostCommentText => WebUtility.HtmlEncode(_blogComment?.CommentText); public IDictionary AdditionalTokens { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidCustomer.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidCustomer.cs index 938d98863..462406293 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidCustomer.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidCustomer.cs @@ -11,12 +11,12 @@ namespace Grand.Business.Messages.DotLiquidDrops; public class LiquidCustomer : Drop { private readonly Customer _customer; - private readonly CustomerNote _customerNote; - private readonly DomainHost _host; + private readonly CustomerNote? _customerNote; + private readonly DomainHost? _host; private readonly Store _store; private readonly string url; - public LiquidCustomer(Customer customer, Store store, DomainHost host, CustomerNote customerNote = null) + public LiquidCustomer(Customer customer, Store store, DomainHost host, CustomerNote? customerNote = null) { _customer = customer; _customerNote = customerNote; @@ -26,35 +26,35 @@ public LiquidCustomer(Customer customer, Store store, DomainHost host, CustomerN AdditionalTokens = new Dictionary(); } - public string Email => WebUtility.HtmlEncode(_customer.Email); + public string? Email => WebUtility.HtmlEncode(_customer.Email); - public string Username => WebUtility.HtmlEncode(_customer.Username); + public string? Username => WebUtility.HtmlEncode(_customer.Username); public string FullName => WebUtility.HtmlEncode(_customer.GetFullName()); - public string FirstName => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.FirstName)); + public string? FirstName => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.FirstName)); - public string LastName => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.LastName)); + public string? LastName => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.LastName)); - public string Gender => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.Gender)); + public string? Gender => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.Gender)); - public string DateOfBirth => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.DateOfBirth)); + public string? DateOfBirth => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.DateOfBirth)); - public string Company => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.Company)); + public string? Company => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.Company)); - public string StreetAddress => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.StreetAddress)); + public string? StreetAddress => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.StreetAddress)); - public string StreetAddress2 => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.StreetAddress2)); + public string? StreetAddress2 => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.StreetAddress2)); - public string ZipPostalCode => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.ZipPostalCode)); + public string? ZipPostalCode => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.ZipPostalCode)); - public string City => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.City)); + public string? City => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.City)); - public string Phone => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.Phone)); + public string? Phone => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.Phone)); - public string Fax => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.Fax)); + public string? Fax => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.Fax)); - public string VatNumber => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.VatNumber)); + public string? VatNumber => WebUtility.HtmlEncode(_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.VatNumber)); public string VatNumberStatus => ((VatNumberStatus)_customer.GetUserFieldFromEntity(SystemCustomerFieldNames.VatNumberStatusId)).ToString(); @@ -76,13 +76,13 @@ private string PasswordRecoveryAreaPath public string WishlistURLForCustomer => $"{url}/wishlist/{_customer.CustomerGuid}"; - public string NewNoteText => FormatText.ConvertText(_customerNote.Note); + public string NewNoteText => FormatText.ConvertText(_customerNote?.Note); - public string NewTitleText => WebUtility.HtmlEncode(_customerNote.Title); + public string? NewTitleText => WebUtility.HtmlEncode(_customerNote?.Title); - public string CustomerNoteAttachmentUrl => $"{url}/download/customernotefile/{_customerNote.Id}"; + public string CustomerNoteAttachmentUrl => $"{url}/download/customernotefile/{_customerNote?.Id}"; - public string Token => _customer.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorValidCode); + public string? Token => _customer.GetUserFieldFromEntity(SystemCustomerFieldNames.TwoFactorValidCode); public IDictionary AdditionalTokens { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidGiftVoucher.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidGiftVoucher.cs index f0ad81612..731a19d57 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidGiftVoucher.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidGiftVoucher.cs @@ -16,17 +16,17 @@ public LiquidGiftVoucher(GiftVoucher giftVoucher) AdditionalTokens = new Dictionary(); } - public string SenderName => WebUtility.HtmlEncode(_giftVoucher.SenderName); + public string? SenderName => WebUtility.HtmlEncode(_giftVoucher.SenderName); - public string SenderEmail => WebUtility.HtmlEncode(_giftVoucher.SenderEmail); + public string? SenderEmail => WebUtility.HtmlEncode(_giftVoucher.SenderEmail); - public string RecipientName => WebUtility.HtmlEncode(_giftVoucher.RecipientName); + public string? RecipientName => WebUtility.HtmlEncode(_giftVoucher.RecipientName); - public string RecipientEmail => WebUtility.HtmlEncode(_giftVoucher.RecipientEmail); + public string? RecipientEmail => WebUtility.HtmlEncode(_giftVoucher.RecipientEmail); - public string Amount { get; set; } + public string? Amount { get; set; } - public string CouponCode => _giftVoucher.Code; + public string? CouponCode => _giftVoucher.Code; public string Message { get { diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidGuestOrderLink.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidGuestOrderLink.cs index 1589ffe16..15a9c85c5 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidGuestOrderLink.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidGuestOrderLink.cs @@ -22,7 +22,7 @@ public LiquidGuestOrderLink(Order order, Store store, DomainHost host, string to AdditionalTokens = new Dictionary(); } - public string OrderCode => _order.Code; + public string? OrderCode => _order.Code; public string Url => $"{url}/guestorder/access?token={WebUtility.UrlEncode(_token)}"; diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidInventory.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidInventory.cs index 5dfd013b8..5015778de 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidInventory.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidInventory.cs @@ -31,10 +31,10 @@ public LiquidBatch(ExpiringBatch batch) _batch = batch; } - public string ProductName => _batch.ProductName; - public string Sku => _batch.Sku; + public string? ProductName => _batch.ProductName; + public string? Sku => _batch.Sku; public string Warehouse => _batch.WarehouseName; - public string Number => _batch.Batch.Number; + public string? Number => _batch.Batch.Number; public string ExpiryDate => _batch.Batch.ExpiryDateUtc?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) ?? ""; diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidKnowledgebase.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidKnowledgebase.cs index 67cb01793..2d6381403 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidKnowledgebase.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidKnowledgebase.cs @@ -10,7 +10,7 @@ public class LiquidKnowledgebase : Drop { private readonly KnowledgebaseArticle _article; private readonly KnowledgebaseArticleComment _articleComment; - private readonly DomainHost _host; + private readonly DomainHost? _host; private readonly Language _language; private readonly Store _store; @@ -30,9 +30,9 @@ public LiquidKnowledgebase(KnowledgebaseArticle article, KnowledgebaseArticleCom AdditionalTokens = new Dictionary(); } - public string ArticleTitle => _article.Name; + public string? ArticleTitle => _article.Name; - public string ArticleCommentText => WebUtility.HtmlEncode(_articleComment.CommentText); + public string? ArticleCommentText => WebUtility.HtmlEncode(_articleComment.CommentText); public string ArticleCommentUrl => $"{url}/{_article.SeName}"; diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidMerchandiseReturn.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidMerchandiseReturn.cs index e059358df..15450ce13 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidMerchandiseReturn.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidMerchandiseReturn.cs @@ -8,17 +8,17 @@ namespace Grand.Business.Messages.DotLiquidDrops; public class LiquidMerchandiseReturn : Drop { - private readonly DomainHost _host; + private readonly DomainHost? _host; private readonly MerchandiseReturn _merchandiseReturn; - private readonly MerchandiseReturnNote _merchandiseReturnNote; + private readonly MerchandiseReturnNote? _merchandiseReturnNote; private readonly Order _order; private readonly Store _store; private readonly string url; public LiquidMerchandiseReturn(MerchandiseReturn merchandiseReturn, Store store, DomainHost host, - Order order, MerchandiseReturnNote merchandiseReturnNote = null) + Order order, MerchandiseReturnNote? merchandiseReturnNote = null) { _merchandiseReturn = merchandiseReturn; _order = order; @@ -36,19 +36,19 @@ public LiquidMerchandiseReturn(MerchandiseReturn merchandiseReturn, Store store, public int ReturnNumber => _merchandiseReturn.ReturnNumber; - public string ExternalId => _merchandiseReturn.ExternalId; + public string? ExternalId => _merchandiseReturn.ExternalId; public string OrderId => _order.Id; public string OrderNumber => _order.OrderNumber.ToString(); - public string OrderCode => _order.Code; + public string? OrderCode => _order.Code; public string CustomerComment => FormatText.ConvertText(_merchandiseReturn.CustomerComments); public string StaffNotes => FormatText.ConvertText(_merchandiseReturn.StaffNotes); - public string Status { get; set; } + public string? Status { get; set; } public ICollection Items { get; } @@ -61,31 +61,31 @@ public LiquidMerchandiseReturn(MerchandiseReturn merchandiseReturn, Store store, public DateTime PickupDateUtc => _merchandiseReturn.PickupDate; - public string PickupAddressFirstName => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress.FirstName); + public string? PickupAddressFirstName => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress?.FirstName); - public string PickupAddressLastName => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress.LastName); + public string? PickupAddressLastName => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress?.LastName); - public string PickupAddressPhoneNumber => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress.PhoneNumber); + public string? PickupAddressPhoneNumber => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress?.PhoneNumber); - public string PickupAddressEmail => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress.Email); + public string? PickupAddressEmail => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress?.Email); - public string PickupAddressFaxNumber => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress.FaxNumber); + public string? PickupAddressFaxNumber => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress?.FaxNumber); - public string PickupAddressCompany => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress.Company); + public string? PickupAddressCompany => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress?.Company); - public string PickupAddressVatNumber => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress.VatNumber); + public string? PickupAddressVatNumber => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress?.VatNumber); - public string PickupAddressAddress1 => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress.Address1); + public string? PickupAddressAddress1 => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress?.Address1); - public string PickupAddressAddress2 => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress.Address2); + public string? PickupAddressAddress2 => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress?.Address2); - public string PickupAddressCity => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress.City); + public string? PickupAddressCity => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress?.City); - public string PickupAddressStateProvince { get; set; } + public string? PickupAddressStateProvince { get; set; } - public string PickupAddressZipPostalCode => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress.ZipPostalCode); + public string? PickupAddressZipPostalCode => WebUtility.HtmlEncode(_merchandiseReturn.PickupAddress?.ZipPostalCode); - public string PickupAddressCountry { get; set; } + public string? PickupAddressCountry { get; set; } public string NewNoteText => FormatText.ConvertText(_merchandiseReturnNote?.Note); diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidMerchandiseReturnItem.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidMerchandiseReturnItem.cs index 35b043041..3022f6c96 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidMerchandiseReturnItem.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidMerchandiseReturnItem.cs @@ -8,12 +8,12 @@ namespace Grand.Business.Messages.DotLiquidDrops; public class LiquidMerchandiseReturnItem : Drop { private readonly MerchandiseReturnItem _item; - private readonly string _languageId; + private readonly string? _languageId; private readonly OrderItem _orderItem; - private readonly Product _product; + private readonly Product? _product; - public LiquidMerchandiseReturnItem(MerchandiseReturnItem item, OrderItem orderItem, Product product, - string languageid) + public LiquidMerchandiseReturnItem(MerchandiseReturnItem item, OrderItem orderItem, Product? product, + string? languageid) { _item = item; _orderItem = orderItem; @@ -23,7 +23,7 @@ public LiquidMerchandiseReturnItem(MerchandiseReturnItem item, OrderItem orderIt } - public string ProductName { + public string? ProductName { get { var name = ""; @@ -34,7 +34,7 @@ public string ProductName { } } - public string ProductSeName { + public string? ProductSeName { get { var name = ""; @@ -44,7 +44,7 @@ public string ProductSeName { } } - public string ProductShortDescription { + public string? ProductShortDescription { get { var desc = ""; @@ -55,7 +55,7 @@ public string ProductShortDescription { } } - public string ProductFullDescription { + public string? ProductFullDescription { get { var desc = ""; @@ -67,13 +67,13 @@ public string ProductFullDescription { } - public string ProductId => _product.Id; + public string? ProductId => _product?.Id; public int Quantity => _item.Quantity; - public string ReasonForReturn => _item.ReasonForReturn; + public string? ReasonForReturn => _item.ReasonForReturn; - public string RequestedAction => _item.RequestedAction; + public string? RequestedAction => _item.RequestedAction; public double UnitPriceWithoutDiscInclTax => _orderItem.UnitPriceWithoutDiscInclTax; @@ -93,7 +93,7 @@ public string ProductFullDescription { public double OriginalProductCost => _orderItem.OriginalProductCost; - public string AttributeDescription => _orderItem.AttributeDescription; + public string? AttributeDescription => _orderItem.AttributeDescription; public IDictionary AdditionalTokens { get; set; } diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidNewsComment.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidNewsComment.cs index bbdd4494a..1a752ee9f 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidNewsComment.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidNewsComment.cs @@ -8,7 +8,7 @@ namespace Grand.Business.Messages.DotLiquidDrops; public class LiquidNewsComment : Drop { - private readonly DomainHost _host; + private readonly DomainHost? _host; private readonly Language _language; private readonly NewsComment _newsComment; private readonly NewsItem _newsItem; @@ -30,11 +30,11 @@ public LiquidNewsComment(NewsItem newsItem, NewsComment newsComment, Store store AdditionalTokens = new Dictionary(); } - public string NewsTitle => _newsItem.Title; + public string? NewsTitle => _newsItem.Title; - public string CommentText => WebUtility.HtmlEncode(_newsComment.CommentText); + public string? CommentText => WebUtility.HtmlEncode(_newsComment.CommentText); - public string CommentTitle => WebUtility.HtmlEncode(_newsComment.CommentTitle); + public string? CommentTitle => WebUtility.HtmlEncode(_newsComment.CommentTitle); public string NewsURL => $"{url}/{_newsItem.SeName}"; diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidNewsLetterSubscription.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidNewsLetterSubscription.cs index 4c9d30444..4a5f54e15 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidNewsLetterSubscription.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidNewsLetterSubscription.cs @@ -7,7 +7,7 @@ namespace Grand.Business.Messages.DotLiquidDrops; public class LiquidNewsLetterSubscription : Drop { - private readonly DomainHost _host; + private readonly DomainHost? _host; private readonly Store _store; private readonly NewsLetterSubscription _subscription; @@ -24,7 +24,7 @@ public LiquidNewsLetterSubscription(NewsLetterSubscription subscription, Store s AdditionalTokens = new Dictionary(); } - public string Email => WebUtility.HtmlEncode(_subscription.Email); + public string? Email => WebUtility.HtmlEncode(_subscription.Email); public string ActivationUrl { get { diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidObjectBuilder.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidObjectBuilder.cs index d30b4aa1d..1491092cf 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidObjectBuilder.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidObjectBuilder.cs @@ -59,8 +59,8 @@ public LiquidObjectBuilder AddStoreTokens(Store store, Language language, EmailA return this; } - public LiquidObjectBuilder AddOrderTokens(Order order, Customer customer, Store store, DomainHost host, - OrderNote orderNote = null, Vendor vendor = null, double refundedAmount = 0) + public LiquidObjectBuilder AddOrderTokens(Order order, Customer? customer, Store store, DomainHost host, + OrderNote? orderNote = null, Vendor? vendor = null, double refundedAmount = 0) { _chain.Add(async liquidObject => { @@ -80,7 +80,7 @@ public LiquidObjectBuilder AddOrderTokens(Order order, Customer customer, Store } public LiquidObjectBuilder AddOrderApprovalTokens(OrderApproval approval, Customer buyer, Store store, - DomainHost host, Language language, string panelArea = null) + DomainHost host, Language language, string? panelArea = null) { _chain.Add(async liquidObject => { @@ -121,8 +121,8 @@ public LiquidObjectBuilder AddShipmentTokens(Shipment shipment, Order order, Sto } public LiquidObjectBuilder AddMerchandiseReturnTokens(MerchandiseReturn merchandiseReturn, Store store, - DomainHost host, Order order, Language language, MerchandiseReturnNote merchandiseReturnNote = null, - string statusNote = null) + DomainHost host, Order order, Language language, MerchandiseReturnNote? merchandiseReturnNote = null, + string? statusNote = null) { _chain.Add(async liquidObject => { @@ -149,7 +149,7 @@ public LiquidObjectBuilder AddGiftVoucherTokens(GiftVoucher giftVoucher, Languag } public LiquidObjectBuilder AddCustomerTokens(Customer customer, Store store, DomainHost host, Language language, - CustomerNote customerNote = null) + CustomerNote? customerNote = null) { _chain.Add(async liquidObject => { diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidObjectBuilderExtensions.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidObjectBuilderExtensions.cs index 79cf33078..11a15257f 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidObjectBuilderExtensions.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidObjectBuilderExtensions.cs @@ -7,7 +7,7 @@ namespace Grand.Business.Messages.DotLiquidDrops; internal static class LiquidObjectBuilderExtensions { public static LiquidObjectBuilder AddCustomerTokensIfNotNull(this LiquidObjectBuilder builder, - Customer customer, Store store, DomainHost host, Language language) + Customer? customer, Store store, DomainHost host, Language language) { if (customer != null) { diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidOrder.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidOrder.cs index 0e024732a..dd177ef0f 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidOrder.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidOrder.cs @@ -13,19 +13,19 @@ namespace Grand.Business.Messages.DotLiquidDrops; public class LiquidOrder : Drop { - private readonly Currency _currency; - private readonly Customer _customer; - private readonly DomainHost _host; - private readonly Language _language; + private readonly Currency? _currency; + private readonly Customer? _customer; + private readonly DomainHost? _host; + private readonly Language? _language; private readonly Order _order; - private readonly OrderNote _orderNote; + private readonly OrderNote? _orderNote; private readonly Store _store; - private readonly Vendor _vendor; + private readonly Vendor? _vendor; private readonly string url; - public LiquidOrder(Order order, Customer customer, Language language, Currency currency, Store store, - DomainHost host, OrderNote orderNote = null, Vendor vendor = null) + public LiquidOrder(Order order, Customer? customer, Language? language, Currency? currency, Store store, + DomainHost host, OrderNote? orderNote = null, Vendor? vendor = null) { _order = order; _customer = customer; @@ -45,83 +45,83 @@ public LiquidOrder(Order order, Customer customer, Language language, Currency c public string OrderNumber => _order.OrderNumber.ToString(); - public string OrderCode => _order.Code; + public string? OrderCode => _order.Code; public string PurchaseOrderNumber => WebUtility.HtmlEncode(_order.PurchaseOrderNumber ?? ""); //the due date is a calendar date, so it is shown as stored, without a time zone shift public string PaymentDueDate => _order.PaymentDueDateUtc?.ToString("D") ?? ""; - public string CustomerFullName => WebUtility.HtmlEncode($"{_order.BillingAddress.FirstName} {_order.BillingAddress.LastName}"); + public string CustomerFullName => WebUtility.HtmlEncode($"{_order.BillingAddress?.FirstName} {_order.BillingAddress?.LastName}"); - public string CustomerEmail => WebUtility.HtmlEncode(_order.BillingAddress.Email); + public string? CustomerEmail => WebUtility.HtmlEncode(_order.BillingAddress?.Email); - public string BillingAddressName => WebUtility.HtmlEncode(_order.BillingAddress.Name); + public string? BillingAddressName => WebUtility.HtmlEncode(_order.BillingAddress?.Name); - public string BillingFirstName => WebUtility.HtmlEncode(_order.BillingAddress.FirstName); + public string? BillingFirstName => WebUtility.HtmlEncode(_order.BillingAddress?.FirstName); - public string BillingLastName => WebUtility.HtmlEncode(_order.BillingAddress.LastName); + public string? BillingLastName => WebUtility.HtmlEncode(_order.BillingAddress?.LastName); - public string BillingPhoneNumber => WebUtility.HtmlEncode(_order.BillingAddress.PhoneNumber); + public string? BillingPhoneNumber => WebUtility.HtmlEncode(_order.BillingAddress?.PhoneNumber); - public string BillingEmail => WebUtility.HtmlEncode(_order.BillingAddress.Email); + public string? BillingEmail => WebUtility.HtmlEncode(_order.BillingAddress?.Email); - public string BillingFaxNumber => WebUtility.HtmlEncode(_order.BillingAddress.FaxNumber); + public string? BillingFaxNumber => WebUtility.HtmlEncode(_order.BillingAddress?.FaxNumber); - public string BillingCompany => WebUtility.HtmlEncode(_order.BillingAddress.Company); + public string? BillingCompany => WebUtility.HtmlEncode(_order.BillingAddress?.Company); - public string BillingVatNumber => WebUtility.HtmlEncode(_order.BillingAddress.VatNumber); + public string? BillingVatNumber => WebUtility.HtmlEncode(_order.BillingAddress?.VatNumber); - public string BillingAddress1 => WebUtility.HtmlEncode(_order.BillingAddress.Address1); + public string? BillingAddress1 => WebUtility.HtmlEncode(_order.BillingAddress?.Address1); - public string BillingAddress2 => WebUtility.HtmlEncode(_order.BillingAddress.Address2); + public string? BillingAddress2 => WebUtility.HtmlEncode(_order.BillingAddress?.Address2); - public string BillingCity => WebUtility.HtmlEncode(_order.BillingAddress.City); + public string? BillingCity => WebUtility.HtmlEncode(_order.BillingAddress?.City); - public string BillingStateProvince { get; set; } + public string? BillingStateProvince { get; set; } - public string BillingZipPostalCode => WebUtility.HtmlEncode(_order.BillingAddress.ZipPostalCode); + public string? BillingZipPostalCode => WebUtility.HtmlEncode(_order.BillingAddress?.ZipPostalCode); - public string BillingCountry { get; set; } + public string? BillingCountry { get; set; } - public string BillingCustomAttributes { get; set; } + public string? BillingCustomAttributes { get; set; } - public string ShippingMethod => _order.ShippingMethod; + public string? ShippingMethod => _order.ShippingMethod; - public string ShippingAdditionDescription => _order.ShippingOptionAttributeDescription; + public string? ShippingAdditionDescription => _order.ShippingOptionAttributeDescription; - public string ShippingAddressName => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.Name : ""); + public string? ShippingAddressName => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.Name : ""); - public string ShippingFirstName => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.FirstName : ""); + public string? ShippingFirstName => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.FirstName : ""); - public string ShippingLastName => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.LastName : ""); + public string? ShippingLastName => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.LastName : ""); - public string ShippingPhoneNumber => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.PhoneNumber : ""); + public string? ShippingPhoneNumber => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.PhoneNumber : ""); - public string ShippingEmail => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.Email : ""); + public string? ShippingEmail => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.Email : ""); - public string ShippingFaxNumber => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.FaxNumber : ""); + public string? ShippingFaxNumber => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.FaxNumber : ""); - public string ShippingCompany => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.Company : ""); + public string? ShippingCompany => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.Company : ""); - public string ShippingAddress1 => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.Address1 : ""); + public string? ShippingAddress1 => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.Address1 : ""); - public string ShippingAddress2 => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.Address2 : ""); + public string? ShippingAddress2 => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.Address2 : ""); - public string ShippingCity => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.City : ""); + public string? ShippingCity => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.City : ""); - public string ShippingStateProvince { get; set; } + public string? ShippingStateProvince { get; set; } - public string ShippingZipPostalCode => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.ZipPostalCode : ""); + public string? ShippingZipPostalCode => WebUtility.HtmlEncode(_order.ShippingAddress != null ? _order.ShippingAddress.ZipPostalCode : ""); - public string ShippingCountry { get; set; } + public string? ShippingCountry { get; set; } - public string ShippingCustomAttributes { get; set; } + public string? ShippingCustomAttributes { get; set; } - public string PaymentMethod { get; set; } + public string? PaymentMethod { get; set; } - public string VatNumber => WebUtility.HtmlEncode(_order.VatNumber); + public string? VatNumber => WebUtility.HtmlEncode(_order.VatNumber); public string CreatedOn => _order.CreatedOnUtc.ToLocalTime().ToString("D"); @@ -133,52 +133,52 @@ public LiquidOrder(Order order, Customer customer, Language language, Currency c public double RefundedAmount => _order.RefundedAmount; - public string NewNoteText => FormatText.ConvertText(_orderNote.Note); + public string NewNoteText => FormatText.ConvertText(_orderNote?.Note); - public string OrderNoteAttachmentUrl => $"{url}/download/ordernotefile/{_orderNote.Id}"; + public string OrderNoteAttachmentUrl => $"{url}/download/ordernotefile/{_orderNote?.Id}"; - public string VendorName => WebUtility.HtmlEncode(_vendor?.Name); + public string? VendorName => WebUtility.HtmlEncode(_vendor?.Name); - public string VendorEmail => WebUtility.HtmlEncode(_vendor?.Email); + public string? VendorEmail => WebUtility.HtmlEncode(_vendor?.Email); public ICollection OrderItems { get; } public bool DisplaySubTotalDiscount { get; set; } - public string SubTotalDiscount { get; set; } + public string? SubTotalDiscount { get; set; } - public string SubTotal { get; set; } + public string? SubTotal { get; set; } - public string Shipping { get; set; } + public string? Shipping { get; set; } - public string Tax { get; set; } + public string? Tax { get; set; } - public string Total { get; set; } + public string? Total { get; set; } public bool DisplayShipping => _order.ShippingStatusId != ShippingStatus.ShippingNotRequired; public bool DisplayPaymentMethodFee => _order.PaymentMethodAdditionalFeeExclTax > 0; - public string PaymentMethodAdditionalFee { get; set; } + public string? PaymentMethodAdditionalFee { get; set; } public bool DisplayTax { get; set; } public bool DisplayTaxRates { get; set; } - public Dictionary TaxRates { get; set; } + public Dictionary? TaxRates { get; set; } public bool DisplayDiscount { get; set; } - public string Discount { get; set; } + public string? Discount { get; set; } - public string CheckoutAttributeDescription => _order.CheckoutAttributeDescription; + public string? CheckoutAttributeDescription => _order.CheckoutAttributeDescription; - public Dictionary GiftVouchers { get; set; } + public Dictionary? GiftVouchers { get; set; } public bool RedeemedLoyaltyPointsEntryExists => _order.RedeemedLoyaltyPoints > 0; - public string RPAmount { get; set; } - public string RPPoints { get; set; } + public string? RPAmount { get; set; } + public string? RPPoints { get; set; } public bool IsRecurring => _order.IsRecurring; diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidOrderApproval.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidOrderApproval.cs index 2803e491a..1ff593b59 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidOrderApproval.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidOrderApproval.cs @@ -12,51 +12,51 @@ public LiquidOrderApproval() AdditionalTokens = new Dictionary(); } - public string BuyerName { get; set; } + public string? BuyerName { get; set; } - public string BuyerEmail { get; set; } + public string? BuyerEmail { get; set; } - public string Status { get; set; } + public string? Status { get; set; } /// /// The order total, already formatted in the buyer's currency /// - public string Total { get; set; } + public string? Total { get; set; } /// /// The cart lines as an HTML table; every value is HTML-encoded /// - public string ItemsHtml { get; set; } + public string? ItemsHtml { get; set; } /// /// The approver's comment; HTML-encoded /// - public string DecisionComment { get; set; } + public string? DecisionComment { get; set; } /// /// Absolute link to the approval request /// - public string Url { get; set; } + public string? Url { get; set; } /// /// Number of the order awaiting the decision; empty when the order no longer exists /// - public string OrderNumber { get; set; } + public string? OrderNumber { get; set; } /// /// Absolute link to the order in the buyer's account /// - public string OrderUrl { get; set; } + public string? OrderUrl { get; set; } /// /// Why the order needs an approval, as an HTML list; every value is HTML-encoded. Empty when there is no reason. /// - public string ReasonsHtml { get; set; } + public string? ReasonsHtml { get; set; } /// /// Absolute link to the order in the back office panel the recipient works in; empty for a message to the buyer /// - public string PanelUrl { get; set; } + public string? PanelUrl { get; set; } public IDictionary AdditionalTokens { get; set; } } diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidOrderItem.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidOrderItem.cs index 56458dfe4..1f3a1fbd7 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidOrderItem.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidOrderItem.cs @@ -11,17 +11,17 @@ namespace Grand.Business.Messages.DotLiquidDrops; public class LiquidOrderItem : Drop { - private readonly DomainHost _host; - private readonly Language _language; + private readonly DomainHost? _host; + private readonly Language? _language; private readonly OrderItem _orderItem; - private readonly Product _product; + private readonly Product? _product; private readonly Store _store; - private readonly Vendor _vendor; + private readonly Vendor? _vendor; private readonly string url; - public LiquidOrderItem(OrderItem orderItem, Product product, Language language, Store store, DomainHost host, - Vendor vendor) + public LiquidOrderItem(OrderItem orderItem, Product? product, Language? language, Store store, DomainHost host, + Vendor? vendor) { _orderItem = orderItem; _store = store; @@ -35,13 +35,13 @@ public LiquidOrderItem(OrderItem orderItem, Product product, Language language, AdditionalTokens = new Dictionary(); } - public string UnitPrice { get; set; } + public string? UnitPrice { get; set; } public bool UnitPriceWithTax { get; set; } - public string TotalPrice { get; set; } + public string? TotalPrice { get; set; } public bool TotalPriceWithTax { get; set; } - public string ProductSku { get; set; } + public string? ProductSku { get; set; } public bool IsDownloadAllowed { get; set; } @@ -63,56 +63,56 @@ public string LicenseUrl { public Guid OrderItemGuid => _orderItem.OrderItemGuid; - public string ProductName { + public string? ProductName { get { var name = ""; if (_product != null) - name = WebUtility.HtmlEncode(_product.GetTranslation(x => x.Name, _language.Id)); + name = WebUtility.HtmlEncode(_product.GetTranslation(x => x.Name, _language?.Id)); return name; } } - public string ProductSeName { + public string? ProductSeName { get { var name = ""; if (_product != null) - name = _product.GetTranslation(x => x.SeName, _language.Id); + name = _product.GetTranslation(x => x.SeName, _language?.Id); return name; } } - public string ProductShortDescription { + public string? ProductShortDescription { get { var desc = ""; if (_product != null) - desc = WebUtility.HtmlEncode(_product.GetTranslation(x => x.ShortDescription, _language.Id)); + desc = WebUtility.HtmlEncode(_product.GetTranslation(x => x.ShortDescription, _language?.Id)); return desc; } } - public string ProductFullDescription { + public string? ProductFullDescription { get { var desc = ""; if (_product != null) - desc = WebUtility.HtmlDecode(_product.GetTranslation(x => x.FullDescription, _language.Id)); + desc = WebUtility.HtmlDecode(_product.GetTranslation(x => x.FullDescription, _language?.Id)); return desc; } } - public string ProductId => _orderItem.ProductId; + public string? ProductId => _orderItem.ProductId; - public string VendorId => _orderItem.VendorId; + public string? VendorId => _orderItem.VendorId; - public string VendorName => _vendor?.Name; + public string? VendorName => _vendor?.Name; - public string WarehouseId => _orderItem.WarehouseId; + public string? WarehouseId => _orderItem.WarehouseId; public int Quantity => _orderItem.Quantity; @@ -142,29 +142,29 @@ public string ProductFullDescription { public double OriginalProductCost => _orderItem.OriginalProductCost; - public string AttributeDescription => _orderItem.AttributeDescription; + public string? AttributeDescription => _orderItem.AttributeDescription; public int DownloadCount => _orderItem.DownloadCount; public bool IsDownloadActivated => _orderItem.IsDownloadActivated; - public string LicenseDownloadId => _orderItem.LicenseDownloadId; + public string? LicenseDownloadId => _orderItem.LicenseDownloadId; public double? ItemWeight => _orderItem.ItemWeight; - public double ProductWeight => _product.Weight; + public double ProductWeight => _product?.Weight ?? 0; - public double ProductLength => _product.Length; + public double ProductLength => _product?.Length ?? 0; - public double ProductWidth => _product.Width; + public double ProductWidth => _product?.Width ?? 0; - public double ProductHeight => _product.Height; + public double ProductHeight => _product?.Height ?? 0; - public double ProductCatalogPrice => _product.CatalogPrice; + public double ProductCatalogPrice => _product?.CatalogPrice ?? 0; - public double ProductOldPrice => _product.OldPrice; + public double ProductOldPrice => _product?.OldPrice ?? 0; - public string ProductFlag => _product.Flag; + public string? ProductFlag => _product?.Flag; public DateTime? RentalStartDateUtc => _orderItem.RentalStartDateUtc; diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidOutOfStockSubscription.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidOutOfStockSubscription.cs index 5672aa60c..6c11a5381 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidOutOfStockSubscription.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidOutOfStockSubscription.cs @@ -7,7 +7,7 @@ namespace Grand.Business.Messages.DotLiquidDrops; public class LiquidOutOfStockSubscription : Drop { - private readonly DomainHost _host; + private readonly DomainHost? _host; private readonly Language _language; private readonly OutOfStockSubscription _outOfStockSubscription; private readonly Product _product; @@ -28,9 +28,9 @@ public LiquidOutOfStockSubscription(Product product, OutOfStockSubscription outO AdditionalTokens = new Dictionary(); } - public string ProductName => _product.Name; + public string? ProductName => _product.Name; - public string AttributeInfo => _outOfStockSubscription.AttributeInfo; + public string? AttributeInfo => _outOfStockSubscription.AttributeInfo; public string ProductUrl => $"{url}/{_product.SeName}"; diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidProduct.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidProduct.cs index 8bbd877f2..fa63608ea 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidProduct.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidProduct.cs @@ -8,7 +8,7 @@ namespace Grand.Business.Messages.DotLiquidDrops; public class LiquidProduct : Drop { - private readonly DomainHost _host; + private readonly DomainHost? _host; private readonly Language _language; private readonly Product _product; private readonly Store _store; @@ -27,17 +27,17 @@ public LiquidProduct(Product product, Language language, Store store, DomainHost public string Id => _product.Id; - public string Name => _product.GetTranslation(x => x.Name, _language.Id); + public string? Name => _product.GetTranslation(x => x.Name, _language.Id); - public string ShortDescription => _product.GetTranslation(x => x.ShortDescription, _language.Id); + public string? ShortDescription => _product.GetTranslation(x => x.ShortDescription, _language.Id); - public string SKU => _product.Sku; + public string? SKU => _product.Sku; - public string ExternalId => _product.ExternalId; + public string? ExternalId => _product.ExternalId; - public string Mpn => _product.Mpn; + public string? Mpn => _product.Mpn; - public string Gtin => _product.Gtin; + public string? Gtin => _product.Gtin; public double AdditionalShippingCharge => _product.AdditionalShippingCharge; @@ -50,7 +50,7 @@ public LiquidProduct(Product product, Language language, Store store, DomainHost public double OldPrice => _product.OldPrice; - public string Flag => _product.Flag; + public string? Flag => _product.Flag; public string ProductURLForCustomer => $"{url}/{_product.GetSeName(_language.Id)}"; diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidProductReview.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidProductReview.cs index c46b2c296..65db3b630 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidProductReview.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidProductReview.cs @@ -15,9 +15,9 @@ public LiquidProductReview(Product product, ProductReview productReview) AdditionalTokens = new Dictionary(); } - public string ProductName => _product.Name; + public string? ProductName => _product.Name; - public string ProductReviewReplyText => _productReview.ReplyText; + public string? ProductReviewReplyText => _productReview.ReplyText; public IDictionary AdditionalTokens { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidRecurringPayment.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidRecurringPayment.cs index 79e9eebaa..9af3a6a69 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidRecurringPayment.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidRecurringPayment.cs @@ -18,7 +18,7 @@ public LiquidRecurringPayment() /// /// The cycle period, translated /// - public string CyclePeriod { get; set; } + public string? CyclePeriod { get; set; } public int CyclesPaid { get; set; } @@ -30,12 +30,12 @@ public LiquidRecurringPayment() /// /// The reason the last cycle failed, as the gateway reported it; HTML-encoded /// - public string LastError { get; set; } + public string? LastError { get; set; } /// /// Who cancelled: the customer, a staff name or the provider; HTML-encoded /// - public string CancelledBy { get; set; } + public string? CancelledBy { get; set; } public IDictionary AdditionalTokens { get; set; } } diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidShipment.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidShipment.cs index 97d8b00d9..d8a26766a 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidShipment.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidShipment.cs @@ -8,7 +8,7 @@ namespace Grand.Business.Messages.DotLiquidDrops; public class LiquidShipment : Drop { - private readonly DomainHost _host; + private readonly DomainHost? _host; private readonly Language _language; private readonly Order _order; private readonly Shipment _shipment; @@ -33,7 +33,7 @@ public LiquidShipment(Shipment shipment, Order order, Store store, DomainHost ho public string ShipmentNumber => _shipment.ShipmentNumber.ToString(); - public string TrackingNumber => _shipment.TrackingNumber; + public string? TrackingNumber => _shipment.TrackingNumber; public DateTime? ShippedDateUtc => _shipment.ShippedDateUtc; @@ -41,7 +41,7 @@ public LiquidShipment(Shipment shipment, Order order, Store store, DomainHost ho public DateTime CreatedOnUtc => _shipment.CreatedOnUtc; - public string AdminComment => _shipment.AdminComment; + public string? AdminComment => _shipment.AdminComment; public string URLForCustomer => $"{url}/orderdetails/shipment/{_shipment.Id}"; diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidShipmentItem.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidShipmentItem.cs index 945b2297f..7a399883b 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidShipmentItem.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidShipmentItem.cs @@ -12,13 +12,13 @@ public class LiquidShipmentItem : Drop { private readonly Language _language; private readonly Order _order; - private readonly OrderItem _orderItem; - private readonly Product _product; + private readonly OrderItem? _orderItem; + private readonly Product? _product; private readonly Shipment _shipment; private readonly ShipmentItem _shipmentItem; - public LiquidShipmentItem(ShipmentItem shipmentItem, Shipment shipment, Order order, OrderItem orderItem, - Product product, Language language) + public LiquidShipmentItem(ShipmentItem shipmentItem, Shipment shipment, Order order, OrderItem? orderItem, + Product? product, Language language) { _shipmentItem = shipmentItem; _language = language; @@ -32,7 +32,7 @@ public LiquidShipmentItem(ShipmentItem shipmentItem, Shipment shipment, Order or public bool ShowSkuOnProductDetailsPage { get; set; } - public string ProductName { + public string? ProductName { get { var name = ""; if (_product != null) @@ -42,9 +42,9 @@ public string ProductName { } } - public string ProductSku => _orderItem.Sku; + public string? ProductSku => _orderItem?.Sku; - public string AttributeDescription { + public string? AttributeDescription { get { var attDesc = ""; @@ -57,13 +57,13 @@ public string AttributeDescription { public string ShipmentId => _shipment.Id; - public string OrderItemId => _shipmentItem.OrderItemId; + public string? OrderItemId => _shipmentItem.OrderItemId; - public string ProductId => _shipmentItem.ProductId; + public string? ProductId => _shipmentItem.ProductId; public int Quantity => _shipmentItem.Quantity; - public string WarehouseId => _shipmentItem.WarehouseId; + public string? WarehouseId => _shipmentItem.WarehouseId; /// /// The serial numbers shipped, comma separated; empty for a product tracking none diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidShoppingCart.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidShoppingCart.cs index c17f00aed..5d7da45d9 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidShoppingCart.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidShoppingCart.cs @@ -15,15 +15,15 @@ public LiquidShoppingCart(Customer customer) AdditionalTokens = new Dictionary(); } - public string Email => _customer.Email; + public string? Email => _customer.Email; - public string Username => _customer.Username; + public string? Username => _customer.Username; public string FullName => _customer.GetFullName(); - public string FirstName => _customer.GetUserFieldFromEntity(SystemCustomerFieldNames.FirstName); + public string? FirstName => _customer.GetUserFieldFromEntity(SystemCustomerFieldNames.FirstName); - public string LastName => _customer.GetUserFieldFromEntity(SystemCustomerFieldNames.LastName); + public string? LastName => _customer.GetUserFieldFromEntity(SystemCustomerFieldNames.LastName); public ICollection Items { get; } diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidShoppingCartItem.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidShoppingCartItem.cs index 858a8c79f..bbaf4dd14 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidShoppingCartItem.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidShoppingCartItem.cs @@ -35,7 +35,7 @@ public LiquidShoppingCartItem(Product product, public ShoppingCartType ShoppingCartType => _shoppingCartItem.ShoppingCartTypeId; - public string ProductName { + public string? ProductName { get { var name = ""; @@ -46,7 +46,7 @@ public string ProductName { } } - public string ProductSeName { + public string? ProductSeName { get { var name = ""; @@ -56,7 +56,7 @@ public string ProductSeName { } } - public string ProductShortDescription { + public string? ProductShortDescription { get { var desc = ""; @@ -67,7 +67,7 @@ public string ProductShortDescription { } } - public string ProductFullDescription { + public string? ProductFullDescription { get { var desc = ""; diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidStore.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidStore.cs index 15ff9a6d5..711f7982d 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidStore.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidStore.cs @@ -7,11 +7,11 @@ namespace Grand.Business.Messages.DotLiquidDrops; public class LiquidStore : Drop { - private readonly EmailAccount _emailAccount; + private readonly EmailAccount? _emailAccount; private readonly Language _language; private readonly Store _store; - public LiquidStore(Store store, Language language, EmailAccount emailAccount = null) + public LiquidStore(Store store, Language language, EmailAccount? emailAccount = null) { _store = store; _language = language; @@ -20,47 +20,47 @@ public LiquidStore(Store store, Language language, EmailAccount emailAccount = n AdditionalTokens = new Dictionary(); } - public string Name => _store.Name; + public string? Name => _store.Name; - public string Shortcut => _store.Shortcut; + public string? Shortcut => _store.Shortcut; - public string URL => _store.Url; + public string? URL => _store.Url; - public string Email => _emailAccount.Email; + public string? Email => _emailAccount?.Email; - public string CompanyName => _store.CompanyName; + public string? CompanyName => _store.CompanyName; - public string CompanyAddress => _store.CompanyAddress; + public string? CompanyAddress => _store.CompanyAddress; - public string CompanyPhoneNumber => _store.CompanyPhoneNumber; + public string? CompanyPhoneNumber => _store.CompanyPhoneNumber; - public string CompanyEmail => _store.CompanyEmail; + public string? CompanyEmail => _store.CompanyEmail; - public string CompanyHours => _store.CompanyHours; + public string? CompanyHours => _store.CompanyHours; - public string CompanyRegNo => _store.CompanyRegNo; + public string? CompanyRegNo => _store.CompanyRegNo; - public string CompanyVat => _store.CompanyVat; + public string? CompanyVat => _store.CompanyVat; - public string BankCode => _store.BankAccount?.BankCode; + public string? BankCode => _store.BankAccount?.BankCode; - public string BankName => _store.BankAccount?.BankName; + public string? BankName => _store.BankAccount?.BankName; - public string SwiftCode => _store.BankAccount?.SwiftCode; + public string? SwiftCode => _store.BankAccount?.SwiftCode; - public string AccountNumber => _store.BankAccount?.AccountNumber; + public string? AccountNumber => _store.BankAccount?.AccountNumber; - public string TwitterLink { get; set; } + public string? TwitterLink { get; set; } - public string FacebookLink { get; set; } + public string? FacebookLink { get; set; } - public string YoutubeLink { get; set; } + public string? YoutubeLink { get; set; } - public string InstagramLink { get; set; } + public string? InstagramLink { get; set; } - public string LinkedInLink { get; set; } + public string? LinkedInLink { get; set; } - public string PinterestLink { get; set; } + public string? PinterestLink { get; set; } public IDictionary AdditionalTokens { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidVendor.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidVendor.cs index 5a2d80a52..835f22b1e 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidVendor.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidVendor.cs @@ -14,29 +14,29 @@ public LiquidVendor(Vendor vendor) AdditionalTokens = new Dictionary(); } - public string Name => WebUtility.HtmlEncode(_vendor.Name); + public string? Name => WebUtility.HtmlEncode(_vendor.Name); - public string Email => WebUtility.HtmlEncode(_vendor.Email); + public string? Email => WebUtility.HtmlEncode(_vendor.Email); - public string Description => _vendor.Description; + public string? Description => _vendor.Description; - public string Address1 => WebUtility.HtmlEncode(_vendor.Address?.Address1); + public string? Address1 => WebUtility.HtmlEncode(_vendor.Address?.Address1); - public string Address2 => WebUtility.HtmlEncode(_vendor.Address?.Address2); + public string? Address2 => WebUtility.HtmlEncode(_vendor.Address?.Address2); - public string City => WebUtility.HtmlEncode(_vendor.Address?.City); + public string? City => WebUtility.HtmlEncode(_vendor.Address?.City); - public string Company => WebUtility.HtmlEncode(_vendor.Address?.Company); + public string? Company => WebUtility.HtmlEncode(_vendor.Address?.Company); - public string FaxNumber => WebUtility.HtmlEncode(_vendor.Address?.FaxNumber); + public string? FaxNumber => WebUtility.HtmlEncode(_vendor.Address?.FaxNumber); - public string PhoneNumber => WebUtility.HtmlEncode(_vendor.Address?.PhoneNumber); + public string? PhoneNumber => WebUtility.HtmlEncode(_vendor.Address?.PhoneNumber); - public string ZipPostalCode => WebUtility.HtmlEncode(_vendor.Address?.ZipPostalCode); + public string? ZipPostalCode => WebUtility.HtmlEncode(_vendor.Address?.ZipPostalCode); - public string StateProvince { get; set; } + public string? StateProvince { get; set; } - public string Country { get; set; } + public string? Country { get; set; } public IDictionary AdditionalTokens { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidVendorReview.cs b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidVendorReview.cs index aa33850c3..3a9a5b71c 100644 --- a/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidVendorReview.cs +++ b/src/Business/Grand.Business.Messages/DotLiquidDrops/LiquidVendorReview.cs @@ -17,11 +17,11 @@ public LiquidVendorReview(Vendor vendor, VendorReview vendorReview) AdditionalTokens = new Dictionary(); } - public string VendorName => WebUtility.HtmlEncode(_vendor.Name); + public string? VendorName => WebUtility.HtmlEncode(_vendor.Name); - public string Title => WebUtility.HtmlEncode(_vendorReview.Title); + public string? Title => WebUtility.HtmlEncode(_vendorReview.Title); - public string ReviewText => WebUtility.HtmlEncode(_vendorReview.ReviewText); + public string? ReviewText => WebUtility.HtmlEncode(_vendorReview.ReviewText); public IDictionary AdditionalTokens { get; set; } } \ No newline at end of file diff --git a/src/Business/Grand.Business.Messages/Grand.Business.Messages.csproj b/src/Business/Grand.Business.Messages/Grand.Business.Messages.csproj index 6eb8385ff..08babeddb 100644 --- a/src/Business/Grand.Business.Messages/Grand.Business.Messages.csproj +++ b/src/Business/Grand.Business.Messages/Grand.Business.Messages.csproj @@ -9,4 +9,7 @@ + + enable + diff --git a/src/Business/Grand.Business.Messages/Queries/Handlers/GetCustomerByIdQueryHandler.cs b/src/Business/Grand.Business.Messages/Queries/Handlers/GetCustomerByIdQueryHandler.cs index e8ccda7b4..387994f73 100644 --- a/src/Business/Grand.Business.Messages/Queries/Handlers/GetCustomerByIdQueryHandler.cs +++ b/src/Business/Grand.Business.Messages/Queries/Handlers/GetCustomerByIdQueryHandler.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Messages.Queries.Handlers; -public class GetCustomerByIdQueryHandler : IRequestHandler +public class GetCustomerByIdQueryHandler : IRequestHandler { private readonly IRepository _customerRepository; @@ -14,7 +14,7 @@ public GetCustomerByIdQueryHandler(IRepository customerRepository) _customerRepository = customerRepository; } - public async Task Handle(GetCustomerByIdQuery request, CancellationToken cancellationToken) + public async Task Handle(GetCustomerByIdQuery request, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(request.Id)) return null; diff --git a/src/Business/Grand.Business.Messages/Queries/Handlers/GetProductByIdQueryHandler.cs b/src/Business/Grand.Business.Messages/Queries/Handlers/GetProductByIdQueryHandler.cs index 94aa53bb2..e782e063c 100644 --- a/src/Business/Grand.Business.Messages/Queries/Handlers/GetProductByIdQueryHandler.cs +++ b/src/Business/Grand.Business.Messages/Queries/Handlers/GetProductByIdQueryHandler.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Messages.Queries.Handlers; -public class GetProductByIdQueryHandler : IRequestHandler +public class GetProductByIdQueryHandler : IRequestHandler { private readonly IRepository _productRepository; @@ -14,7 +14,7 @@ public GetProductByIdQueryHandler(IRepository productRepository) _productRepository = productRepository; } - public async Task Handle(GetProductByIdQuery request, CancellationToken cancellationToken) + public async Task Handle(GetProductByIdQuery request, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(request.Id)) return null; diff --git a/src/Business/Grand.Business.Messages/Queries/Handlers/GetVendorByIdQueryHandler.cs b/src/Business/Grand.Business.Messages/Queries/Handlers/GetVendorByIdQueryHandler.cs index ba1bf86f8..5badef2d1 100644 --- a/src/Business/Grand.Business.Messages/Queries/Handlers/GetVendorByIdQueryHandler.cs +++ b/src/Business/Grand.Business.Messages/Queries/Handlers/GetVendorByIdQueryHandler.cs @@ -5,7 +5,7 @@ namespace Grand.Business.Messages.Queries.Handlers; -public class GetVendorByIdQueryHandler : IRequestHandler +public class GetVendorByIdQueryHandler : IRequestHandler { private readonly IRepository _vendorRepository; @@ -14,7 +14,7 @@ public GetVendorByIdQueryHandler(IRepository vendorRepository) _vendorRepository = vendorRepository; } - public async Task Handle(GetVendorByIdQuery request, CancellationToken cancellationToken) + public async Task Handle(GetVendorByIdQuery request, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(request.Id)) return null; diff --git a/src/Business/Grand.Business.Messages/Services/CatalogMessageProviderService.cs b/src/Business/Grand.Business.Messages/Services/CatalogMessageProviderService.cs index c73f25467..ab2bd5285 100644 --- a/src/Business/Grand.Business.Messages/Services/CatalogMessageProviderService.cs +++ b/src/Business/Grand.Business.Messages/Services/CatalogMessageProviderService.cs @@ -57,8 +57,8 @@ public CatalogMessageProviderService( /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - public virtual async Task SendProductEmailAFriendMessage(Customer customer, Store store, string languageId, - Product product, string customerEmail, string friendsEmail, string personalMessage, DomainHost host = null) + public virtual async Task SendProductEmailAFriendMessage(Customer customer, Store store, string? languageId, + Product product, string customerEmail, string friendsEmail, string personalMessage, DomainHost? host = null) { ArgumentNullException.ThrowIfNull(customer); ArgumentNullException.ThrowIfNull(product); @@ -104,8 +104,8 @@ public virtual async Task SendProductEmailAFriendMessage(Customer customer, /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - public virtual async Task SendWishlistEmailAFriendMessage(Customer customer, Store store, string languageId, - string customerEmail, string friendsEmail, string personalMessage, DomainHost host = null) + public virtual async Task SendWishlistEmailAFriendMessage(Customer customer, Store store, string? languageId, + string customerEmail, string friendsEmail, string personalMessage, DomainHost? host = null) { ArgumentNullException.ThrowIfNull(customer); @@ -145,9 +145,9 @@ public virtual async Task SendWishlistEmailAFriendMessage(Customer customer /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - public virtual async Task SendProductQuestionMessage(Customer customer, Store store, string languageId, + public virtual async Task SendProductQuestionMessage(Customer customer, Store store, string? languageId, Product product, string customerEmail, string fullName, string phone, string message, string ipaddress, - DomainHost host = null) + DomainHost? host = null) { ArgumentNullException.ThrowIfNull(customer); ArgumentNullException.ThrowIfNull(product); @@ -178,8 +178,8 @@ public virtual async Task SendProductQuestionMessage(Customer customer, Sto var subject = messageTemplate.GetTranslation(mt => mt.Subject, languageId); var body = messageTemplate.GetTranslation(mt => mt.Body, languageId); - var subjectReplaced = LiquidExtensions.RenderSubject(liquidObject, subject); - var bodyReplaced = LiquidExtensions.Render(liquidObject, body); + var subjectReplaced = LiquidExtensions.RenderSubject(liquidObject, subject ?? ""); + var bodyReplaced = LiquidExtensions.Render(liquidObject, body ?? ""); await _mediator.Send(new InsertContactUsCommand { CustomerId = customer.Id, @@ -224,7 +224,7 @@ await _mediator.Send(new InsertContactUsCommand { /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// public virtual async Task SendProductReviewMessage(Product product, ProductReview productReview, - Store store, string languageId, DomainHost host = null) + Store store, string? languageId, DomainHost? host = null) { ArgumentNullException.ThrowIfNull(productReview); @@ -263,7 +263,7 @@ public virtual async Task SendProductReviewMessage(Product product, Product /// Product /// Message language identifier public virtual async Task SendBatchesExpiringStoreOwnerMessage(Store store, IList batches, - string languageId) + string? languageId) { ArgumentNullException.ThrowIfNull(store); ArgumentNullException.ThrowIfNull(batches); @@ -284,7 +284,7 @@ public virtual async Task SendBatchesExpiringStoreOwnerMessage(Store store, liquidObject, emailAccount.Email, emailAccount.DisplayName); } - public virtual async Task SendQuantityBelowStoreOwnerMessage(Product product, string languageId) + public virtual async Task SendQuantityBelowStoreOwnerMessage(Product product, string? languageId) { ArgumentNullException.ThrowIfNull(product); @@ -321,7 +321,7 @@ public virtual async Task SendQuantityBelowStoreOwnerMessage(Product produc /// Attribute combination /// Message language identifier public virtual async Task SendQuantityBelowStoreOwnerMessage(Product product, - ProductAttributeCombination combination, string languageId) + ProductAttributeCombination combination, string? languageId) { ArgumentNullException.ThrowIfNull(combination); @@ -361,7 +361,7 @@ public virtual async Task SendQuantityBelowStoreOwnerMessage(Product produc /// Subscription /// Message language identifier public virtual async Task SendBackInStockMessage(Customer customer, Product product, - OutOfStockSubscription subscription, string languageId) + OutOfStockSubscription subscription, string? languageId) { ArgumentNullException.ThrowIfNull(subscription); @@ -393,7 +393,7 @@ public virtual async Task SendBackInStockMessage(Customer customer, Product reference: Reference.Customer, objectId: customer?.Id); } - public virtual async Task SendAuctionWinEndedCustomerMessage(Product product, string languageId, Bid bid) + public virtual async Task SendAuctionWinEndedCustomerMessage(Product product, string? languageId, Bid bid) { ArgumentNullException.ThrowIfNull(product); @@ -430,7 +430,7 @@ public virtual async Task SendAuctionWinEndedCustomerMessage(Product produc reference: Reference.Customer, objectId: customer.Id); } - public virtual async Task SendAuctionEndedLostCustomerMessage(Product product, string languageId, Bid bid) + public virtual async Task SendAuctionEndedLostCustomerMessage(Product product, string? languageId, Bid bid) { ArgumentNullException.ThrowIfNull(product); @@ -483,8 +483,8 @@ await _messageProviderService.SendNotification(messageTemplate, emailAccount, return 0; } - public virtual async Task SendAuctionEndedBinCustomerMessage(Product product, string customerId, - string languageId, string storeId) + public virtual async Task SendAuctionEndedBinCustomerMessage(Product product, string? customerId, + string? languageId, string? storeId) { ArgumentNullException.ThrowIfNull(product); @@ -531,13 +531,13 @@ await _messageProviderService.SendNotification(messageTemplate, emailAccount, return 0; } - public virtual async Task SendAuctionEndedStoreOwnerMessage(Product product, string languageId, Bid bid) + public virtual async Task SendAuctionEndedStoreOwnerMessage(Product product, string? languageId, Bid bid) { ArgumentNullException.ThrowIfNull(product); var builder = new LiquidObjectBuilder(_mediator); - MessageTemplate messageTemplate; - EmailAccount emailAccount; + MessageTemplate? messageTemplate; + EmailAccount? emailAccount; if (bid != null) { @@ -588,7 +588,7 @@ public virtual async Task SendAuctionEndedStoreOwnerMessage(Product product /// Message language identifier /// Product /// - public virtual async Task SendOutBidCustomerMessage(Product product, string languageId, Bid bid) + public virtual async Task SendOutBidCustomerMessage(Product product, string? languageId, Bid bid) { ArgumentNullException.ThrowIfNull(product); diff --git a/src/Business/Grand.Business.Messages/Services/CmsMessageProviderService.cs b/src/Business/Grand.Business.Messages/Services/CmsMessageProviderService.cs index 81d20695c..cc2b3657a 100644 --- a/src/Business/Grand.Business.Messages/Services/CmsMessageProviderService.cs +++ b/src/Business/Grand.Business.Messages/Services/CmsMessageProviderService.cs @@ -49,8 +49,8 @@ public CmsMessageProviderService( /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - public virtual async Task SendBlogCommentMessage(BlogPost blogPost, BlogComment blogComment, string languageId, - DomainHost host = null) + public virtual async Task SendBlogCommentMessage(BlogPost blogPost, BlogComment blogComment, string? languageId, + DomainHost? host = null) { ArgumentNullException.ThrowIfNull(blogComment); @@ -95,7 +95,7 @@ public virtual async Task SendBlogCommentMessage(BlogPost blogPost, BlogCom /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// public virtual async Task SendArticleCommentMessage(KnowledgebaseArticle article, - KnowledgebaseArticleComment articleComment, string languageId, DomainHost host = null) + KnowledgebaseArticleComment articleComment, string? languageId, DomainHost? host = null) { ArgumentNullException.ThrowIfNull(articleComment); @@ -137,8 +137,8 @@ public virtual async Task SendArticleCommentMessage(KnowledgebaseArticle ar /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - public virtual async Task SendNewsCommentMessage(NewsItem newsItem, NewsComment newsComment, string languageId, - DomainHost host = null) + public virtual async Task SendNewsCommentMessage(NewsItem newsItem, NewsComment newsComment, string? languageId, + DomainHost? host = null) { ArgumentNullException.ThrowIfNull(newsComment); diff --git a/src/Business/Grand.Business.Messages/Services/CustomerMessageProviderService.cs b/src/Business/Grand.Business.Messages/Services/CustomerMessageProviderService.cs index 602c067af..128fb9f71 100644 --- a/src/Business/Grand.Business.Messages/Services/CustomerMessageProviderService.cs +++ b/src/Business/Grand.Business.Messages/Services/CustomerMessageProviderService.cs @@ -54,8 +54,8 @@ public CustomerMessageProviderService( /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - protected virtual async Task SendCustomerMessage(Customer customer, Store store, string languageId, - string templateName, bool toEmailAccount = false, CustomerNote customerNote = null, DomainHost host = null) + protected virtual async Task SendCustomerMessage(Customer customer, Store store, string? languageId, + string templateName, bool toEmailAccount = false, CustomerNote? customerNote = null, DomainHost? host = null) { ArgumentNullException.ThrowIfNull(customer); @@ -88,8 +88,8 @@ protected virtual async Task SendCustomerMessage(Customer customer, Store s /// Send an order approval message; the recipient also provides the customer tokens /// protected virtual async Task SendOrderApprovalMessage(OrderApproval approval, Customer buyer, - Customer recipient, Store store, string languageId, string templateName, DomainHost host, - string toEmail = null) + Customer recipient, Store store, string? languageId, string templateName, DomainHost? host, + string? toEmail = null) { ArgumentNullException.ThrowIfNull(approval); ArgumentNullException.ThrowIfNull(buyer); @@ -129,7 +129,7 @@ protected virtual async Task SendOrderApprovalMessage(OrderApproval approva /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// public virtual async Task SendOrderApprovalRequestedMessage(OrderApproval approval, Customer buyer, - Customer approver, Store store, string languageId, DomainHost host = null) + Customer approver, Store store, string? languageId, DomainHost? host = null) { return await SendOrderApprovalMessage(approval, buyer, approver, store, languageId, MessageTemplateNames.OrderApprovalRequested, host); @@ -146,7 +146,7 @@ public virtual async Task SendOrderApprovalRequestedMessage(OrderApproval a /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// public virtual async Task SendOrderApprovalDecidedMessage(OrderApproval approval, Customer buyer, - Store store, string languageId, DomainHost host = null) + Store store, string? languageId, DomainHost? host = null) { return await SendOrderApprovalMessage(approval, buyer, buyer, store, languageId, MessageTemplateNames.OrderApprovalDecided, host); @@ -164,7 +164,7 @@ public virtual async Task SendOrderApprovalDecidedMessage(OrderApproval app /// /// Recipient public virtual async Task SendOrderApprovalDecidedMessage(OrderApproval approval, Customer buyer, - Store store, string languageId, DomainHost host, string toEmail) + Store store, string? languageId, DomainHost? host, string toEmail) { return await SendOrderApprovalMessage(approval, buyer, buyer, store, languageId, MessageTemplateNames.OrderApprovalDecided, host, toEmail); @@ -181,7 +181,7 @@ public virtual async Task SendOrderApprovalDecidedMessage(OrderApproval app /// The back office panel the recipient works in /// Message language identifier public virtual async Task SendOrderApprovalStaffMessage(OrderApproval approval, Customer buyer, Store store, - string toEmail, string toName, string panelArea, string languageId) + string? toEmail, string? toName, string panelArea, string? languageId) { ArgumentNullException.ThrowIfNull(approval); ArgumentNullException.ThrowIfNull(buyer); @@ -219,8 +219,8 @@ public virtual async Task SendOrderApprovalStaffMessage(OrderApproval appro /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - public virtual async Task SendCustomerRegisteredMessage(Customer customer, Store store, string languageId, - DomainHost host = null) + public virtual async Task SendCustomerRegisteredMessage(Customer customer, Store store, string? languageId, + DomainHost? host = null) { return await SendCustomerMessage(customer, store, languageId, MessageTemplateNames.CustomerRegistered, true, host: host); @@ -235,8 +235,8 @@ public virtual async Task SendCustomerRegisteredMessage(Customer customer, /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - public virtual async Task SendCustomerWelcomeMessage(Customer customer, Store store, string languageId, - DomainHost host = null) + public virtual async Task SendCustomerWelcomeMessage(Customer customer, Store store, string? languageId, + DomainHost? host = null) { return await SendCustomerMessage(customer, store, languageId, MessageTemplateNames.CustomerWelcome, host: host); } @@ -250,8 +250,8 @@ public virtual async Task SendCustomerWelcomeMessage(Customer customer, Sto /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - public virtual async Task SendCustomerEmailValidationMessage(Customer customer, Store store, string languageId, - DomainHost host = null) + public virtual async Task SendCustomerEmailValidationMessage(Customer customer, Store store, string? languageId, + DomainHost? host = null) { return await SendCustomerMessage(customer, store, languageId, MessageTemplateNames.CustomerEmailValidation, host: host); @@ -267,7 +267,7 @@ public virtual async Task SendCustomerEmailValidationMessage(Customer custo /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// public virtual async Task SendCustomerPasswordRecoveryMessage(Customer customer, Store store, - string languageId, DomainHost host = null) + string? languageId, DomainHost? host = null) { return await SendCustomerMessage(customer, store, languageId, MessageTemplateNames.CustomerPasswordRecovery, host: host); @@ -282,7 +282,7 @@ public virtual async Task SendCustomerPasswordRecoveryMessage(Customer cust /// Message language identifier /// Queued email identifier public virtual async Task SendNewCustomerNoteMessage(CustomerNote customerNote, Customer customer, Store store, - string languageId) + string? languageId) { return await SendCustomerMessage(customer, store, languageId, MessageTemplateNames.CustomerNewCustomerNote, customerNote: customerNote); @@ -298,7 +298,7 @@ public virtual async Task SendNewCustomerNoteMessage(CustomerNote customerN /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// public virtual async Task SendCustomerEmailTokenValidationMessage(Customer customer, Store store, - string languageId, DomainHost host = null) + string? languageId, DomainHost? host = null) { return await SendCustomerMessage(customer, store, languageId, MessageTemplateNames.CustomerEmailTokenValidationMessage, host: host); @@ -312,8 +312,8 @@ public virtual async Task SendCustomerEmailTokenValidationMessage(Customer /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - public virtual async Task SendCustomerDeleteStoreOwnerMessage(Customer customer, string languageId, - DomainHost host = null) + public virtual async Task SendCustomerDeleteStoreOwnerMessage(Customer customer, string? languageId, + DomainHost? host = null) { ArgumentNullException.ThrowIfNull(customer); @@ -360,10 +360,10 @@ public virtual async Task SendCustomerDeleteStoreOwnerMessage(Customer cust /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - public virtual async Task SendContactUsMessage(Customer customer, Store store, string languageId, + public virtual async Task SendContactUsMessage(Customer customer, Store store, string? languageId, string senderEmail, string senderName, string subject, string body, string attrInfo, IList customAttributes, - string ipaddress, DomainHost host = null) + string ipaddress, DomainHost? host = null) { var language = await _messageLookupService.EnsureLanguageIsActive(languageId, store.Id); var messageTemplate = await _messageLookupService.GetMessageTemplate("Service.ContactUs", store.Id); @@ -373,8 +373,8 @@ public virtual async Task SendContactUsMessage(Customer customer, Store sto //email account var emailAccount = await _messageLookupService.GetEmailAccountOfMessageTemplate(messageTemplate, language.Id); - string fromEmail; - string fromName; + string? fromEmail; + string? fromName; senderName = WebUtility.HtmlEncode(senderName); senderEmail = WebUtility.HtmlEncode(senderEmail); //required for some SMTP servers diff --git a/src/Business/Grand.Business.Messages/Services/EmailAccountService.cs b/src/Business/Grand.Business.Messages/Services/EmailAccountService.cs index b9baf3028..6ad5d7e8b 100644 --- a/src/Business/Grand.Business.Messages/Services/EmailAccountService.cs +++ b/src/Business/Grand.Business.Messages/Services/EmailAccountService.cs @@ -118,7 +118,7 @@ public virtual async Task DeleteEmailAccount(EmailAccount emailAccount) /// /// The email account identifier /// Email account - public virtual async Task GetEmailAccountById(string emailAccountId) + public virtual async Task GetEmailAccountById(string? emailAccountId) { var key = string.Format(CacheKey.EMAILACCOUNT_BY_ID_KEY, emailAccountId); return await _cacheBase.GetAsync(key, () => _emailAccountRepository.GetByIdAsync(emailAccountId)); diff --git a/src/Business/Grand.Business.Messages/Services/EmailSender.cs b/src/Business/Grand.Business.Messages/Services/EmailSender.cs index fbae700da..f69efb771 100644 --- a/src/Business/Grand.Business.Messages/Services/EmailSender.cs +++ b/src/Business/Grand.Business.Messages/Services/EmailSender.cs @@ -1,6 +1,7 @@ using Grand.Business.Core.Interfaces.Messages; using Grand.Business.Core.Interfaces.Storage; using Grand.Domain.Messages; +using Grand.SharedKernel; using MailKit.Net.Smtp; using MailKit.Security; using MimeKit; @@ -46,11 +47,11 @@ public EmailSender(IDownloadService downloadService, IMimeMappingService mimeMap /// not cancelled: the server may already have accepted it /// public virtual async Task SendEmail(EmailAccount emailAccount, string subject, string body, - string fromAddress, string fromName, string toAddress, string toName, - string replyToAddress = null, string replyToName = null, - IEnumerable bccAddresses = null, IEnumerable ccAddresses = null, - string attachmentFilePath = null, string attachmentFileName = null, - IEnumerable attachedDownloads = null, CancellationToken cancellationToken = default) + string fromAddress, string? fromName, string toAddress, string? toName, + string? replyToAddress = null, string? replyToName = null, + IEnumerable? bccAddresses = null, IEnumerable? ccAddresses = null, + string? attachmentFilePath = null, string? attachmentFileName = null, + IEnumerable? attachedDownloads = null, CancellationToken cancellationToken = default) { var message = new MimeMessage(); @@ -81,8 +82,9 @@ public virtual async Task SendEmail(EmailAccount emailAccount, string subject, s if (!string.IsNullOrEmpty(attachmentFilePath) && File.Exists(attachmentFilePath)) { - // TODO: should probably include a check for the attachmentFileName not being null or white space - var attachment = new MimePart(_mimeMappingService.Map(attachmentFileName)) { + //the type comes from the name the attachment is given, else from the file's own + var attachment = new MimePart(_mimeMappingService.Map( + string.IsNullOrWhiteSpace(attachmentFileName) ? Path.GetFileName(attachmentFilePath) : attachmentFileName)) { Content = new MimeContent(File.OpenRead(attachmentFilePath)), ContentDisposition = new ContentDisposition(ContentDisposition.Attachment) { CreationDate = File.GetCreationTime(attachmentFilePath), @@ -100,7 +102,7 @@ public virtual async Task SendEmail(EmailAccount emailAccount, string subject, s foreach (var attachedDownloadId in attachedDownloads) { var download = await _downloadService.GetDownloadById(attachedDownloadId); - if (download == null || download.UseDownloadUrl) continue; + if (download?.DownloadBinary == null || download.UseDownloadUrl) continue; var fileName = !string.IsNullOrWhiteSpace(download.Filename) ? download.Filename : download.Id; fileName += download.Extension; var ms = new MemoryStream(download.DownloadBinary); @@ -123,9 +125,13 @@ public virtual async Task SendEmail(EmailAccount emailAccount, string subject, s using var smtpClient = new SmtpClient(); smtpClient.ServerCertificateValidationCallback = (_, _, _, _) => emailAccount.UseServerCertificateValidation; - await smtpClient.ConnectAsync(emailAccount.Host, emailAccount.Port, - (SecureSocketOptions)emailAccount.SecureSocketOptionsId, cancellationToken); - await smtpClient.AuthenticateAsync(emailAccount.Username, emailAccount.Password, cancellationToken); + await smtpClient.ConnectAsync( + emailAccount.Host ?? throw new GrandException($"The email account {emailAccount.Id} has no host"), + emailAccount.Port, (SecureSocketOptions)emailAccount.SecureSocketOptionsId, cancellationToken); + await smtpClient.AuthenticateAsync( + emailAccount.Username ?? throw new GrandException($"The email account {emailAccount.Id} has no user name"), + emailAccount.Password ?? throw new GrandException($"The email account {emailAccount.Id} has no password"), + cancellationToken); //not cancellable: the server may accept the message before its reply arrives, and a cancelled //send would then be reported as not sent - and the message sent again on the next try await smtpClient.SendAsync(message, CancellationToken.None); diff --git a/src/Business/Grand.Business.Messages/Services/MerchandiseReturnMessageProviderService.cs b/src/Business/Grand.Business.Messages/Services/MerchandiseReturnMessageProviderService.cs index efe795f42..547774137 100644 --- a/src/Business/Grand.Business.Messages/Services/MerchandiseReturnMessageProviderService.cs +++ b/src/Business/Grand.Business.Messages/Services/MerchandiseReturnMessageProviderService.cs @@ -47,7 +47,7 @@ public MerchandiseReturnMessageProviderService( /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// public virtual async Task SendNewMerchandiseReturnStoreOwnerMessage(MerchandiseReturn merchandiseReturn, - Order order, string languageId, DomainHost host = null) + Order order, string? languageId, DomainHost? host = null) { ArgumentNullException.ThrowIfNull(merchandiseReturn); @@ -106,7 +106,7 @@ await _messageProviderService.SendNotification(messageTemplate, emailAccount, /// Message language identifier /// The note shown to the customer with the change public virtual async Task SendMerchandiseReturnStatusChangedCustomerMessage( - MerchandiseReturn merchandiseReturn, Order order, string languageId, string statusNote = null) + MerchandiseReturn merchandiseReturn, Order order, string? languageId, string? statusNote = null) { ArgumentNullException.ThrowIfNull(merchandiseReturn); @@ -137,8 +137,8 @@ public virtual async Task SendMerchandiseReturnStatusChangedCustomerMessage //event notification await _mediator.MessageTokensAdded(messageTemplate, liquidObject); - var toEmail = string.IsNullOrEmpty(customer?.Email) ? order.BillingAddress.Email : customer.Email; - var toName = string.IsNullOrEmpty(customer?.Email) ? order.BillingAddress.FirstName : customer.GetFullName(); + var toEmail = string.IsNullOrEmpty(customer?.Email) ? order.BillingAddress?.Email : customer.Email; + var toName = string.IsNullOrEmpty(customer?.Email) ? order.BillingAddress?.FirstName : customer.GetFullName(); return await _messageProviderService.SendNotification(messageTemplate, emailAccount, languageId, liquidObject, toEmail, toName, @@ -155,7 +155,7 @@ public virtual async Task SendMerchandiseReturnStatusChangedCustomerMessage /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// public virtual async Task SendNewMerchandiseReturnCustomerMessage(MerchandiseReturn merchandiseReturn, - Order order, string languageId, DomainHost host = null) + Order order, string? languageId, DomainHost? host = null) { ArgumentNullException.ThrowIfNull(merchandiseReturn); @@ -182,8 +182,8 @@ public virtual async Task SendNewMerchandiseReturnCustomerMessage(Merchandi //event notification await _mediator.MessageTokensAdded(messageTemplate, liquidObject); - var toEmail = string.IsNullOrEmpty(customer?.Email) ? order.BillingAddress.Email : customer.Email; - var toName = string.IsNullOrEmpty(customer?.Email) ? order.BillingAddress.FirstName : customer.GetFullName(); + var toEmail = string.IsNullOrEmpty(customer?.Email) ? order.BillingAddress?.Email : customer.Email; + var toName = string.IsNullOrEmpty(customer?.Email) ? order.BillingAddress?.FirstName : customer.GetFullName(); return await _messageProviderService.SendNotification(messageTemplate, emailAccount, languageId, liquidObject, toEmail, toName, @@ -226,8 +226,8 @@ public virtual async Task SendNewMerchandiseReturnNoteAddedCustomerMessage( //event notification await _mediator.MessageTokensAdded(messageTemplate, liquidObject); - var toEmail = string.IsNullOrEmpty(customer?.Email) ? order.BillingAddress.Email : customer.Email; - var toName = string.IsNullOrEmpty(customer?.Email) ? order.BillingAddress.FirstName : customer.GetFullName(); + var toEmail = string.IsNullOrEmpty(customer?.Email) ? order.BillingAddress?.Email : customer.Email; + var toName = string.IsNullOrEmpty(customer?.Email) ? order.BillingAddress?.FirstName : customer.GetFullName(); return await _messageProviderService.SendNotification(messageTemplate, emailAccount, language.Id, liquidObject, toEmail, toName, @@ -246,7 +246,7 @@ public virtual async Task SendNewMerchandiseReturnNoteAddedCustomerMessage( /// public virtual async Task SendNewMerchandiseReturnNoteAddedStoreOwnerMessage( MerchandiseReturn merchandiseReturn, MerchandiseReturnNote merchandiseReturnNote, Order order, - string languageId, DomainHost host = null) + string? languageId, DomainHost? host = null) { ArgumentNullException.ThrowIfNull(merchandiseReturn); ArgumentNullException.ThrowIfNull(merchandiseReturnNote); diff --git a/src/Business/Grand.Business.Messages/Services/MessageLookupService.cs b/src/Business/Grand.Business.Messages/Services/MessageLookupService.cs index 1e63326c1..e32a42ad1 100644 --- a/src/Business/Grand.Business.Messages/Services/MessageLookupService.cs +++ b/src/Business/Grand.Business.Messages/Services/MessageLookupService.cs @@ -5,6 +5,7 @@ using Grand.Domain.Localization; using Grand.Domain.Messages; using Grand.Domain.Stores; +using Grand.SharedKernel; namespace Grand.Business.Messages.Services; @@ -40,12 +41,13 @@ public MessageLookupService( #region Methods - public virtual async Task GetStore(string storeId) + public virtual async Task GetStore(string? storeId) { - return await _storeService.GetStoreById(storeId) ?? (await _storeService.GetAllStores()).FirstOrDefault(); + return await _storeService.GetStoreById(storeId) ?? (await _storeService.GetAllStores()).FirstOrDefault() ?? + throw new GrandException("No store is configured to send messages from"); } - public virtual async Task GetMessageTemplate(string messageTemplateName, string storeId) + public virtual async Task GetMessageTemplate(string messageTemplateName, string? storeId) { var messageTemplate = await _messageTemplateService.GetMessageTemplateByName(messageTemplateName, storeId); @@ -65,10 +67,10 @@ public virtual async Task GetEmailAccountOfMessageTemplate(Message var emailAccount = await _emailAccountService.GetEmailAccountById(emailAccounId); emailAccount ??= await _emailAccountService.GetEmailAccountById(_emailAccountSettings.DefaultEmailAccountId); emailAccount ??= (await _emailAccountService.GetAllEmailAccounts()).FirstOrDefault(); - return emailAccount; + return emailAccount ?? throw new GrandException("No email account is configured to send messages with"); } - public virtual async Task EnsureLanguageIsActive(string languageId, string storeId) + public virtual async Task EnsureLanguageIsActive(string? languageId, string storeId) { //load language by specified ID var language = await _languageService.GetLanguageById(languageId); diff --git a/src/Business/Grand.Business.Messages/Services/MessageProviderService.cs b/src/Business/Grand.Business.Messages/Services/MessageProviderService.cs index c15e693ef..d417fc36e 100644 --- a/src/Business/Grand.Business.Messages/Services/MessageProviderService.cs +++ b/src/Business/Grand.Business.Messages/Services/MessageProviderService.cs @@ -27,13 +27,13 @@ public MessageProviderService(IQueuedEmailService queuedEmailService) #region Methods public virtual async Task SendNotification(MessageTemplate messageTemplate, - EmailAccount emailAccount, string languageId, LiquidObject liquidObject, - string toEmailAddress, string toName, - string attachmentFilePath = null, string attachmentFileName = null, - IEnumerable attachedDownloads = null, - string replyToEmailAddress = null, string replyToName = null, - string fromEmail = null, string fromName = null, string subject = null, - Reference reference = Reference.None, string objectId = "", string invoiceDownloadId = null) + EmailAccount emailAccount, string? languageId, LiquidObject liquidObject, + string? toEmailAddress, string? toName, + string? attachmentFilePath = null, string? attachmentFileName = null, + IEnumerable? attachedDownloads = null, + string? replyToEmailAddress = null, string? replyToName = null, + string? fromEmail = null, string? fromName = null, string? subject = null, + Reference reference = Reference.None, string? objectId = "", string? invoiceDownloadId = null) { if (string.IsNullOrEmpty(toEmailAddress)) return 0; @@ -49,8 +49,8 @@ public virtual async Task SendNotification(MessageTemplate messageTemplate, var email = new QueuedEmail(); liquidObject.Email = new LiquidEmail(email.Id); - var subjectReplaced = LiquidExtensions.RenderSubject(liquidObject, subject); - var bodyReplaced = LiquidExtensions.Render(liquidObject, body); + var subjectReplaced = LiquidExtensions.RenderSubject(liquidObject, subject ?? ""); + var bodyReplaced = LiquidExtensions.Render(liquidObject, body ?? ""); var attachments = new List(); if (attachedDownloads != null) diff --git a/src/Business/Grand.Business.Messages/Services/MessageTemplateNames.cs b/src/Business/Grand.Business.Messages/Services/MessageTemplateNames.cs index 83817d7e5..1a628ed30 100644 --- a/src/Business/Grand.Business.Messages/Services/MessageTemplateNames.cs +++ b/src/Business/Grand.Business.Messages/Services/MessageTemplateNames.cs @@ -86,7 +86,7 @@ public static class MessageTemplateNames /// The customer's message for a merchandise return that reached the status; null for a status told by the /// generic status changed message (a return opened again, a cancelled one) /// - public static string MerchandiseReturnStatusTemplate(MerchandiseReturnStatus status) + public static string? MerchandiseReturnStatusTemplate(MerchandiseReturnStatus status) { return status switch { MerchandiseReturnStatus.Accepted => SendMerchandiseReturnAcceptedCustomerMessage, diff --git a/src/Business/Grand.Business.Messages/Services/MessageTemplateService.cs b/src/Business/Grand.Business.Messages/Services/MessageTemplateService.cs index 9ce12b952..07a73ce27 100644 --- a/src/Business/Grand.Business.Messages/Services/MessageTemplateService.cs +++ b/src/Business/Grand.Business.Messages/Services/MessageTemplateService.cs @@ -91,7 +91,7 @@ public virtual async Task DeleteMessageTemplate(MessageTemplate messageTemplate) /// /// Message template identifier /// Message template - public virtual Task GetMessageTemplateById(string messageTemplateId) + public virtual Task GetMessageTemplateById(string messageTemplateId) { return _messageTemplateRepository.GetByIdAsync(messageTemplateId); } @@ -104,7 +104,7 @@ public virtual Task GetMessageTemplateById(string messageTempla /// /// The template a store overrode this name with, if it has one; otherwise the template shared by every store /// - public virtual async Task GetMessageTemplateByName(string messageTemplateName, string storeId) + public virtual async Task GetMessageTemplateByName(string messageTemplateName, string? storeId) { if (string.IsNullOrWhiteSpace(messageTemplateName)) throw new ArgumentException(null, nameof(messageTemplateName)); @@ -152,7 +152,7 @@ public virtual async Task> GetAllMessageTemplates(st if (!string.IsNullOrEmpty(keywords)) { var lowerKeywords = keywords.ToLower(); - query = query.Where(t => t.Name.ToLower().Contains(lowerKeywords) || + query = query.Where(t => t.Name != null && t.Name.ToLower().Contains(lowerKeywords) || (t.Subject != null && t.Subject.Contains(lowerKeywords, StringComparison.CurrentCultureIgnoreCase))); } diff --git a/src/Business/Grand.Business.Messages/Services/NewsletterMessageProviderService.cs b/src/Business/Grand.Business.Messages/Services/NewsletterMessageProviderService.cs index 830776160..f06e79bdf 100644 --- a/src/Business/Grand.Business.Messages/Services/NewsletterMessageProviderService.cs +++ b/src/Business/Grand.Business.Messages/Services/NewsletterMessageProviderService.cs @@ -45,7 +45,7 @@ public NewsletterMessageProviderService( /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// public virtual async Task SendNewsLetterSubscriptionActivationMessage(NewsLetterSubscription subscription, - string languageId, DomainHost host = null) + string? languageId, DomainHost? host = null) { return await SendNewsLetterSubscriptionMessage(MessageTemplateNames.SendNewsLetterSubscriptionActivationMessage, subscription, languageId, host: host); @@ -60,7 +60,7 @@ public virtual async Task SendNewsLetterSubscriptionActivationMessage(NewsL /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// public virtual async Task SendNewsLetterSubscriptionDeactivationMessage(NewsLetterSubscription subscription, - string languageId, DomainHost host = null) + string? languageId, DomainHost? host = null) { return await SendNewsLetterSubscriptionMessage( MessageTemplateNames.SendNewsLetterSubscriptionDeactivationMessage, subscription, languageId, host: host); @@ -76,7 +76,7 @@ public virtual async Task SendNewsLetterSubscriptionDeactivationMessage(New /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// private async Task SendNewsLetterSubscriptionMessage(string message, NewsLetterSubscription subscription, - string languageId, DomainHost host = null) + string? languageId, DomainHost? host = null) { ArgumentNullException.ThrowIfNull(subscription); diff --git a/src/Business/Grand.Business.Messages/Services/OrderMessageProviderService.cs b/src/Business/Grand.Business.Messages/Services/OrderMessageProviderService.cs index c8ebd1d25..4fe9ca712 100644 --- a/src/Business/Grand.Business.Messages/Services/OrderMessageProviderService.cs +++ b/src/Business/Grand.Business.Messages/Services/OrderMessageProviderService.cs @@ -56,8 +56,8 @@ public OrderMessageProviderService( /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - public virtual async Task SendOrderPlacedStoreOwnerMessage(Order order, Customer customer, string languageId, - DomainHost host = null) + public virtual async Task SendOrderPlacedStoreOwnerMessage(Order order, Customer? customer, string? languageId, + DomainHost? host = null) { return await SendOrderStoreOwnerMessage(MessageTemplateNames.SendOrderPlacedStoreOwnerMessage, order, customer, languageId, host: host); @@ -69,7 +69,7 @@ public virtual async Task SendOrderPlacedStoreOwnerMessage(Order order, Cus /// Order instance /// Customer instance /// Message language identifier - public virtual async Task SendOrderPaidStoreOwnerMessage(Order order, Customer customer, string languageId) + public virtual async Task SendOrderPaidStoreOwnerMessage(Order order, Customer? customer, string? languageId) { return await SendOrderStoreOwnerMessage(MessageTemplateNames.SendOrderPaidStoreOwnerMessage, order, customer, languageId); @@ -82,8 +82,8 @@ public virtual async Task SendOrderPaidStoreOwnerMessage(Order order, Custo /// Customer instance /// Message language identifier /// Queued email identifier - public virtual async Task SendOrderCancelledStoreOwnerMessage(Order order, Customer customer, - string languageId) + public virtual async Task SendOrderCancelledStoreOwnerMessage(Order order, Customer? customer, + string? languageId) { return await SendOrderStoreOwnerMessage(MessageTemplateNames.SendOrderCancelledStoreOwnerMessage, order, customer, languageId); @@ -94,7 +94,7 @@ public virtual async Task SendOrderCancelledStoreOwnerMessage(Order order, /// Amount refunded /// Message language identifier public virtual async Task SendOrderRefundedStoreOwnerMessage(Order order, double refundedAmount, - string languageId) + string? languageId) { var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = order.CustomerId }); return await SendOrderStoreOwnerMessage(MessageTemplateNames.SendOrderRefundedStoreOwnerMessage, order, @@ -112,8 +112,8 @@ public virtual async Task SendOrderRefundedStoreOwnerMessage(Order order, d /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - private async Task SendOrderStoreOwnerMessage(string template, Order order, Customer customer, - string languageId, double refundedAmount = 0, DomainHost host = null) + private async Task SendOrderStoreOwnerMessage(string template, Order order, Customer? customer, + string? languageId, double refundedAmount = 0, DomainHost? host = null) { ArgumentNullException.ThrowIfNull(order); @@ -157,8 +157,8 @@ private async Task SendOrderStoreOwnerMessage(string template, Order order, /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - public virtual async Task SendOrderPlacedCustomerMessage(Order order, Customer customer, string languageId, - string invoiceDownloadId = null, DomainHost host = null) + public virtual async Task SendOrderPlacedCustomerMessage(Order order, Customer? customer, string? languageId, + string? invoiceDownloadId = null, DomainHost? host = null) { return await SendOrderInvoiceMessage(MessageTemplateNames.SendOrderPlacedCustomerMessage, order, customer, languageId, invoiceDownloadId, host); @@ -173,8 +173,8 @@ public virtual async Task SendOrderPlacedCustomerMessage(Order order, Custo /// /// Download of the invoice to attach. The queued email takes ownership of it; it is deleted when no email is queued /// - public virtual async Task SendOrderPaidCustomerMessage(Order order, Customer customer, string languageId, - string invoiceDownloadId = null) + public virtual async Task SendOrderPaidCustomerMessage(Order order, Customer? customer, string? languageId, + string? invoiceDownloadId = null) { return await SendOrderInvoiceMessage(MessageTemplateNames.SendOrderPaidCustomerMessage, order, customer, languageId, invoiceDownloadId); @@ -189,8 +189,8 @@ public virtual async Task SendOrderPaidCustomerMessage(Order order, Custome /// /// Download of the invoice to attach. The queued email takes ownership of it; it is deleted when no email is queued /// - public virtual async Task SendOrderCompletedCustomerMessage(Order order, Customer customer, string languageId, - string invoiceDownloadId = null) + public virtual async Task SendOrderCompletedCustomerMessage(Order order, Customer? customer, string? languageId, + string? invoiceDownloadId = null) { return await SendOrderInvoiceMessage(MessageTemplateNames.SendOrderCompletedCustomerMessage, order, customer, languageId, invoiceDownloadId); @@ -202,7 +202,7 @@ public virtual async Task SendOrderCompletedCustomerMessage(Order order, Cu /// Order instance /// Customer instance /// Message language identifier - public virtual async Task SendOrderCancelledCustomerMessage(Order order, Customer customer, string languageId) + public virtual async Task SendOrderCancelledCustomerMessage(Order order, Customer? customer, string? languageId) { return await SendOrderCustomerMessage(MessageTemplateNames.SendOrderCancelledCustomerMessage, order, customer, languageId); @@ -216,7 +216,7 @@ public virtual async Task SendOrderCancelledCustomerMessage(Order order, Cu /// Message language identifier /// Queued email identifier public virtual async Task SendOrderRefundedCustomerMessage(Order order, double refundedAmount, - string languageId) + string? languageId) { var customer = await _mediator.Send(new GetCustomerByIdQuery { Id = order.CustomerId }); return await SendOrderCustomerMessage(MessageTemplateNames.SendOrderRefundedCustomerMessage, order, customer, @@ -230,8 +230,8 @@ public virtual async Task SendOrderRefundedCustomerMessage(Order order, dou /// Customer /// Message language identifier /// Queued email identifier - public virtual async Task SendPaymentDueReminderCustomerMessage(Order order, Customer customer, - string languageId) + public virtual async Task SendPaymentDueReminderCustomerMessage(Order order, Customer? customer, + string? languageId) { return await SendOrderCustomerMessage(MessageTemplateNames.SendPaymentDueReminderCustomerMessage, order, customer, languageId); @@ -244,8 +244,8 @@ public virtual async Task SendPaymentDueReminderCustomerMessage(Order order /// Customer /// Message language identifier /// Queued email identifier - public virtual async Task SendPaymentOverdueCustomerMessage(Order order, Customer customer, - string languageId) + public virtual async Task SendPaymentOverdueCustomerMessage(Order order, Customer? customer, + string? languageId) { return await SendOrderCustomerMessage(MessageTemplateNames.SendPaymentOverdueCustomerMessage, order, customer, languageId); @@ -254,8 +254,8 @@ public virtual async Task SendPaymentOverdueCustomerMessage(Order order, Cu /// /// Sends an order notification with an invoice to a customer /// - private async Task SendOrderInvoiceMessage(string message, Order order, Customer customer, string languageId, - string invoiceDownloadId, DomainHost host = null) + private async Task SendOrderInvoiceMessage(string message, Order order, Customer? customer, string? languageId, + string? invoiceDownloadId, DomainHost? host = null) { var queuedEmails = 0; try @@ -272,7 +272,7 @@ private async Task SendOrderInvoiceMessage(string message, Order order, Cus } } - private async Task DeleteUnusedInvoice(string invoiceDownloadId) + private async Task DeleteUnusedInvoice(string? invoiceDownloadId) { try { @@ -297,8 +297,8 @@ private async Task DeleteUnusedInvoice(string invoiceDownloadId) /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - private async Task SendOrderCustomerMessage(string message, Order order, Customer customer, string languageId, - string invoiceDownloadId = null, double refundedAmount = 0, DomainHost host = null) + private async Task SendOrderCustomerMessage(string message, Order order, Customer? customer, string? languageId, + string? invoiceDownloadId = null, double refundedAmount = 0, DomainHost? host = null) { ArgumentNullException.ThrowIfNull(order); @@ -322,8 +322,8 @@ private async Task SendOrderCustomerMessage(string message, Order order, Cu //event notification await _mediator.MessageTokensAdded(messageTemplate, liquidObject); - var toEmail = order.BillingAddress.Email; - var toName = $"{order.BillingAddress.FirstName} {order.BillingAddress.LastName}"; + var toEmail = order.BillingAddress?.Email; + var toName = $"{order.BillingAddress?.FirstName} {order.BillingAddress?.LastName}"; return await _messageProviderService.SendNotification(messageTemplate, emailAccount, languageId, liquidObject, toEmail, toName, @@ -340,8 +340,8 @@ private async Task SendOrderCustomerMessage(string message, Order order, Cu /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - public virtual async Task SendOrderPlacedVendorMessage(Order order, Customer customer, Vendor vendor, - string languageId, DomainHost host = null) + public virtual async Task SendOrderPlacedVendorMessage(Order order, Customer? customer, Vendor vendor, + string? languageId, DomainHost? host = null) { return await SendOrderVendorMessage(MessageTemplateNames.SendOrderPlacedVendorMessage, order, vendor, languageId, host: host); @@ -353,7 +353,7 @@ public virtual async Task SendOrderPlacedVendorMessage(Order order, Custome /// Order instance /// Vendor instance /// Message language identifier - public virtual async Task SendOrderPaidVendorMessage(Order order, Vendor vendor, string languageId) + public virtual async Task SendOrderPaidVendorMessage(Order order, Vendor vendor, string? languageId) { return await SendOrderVendorMessage(MessageTemplateNames.SendOrderPaidVendorMessage, order, vendor, languageId); } @@ -364,7 +364,7 @@ public virtual async Task SendOrderPaidVendorMessage(Order order, Vendor ve /// Order instance /// Vendor instance /// Message language identifier - public virtual async Task SendOrderCancelledVendorMessage(Order order, Vendor vendor, string languageId) + public virtual async Task SendOrderCancelledVendorMessage(Order order, Vendor vendor, string? languageId) { return await SendOrderVendorMessage(MessageTemplateNames.SendOrderCancelledVendorMessage, order, vendor, languageId); @@ -380,8 +380,8 @@ public virtual async Task SendOrderCancelledVendorMessage(Order order, Vend /// /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// - private async Task SendOrderVendorMessage(string message, Order order, Vendor vendor, string languageId, - DomainHost host = null) + private async Task SendOrderVendorMessage(string message, Order order, Vendor vendor, string? languageId, + DomainHost? host = null) { ArgumentNullException.ThrowIfNull(order); ArgumentNullException.ThrowIfNull(vendor); @@ -475,8 +475,8 @@ private async Task SendShipmentCustomerMessage(string message, Shipment shi //event notification await _mediator.MessageTokensAdded(messageTemplate, liquidObject); - var toEmail = order.BillingAddress.Email; - var toName = $"{order.BillingAddress.FirstName} {order.BillingAddress.LastName}"; + var toEmail = order.BillingAddress?.Email; + var toName = $"{order.BillingAddress?.FirstName} {order.BillingAddress?.LastName}"; return await _messageProviderService.SendNotification(messageTemplate, emailAccount, language.Id, liquidObject, toEmail, toName, @@ -492,7 +492,7 @@ private async Task SendShipmentCustomerMessage(string message, Shipment shi /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// public virtual async Task SendNewOrderNoteAddedCustomerMessage(Order order, OrderNote orderNote, - DomainHost host = null) + DomainHost? host = null) { ArgumentNullException.ThrowIfNull(orderNote); ArgumentNullException.ThrowIfNull(order); @@ -521,8 +521,8 @@ public virtual async Task SendNewOrderNoteAddedCustomerMessage(Order order, //event notification await _mediator.MessageTokensAdded(messageTemplate, liquidObject); - var toEmail = order.BillingAddress.Email; - var toName = $"{order.BillingAddress.FirstName} {order.BillingAddress.LastName}"; + var toEmail = order.BillingAddress?.Email; + var toName = $"{order.BillingAddress?.FirstName} {order.BillingAddress?.LastName}"; return await _messageProviderService.SendNotification(messageTemplate, emailAccount, language.Id, liquidObject, toEmail, toName, @@ -535,15 +535,15 @@ public virtual async Task SendNewOrderNoteAddedCustomerMessage(Order order, /// Gift voucher /// Order /// Message language identifier - public virtual async Task SendGiftVoucherMessage(GiftVoucher giftVoucher, Order order, string languageId) + public virtual async Task SendGiftVoucherMessage(GiftVoucher giftVoucher, Order order, string? languageId) { ArgumentNullException.ThrowIfNull(giftVoucher); var store = await _messageLookupService.GetStore(order?.StoreId); - var language = await _messageLookupService.EnsureLanguageIsActive(languageId, store?.Id); + var language = await _messageLookupService.EnsureLanguageIsActive(languageId, store.Id); - var messageTemplate = await _messageLookupService.GetMessageTemplate("GiftVoucher.Notification", store?.Id); + var messageTemplate = await _messageLookupService.GetMessageTemplate("GiftVoucher.Notification", store.Id); if (messageTemplate == null) return 0; @@ -570,7 +570,7 @@ public virtual async Task SendGiftVoucherMessage(GiftVoucher giftVoucher, O /// The protected token the link carries /// Host of the storefront request public virtual async Task SendGuestOrderLinkCustomerMessage(Order order, string token, - DomainHost host = null) + DomainHost? host = null) { ArgumentNullException.ThrowIfNull(order); diff --git a/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs b/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs index c382e0fd9..3d133434d 100644 --- a/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs +++ b/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs @@ -94,7 +94,7 @@ public virtual async Task DeleteQueuedEmail(QueuedEmail queuedEmail) /// /// Download identifier of the invoice /// Download identifier of the copy; null when there is no invoice to copy - public virtual async Task CopyInvoiceDownload(string invoiceDownloadId) + public virtual async Task CopyInvoiceDownload(string invoiceDownloadId) { var invoice = await _downloadService.GetDownloadById(invoiceDownloadId); if (invoice == null) @@ -137,7 +137,7 @@ public virtual async Task DeleteOrderInvoiceEmails(IEnumerable orderIds) return; await DeleteInvoiceEmails(_queuedEmailRepository.Table.Where(x => - x.Reference == Reference.Order && ids.Contains(x.ObjectId))); + x.Reference == Reference.Order && x.ObjectId != null && ids.Contains(x.ObjectId))); } /// @@ -145,7 +145,7 @@ await DeleteInvoiceEmails(_queuedEmailRepository.Table.Where(x => /// /// Queued email identifier /// Queued email - public virtual Task GetQueuedEmailById(string queuedEmailId) + public virtual Task GetQueuedEmailById(string queuedEmailId) { return _queuedEmailRepository.GetByIdAsync(queuedEmailId); } @@ -167,7 +167,7 @@ where queuedEmailIds.Contains(qe.Id) //sort by passed identifiers var sortedQueuedEmails = queuedEmailIds.Select(id => queuedEmails.FirstOrDefault(email => email.Id == id)) - .Where(queuedEmail => queuedEmail != null) + .OfType() .ToList(); return await Task.FromResult(sortedQueuedEmails); @@ -202,12 +202,12 @@ public virtual async Task> SearchEmails(string fromEmail select p; if (!string.IsNullOrEmpty(fromEmail)) - query = query.Where(qe => qe.From.ToLower().Contains(fromEmail.ToLower())); + query = query.Where(qe => qe.From != null && qe.From.ToLower().Contains(fromEmail.ToLower())); if (!string.IsNullOrEmpty(toEmail)) - query = query.Where(qe => qe.To.ToLower().Contains(toEmail.ToLower())); + query = query.Where(qe => qe.To != null && qe.To.ToLower().Contains(toEmail.ToLower())); if (!string.IsNullOrEmpty(text)) query = query.Where(qe => - qe.Subject.ToLower().Contains(text.ToLower()) || qe.Body.ToLower().Contains(text.ToLower())); + qe.Subject != null && qe.Subject.ToLower().Contains(text.ToLower()) || qe.Body != null && qe.Body.ToLower().Contains(text.ToLower())); if (createdFromUtc.HasValue) query = query.Where(qe => qe.CreatedOnUtc >= createdFromUtc.Value); @@ -261,7 +261,7 @@ private async Task DeleteInvoiceEmails(IQueryable emails) await _queuedEmailRepository.DeleteAsync(invoiceEmails); } - private async Task DeleteInvoices(IEnumerable invoiceDownloadIds) + private async Task DeleteInvoices(IEnumerable invoiceDownloadIds) { foreach (var invoiceDownloadId in invoiceDownloadIds) try diff --git a/src/Business/Grand.Business.Messages/Services/RecurringPaymentMessageProviderService.cs b/src/Business/Grand.Business.Messages/Services/RecurringPaymentMessageProviderService.cs index 5290bb4f5..08969207c 100644 --- a/src/Business/Grand.Business.Messages/Services/RecurringPaymentMessageProviderService.cs +++ b/src/Business/Grand.Business.Messages/Services/RecurringPaymentMessageProviderService.cs @@ -40,7 +40,7 @@ public RecurringPaymentMessageProviderService( /// toStoreOwner is set /// protected virtual async Task SendRecurringPaymentMessage(string templateName, - RecurringPayment recurringPayment, Order initialOrder, Customer customer, string languageId, + RecurringPayment recurringPayment, Order initialOrder, Customer? customer, string? languageId, bool toStoreOwner) { ArgumentNullException.ThrowIfNull(recurringPayment); @@ -68,8 +68,8 @@ protected virtual async Task SendRecurringPaymentMessage(string templateNam var liquidObject = await builder.BuildAsync(); await _mediator.MessageTokensAdded(messageTemplate, liquidObject); - var toEmail = toStoreOwner ? emailAccount.Email : customer.Email; - var toName = toStoreOwner ? emailAccount.DisplayName : customer.GetFullName(); + var toEmail = toStoreOwner ? emailAccount.Email : customer?.Email; + var toName = toStoreOwner ? emailAccount.DisplayName : customer?.GetFullName(); return await _messageProviderService.SendNotification(messageTemplate, emailAccount, language.Id, liquidObject, toEmail, toName, @@ -80,7 +80,7 @@ protected virtual async Task SendRecurringPaymentMessage(string templateNam /// Sends a 'Recurring payment cancelled' message to the customer /// public virtual async Task SendRecurringPaymentCancelledCustomerMessage(RecurringPayment recurringPayment, - Order initialOrder, Customer customer, string languageId) + Order initialOrder, Customer? customer, string? languageId) { return await SendRecurringPaymentMessage(MessageTemplateNames.RecurringPaymentCancelledCustomerNotification, recurringPayment, initialOrder, customer, languageId, toStoreOwner: false); @@ -90,7 +90,7 @@ public virtual async Task SendRecurringPaymentCancelledCustomerMessage(Recu /// Sends a 'Recurring payment cancelled' message to the store owner /// public virtual async Task SendRecurringPaymentCancelledStoreOwnerMessage(RecurringPayment recurringPayment, - Order initialOrder, Customer customer, string languageId) + Order initialOrder, Customer? customer, string? languageId) { return await SendRecurringPaymentMessage(MessageTemplateNames.RecurringPaymentCancelledStoreOwnerNotification, recurringPayment, initialOrder, customer, languageId, toStoreOwner: true); @@ -100,7 +100,7 @@ public virtual async Task SendRecurringPaymentCancelledStoreOwnerMessage(Re /// Sends a 'Recurring payment failed' message to the customer /// public virtual async Task SendRecurringPaymentFailedCustomerMessage(RecurringPayment recurringPayment, - Order initialOrder, Customer customer, string languageId) + Order initialOrder, Customer? customer, string? languageId) { return await SendRecurringPaymentMessage(MessageTemplateNames.RecurringPaymentFailedCustomerNotification, recurringPayment, initialOrder, customer, languageId, toStoreOwner: false); @@ -110,7 +110,7 @@ public virtual async Task SendRecurringPaymentFailedCustomerMessage(Recurri /// Sends a 'Recurring payment failed' message to the store owner /// public virtual async Task SendRecurringPaymentFailedStoreOwnerMessage(RecurringPayment recurringPayment, - Order initialOrder, Customer customer, string languageId) + Order initialOrder, Customer? customer, string? languageId) { return await SendRecurringPaymentMessage(MessageTemplateNames.RecurringPaymentFailedStoreOwnerNotification, recurringPayment, initialOrder, customer, languageId, toStoreOwner: true); diff --git a/src/Business/Grand.Business.Messages/Services/VendorMessageProviderService.cs b/src/Business/Grand.Business.Messages/Services/VendorMessageProviderService.cs index 2baaf0756..09948f572 100644 --- a/src/Business/Grand.Business.Messages/Services/VendorMessageProviderService.cs +++ b/src/Business/Grand.Business.Messages/Services/VendorMessageProviderService.cs @@ -55,7 +55,7 @@ public VendorMessageProviderService( /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// public virtual async Task SendNewVendorAccountApplyStoreOwnerMessage(Customer customer, Vendor vendor, - Store store, string languageId, DomainHost host = null) + Store store, string? languageId, DomainHost? host = null) { ArgumentNullException.ThrowIfNull(customer); ArgumentNullException.ThrowIfNull(vendor); @@ -92,7 +92,7 @@ public virtual async Task SendNewVendorAccountApplyStoreOwnerMessage(Custom /// Vendor /// Store /// Message language identifier - public virtual async Task SendVendorInformationChangeMessage(Vendor vendor, Store store, string languageId) + public virtual async Task SendVendorInformationChangeMessage(Vendor vendor, Store store, string? languageId) { ArgumentNullException.ThrowIfNull(vendor); @@ -129,7 +129,7 @@ public virtual async Task SendVendorInformationChangeMessage(Vendor vendor, /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// public virtual async Task SendVendorReviewMessage(VendorReview vendorReview, Store store, - string languageId, DomainHost host = null) + string? languageId, DomainHost? host = null) { ArgumentNullException.ThrowIfNull(vendorReview); @@ -184,8 +184,8 @@ public virtual async Task SendVendorReviewMessage(VendorReview vendorReview /// Host of the storefront request; links use it when it is one of the store's domains, else the primary domain /// public virtual async Task SendContactVendorMessage(Customer customer, Store store, Vendor vendor, - string languageId, string senderEmail, - string senderName, string subject, string body, string ipaddress, DomainHost host = null) + string? languageId, string senderEmail, + string senderName, string subject, string body, string ipaddress, DomainHost? host = null) { ArgumentNullException.ThrowIfNull(vendor); @@ -198,8 +198,8 @@ public virtual async Task SendContactVendorMessage(Customer customer, Store //email account var emailAccount = await _messageLookupService.GetEmailAccountOfMessageTemplate(messageTemplate, language.Id); - string fromEmail; - string fromName; + string? fromEmail; + string? fromName; senderName = WebUtility.HtmlEncode(senderName); senderEmail = WebUtility.HtmlEncode(senderEmail); diff --git a/src/Business/Grand.Business.Storage/Grand.Business.Storage.csproj b/src/Business/Grand.Business.Storage/Grand.Business.Storage.csproj index 5bf05f82c..690ab1e75 100644 --- a/src/Business/Grand.Business.Storage/Grand.Business.Storage.csproj +++ b/src/Business/Grand.Business.Storage/Grand.Business.Storage.csproj @@ -13,4 +13,7 @@ + + enable + diff --git a/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs b/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs index a9ffb7d10..aa15827db 100644 --- a/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs +++ b/src/Business/Grand.Business.Storage/Services/AmazonPictureService.cs @@ -65,7 +65,7 @@ public AmazonPictureService(IRepository pictureRepository, private readonly AmazonConfig _config; private readonly string _bucketName; - private readonly string _distributionDomainName; + private readonly string? _distributionDomainName; private bool _bucketExist; private readonly IAmazonS3 _s3Client; @@ -137,7 +137,7 @@ protected override async Task DeletePictureThumbs(Picture picture) /// /// Filename /// Local picture thumb path - protected override async Task GetThumbPhysicalPath(string thumbFileName) + protected override async Task GetThumbPhysicalPath(string thumbFileName) { if (!await GeneratedThumbExists(thumbFileName)) return null; @@ -173,7 +173,7 @@ private async Task GeneratedThumbExists(string thumbFileName) /// Filename /// Store location URL; null to use determine the current store location automatically /// Local picture thumb path - protected override string GetThumbUrl(string thumbFileName, string storeLocation = null) + protected override string GetThumbUrl(string thumbFileName, string? storeLocation = null) { return string.IsNullOrEmpty(_distributionDomainName) ? $"https://{_bucketName}.s3.amazonAws.com/{thumbFileName}" @@ -185,11 +185,11 @@ protected override string GetThumbUrl(string thumbFileName, string storeLocation /// /// Thumb file name /// Picture binary - protected override async Task SaveThumb(string thumbFileName, byte[] binary) + protected override async Task SaveThumb(string thumbFileName, byte[]? binary) { await CheckBucketExists(); - using (Stream stream = new MemoryStream(binary)) + using (Stream stream = new MemoryStream(binary ?? [])) { var putObjectRequest = new PutObjectRequest { BucketName = _bucketName, diff --git a/src/Business/Grand.Business.Storage/Services/AzurePictureService.cs b/src/Business/Grand.Business.Storage/Services/AzurePictureService.cs index 0caaab2f0..574995f8d 100644 --- a/src/Business/Grand.Business.Storage/Services/AzurePictureService.cs +++ b/src/Business/Grand.Business.Storage/Services/AzurePictureService.cs @@ -54,7 +54,7 @@ IMimeMappingService mimeMappingService #region Fields - private static BlobContainerClient _container; + private readonly BlobContainerClient _container; private readonly AzureConfig _config; private readonly IMimeMappingService _mimeMappingService; @@ -79,7 +79,7 @@ protected override async Task DeletePictureThumbs(Picture picture) /// /// Filename /// Local picture thumb path - protected override async Task GetThumbPhysicalPath(string thumbFileName) + protected override async Task GetThumbPhysicalPath(string thumbFileName) { var thumbFilePath = $"{_config.AzureBlobStorageEndPoint}{_config.AzureBlobStorageContainerName}/{thumbFileName}"; @@ -94,7 +94,7 @@ protected override async Task GetThumbPhysicalPath(string thumbFileName) /// Filename /// Store location URL; null to use determine the current store location automatically /// Local picture thumb path - protected override string GetThumbUrl(string thumbFileName, string storeLocation = null) + protected override string GetThumbUrl(string thumbFileName, string? storeLocation = null) { var url = _config.AzureBlobStorageEndPoint + _config.AzureBlobStorageContainerName + "/"; url += thumbFileName; @@ -106,9 +106,9 @@ protected override string GetThumbUrl(string thumbFileName, string storeLocation /// /// Thumb file name /// Picture binary - protected override Task SaveThumb(string thumbFileName, byte[] binary) + protected override Task SaveThumb(string thumbFileName, byte[]? binary) { - Stream stream = new MemoryStream(binary); + Stream stream = new MemoryStream(binary ?? []); _container.UploadBlob(thumbFileName, stream); //Update content type and other properties diff --git a/src/Business/Grand.Business.Storage/Services/DefaultMediaFileStore.cs b/src/Business/Grand.Business.Storage/Services/DefaultMediaFileStore.cs index a1dcf5c2e..e787f3add 100644 --- a/src/Business/Grand.Business.Storage/Services/DefaultMediaFileStore.cs +++ b/src/Business/Grand.Business.Storage/Services/DefaultMediaFileStore.cs @@ -16,22 +16,22 @@ public DefaultMediaFileStore( } - public virtual Task GetFileInfo(string path) + public virtual Task GetFileInfo(string path) { return _fileStore.GetFileInfo(path); } - public virtual IFileStoreEntry GetDirectoryInfo(string path) + public virtual IFileStoreEntry? GetDirectoryInfo(string path) { return _fileStore.GetDirectoryInfo(path); } - public virtual Task GetPhysicalDirectoryInfo(string directoryPath) + public virtual Task GetPhysicalDirectoryInfo(string directoryPath) { return _fileStore.GetPhysicalDirectoryInfo(directoryPath); } - public virtual IList GetDirectoryContent(string path = null, bool includeSubDirectories = false, + public virtual IList GetDirectoryContent(string? path = null, bool includeSubDirectories = false, bool listDirectories = true, bool listFiles = true) { return _fileStore.GetDirectoryContent(path, includeSubDirectories, listDirectories, listFiles); diff --git a/src/Business/Grand.Business.Storage/Services/DownloadService.cs b/src/Business/Grand.Business.Storage/Services/DownloadService.cs index c5327ebc8..31eded64e 100644 --- a/src/Business/Grand.Business.Storage/Services/DownloadService.cs +++ b/src/Business/Grand.Business.Storage/Services/DownloadService.cs @@ -45,13 +45,14 @@ public DownloadService(IRepository downloadRepository, /// /// Download identifier /// Download - public virtual async Task GetDownloadById(string downloadId) + public virtual async Task GetDownloadById(string downloadId) { if (string.IsNullOrEmpty(downloadId)) return null; var download = await _downloadRepository.GetByIdAsync(downloadId); - if (download is { UseDownloadUrl: false }) + //a download kept in the database without a stored file has no binary to read + if (download is { UseDownloadUrl: false, DownloadObjectId: not null }) download.DownloadBinary = await DownloadAsBytes(download.DownloadObjectId); return download; @@ -68,7 +69,7 @@ protected virtual async Task DownloadAsBytes(string objectId) /// /// Download GUID /// Download - public virtual async Task GetDownloadByGuid(Guid downloadGuid) + public virtual async Task GetDownloadByGuid(Guid downloadGuid) { if (downloadGuid == Guid.Empty) return null; @@ -78,7 +79,7 @@ public virtual async Task GetDownloadByGuid(Guid downloadGuid) select o; var order = query.FirstOrDefault(); - if (order is { UseDownloadUrl: false }) + if (order is { UseDownloadUrl: false, DownloadObjectId: not null }) order.DownloadBinary = await DownloadAsBytes(order.DownloadObjectId); return await Task.FromResult(order); @@ -93,7 +94,7 @@ public virtual async Task InsertDownload(Download download) ArgumentNullException.ThrowIfNull(download); if (!download.UseDownloadUrl) download.DownloadObjectId = - await _storeFilesContext.BucketUploadFromBytes(download.Filename, download.DownloadBinary); + await _storeFilesContext.BucketUploadFromBytes(download.Filename ?? string.Empty, download.DownloadBinary ?? []); download.DownloadBinary = null; await _downloadRepository.InsertAsync(download); @@ -135,7 +136,7 @@ public virtual async Task DeleteDownload(Download download) /// Deletes a download by identifier, without loading its file. Does nothing when it no longer exists /// /// Download identifier - public virtual async Task DeleteDownloadById(string downloadId) + public virtual async Task DeleteDownloadById(string? downloadId) { if (string.IsNullOrEmpty(downloadId)) return; diff --git a/src/Business/Grand.Business.Storage/Services/FileSystemStore.cs b/src/Business/Grand.Business.Storage/Services/FileSystemStore.cs index 4f5c82bea..ba4423c69 100644 --- a/src/Business/Grand.Business.Storage/Services/FileSystemStore.cs +++ b/src/Business/Grand.Business.Storage/Services/FileSystemStore.cs @@ -14,16 +14,16 @@ public FileSystemStore(string fileSystemPath) _fileSystemPath = Path.GetFullPath(fileSystemPath); } - public Task GetFileInfo(string path) + public Task GetFileInfo(string path) { var physicalPath = GetPhysicalPath(path); var fileInfo = new PhysicalFileInfo(new FileInfo(physicalPath)); - return Task.FromResult(fileInfo.Exists ? new FileSystemStoreEntry(path, fileInfo) : null); + return Task.FromResult(fileInfo.Exists ? new FileSystemStoreEntry(path, fileInfo) : null); } - public IFileStoreEntry GetDirectoryInfo(string path) + public IFileStoreEntry? GetDirectoryInfo(string path) { var physicalPath = GetPhysicalPath(path); @@ -32,16 +32,16 @@ public IFileStoreEntry GetDirectoryInfo(string path) return directoryInfo.Exists ? new FileSystemStoreEntry(path, directoryInfo) : null; } - public Task GetPhysicalDirectoryInfo(string directoryPath) + public Task GetPhysicalDirectoryInfo(string directoryPath) { var physicalPath = GetPhysicalPath(directoryPath); var directoryInfo = new PhysicalDirectoryInfo(new DirectoryInfo(physicalPath)); - return directoryInfo.Exists ? Task.FromResult(directoryInfo) : Task.FromResult(null); + return Task.FromResult(directoryInfo.Exists ? directoryInfo : null); } - public IList GetDirectoryContent(string path = null, bool includeSubDirectories = false, + public IList GetDirectoryContent(string? path = null, bool includeSubDirectories = false, bool listDirectories = true, bool listFiles = true) { var physicalPath = GetPhysicalPath(path); @@ -215,7 +215,8 @@ public async Task CreateFileFromStream(string path, Stream inputStream, // Create directory path if it doesn't exist. var physicalDirectoryPath = Path.GetDirectoryName(physicalPath); - Directory.CreateDirectory(physicalDirectoryPath); + if (physicalDirectoryPath != null) + Directory.CreateDirectory(physicalDirectoryPath); var fileInfo = new FileInfo(physicalPath); await using var outputStream = fileInfo.Create(); @@ -246,7 +247,7 @@ public Task WriteAllText(string path, string text) /// The relative path within the file store. /// /// The resulting physical path is verified to be inside designated root file system path. - private string GetPhysicalPath(string path) + private string GetPhysicalPath(string? path) { path = this.NormalizePath(path); diff --git a/src/Business/Grand.Business.Storage/Services/FileSystemStoreEntry.cs b/src/Business/Grand.Business.Storage/Services/FileSystemStoreEntry.cs index 0b4b04ab6..5add67d97 100644 --- a/src/Business/Grand.Business.Storage/Services/FileSystemStoreEntry.cs +++ b/src/Business/Grand.Business.Storage/Services/FileSystemStoreEntry.cs @@ -9,7 +9,7 @@ public class FileSystemStoreEntry : IFileStoreEntry { private readonly IFileInfo _fileInfo; - internal FileSystemStoreEntry(string path, IFileInfo fileInfo) + internal FileSystemStoreEntry(string? path, IFileInfo fileInfo) { _fileInfo = fileInfo ?? throw new ArgumentNullException(nameof(fileInfo)); Path = path ?? throw new ArgumentNullException(nameof(path)); @@ -19,7 +19,7 @@ internal FileSystemStoreEntry(string path, IFileInfo fileInfo) public string Name => _fileInfo.Name; public string DirectoryPath => Path[..^Name.Length].TrimEnd('/'); - public string PhysicalPath => _fileInfo.PhysicalPath; + public string? PhysicalPath => _fileInfo.PhysicalPath; public DateTime LastModifiedUtc => _fileInfo.LastModified.UtcDateTime; public long Length => _fileInfo.Length; public bool IsDirectory => _fileInfo.IsDirectory; diff --git a/src/Business/Grand.Business.Storage/Services/LayeredFileStore.cs b/src/Business/Grand.Business.Storage/Services/LayeredFileStore.cs index 076d8c32a..0d49bc23f 100644 --- a/src/Business/Grand.Business.Storage/Services/LayeredFileStore.cs +++ b/src/Business/Grand.Business.Storage/Services/LayeredFileStore.cs @@ -26,13 +26,13 @@ public LayeredFileStore(IFileStore primary, IFileStore fallback, IEnumerable this.NormalizePath(p)).ToArray(); } - public async Task GetFileInfo(string path) + public async Task GetFileInfo(string path) { return await _primary.GetFileInfo(path) ?? (IsPrimaryOnly(path) ? null : await _fallback.GetFileInfo(path)); } - public IFileStoreEntry GetDirectoryInfo(string path) + public IFileStoreEntry? GetDirectoryInfo(string path) { var entry = _primary.GetDirectoryInfo(path); if (entry != null) return entry; @@ -44,14 +44,14 @@ public IFileStoreEntry GetDirectoryInfo(string path) return _primary.GetDirectoryInfo(path); } - public Task GetPhysicalDirectoryInfo(string directoryPath) + public Task GetPhysicalDirectoryInfo(string directoryPath) { return GetDirectoryInfo(directoryPath) == null - ? Task.FromResult(null) + ? Task.FromResult(null) : _primary.GetPhysicalDirectoryInfo(directoryPath); } - public IList GetDirectoryContent(string path = null, bool includeSubDirectories = false, + public IList GetDirectoryContent(string? path = null, bool includeSubDirectories = false, bool listDirectories = true, bool listFiles = true) { var primaryEntries = _primary.GetDirectoryContent(path, includeSubDirectories, listDirectories, listFiles); @@ -96,7 +96,7 @@ private async Task ReadSource(string path) return IsPrimaryOnly(path) || await _primary.GetFileInfo(path) != null ? _primary : _fallback; } - private bool IsPrimaryOnly(string path) + private bool IsPrimaryOnly(string? path) { var normalized = this.NormalizePath(path) ?? ""; return _primaryOnlyPaths.Any(p => diff --git a/src/Business/Grand.Business.Storage/Services/PictureService.cs b/src/Business/Grand.Business.Storage/Services/PictureService.cs index 21a617a02..a55091839 100644 --- a/src/Business/Grand.Business.Storage/Services/PictureService.cs +++ b/src/Business/Grand.Business.Storage/Services/PictureService.cs @@ -73,7 +73,7 @@ public PictureService(IRepository pictureRepository, /// /// Mime type /// File extension - private static string GetFileExtensionFromMimeType(string mimeType) + private static string? GetFileExtensionFromMimeType(string? mimeType) { if (mimeType == null) return null; @@ -102,7 +102,7 @@ private static string GetFileExtensionFromMimeType(string mimeType) /// Picture identifier /// MIME type /// Picture binary - protected async Task LoadPictureFromFile(string pictureId, string mimeType) + protected async Task LoadPictureFromFile(string pictureId, string? mimeType) { var lastPart = GetFileExtensionFromMimeType(mimeType); var fileName = $"{pictureId}_0.{lastPart}"; @@ -122,7 +122,7 @@ protected virtual Task DeletePictureThumbs(Picture picture) { var filter = $"{picture.Id}*.*"; var thumbDirectoryPath = _mediaFileStore.GetDirectoryInfo(ImageThumbPath); - if (thumbDirectoryPath == null) return Task.CompletedTask; + if (thumbDirectoryPath?.PhysicalPath == null) return Task.CompletedTask; var currentFiles = Directory.GetFiles(thumbDirectoryPath.PhysicalPath, filter, SearchOption.AllDirectories); foreach (var currentFileName in currentFiles) try @@ -143,7 +143,7 @@ protected virtual Task DeletePictureThumbs(Picture picture) /// /// Filename /// Local picture physical path - protected virtual async Task GetThumbPhysicalPath(string thumbFileName) + protected virtual async Task GetThumbPhysicalPath(string thumbFileName) { var thumbFile = _mediaFileStore.Combine(ImageThumbPath, thumbFileName); var fileInfo = await _mediaFileStore.GetFileInfo(thumbFile); @@ -156,7 +156,7 @@ protected virtual async Task GetThumbPhysicalPath(string thumbFileName) /// Filename /// Store location URL; null to use determine the current store location automatically /// Local picture thumb path - protected virtual string GetThumbUrl(string thumbFileName, string storeLocation = null) + protected virtual string? GetThumbUrl(string thumbFileName, string? storeLocation = null) { var thumbPath = _mediaFileStore.Combine(ImageThumbPath, thumbFileName); if (string.IsNullOrEmpty(storeLocation)) @@ -170,7 +170,7 @@ protected virtual string GetThumbUrl(string thumbFileName, string storeLocation /// /// Filename /// Physical picture path - protected virtual async Task GetPicturePhysicalPath(string fileName) + protected virtual async Task GetPicturePhysicalPath(string fileName) { var fileInfo = await _mediaFileStore.GetFileInfo(_mediaFileStore.Combine(ImagePath, fileName)); return fileInfo?.PhysicalPath; @@ -182,12 +182,12 @@ protected virtual async Task GetPicturePhysicalPath(string fileName) /// Picture /// Load from database; otherwise, from file system /// Picture binary - public virtual async Task LoadPictureBinary(Picture picture, bool fromDb) + public virtual async Task LoadPictureBinary(Picture picture, bool fromDb) { ArgumentNullException.ThrowIfNull(picture); var result = fromDb - ? (await _pictureRepository.GetByIdAsync(picture.Id)).PictureBinary + ? (await _pictureRepository.GetByIdAsync(picture.Id))?.PictureBinary : await LoadPictureFromFile(picture.Id, picture.MimeType); return result; @@ -198,7 +198,7 @@ public virtual async Task LoadPictureBinary(Picture picture, bool fromDb /// /// Thumb file name /// Picture binary - protected virtual async Task SaveThumb(string thumbFileName, byte[] binary) + protected virtual async Task SaveThumb(string thumbFileName, byte[]? binary) { try { @@ -235,7 +235,7 @@ protected virtual async Task SaveThumb(string thumbFileName, byte[] binary) /// /// Picture /// Picture binary - public virtual async Task LoadPictureBinary(Picture picture) + public virtual async Task LoadPictureBinary(Picture picture) { return await LoadPictureBinary(picture, _storageSettings.PictureStoreInDb); } @@ -245,7 +245,7 @@ public virtual async Task LoadPictureBinary(Picture picture) /// /// Name /// Result - public virtual string GetPictureSeName(string name) + public virtual string? GetPictureSeName(string? name) { return SeoExtensions.GenerateSlug(name, true, false, false); } @@ -256,7 +256,7 @@ public virtual string GetPictureSeName(string name) /// The target picture size (longest side) /// Store location URL; null to use determine the current store location automatically /// Picture URL - public virtual async Task GetDefaultPictureUrl(int targetSize = 0, string storeLocation = null) + public virtual async Task GetDefaultPictureUrl(int targetSize = 0, string? storeLocation = null) { var filePath = await GetPicturePhysicalPath(_mediaSettings.DefaultImageName); if (string.IsNullOrEmpty(filePath)) return _mediaFileStore.Combine(ImagePath, "no-image.png"); @@ -289,10 +289,10 @@ public virtual async Task GetDefaultPictureUrl(int targetSize = 0, strin /// A value indicating whether the default picture is shown /// Store location URL; null to use determine the current store location automatically /// Picture URL - public virtual async Task GetPictureUrl(string pictureId, + public virtual async Task GetPictureUrl(string pictureId, int targetSize = 0, bool showDefaultPicture = true, - string storeLocation = null) + string? storeLocation = null) { var pictureKey = string.Format(CacheKey.PICTURE_BY_KEY, pictureId, targetSize, showDefaultPicture, storeLocation); @@ -311,10 +311,10 @@ public virtual async Task GetPictureUrl(string pictureId, /// A value indicating whether the default picture is shown /// Store location URL; null to use determine the current store location automatically /// Picture URL - public virtual async Task GetPictureUrl(Picture picture, + public virtual async Task GetPictureUrl(Picture? picture, int targetSize = 0, bool showDefaultPicture = true, - string storeLocation = null) + string? storeLocation = null) { if (picture == null) return showDefaultPicture ? await GetDefaultPictureUrl(targetSize, storeLocation) : string.Empty; @@ -386,7 +386,7 @@ public virtual async Task GetPictureUrl(Picture picture, /// The target picture size (longest side) /// A value indicating whether the default picture is shown /// - public virtual async Task GetThumbPhysicalPath(Picture picture, int targetSize = 0, + public virtual async Task GetThumbPhysicalPath(Picture? picture, int targetSize = 0, bool showDefaultPicture = true) { var url = await GetPictureUrl(picture, targetSize, showDefaultPicture); @@ -405,7 +405,7 @@ public virtual async Task GetThumbPhysicalPath(Picture picture, int targ /// /// Picture identifier /// Picture - public virtual async Task GetPictureById(string pictureId) + public virtual async Task GetPictureById(string pictureId) { var pictureKey = string.Format(CacheKey.PICTURE_BY_ID, pictureId); return await _cacheBase.GetAsync(pictureKey, async () => @@ -517,8 +517,8 @@ public virtual async Task> GetPictures(int pageIndex = 0, in /// Object id for reference /// A value indicating whether to validated provided picture binary /// Picture - public virtual async Task InsertPicture(byte[] pictureBinary, string mimeType, string seoFilename, - string altAttribute = null, string titleAttribute = null, + public virtual async Task InsertPicture(byte[] pictureBinary, string mimeType, string? seoFilename, + string? altAttribute = null, string? titleAttribute = null, bool isNew = true, Reference reference = Reference.None, string objectId = "", bool validateBinary = false) { mimeType = CommonHelper.EnsureNotNull(mimeType); @@ -564,9 +564,9 @@ public virtual async Task InsertPicture(byte[] pictureBinary, string mi /// A value indicating whether the picture is new /// A value indicating whether to validated provided picture binary /// Picture - public virtual async Task UpdatePicture(string pictureId, byte[] pictureBinary, string mimeType, - string seoFilename, string altAttribute = null, string titleAttribute = null, - string style = null, string extraField = null, + public virtual async Task UpdatePicture(string pictureId, byte[] pictureBinary, string mimeType, + string seoFilename, string? altAttribute = null, string? titleAttribute = null, + string? style = null, string? extraField = null, bool isNew = true, bool validateBinary = true) { mimeType = CommonHelper.EnsureNotNull(mimeType); @@ -769,7 +769,7 @@ public virtual byte[] ConvertPicture(byte[] pictureBinary, int imageQuality, str } - private static SKEncodedImageFormat EncodedImageFormat(string mimetype) + private static SKEncodedImageFormat EncodedImageFormat(string? mimetype) { const SKEncodedImageFormat defaultFormat = SKEncodedImageFormat.Jpeg; if (string.IsNullOrEmpty(mimetype)) @@ -805,7 +805,7 @@ private static SKEncodedImageFormat EncodedImageFormat(string mimetype) return mimetype.Contains("ico") ? SKEncodedImageFormat.Ico : defaultFormat; } - private byte[] ApplyResize(SKBitmap image, SKEncodedImageFormat format, int targetSize) + private byte[]? ApplyResize(SKBitmap image, SKEncodedImageFormat format, int targetSize) { ArgumentNullException.ThrowIfNull(image); diff --git a/src/Core/Grand.Data/IRepository.cs b/src/Core/Grand.Data/IRepository.cs index c6eb9d5f8..64fc5da10 100644 --- a/src/Core/Grand.Data/IRepository.cs +++ b/src/Core/Grand.Data/IRepository.cs @@ -19,14 +19,14 @@ public interface IRepository where T : BaseEntity /// /// Identifier /// Entity - T? GetById(string id); + T? GetById(string? id); /// /// Get async entity by identifier /// /// Identifier /// Entity - Task GetByIdAsync(string id); + Task GetByIdAsync(string? id); /// /// Get entity by identifier diff --git a/src/Core/Grand.Data/LiteDb/LiteDBRepository.cs b/src/Core/Grand.Data/LiteDb/LiteDBRepository.cs index 56d03dce7..39e0ffc20 100644 --- a/src/Core/Grand.Data/LiteDb/LiteDBRepository.cs +++ b/src/Core/Grand.Data/LiteDb/LiteDBRepository.cs @@ -88,7 +88,7 @@ private static InvalidOperationException NotConfigured() /// /// Identifier /// Entity - public virtual T? GetById(string id) + public virtual T? GetById(string? id) { return Collection.Find(e => e.Id == id).FirstOrDefault(); } @@ -98,7 +98,7 @@ private static InvalidOperationException NotConfigured() /// /// Identifier /// Entity - public virtual async Task GetByIdAsync(string id) + public virtual async Task GetByIdAsync(string? id) { return await Task.FromResult(GetById(id)); } diff --git a/src/Core/Grand.Data/Mongo/MongoRepository.cs b/src/Core/Grand.Data/Mongo/MongoRepository.cs index 45093725d..4d664d45b 100644 --- a/src/Core/Grand.Data/Mongo/MongoRepository.cs +++ b/src/Core/Grand.Data/Mongo/MongoRepository.cs @@ -82,7 +82,7 @@ private static InvalidOperationException NotConfigured() /// /// Identifier /// Entity - public virtual T? GetById(string id) + public virtual T? GetById(string? id) { return Collection.Find(e => e.Id == id).FirstOrDefault(); } @@ -92,7 +92,7 @@ private static InvalidOperationException NotConfigured() /// /// Identifier /// Entity - public virtual async Task GetByIdAsync(string id) + public virtual async Task GetByIdAsync(string? id) { return await Collection.Find(e => e.Id == id).FirstOrDefaultAsync(); } diff --git a/src/Core/Grand.Domain/Catalog/ProductBatch.cs b/src/Core/Grand.Domain/Catalog/ProductBatch.cs index d6b53bc32..c692986ac 100644 --- a/src/Core/Grand.Domain/Catalog/ProductBatch.cs +++ b/src/Core/Grand.Domain/Catalog/ProductBatch.cs @@ -30,12 +30,12 @@ public class ProductBatch : BaseEntity /// /// The batch number as entered /// - public string? Number { get; set; } + public string Number { get; set; } = null!; /// /// The number trimmed and upper-cased: what lookups and the unique index compare /// - public string? NumberKey { get; set; } + public string NumberKey { get; set; } = null!; /// /// The expiry date, a date without time diff --git a/src/Core/Grand.Domain/Catalog/ProductExtensions.cs b/src/Core/Grand.Domain/Catalog/ProductExtensions.cs index 9d6f1fb63..93f5f819e 100644 --- a/src/Core/Grand.Domain/Catalog/ProductExtensions.cs +++ b/src/Core/Grand.Domain/Catalog/ProductExtensions.cs @@ -157,7 +157,7 @@ public static IList ParseProductAttributeMappings(this /// Attributes /// Product attribute values public static IList ParseProductAttributeValues(this Product product, - IList customAttributes) + IList? customAttributes) { var values = new List(); if (customAttributes == null || !customAttributes.Any()) diff --git a/src/Core/Grand.Domain/Catalog/ProductSerialNumber.cs b/src/Core/Grand.Domain/Catalog/ProductSerialNumber.cs index 9b4fb7fe7..b9e2be33a 100644 --- a/src/Core/Grand.Domain/Catalog/ProductSerialNumber.cs +++ b/src/Core/Grand.Domain/Catalog/ProductSerialNumber.cs @@ -19,12 +19,12 @@ public class ProductSerialNumber : BaseEntity /// /// The serial number as entered /// - public string? Number { get; set; } + public string Number { get; set; } = null!; /// /// The number trimmed and upper-cased: what lookups and the unique index compare /// - public string? NumberKey { get; set; } + public string NumberKey { get; set; } = null!; public SerialNumberStatus StatusId { get; set; } diff --git a/src/Core/Grand.Domain/Common/UserFieldExtensions.cs b/src/Core/Grand.Domain/Common/UserFieldExtensions.cs index 170263334..0ed256758 100644 --- a/src/Core/Grand.Domain/Common/UserFieldExtensions.cs +++ b/src/Core/Grand.Domain/Common/UserFieldExtensions.cs @@ -12,7 +12,7 @@ public static class UserFieldExtensions /// Key /// Load a value specific for a certain store; pass 0 to load a value shared for all stores /// Attribute - public static TPropType? GetUserFieldFromEntity(this BaseEntity entity, string key, string storeId = "") + public static TPropType? GetUserFieldFromEntity(this BaseEntity entity, string key, string? storeId = "") { ArgumentNullException.ThrowIfNull(entity); diff --git a/src/Core/Grand.Domain/Orders/OrderExtensions.cs b/src/Core/Grand.Domain/Orders/OrderExtensions.cs index 1f7a4d37d..02d0202f2 100644 --- a/src/Core/Grand.Domain/Orders/OrderExtensions.cs +++ b/src/Core/Grand.Domain/Orders/OrderExtensions.cs @@ -12,7 +12,7 @@ public static class OrderExtensions /// Order item to check /// Product /// True if download is allowed; otherwise, false. - public static bool IsDownloadAllowed(this Order order, OrderItem orderItem, Product product) + public static bool IsDownloadAllowed(this Order order, OrderItem orderItem, Product? product) { if (orderItem == null) return false; @@ -76,7 +76,7 @@ public static bool IsDownloadAllowed(this Order order, OrderItem orderItem, Prod /// Order item to check /// Product /// True if license download is allowed; otherwise, false. - public static bool IsLicenseDownloadAllowed(this Order order, OrderItem orderItem, Product product) + public static bool IsLicenseDownloadAllowed(this Order order, OrderItem orderItem, Product? product) { if (orderItem == null) return false; diff --git a/src/Core/Grand.Domain/Orders/ShoppingCartExtensions.cs b/src/Core/Grand.Domain/Orders/ShoppingCartExtensions.cs index b352b06a7..1306792c9 100644 --- a/src/Core/Grand.Domain/Orders/ShoppingCartExtensions.cs +++ b/src/Core/Grand.Domain/Orders/ShoppingCartExtensions.cs @@ -16,7 +16,7 @@ public static bool RequiresShipping(this IList shoppingCart) } public static IEnumerable LimitPerStore(this IEnumerable cart, - bool cartsSharedBetweenStores, string storeId) + bool cartsSharedBetweenStores, string? storeId) { return cartsSharedBetweenStores ? cart : cart.Where(x => x.StoreId == storeId); } diff --git a/src/Core/Grand.Infrastructure/Configuration/OidcLoginConfig.cs b/src/Core/Grand.Infrastructure/Configuration/OidcLoginConfig.cs index f5ddd28c4..2f47f9e9a 100644 --- a/src/Core/Grand.Infrastructure/Configuration/OidcLoginConfig.cs +++ b/src/Core/Grand.Infrastructure/Configuration/OidcLoginConfig.cs @@ -61,7 +61,7 @@ public class OidcLoginConfig public bool ProviderOnly => SignInMode == OidcSignInMode.ProviderOnly; - public bool IsBreakGlass(string email) + public bool IsBreakGlass(string? email) { if (string.IsNullOrWhiteSpace(email) || BreakGlassAccounts == null) return false; diff --git a/src/Core/Grand.Infrastructure/Extensions/ProviderExtensions.cs b/src/Core/Grand.Infrastructure/Extensions/ProviderExtensions.cs index 4e23947c6..273aeed88 100644 --- a/src/Core/Grand.Infrastructure/Extensions/ProviderExtensions.cs +++ b/src/Core/Grand.Infrastructure/Extensions/ProviderExtensions.cs @@ -15,7 +15,7 @@ public static bool IsAuthenticateStore(this IProvider method, Store store) return store == null || IsAuthenticateStore(method, store.Id); } - public static bool IsAuthenticateStore(this IProvider method, string storeId) + public static bool IsAuthenticateStore(this IProvider method, string? storeId) { ArgumentNullException.ThrowIfNull(method); @@ -28,7 +28,7 @@ public static bool IsAuthenticateStore(this IProvider method, string storeId) return method.LimitedToStores.Contains(storeId); } - public static bool IsAuthenticateGroup(this IProvider method, Customer customer) + public static bool IsAuthenticateGroup(this IProvider method, Customer? customer) { ArgumentNullException.ThrowIfNull(method); diff --git a/src/Core/Grand.Infrastructure/Plugins/IProvider.cs b/src/Core/Grand.Infrastructure/Plugins/IProvider.cs index 0b5ca5f97..275d938a8 100644 --- a/src/Core/Grand.Infrastructure/Plugins/IProvider.cs +++ b/src/Core/Grand.Infrastructure/Plugins/IProvider.cs @@ -5,7 +5,7 @@ public interface IProvider /// /// Gets a configuration URL /// - string ConfigurationUrl { get; } + string? ConfigurationUrl { get; } /// /// Gets a system name for provider diff --git a/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs b/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs index 2b4a2f59e..52ae8296f 100644 --- a/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs +++ b/src/Core/Grand.SharedKernel/Extensions/CommonHelper.cs @@ -18,7 +18,7 @@ public static class CommonHelper /// /// The email. /// - public static string EnsureSubscriberEmailOrThrow(string email) + public static string EnsureSubscriberEmailOrThrow(string? email) { var output = EnsureNotNull(email); output = output.Trim(); @@ -34,7 +34,7 @@ public static string EnsureSubscriberEmailOrThrow(string email) /// /// Email to verify /// true if the string is a valid e-mail address and false if it's not - public static bool IsValidEmail(string email) + public static bool IsValidEmail(string? email) { if (string.IsNullOrEmpty(email)) return false; @@ -109,7 +109,7 @@ public static int GenerateRandomInteger(int min = 0, int max = int.MaxValue) /// /// Input string /// Result - public static string EnsureNotNull(string str) + public static string EnsureNotNull(string? str) { return str ?? string.Empty; } @@ -172,7 +172,7 @@ public static bool IsSimpleType(Type? type) /// The value to convert. /// The type to convert the value to. /// The converted value. - public static object? To(object value, Type destinationType) + public static object? To(object? value, Type destinationType) { return To(value, destinationType, CultureInfo.InvariantCulture); } @@ -184,7 +184,7 @@ public static bool IsSimpleType(Type? type) /// The type to convert the value to. /// Culture /// The converted value. - public static object? To(object value, Type destinationType, CultureInfo culture) + public static object? To(object? value, Type destinationType, CultureInfo culture) { if (value != null) { @@ -214,7 +214,7 @@ public static bool IsSimpleType(Type? type) /// The value to convert. /// The type to convert the value to. /// The converted value. - public static T? To(object value) + public static T? To(object? value) { return (T?)To(value, typeof(T)); } diff --git a/src/Core/Grand.SharedKernel/Extensions/FormatText.cs b/src/Core/Grand.SharedKernel/Extensions/FormatText.cs index a7e2f85ec..61e583d96 100644 --- a/src/Core/Grand.SharedKernel/Extensions/FormatText.cs +++ b/src/Core/Grand.SharedKernel/Extensions/FormatText.cs @@ -4,7 +4,7 @@ namespace Grand.SharedKernel.Extensions; public static class FormatText { - public static string ConvertText(string text) + public static string ConvertText(string? text) { if (string.IsNullOrEmpty(text)) return string.Empty; diff --git a/src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs b/src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs index e6e2c92c8..7e989b6bc 100644 --- a/src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs +++ b/src/Tests/Grand.Business.Authentication.Tests/Services/ExternalAuthenticationServiceTests.cs @@ -307,7 +307,7 @@ public async Task AssociateCustomerTest() { //Act await _externalAuthenticationService.AssociateCustomer(new Customer(), - new ExternalAuthParam { ProviderSystemName = "ExternalAuthenticationProviderTest" }); + new ExternalAuthParam { ProviderSystemName = "ExternalAuthenticationProviderTest", Identifier = "1" }); //Assert Assert.IsTrue(_externalAuthenticationRecordRepository.Table.Any()); } diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerApprovalTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerApprovalTests.cs index 897756fbb..b54a5ef39 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerApprovalTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerApprovalTests.cs @@ -62,6 +62,8 @@ public void Init() Host = new DomainHost { Url = "https://shop.example/" } }; _details = new PlaceOrderContainer { + Host = new DomainHost(), + WorkingLanguage = new Language(), Context = context, Customer = customer, Store = store, @@ -298,14 +300,14 @@ private static ICheckoutClaimService Claims() { var claims = new Mock(); claims.Setup(x => x.Claim(It.IsAny(), It.IsAny())) - .ReturnsAsync(new CheckoutClaim { Succeeded = true }); + .ReturnsAsync(new CheckoutClaim { CustomerId = "", OrderCode = "", OrderId = "", StoreId = "", Succeeded = true }); return claims.Object; } protected override Task PreparePaymentTransaction(PlaceOrderContainer details) { return Task.FromResult(new PaymentTransaction { - Id = "tx", StoreId = "store", PaymentMethodSystemName = details.PaymentMethodSystemName + Id = "tx", StoreId = "store", OrderCode = "code", PaymentMethodSystemName = details.PaymentMethodSystemName }); } diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerPurchaseOrderTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerPurchaseOrderTests.cs index df5b5f28e..69ad88799 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerPurchaseOrderTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerPurchaseOrderTests.cs @@ -56,6 +56,8 @@ public void Init() Host = new DomainHost { Url = "https://shop.example/" } }; _details = new PlaceOrderContainer { + Host = new DomainHost(), + WorkingLanguage = new Language(), Context = context, Customer = customer, Store = store, @@ -184,14 +186,14 @@ private static ICheckoutClaimService Claims() { var claims = new Mock(); claims.Setup(x => x.Claim(It.IsAny(), It.IsAny())) - .ReturnsAsync(new CheckoutClaim { Succeeded = true }); + .ReturnsAsync(new CheckoutClaim { CustomerId = "", OrderCode = "", OrderId = "", StoreId = "", Succeeded = true }); return claims.Object; } protected override Task PreparePaymentTransaction(PlaceOrderContainer details) { return Task.FromResult(new PaymentTransaction { - Id = "tx", StoreId = "store", PaymentMethodSystemName = details.PaymentMethodSystemName + Id = "tx", StoreId = "store", OrderCode = "code", PaymentMethodSystemName = details.PaymentMethodSystemName }); } diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerTests.cs index 884ba8984..96668ef06 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/PlaceOrderCommandHandlerTests.cs @@ -154,6 +154,8 @@ public async Task Handle_PreparesDetailsFromTheCommand() var context = new CalculationContext(customer, store, new Currency { CurrencyCode = "EUR", Rate = 1 }, TaxDisplayType.IncludingTax); var details = new PlaceOrderContainer { + Host = new DomainHost(), + WorkingLanguage = new Language(), Context = context, Customer = customer, Store = store, @@ -173,7 +175,7 @@ public async Task Handle_PreparesDetailsFromTheCommand() var claims = new Mock(); claims.Setup(x => x.Claim(It.IsAny(), It.IsAny())) .Callback(() => calls.Add("claim")) - .ReturnsAsync((PlaceOrderContainer d, string _) => new CheckoutClaim { OrderId = d.OrderId, Succeeded = true }); + .ReturnsAsync((PlaceOrderContainer d, string _) => new CheckoutClaim { CustomerId = "", OrderCode = "", StoreId = "", OrderId = d.OrderId, Succeeded = true }); var orders = new Mock(); var inventory = new Mock(); var giftVouchers = new Mock(); @@ -214,7 +216,7 @@ public async Task Handle_ClaimRefused_ReturnsErrorAndSkipsPayment() { var (handler, claims, orders, _, _, _, details, _) = ClaimSetup(); claims.Setup(x => x.Claim(It.IsAny(), It.IsAny())) - .ReturnsAsync(new CheckoutClaim { Succeeded = false }); + .ReturnsAsync(new CheckoutClaim { CustomerId = "", OrderCode = "", OrderId = "", StoreId = "", Succeeded = false }); var result = await handler.Handle(ClaimCommand(details), CancellationToken.None); @@ -228,7 +230,7 @@ public async Task Handle_ClaimRefused_RecordsWhyOnThePaymentTransaction() { var (handler, claims, _, _, _, _, details, _) = ClaimSetup(); claims.Setup(x => x.Claim(It.IsAny(), It.IsAny())) - .ReturnsAsync(new CheckoutClaim { Succeeded = false }); + .ReturnsAsync(new CheckoutClaim { CustomerId = "", OrderCode = "", OrderId = "", StoreId = "", Succeeded = false }); await handler.Handle(ClaimCommand(details), CancellationToken.None); diff --git a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandlerTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandlerTests.cs index dd178831a..d27aefc4b 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandlerTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Commands/Handlers/Orders/ReturnBackRedeemedLoyaltyPointsCommandHandlerTests.cs @@ -38,7 +38,7 @@ public async Task HandleTest() { //Arrange var command = new ReturnBackRedeemedLoyaltyPointsCommand { - Order = new Order { RedeemedLoyaltyPoints = 10, CustomerLanguageId = "lang1" } + Order = new Order { CustomerId = "c1", RedeemedLoyaltyPoints = 10, CustomerLanguageId = "lang1" } }; //the message is written in the language the order was placed in _translationServiceMock.Setup(x => x.GetResource(It.IsAny(), "lang1", It.IsAny(), @@ -56,7 +56,7 @@ public async Task Handle_OrderWithoutLanguage_WritesTheMessageInTheStoreDefaultL { //Arrange var command = new ReturnBackRedeemedLoyaltyPointsCommand { - Order = new Order { RedeemedLoyaltyPoints = 10, StoreId = "store1", CustomerLanguageId = null } + Order = new Order { CustomerId = "c1", RedeemedLoyaltyPoints = 10, StoreId = "store1", CustomerLanguageId = null } }; _storeServiceMock.Setup(c => c.GetStoreById("store1")) .ReturnsAsync(new Store { Id = "store1", DefaultLanguageId = "store-lang" }); diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/CheckoutClaimServiceTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/CheckoutClaimServiceTests.cs index c5e61ba47..95b4221e2 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/CheckoutClaimServiceTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Orders/CheckoutClaimServiceTests.cs @@ -10,9 +10,12 @@ using Grand.Domain.Catalog; using Grand.Domain.Common; using Grand.Domain.Customers; +using Grand.Domain.Directory; using Grand.Domain.Discounts; +using Grand.Domain.Localization; using Grand.Domain.Orders; using Grand.Domain.Stores; +using Grand.Domain.Tax; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; @@ -58,10 +61,15 @@ public void Init() .ReturnsAsync(new LoyaltyPointsHistory()); _attributes = [new CustomAttribute { Key = "a", Value = "b" }]; + var customer = new Customer { Id = "c1" }; + var store = new Store { Id = "s1" }; _details = new PlaceOrderContainer { + Context = new CalculationContext(customer, store, new Currency(), TaxDisplayType.IncludingTax), + Host = new DomainHost(), + WorkingLanguage = new Language(), OrderId = "o1", - Customer = new Customer { Id = "c1" }, - Store = new Store { Id = "s1" }, + Customer = customer, + Store = store, Cart = [new ShoppingCartItem { ProductId = "p1", Quantity = 2, WarehouseId = "w1", Attributes = _attributes }], AppliedDiscounts = [new ApplyDiscount { DiscountId = "d1", CouponCode = "COUPON" }], AppliedGiftVouchers = [ diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ReturnProviders/InStoreReturnProviderTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ReturnProviders/InStoreReturnProviderTests.cs index a1af9218b..52823275a 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ReturnProviders/InStoreReturnProviderTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ReturnProviders/InStoreReturnProviderTests.cs @@ -53,7 +53,7 @@ public void Init() public async Task InStore_StoreReturnWithPoints_OffersOptionWithForm() { var options = await _provider.GetReturnOptions(new ReturnShippingRequest - { StoreId = "s1", VendorId = "", LanguageId = "l1" }); + { Order = new Order(), StoreId = "s1", VendorId = "", LanguageId = "l1" }); Assert.AreEqual(1, options.Count); Assert.AreEqual("instore", options[0].Code); @@ -65,7 +65,7 @@ public async Task InStore_StoreReturnWithPoints_OffersOptionWithForm() [TestMethod] public async Task InStore_VendorReturn_NoOption() { - var options = await _provider.GetReturnOptions(new ReturnShippingRequest { StoreId = "s1", VendorId = "v1" }); + var options = await _provider.GetReturnOptions(new ReturnShippingRequest { Order = new Order(), StoreId = "s1", VendorId = "v1" }); Assert.AreEqual(0, options.Count); } @@ -73,7 +73,7 @@ public async Task InStore_VendorReturn_NoOption() [TestMethod] public async Task InStore_NoActivePoints_NoOption() { - var options = await _provider.GetReturnOptions(new ReturnShippingRequest { StoreId = "s2", VendorId = "" }); + var options = await _provider.GetReturnOptions(new ReturnShippingRequest { Order = new Order(), StoreId = "s2", VendorId = "" }); Assert.AreEqual(0, options.Count); } @@ -81,7 +81,7 @@ public async Task InStore_NoActivePoints_NoOption() [TestMethod] public async Task InStore_ValidateForm_PointOfOtherStore_Error() { - var result = await _provider.ValidateForm(new ReturnShippingRequest { StoreId = "s2", LanguageId = "l1" }, + var result = await _provider.ValidateForm(new ReturnShippingRequest { Order = new Order(), VendorId = "", StoreId = "s2", LanguageId = "l1" }, "instore", new Dictionary { ["pickupPointId"] = "p1" }); Assert.AreEqual(1, result.Errors.Count); @@ -92,7 +92,7 @@ public async Task InStore_ValidateForm_PointOfOtherStore_Error() [TestMethod] public async Task InStore_ValidateForm_NoPoint_Error() { - var result = await _provider.ValidateForm(new ReturnShippingRequest { StoreId = "s1", LanguageId = "l1" }, + var result = await _provider.ValidateForm(new ReturnShippingRequest { Order = new Order(), VendorId = "", StoreId = "s1", LanguageId = "l1" }, "instore", new Dictionary()); Assert.AreEqual(1, result.Errors.Count); @@ -101,7 +101,7 @@ public async Task InStore_ValidateForm_NoPoint_Error() [TestMethod] public async Task InStore_ValidateForm_SnapshotHasWarehouse() { - var result = await _provider.ValidateForm(new ReturnShippingRequest { StoreId = "s1", LanguageId = "l1" }, + var result = await _provider.ValidateForm(new ReturnShippingRequest { Order = new Order(), VendorId = "", StoreId = "s1", LanguageId = "l1" }, "instore", new Dictionary { ["pickupPointId"] = "p1" }); Assert.AreEqual(0, result.Errors.Count); diff --git a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ReturnProviders/SendYourselfReturnProviderTests.cs b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ReturnProviders/SendYourselfReturnProviderTests.cs index 07190ba31..03b4fb0e9 100644 --- a/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ReturnProviders/SendYourselfReturnProviderTests.cs +++ b/src/Tests/Grand.Business.Checkout.Tests/Services/Shipping/ReturnProviders/SendYourselfReturnProviderTests.cs @@ -56,7 +56,7 @@ public void Init() [TestMethod] public async Task SendYourself_CostFromStoreSettings() { - var options = await _provider.GetReturnOptions(new ReturnShippingRequest { StoreId = "s1", LanguageId = "l1" }); + var options = await _provider.GetReturnOptions(new ReturnShippingRequest { Order = new Order(), VendorId = "", StoreId = "s1", LanguageId = "l1" }); Assert.AreEqual(1, options.Count); Assert.AreEqual("send", options[0].Code); @@ -162,7 +162,7 @@ public async Task SendYourself_CreateLabel_VendorWithoutAddress_StoreAddressNotN [TestMethod] public async Task SendYourself_Option_DescribesTheReturnAddressWithRecipient() { - var options = await _provider.GetReturnOptions(new ReturnShippingRequest { + var options = await _provider.GetReturnOptions(new ReturnShippingRequest { Order = new Order(), VendorId = "", StoreId = "s1", LanguageId = "l1", ReturnAddress = new Address { Company = "Shop Ltd", Address1 = "Main 1", ZipPostalCode = "00-001", City = "Warsaw", CountryId = "pl" @@ -180,7 +180,7 @@ public async Task SendYourself_Option_VendorAddressWithoutNames_DescribedWithThe Address = new Address { Address1 = "Main 1", ZipPostalCode = "00-001", City = "Warsaw", CountryId = "pl" } }); - var options = await _provider.GetReturnOptions(new ReturnShippingRequest { + var options = await _provider.GetReturnOptions(new ReturnShippingRequest { Order = new Order(), StoreId = "s1", LanguageId = "l1", VendorId = "v1", ReturnAddress = new Address { Address1 = "Main 1", ZipPostalCode = "00-001", City = "Warsaw", CountryId = "pl" } @@ -192,7 +192,7 @@ public async Task SendYourself_Option_VendorAddressWithoutNames_DescribedWithThe [TestMethod] public async Task SendYourself_Option_NoReturnAddress_NoDescription() { - var options = await _provider.GetReturnOptions(new ReturnShippingRequest { StoreId = "s1", LanguageId = "l1" }); + var options = await _provider.GetReturnOptions(new ReturnShippingRequest { Order = new Order(), VendorId = "", StoreId = "s1", LanguageId = "l1" }); Assert.AreEqual("", options[0].Description); } diff --git a/src/Tests/Grand.Business.Cms.Tests/Events/BlogPostDeletedEventHandlerTests.cs b/src/Tests/Grand.Business.Cms.Tests/Events/BlogPostDeletedEventHandlerTests.cs index debb7eaa5..1f9d32096 100644 --- a/src/Tests/Grand.Business.Cms.Tests/Events/BlogPostDeletedEventHandlerTests.cs +++ b/src/Tests/Grand.Business.Cms.Tests/Events/BlogPostDeletedEventHandlerTests.cs @@ -24,7 +24,8 @@ public void Init() [TestMethod] public async Task Handle_InvokeSlugService() { - await _handler.Handle(new EntityDeleted(new BlogPost()), default); + _slugServiceMock.Setup(c => c.GetBySlug("post")).ReturnsAsync(new EntityUrl { Slug = "post" }); + await _handler.Handle(new EntityDeleted(new BlogPost { SeName = "post" }), default); _slugServiceMock.Verify(c => c.DeleteEntityUrl(It.IsAny()), Times.Once); } } \ No newline at end of file diff --git a/src/Tests/Grand.Business.Messages.Tests/Commands/GetMerchandiseReturnTokensCommandHandlerTests.cs b/src/Tests/Grand.Business.Messages.Tests/Commands/GetMerchandiseReturnTokensCommandHandlerTests.cs index ce31b460a..6a1a68301 100644 --- a/src/Tests/Grand.Business.Messages.Tests/Commands/GetMerchandiseReturnTokensCommandHandlerTests.cs +++ b/src/Tests/Grand.Business.Messages.Tests/Commands/GetMerchandiseReturnTokensCommandHandlerTests.cs @@ -44,6 +44,7 @@ public void Init() MerchandiseReturn = merchandiseReturn, Order = new Order { CustomerCurrencyCode = "EUR" }, Store = new Store { Url = "https://store.example/" }, + Host = new DomainHost { Url = "https://store.example/" }, Language = new Language { Id = "en" }, StatusNote = statusNote }, default); diff --git a/src/Tests/Grand.Business.Messages.Tests/Commands/InsertContactUsCommandHandlerTests.cs b/src/Tests/Grand.Business.Messages.Tests/Commands/InsertContactUsCommandHandlerTests.cs index 99bc18a4a..7ea06a803 100644 --- a/src/Tests/Grand.Business.Messages.Tests/Commands/InsertContactUsCommandHandlerTests.cs +++ b/src/Tests/Grand.Business.Messages.Tests/Commands/InsertContactUsCommandHandlerTests.cs @@ -27,6 +27,8 @@ public async Task Handler_InsertEntity() var command = new InsertContactUsCommand { ContactAttributeDescription = "d", Email = "grand@gmail.com", + FullName = "John Doe", + Enquiry = "Question", ContactAttributes = new List() }; diff --git a/src/Tests/Grand.Business.Messages.Tests/Services/CampaignMessageRendererTests.cs b/src/Tests/Grand.Business.Messages.Tests/Services/CampaignMessageRendererTests.cs index 39a275c1b..ad7fe3d33 100644 --- a/src/Tests/Grand.Business.Messages.Tests/Services/CampaignMessageRendererTests.cs +++ b/src/Tests/Grand.Business.Messages.Tests/Services/CampaignMessageRendererTests.cs @@ -58,7 +58,8 @@ public async Task Render_WithoutCustomerSubscriptionAndQueuedEmail_SkipsTheirTok }; var result = await _renderer.Render(campaign, new CampaignRecipient { - Store = _store, Language = new Language(), EmailAccount = new EmailAccount(), Host = _host + Store = _store, Language = new Language(), EmailAccount = new EmailAccount(), Host = _host, + Currency = new Currency() }); Assert.AreEqual("Subject", result.Subject); diff --git a/src/Tests/Grand.Web.Common.Tests/Security/Authentication/ExternalSignInServiceTests.cs b/src/Tests/Grand.Web.Common.Tests/Security/Authentication/ExternalSignInServiceTests.cs index cd1535033..089b9bb86 100644 --- a/src/Tests/Grand.Web.Common.Tests/Security/Authentication/ExternalSignInServiceTests.cs +++ b/src/Tests/Grand.Web.Common.Tests/Security/Authentication/ExternalSignInServiceTests.cs @@ -38,7 +38,8 @@ private Task Authenticate(ExternalAuthResult result, string retur .Setup(s => s.Authenticate(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) .ReturnsAsync(result); - return _service.Authenticate(new ExternalAuthParam(), new Customer(), new Store(), new Language { Id = "lang1" }, + return _service.Authenticate(new ExternalAuthParam { ProviderSystemName = "provider", Identifier = "1" }, + new Customer(), new Store(), new Language { Id = "lang1" }, returnUrl); } From 6e117ab934a8667688de2c37377d8635cb52675f Mon Sep 17 00:00:00 2001 From: support Date: Wed, 25 Nov 2026 17:45:27 +0100 Subject: [PATCH 10/30] Enable nullable reference types in the modules Api, Scim, ScheduledTasks join Installer and Migration, which had nullable enabled already; all five build with no nullable warnings. - API request models: the inputs every caller sets are required; DTO fields stay nullable, as a request may leave them out. The login models' e-mail and password, which the validators always require, are not null. - Controllers look an entity up once and answer 404 when it is null, instead of Any() then FirstOrDefault()!: one query less, no forgiving operator. - Update handlers throw an ArgumentException naming the missing entity where a NullReferenceException followed; ids of request DTOs passed on to services are guarded. - Service lookups by id that already cope with null take a nullable id (GetBrandById, GetPictureById, GetCustomerByEmail, ...). - SCIM: results are read through patterns that carry the resource (Outcome Ok with its User/Group); ReadBody returns the body or null. - JWT: a missing secret key throws the configuration error of the refresh token service; empty claim values were already skipped. - Scheduled tasks: a queued e-mail without account, sender or recipient counts as a failed try with a message saying so; an auction whose bidder is gone is skipped with a warning. --- .../JwtBearerAuthenticationService.cs | 2 +- .../JwtBearerCustomerAuthenticationService.cs | 2 +- .../Services/Scim/ScimGroupService.cs | 6 +- .../Services/Scim/ScimUserService.cs | 2 +- .../Services/Brands/BrandService.cs | 2 +- .../Products/SpecificationAttributeService.cs | 2 +- .../Orders/MerchandiseReturnService.cs | 4 +- .../Services/Directory/GroupService.cs | 2 +- .../Services/Security/EncryptionService.cs | 2 +- .../IJwtBearerAuthenticationService.cs | 2 +- ...IJwtBearerCustomerAuthenticationService.cs | 2 +- .../Authentication/IScimGroupService.cs | 4 +- .../Authentication/IScimUserService.cs | 2 +- .../Catalog/Brands/IBrandService.cs | 2 +- .../ISpecificationAttributeService.cs | 2 +- .../Orders/IMerchandiseReturnService.cs | 4 +- .../Common/Directory/IGroupService.cs | 2 +- .../Common/Security/IEncryptionService.cs | 2 +- .../Customers/ICustomerManagerService.cs | 2 +- .../Interfaces/Customers/ICustomerService.cs | 4 +- .../ICatalogMessageProviderService.cs | 2 +- .../Messages/IQueuedEmailService.cs | 6 +- .../Interfaces/Storage/IPictureService.cs | 12 +- .../ScheduleTasks/IScheduleTaskService.cs | 4 +- .../Utilities/Authentication/ScimResults.cs | 4 +- .../Utilities/Catalog/StockChange.cs | 2 +- .../Services/CustomerManagerService.cs | 2 +- .../Services/CustomerService.cs | 4 +- .../Services/CatalogMessageProviderService.cs | 2 +- .../Services/QueuedEmailService.cs | 6 +- .../Services/PictureService.cs | 12 +- .../Configuration/ScimConfig.cs | 3 + .../Migrations/MigrationResult.cs | 2 +- ...ddProductAttributeMappingCommandHandler.cs | 1 + .../AddProductCategoryCommandHandler.cs | 1 + .../AddProductCollectionCommandHandler.cs | 1 + .../AddProductSpecificationCommandHandler.cs | 1 + .../AddProductTierPriceCommandHandler.cs | 1 + ...teProductAttributeMappingCommandHandler.cs | 1 + .../DeleteProductCategoryCommandHandler.cs | 3 +- .../DeleteProductCollectionCommandHandler.cs | 3 +- .../DeleteProductPictureCommandHandler.cs | 3 +- ...eleteProductSpecificationCommandHandler.cs | 3 +- .../DeleteProductTierPriceCommandHandler.cs | 6 +- .../Catalog/UpdateBrandCommandHandler.cs | 3 +- .../Catalog/UpdateCategoryCommandHandler.cs | 3 +- .../Catalog/UpdateCollectionCommandHandler.cs | 3 +- .../UpdateProductAttributeCommandHandler.cs | 3 +- ...teProductAttributeMappingCommandHandler.cs | 1 + .../UpdateProductCategoryCommandHandler.cs | 3 +- .../UpdateProductCollectionCommandHandler.cs | 3 +- .../Catalog/UpdateProductCommandHandler.cs | 3 +- .../UpdateProductPictureCommandHandler.cs | 4 +- ...pdateProductSpecificationCommandHandler.cs | 3 +- .../UpdateProductTierPriceCommandHandler.cs | 3 +- ...ateSpecificationAttributeCommandHandler.cs | 3 +- .../Common/AddPictureCommandHandler.cs | 5 +- .../AddCustomerAddressCommandHandler.cs | 1 + .../Customers/AddCustomerCommandHandler.cs | 2 +- .../DeleteCustomerAddressCommandHandler.cs | 1 + .../UpdateCustomerAddressCommandHandler.cs | 5 +- .../Customers/UpdateCustomerCommandHandler.cs | 5 +- .../UpdateCustomerGroupCommandHandler.cs | 3 +- .../Inventory/ApplyStockCommandHandler.cs | 30 ++-- ...geMerchandiseReturnStatusCommandHandler.cs | 4 +- .../DeleteMerchandiseReturnCommandHandler.cs | 4 +- ...teMerchandiseReturnActionCommandHandler.cs | 3 +- .../UpdateMerchandiseReturnCommandHandler.cs | 6 +- ...teMerchandiseReturnReasonCommandHandler.cs | 3 +- .../Models/Catalog/AddBrandCommand.cs | 2 +- .../Models/Catalog/AddCategoryCommand.cs | 2 +- .../Models/Catalog/AddCollectionCommand.cs | 2 +- .../Catalog/AddProductAttributeCommand.cs | 4 +- .../AddProductAttributeMappingCommand.cs | 4 +- .../Catalog/AddProductCategoryCommand.cs | 4 +- .../Catalog/AddProductCollectionCommand.cs | 4 +- .../Models/Catalog/AddProductCommand.cs | 2 +- .../Catalog/AddProductPictureCommand.cs | 4 +- .../Catalog/AddProductSpecificationCommand.cs | 4 +- .../Catalog/AddProductTierPriceCommand.cs | 4 +- .../AddSpecificationAttributeCommand.cs | 2 +- .../Models/Catalog/DeleteBrandCommand.cs | 2 +- .../Models/Catalog/DeleteCategoryCommand.cs | 2 +- .../Models/Catalog/DeleteCollectionCommand.cs | 2 +- .../Catalog/DeleteProductAttributeCommand.cs | 2 +- .../DeleteProductAttributeMappingCommand.cs | 4 +- .../Catalog/DeleteProductCategoryCommand.cs | 4 +- .../Catalog/DeleteProductCollectionCommand.cs | 4 +- .../Models/Catalog/DeleteProductCommand.cs | 2 +- .../Catalog/DeleteProductPictureCommand.cs | 4 +- .../DeleteProductSpecificationCommand.cs | 4 +- .../Catalog/DeleteProductTierPriceCommand.cs | 4 +- .../DeleteSpecificationAttributeCommand.cs | 2 +- .../Models/Catalog/UpdateBrandCommand.cs | 2 +- .../Models/Catalog/UpdateCategoryCommand.cs | 2 +- .../Models/Catalog/UpdateCollectionCommand.cs | 2 +- .../Catalog/UpdateProductAttributeCommand.cs | 2 +- .../UpdateProductAttributeMappingCommand.cs | 4 +- .../Catalog/UpdateProductCategoryCommand.cs | 4 +- .../Catalog/UpdateProductCollectionCommand.cs | 4 +- .../Models/Catalog/UpdateProductCommand.cs | 2 +- .../Catalog/UpdateProductPictureCommand.cs | 4 +- .../UpdateProductSpecificationCommand.cs | 4 +- .../Catalog/UpdateProductStockCommand.cs | 4 +- .../Catalog/UpdateProductTierPriceCommand.cs | 4 +- .../UpdateSpecificationAttributeCommand.cs | 2 +- .../Models/Common/AddPictureCommand.cs | 2 +- .../Models/Common/DeletePictureCommand.cs | 2 +- .../Models/Common/GenerateTokenCommand.cs | 2 +- .../Models/Common/GenerateTokenWebCommand.cs | 2 +- .../Models/Common/UpdatePictureCommand.cs | 2 +- .../Customers/AddCustomerAddressCommand.cs | 4 +- .../Models/Customers/AddCustomerCommand.cs | 2 +- .../Customers/AddCustomerGroupCommand.cs | 2 +- .../Customers/DeleteCustomerAddressCommand.cs | 4 +- .../Models/Customers/DeleteCustomerCommand.cs | 2 +- .../Customers/DeleteCustomerGroupCommand.cs | 2 +- .../Customers/UpdateCustomerAddressCommand.cs | 6 +- .../Models/Customers/UpdateCustomerCommand.cs | 2 +- .../Customers/UpdateCustomerGroupCommand.cs | 2 +- .../Models/Inventory/ApplyStockCommand.cs | 2 +- .../AddMerchandiseReturnActionCommand.cs | 2 +- .../AddMerchandiseReturnReasonCommand.cs | 2 +- .../ChangeMerchandiseReturnStatusCommand.cs | 8 +- .../DeleteMerchandiseReturnActionCommand.cs | 2 +- .../Orders/DeleteMerchandiseReturnCommand.cs | 4 +- .../DeleteMerchandiseReturnReasonCommand.cs | 2 +- .../UpdateMerchandiseReturnActionCommand.cs | 2 +- .../Orders/UpdateMerchandiseReturnCommand.cs | 6 +- .../UpdateMerchandiseReturnReasonCommand.cs | 2 +- .../Controllers/BaseApiController.cs | 2 +- .../Controllers/BrandController.cs | 18 +- .../Controllers/BrandLayoutController.cs | 6 +- .../Controllers/CategoryController.cs | 18 +- .../Controllers/CategoryLayoutController.cs | 6 +- .../Controllers/CollectionController.cs | 18 +- .../Controllers/CollectionLayoutController.cs | 6 +- .../Controllers/CountryController.cs | 6 +- .../Controllers/CurrencyController.cs | 6 +- .../Controllers/CustomerController.cs | 4 +- .../Controllers/CustomerGroupController.cs | 26 +-- .../Controllers/DeliveryDateController.cs | 6 +- .../Controllers/LanguageController.cs | 6 +- .../MerchandiseReturnActionController.cs | 12 +- .../MerchandiseReturnController.cs | 2 +- .../MerchandiseReturnReasonController.cs | 12 +- .../Controllers/PickupPointController.cs | 6 +- .../Controllers/PictureController.cs | 12 +- .../Controllers/ProductAttributeController.cs | 18 +- .../Controllers/ProductController.cs | 168 +++++++++--------- .../Controllers/ProductLayoutController.cs | 6 +- .../Controllers/ShippingMethodController.cs | 6 +- .../SpecificationAttributeController.cs | 18 +- .../Controllers/StockController.cs | 4 +- .../Controllers/StoreController.cs | 6 +- .../Controllers/TokenController.cs | 2 +- .../Controllers/TokenWebController.cs | 23 +-- .../Controllers/VendorController.cs | 6 +- .../Controllers/WarehouseController.cs | 6 +- .../Grand.Module.Api/DTOs/Catalog/BrandDto.cs | 24 +-- .../DTOs/Catalog/CategoryDTO.cs | 30 ++-- .../DTOs/Catalog/CollectionDto.cs | 24 +-- .../Catalog/ProductAttributeCombinationDto.cs | 10 +- .../DTOs/Catalog/ProductAttributeDto.cs | 6 +- .../ProductAttributeMappingDeleteDto.cs | 2 +- .../Catalog/ProductAttributeMappingDto.cs | 20 +-- .../DTOs/Catalog/ProductCategoryDeleteDto.cs | 2 +- .../DTOs/Catalog/ProductCategoryDto.cs | 2 +- .../Catalog/ProductCollectionDeleteDto.cs | 2 +- .../DTOs/Catalog/ProductCollectionDto.cs | 2 +- .../DTOs/Catalog/ProductDto.cs | 56 +++--- .../DTOs/Catalog/ProductPictureDeleteDto.cs | 2 +- .../DTOs/Catalog/ProductPictureDto.cs | 2 +- .../ProductSpecificationAttributeDeleteDto.cs | 2 +- .../ProductSpecificationAttributeDto.cs | 8 +- .../DTOs/Catalog/ProductTierPriceDeleteDto.cs | 2 +- .../DTOs/Catalog/ProductTierPriceDto.cs | 4 +- .../DTOs/Catalog/ProductUpdateStock.cs | 2 +- .../Catalog/ProductWarehouseInventoryDto.cs | 2 +- .../DTOs/Catalog/SpecificationAttributeDto.cs | 6 +- .../DTOs/Common/CountryDto.cs | 12 +- .../DTOs/Common/CurrencyDto.cs | 8 +- .../DTOs/Common/LanguageDto.cs | 10 +- .../Grand.Module.Api/DTOs/Common/LayoutDto.cs | 4 +- .../DTOs/Common/PictureDto.cs | 16 +- .../Grand.Module.Api/DTOs/Common/StoreDto.cs | 20 +-- .../DTOs/Customers/AddressDto.cs | 30 ++-- .../DTOs/Customers/CustomerDto.cs | 40 ++--- .../DTOs/Customers/CustomerGroupDto.cs | 4 +- .../DTOs/Customers/DeleteAddressDto.cs | 2 +- .../DTOs/Customers/PasswordDto.cs | 2 +- .../DTOs/Customers/VendorDto.cs | 16 +- .../DTOs/Inventory/StockApplyLineDto.cs | 18 +- .../DTOs/Inventory/StockApplyResultDto.cs | 6 +- .../DTOs/Inventory/StockJournalEntryDto.cs | 28 +-- .../DTOs/Inventory/StockJournalResultDto.cs | 2 +- .../DTOs/Orders/MerchandiseReturnActionDto.cs | 2 +- .../DTOs/Orders/MerchandiseReturnDto.cs | 70 ++++---- .../DTOs/Orders/MerchandiseReturnReasonDto.cs | 2 +- .../MerchandiseReturnStatusChangeRequest.cs | 2 +- .../DTOs/Shipping/DeliveryDateDto.cs | 4 +- .../DTOs/Shipping/PickupPointDto.cs | 10 +- .../DTOs/Shipping/ShippingMethodDto.cs | 4 +- .../DTOs/Shipping/WarehouseDto.cs | 4 +- src/Modules/Grand.Module.Api/DTOs/TokenDto.cs | 4 +- .../Extensions/OpenApiOptionsExtensions.cs | 2 +- .../Filters/AuthorizeApiAdminAttribute.cs | 2 +- .../Grand.Module.Api/Grand.Module.Api.csproj | 3 + .../Infrastructure/ApiSecurityStartup.cs | 5 +- .../Extensions/JwtSecurityKey.cs | 8 +- .../Infrastructure/OpenApiStartup.cs | 6 +- .../Grand.Module.Api/Jwt/JwtTokenBuilder.cs | 12 +- .../Models/BaseApiEntityModel.cs | 2 +- .../Models/Common/LoginModel.cs | 4 +- .../Models/Common/LoginWebModel.cs | 4 +- .../Queries/ApiQueryOptions.cs | 4 +- .../Customers/GetCustomerQueryHandler.cs | 7 +- .../Inventory/GetStockJournalQueryHandler.cs | 4 +- .../GetMerchandiseReturnQueryHandler.cs | 4 +- .../Queries/Models/Common/GetGenericQuery.cs | 2 +- .../Queries/Models/Common/GetQuery.cs | 2 +- .../Models/Customers/GetCustomerQuery.cs | 4 +- .../Models/Inventory/GetStockJournalQuery.cs | 8 +- .../Orders/GetMerchandiseReturnQuery.cs | 4 +- .../Validators/Common/LoginValidator.cs | 2 +- .../Validators/Common/LoginWebValidator.cs | 2 +- .../Customers/CustomerGroupValidator.cs | 6 +- .../Controllers/InstallController.cs | 10 +- .../Services/InstallDataPages.cs | 2 + .../Services/InstallDataProducts.Fashion.cs | 2 +- .../1.1/MigrationUpdateMediaSettings.cs | 3 +- .../2.1/MigrationUpdateAdminSiteMap.cs | 10 +- .../2.4/MigrationAddAdminPortalInfoPage.cs | 2 +- .../2.4/MigrationRobotsTxtAiCrawlers.cs | 2 +- .../2.5/MigrationInventoryLedger.cs | 4 +- .../Migrations/2.5/MigrationInventoryUnits.cs | 3 +- .../MigrationMerchandiseReturnReasonIds.cs | 2 +- .../2.5/MigrationReturnShippingMenu.cs | 2 +- .../BackgroundServices/EndAuctionsTask.cs | 10 +- .../QueuedMessagesSendScheduleTask.cs | 13 +- .../BackgroundServices/ScheduleTaskService.cs | 4 +- .../UpdateExchangeRateScheduleTask.cs | 5 +- .../Grand.Module.ScheduledTasks.csproj | 3 + .../Controllers/ScimControllerBase.cs | 13 +- .../Controllers/ScimGroupsController.cs | 42 ++--- .../Controllers/ScimUsersController.cs | 48 ++--- .../Grand.Module.Scim.csproj | 3 + .../Infrastructure/ScimAuthorizeFilter.cs | 2 +- .../Infrastructure/ScimResponse.cs | 2 +- .../Grand.Module.Scim/Models/ScimResources.cs | 60 +++---- .../Grand.Module.Scim/Protocol/ScimFilter.cs | 3 +- .../Protocol/ScimGroupPatch.cs | 9 +- .../Protocol/ScimUserPatch.cs | 8 +- .../ApplyStockCommandHandlerTests.cs | 32 ++-- .../BackgroundService/EndAuctionsTaskTests.cs | 2 + .../QueuedMessagesSendScheduleTaskTests.cs | 16 +- 256 files changed, 941 insertions(+), 864 deletions(-) diff --git a/src/Business/Grand.Business.Authentication/Services/JwtBearerAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/JwtBearerAuthenticationService.cs index cbcdcc55a..20f807c22 100644 --- a/src/Business/Grand.Business.Authentication/Services/JwtBearerAuthenticationService.cs +++ b/src/Business/Grand.Business.Authentication/Services/JwtBearerAuthenticationService.cs @@ -28,7 +28,7 @@ public JwtBearerAuthenticationService( /// Valid /// /// Principal of the validated token - public virtual async Task Valid(ClaimsPrincipal principal) + public virtual async Task Valid(ClaimsPrincipal? principal) { if (principal == null) return await Task.FromResult(false); diff --git a/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs index c7646dad6..b6dfb6382 100644 --- a/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs +++ b/src/Business/Grand.Business.Authentication/Services/JwtBearerCustomerAuthenticationService.cs @@ -32,7 +32,7 @@ public JwtBearerCustomerAuthenticationService(ICustomerService customerService, _oidcLoginConfig = oidcLoginConfig; } - public async Task Valid(ClaimsPrincipal principal) + public async Task Valid(ClaimsPrincipal? principal) { if (principal == null) return false; var customerId = principal.Claims.FirstOrDefault(x => x.Type == "CustomerId")?.Value; diff --git a/src/Business/Grand.Business.Authentication/Services/Scim/ScimGroupService.cs b/src/Business/Grand.Business.Authentication/Services/Scim/ScimGroupService.cs index 887e9ebc4..4b24ce5c1 100644 --- a/src/Business/Grand.Business.Authentication/Services/Scim/ScimGroupService.cs +++ b/src/Business/Grand.Business.Authentication/Services/Scim/ScimGroupService.cs @@ -74,7 +74,7 @@ public virtual async Task Get(string id) return group == null ? new ScimGroupResult(ScimOutcome.NotFound) : new ScimGroupResult(ScimOutcome.Ok, View(group)); } - public virtual async Task> List(string displayName, string externalId, int skip, int take) + public virtual async Task> List(string? displayName, string? externalId, int skip, int take) { var query = groups.Table; if (!string.IsNullOrEmpty(externalId)) @@ -114,7 +114,7 @@ public virtual async Task ModifyMembers(string id, IList Rename(string id, string displayName, string externalId) + public virtual async Task Rename(string id, string? displayName, string? externalId) { var group = await Load(id); if (group == null) @@ -227,7 +227,7 @@ private static bool IsSystemGroup(CustomerGroup group, string systemName) => group.IsSystem && group.SystemName == systemName; //display names may repeat (Entra allows it); the provider's id of a group may not - private async Task ExternalIdTaken(string externalId, string? exceptId) => + private async Task ExternalIdTaken(string? externalId, string? exceptId) => !string.IsNullOrEmpty(externalId) && await groups.AnyAsync(groups.Table.Where(x => x.Id != exceptId && x.ExternalId == externalId)); diff --git a/src/Business/Grand.Business.Authentication/Services/Scim/ScimUserService.cs b/src/Business/Grand.Business.Authentication/Services/Scim/ScimUserService.cs index 077dac967..b8d4f2607 100644 --- a/src/Business/Grand.Business.Authentication/Services/Scim/ScimUserService.cs +++ b/src/Business/Grand.Business.Authentication/Services/Scim/ScimUserService.cs @@ -173,7 +173,7 @@ public virtual async Task Get(string id) : new ScimUserResult(ScimOutcome.NotFound); } - public virtual async Task> List(string userName, string externalId, int skip, int take) + public virtual async Task> List(string? userName, string? externalId, int skip, int take) { var query = users.Table.Where(x => !x.Deprovisioned); if (!string.IsNullOrEmpty(externalId)) diff --git a/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs b/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs index 66b7babbb..3c7a6c41f 100644 --- a/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs @@ -96,7 +96,7 @@ public virtual async Task> GetAllBrands(string brandName, /// /// Brand id /// Brand - public virtual Task GetBrandById(string brandId) + public virtual Task GetBrandById(string? brandId) { var key = string.Format(CacheKey.BRANDS_BY_ID_KEY, brandId); return _cacheBase.GetAsync(key, () => _brandRepository.GetByIdAsync(brandId)); diff --git a/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs b/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs index 644fb5389..7825f7990 100644 --- a/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs +++ b/src/Business/Grand.Business.Catalog/Services/Products/SpecificationAttributeService.cs @@ -52,7 +52,7 @@ public SpecificationAttributeService(ICacheBase cacheBase, /// /// The specification attribute identifier /// Specification attribute - public virtual async Task GetSpecificationAttributeById(string specificationAttributeId) + public virtual async Task GetSpecificationAttributeById(string? specificationAttributeId) { var key = string.Format(CacheKey.SPECIFICATION_BY_ID_KEY, specificationAttributeId); return await _cacheBase.GetAsync(key, diff --git a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs index 83080bd1b..3062264cc 100644 --- a/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs +++ b/src/Business/Grand.Business.Checkout/Services/Orders/MerchandiseReturnService.cs @@ -146,7 +146,7 @@ orderby rra.DisplayOrder /// /// Merchandise return action identifier /// Merchandise return action - public virtual Task GetMerchandiseReturnActionById(string merchandiseReturnActionId) + public virtual Task GetMerchandiseReturnActionById(string? merchandiseReturnActionId) { return _merchandiseReturnActionRepository.GetByIdAsync(merchandiseReturnActionId); } @@ -297,7 +297,7 @@ orderby rra.DisplayOrder /// /// Merchandise return reasons identifier /// Merchandise return reasons - public virtual Task GetMerchandiseReturnReasonById(string merchandiseReturnReasonId) + public virtual Task GetMerchandiseReturnReasonById(string? merchandiseReturnReasonId) { return _merchandiseReturnReasonRepository.GetByIdAsync(merchandiseReturnReasonId); } diff --git a/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs b/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs index 86fe4febd..4558708a5 100644 --- a/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs +++ b/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs @@ -30,7 +30,7 @@ public GroupService(IRepository customerGroupRepository, /// /// Customer group identifier /// Customer group - public virtual Task GetCustomerGroupById(string customerGroupId) + public virtual Task GetCustomerGroupById(string? customerGroupId) { if (string.IsNullOrWhiteSpace(customerGroupId)) return Task.FromResult(null); diff --git a/src/Business/Grand.Business.Common/Services/Security/EncryptionService.cs b/src/Business/Grand.Business.Common/Services/Security/EncryptionService.cs index 5a05d36d2..d28616cf2 100644 --- a/src/Business/Grand.Business.Common/Services/Security/EncryptionService.cs +++ b/src/Business/Grand.Business.Common/Services/Security/EncryptionService.cs @@ -160,7 +160,7 @@ public virtual bool PasswordHashNeedsUpgrade(PasswordFormat passwordFormat, stri return parts.Length != 5 || !int.TryParse(parts[2], out var iterations) || iterations < Iterations; } - public virtual bool IsHashedPassword(string storedPassword) + public virtual bool IsHashedPassword(string? storedPassword) { return IsPbkdf2Hash(storedPassword); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IJwtBearerAuthenticationService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IJwtBearerAuthenticationService.cs index 0343f4bc7..b18532ff9 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IJwtBearerAuthenticationService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IJwtBearerAuthenticationService.cs @@ -9,7 +9,7 @@ public interface IJwtBearerAuthenticationService /// Valid email /// /// Principal of the validated token - Task Valid(ClaimsPrincipal principal); + Task Valid(ClaimsPrincipal? principal); /// /// Get error message diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IJwtBearerCustomerAuthenticationService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IJwtBearerCustomerAuthenticationService.cs index 8a1b473f8..d77f679b6 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IJwtBearerCustomerAuthenticationService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IJwtBearerCustomerAuthenticationService.cs @@ -4,6 +4,6 @@ namespace Grand.Business.Core.Interfaces.Authentication; public interface IJwtBearerCustomerAuthenticationService { - Task Valid(ClaimsPrincipal principal); + Task Valid(ClaimsPrincipal? principal); Task ErrorMessage(); } \ No newline at end of file diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IScimGroupService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IScimGroupService.cs index 647606a56..9b89ec825 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IScimGroupService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IScimGroupService.cs @@ -16,7 +16,7 @@ public interface IScimGroupService Task Get(string id); /// The groups, optionally those with the display name or the externalId (exact, display name case-insensitive) - Task> List(string displayName, string externalId, int skip, int take); + Task> List(string? displayName, string? externalId, int skip, int take); Task Delete(string id); @@ -24,7 +24,7 @@ public interface IScimGroupService Task ModifyMembers(string id, IList add, IList remove, bool replaceAll); /// Changes the name and the externalId only (null keeps the value) - Task Rename(string id, string displayName, string externalId); + Task Rename(string id, string? displayName, string? externalId); Task> GetMappings(); diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IScimUserService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IScimUserService.cs index c21420f88..d2002735c 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IScimUserService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IScimUserService.cs @@ -17,7 +17,7 @@ public interface IScimUserService Task Get(string id); /// The managed users, optionally those with the user name or the externalId (exact, user name case-insensitive) - Task> List(string userName, string externalId, int skip, int take); + Task> List(string? userName, string? externalId, int skip, int take); Task Delete(string id); diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandService.cs index 08ba72110..629775615 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Brands/IBrandService.cs @@ -27,7 +27,7 @@ Task> GetAllBrands(string brandName, /// /// Brand identifier /// Brand - Task GetBrandById(string brandId); + Task GetBrandById(string? brandId); /// /// Inserts a new brand diff --git a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ISpecificationAttributeService.cs b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ISpecificationAttributeService.cs index 6577e016b..6ac401512 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ISpecificationAttributeService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Catalog/Products/ISpecificationAttributeService.cs @@ -15,7 +15,7 @@ public interface ISpecificationAttributeService /// /// The specification attribute identifier /// Specification attribute - Task GetSpecificationAttributeById(string specificationAttributeId); + Task GetSpecificationAttributeById(string? specificationAttributeId); /// /// Gets a specification attribute by se-name diff --git a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnService.cs b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnService.cs index 52e4020af..41cb1786c 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Checkout/Orders/IMerchandiseReturnService.cs @@ -85,7 +85,7 @@ Task> SearchMerchandiseReturns(string storeId = "" /// /// Merchandise return action identifier /// Merchandise return action - Task GetMerchandiseReturnActionById(string merchandiseReturnActionId); + Task GetMerchandiseReturnActionById(string? merchandiseReturnActionId); /// /// Inserts a merchandise return action @@ -117,7 +117,7 @@ Task> SearchMerchandiseReturns(string storeId = "" /// /// Merchandise return reason identifier /// Merchandise return reasons - Task GetMerchandiseReturnReasonById(string merchandiseReturnReasonId); + Task GetMerchandiseReturnReasonById(string? merchandiseReturnReasonId); /// /// Inserts a merchandise return reasons diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IGroupService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IGroupService.cs index d2bde1e21..d7d54aa05 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IGroupService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Directory/IGroupService.cs @@ -91,7 +91,7 @@ Task IsInCustomerGroup(Customer customer, /// /// Customer group identifier /// Customer group - Task GetCustomerGroupById(string customerGroupId); + Task GetCustomerGroupById(string? customerGroupId); /// /// Gets a customer group diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Security/IEncryptionService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Security/IEncryptionService.cs index b4f1a9133..6c7ff7b5f 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Security/IEncryptionService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Security/IEncryptionService.cs @@ -55,7 +55,7 @@ bool VerifyPassword(string enteredPassword, PasswordFormat passwordFormat, strin /// . Use it to pick the verification path for records whose password format is /// not tracked in a separate field (e.g. API users), instead of inferring it from other columns. /// - bool IsHashedPassword(string storedPassword); + bool IsHashedPassword(string? storedPassword); /// /// Encrypt text (legacy TripleDES). Retained only to verify pre-existing reversibly-encrypted values diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs index ffcbfac06..439943a96 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerManagerService.cs @@ -17,7 +17,7 @@ public interface ICustomerManagerService /// Store identifier - used to resolve the customer when per-store customer identity is enabled /// Where the password is used: the sign-in policy decides per surface /// Result - Task LoginCustomer(string usernameOrEmail, string password, string storeId = "", + Task LoginCustomer(string? usernameOrEmail, string password, string storeId = "", SignInSurface surface = SignInSurface.Storefront); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs index 065c4bd27..7b486362f 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Customers/ICustomerService.cs @@ -114,7 +114,7 @@ Task GetCountOnlineShoppingCart(DateTime lastActivityFromUtc, string storeI /// Email /// Store identifier (optional) /// Customer - Task GetCustomerByEmail(string email, string storeId = ""); + Task GetCustomerByEmail(string? email, string storeId = ""); /// /// Get customer by system group @@ -131,7 +131,7 @@ Task GetCountOnlineShoppingCart(DateTime lastActivityFromUtc, string storeI /// Username /// Store identifier (optional) /// Customer - Task GetCustomerByUsername(string username, string storeId = ""); + Task GetCustomerByUsername(string? username, string storeId = ""); /// /// Insert a guest customer diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/ICatalogMessageProviderService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/ICatalogMessageProviderService.cs index 832c7adb3..ba78cf4b1 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/ICatalogMessageProviderService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/ICatalogMessageProviderService.cs @@ -135,7 +135,7 @@ Task SendBackInStockMessage(Customer customer, Product product, OutOfStockS /// Auction /// Bid /// Queued email identifier - Task SendAuctionEndedStoreOwnerMessage(Product product, string? languageId, Bid bid); + Task SendAuctionEndedStoreOwnerMessage(Product product, string? languageId, Bid? bid); /// /// Send outbid notification to a customer diff --git a/src/Business/Grand.Business.Core/Interfaces/Messages/IQueuedEmailService.cs b/src/Business/Grand.Business.Core/Interfaces/Messages/IQueuedEmailService.cs index 966d5d176..56ae91c18 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Messages/IQueuedEmailService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Messages/IQueuedEmailService.cs @@ -73,10 +73,10 @@ public interface IQueuedEmailService /// Page index /// Page size /// Queued emails - Task> SearchEmails(string fromEmail, - string toEmail, string text, DateTime? createdFromUtc, DateTime? createdToUtc, + Task> SearchEmails(string? fromEmail, + string? toEmail, string? text, DateTime? createdFromUtc, DateTime? createdToUtc, bool loadNotSentItemsOnly, bool loadOnlyItemsToBeSent, int maxSendTries, - bool loadNewest, int referenceId = -1, string objectId = "", + bool loadNewest, int referenceId = -1, string? objectId = "", int pageIndex = 0, int pageSize = int.MaxValue); /// diff --git a/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs b/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs index 1d2f5ad28..08f789ba7 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Storage/IPictureService.cs @@ -80,7 +80,7 @@ public interface IPictureService /// /// Picture identifier /// Picture - Task GetPictureById(string pictureId); + Task GetPictureById(string? pictureId); /// /// Deletes a picture @@ -128,9 +128,9 @@ public interface IPictureService /// Object id for reference /// A value indicating whether to validated provided picture binary /// Picture - Task InsertPicture(byte[] pictureBinary, string mimeType, string? seoFilename, + Task InsertPicture(byte[] pictureBinary, string? mimeType, string? seoFilename, string? altAttribute = null, string? titleAttribute = null, - bool isNew = true, Reference reference = Reference.None, string objectId = "", bool validateBinary = false); + bool isNew = true, Reference reference = Reference.None, string? objectId = "", bool validateBinary = false); /// /// Updates the picture @@ -146,8 +146,8 @@ Task InsertPicture(byte[] pictureBinary, string mimeType, string? seoFi /// A value indicating whether the picture is new /// A value indicating whether to validated provided picture binary /// Picture - Task UpdatePicture(string pictureId, byte[] pictureBinary, string mimeType, - string seoFilename, string? altAttribute = null, string? titleAttribute = null, + Task UpdatePicture(string pictureId, byte[]? pictureBinary, string? mimeType, + string? seoFilename, string? altAttribute = null, string? titleAttribute = null, string? style = null, string? extraField = null, bool isNew = true, bool validateBinary = true); @@ -173,7 +173,7 @@ Task UpdatePictureField(Picture picture, /// The picture /// The SEO filename /// Picture - Task SetSeoFilename(Picture picture, string seoFilename); + Task SetSeoFilename(Picture picture, string? seoFilename); /// /// Validates input picture dimensions diff --git a/src/Business/Grand.Business.Core/Interfaces/System/ScheduleTasks/IScheduleTaskService.cs b/src/Business/Grand.Business.Core/Interfaces/System/ScheduleTasks/IScheduleTaskService.cs index 094d82883..2e704bd9e 100644 --- a/src/Business/Grand.Business.Core/Interfaces/System/ScheduleTasks/IScheduleTaskService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/System/ScheduleTasks/IScheduleTaskService.cs @@ -9,14 +9,14 @@ public interface IScheduleTaskService /// /// Task identifier /// Task - Task GetTaskById(string taskId); + Task GetTaskById(string taskId); /// /// Gets a task by its type /// /// Task name /// Task - Task GetTaskByName(string name); + Task GetTaskByName(string name); /// /// Gets all tasks diff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/ScimResults.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/ScimResults.cs index a623a3f66..297e7f711 100644 --- a/src/Business/Grand.Business.Core/Utilities/Authentication/ScimResults.cs +++ b/src/Business/Grand.Business.Core/Utilities/Authentication/ScimResults.cs @@ -15,7 +15,7 @@ public enum ScimOutcome } /// The attributes of a SCIM user that GrandNode keeps -public record ScimUserData(string UserName, string ExternalId, string Email, string GivenName, string FamilyName, bool Active); +public record ScimUserData(string? UserName, string? ExternalId, string? Email, string? GivenName, string? FamilyName, bool Active); public record ScimGroupRef(string Id, string? DisplayName); @@ -36,7 +36,7 @@ public record ScimUserView( public record ScimUserResult(ScimOutcome Outcome, ScimUserView? User = null, string? Detail = null); /// The attributes of a SCIM group that GrandNode keeps; members are SCIM user ids (customer ids) -public record ScimGroupData(string DisplayName, string ExternalId, IList MemberIds); +public record ScimGroupData(string? DisplayName, string? ExternalId, IList MemberIds); public record ScimGroupView( string Id, diff --git a/src/Business/Grand.Business.Core/Utilities/Catalog/StockChange.cs b/src/Business/Grand.Business.Core/Utilities/Catalog/StockChange.cs index eacfb83e8..e6645c1ec 100644 --- a/src/Business/Grand.Business.Core/Utilities/Catalog/StockChange.cs +++ b/src/Business/Grand.Business.Core/Utilities/Catalog/StockChange.cs @@ -18,7 +18,7 @@ public sealed record StockSource( string? PositionId = "", string? Reference = "", string CustomerId = "", - string Comment = ""); + string? Comment = ""); /// /// A change of one stock bucket: the product, its combination, or either of them in one warehouse diff --git a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs index bd919e810..d8abf3a20 100644 --- a/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs +++ b/src/Business/Grand.Business.Customers/Services/CustomerManagerService.cs @@ -85,7 +85,7 @@ public virtual bool PasswordMatch(PasswordFormat passwordFormat, string oldPassw /// Store identifier - used to resolve the customer when per-store customer identity is enabled /// Where the password is used: the sign-in policy decides per surface /// Result - public virtual async Task LoginCustomer(string usernameOrEmail, string password, + public virtual async Task LoginCustomer(string? usernameOrEmail, string password, string storeId = "", SignInSurface surface = SignInSurface.Storefront) { var customer = _customerSettings.UsernamesEnabled diff --git a/src/Business/Grand.Business.Customers/Services/CustomerService.cs b/src/Business/Grand.Business.Customers/Services/CustomerService.cs index 7a002e7c7..efefd036b 100644 --- a/src/Business/Grand.Business.Customers/Services/CustomerService.cs +++ b/src/Business/Grand.Business.Customers/Services/CustomerService.cs @@ -232,7 +232,7 @@ where customerIds.Contains(c.Id) /// /// Email /// Customer - public virtual async Task GetCustomerByEmail(string email, string storeId = "") + public virtual async Task GetCustomerByEmail(string? email, string storeId = "") { if (string.IsNullOrWhiteSpace(email)) return null; @@ -283,7 +283,7 @@ where customerIds.Contains(c.Id) /// /// Username /// Customer - public virtual async Task GetCustomerByUsername(string username, string storeId = "") + public virtual async Task GetCustomerByUsername(string? username, string storeId = "") { if (string.IsNullOrWhiteSpace(username)) return null; diff --git a/src/Business/Grand.Business.Messages/Services/CatalogMessageProviderService.cs b/src/Business/Grand.Business.Messages/Services/CatalogMessageProviderService.cs index ab2bd5285..e226d22d0 100644 --- a/src/Business/Grand.Business.Messages/Services/CatalogMessageProviderService.cs +++ b/src/Business/Grand.Business.Messages/Services/CatalogMessageProviderService.cs @@ -531,7 +531,7 @@ await _messageProviderService.SendNotification(messageTemplate, emailAccount, return 0; } - public virtual async Task SendAuctionEndedStoreOwnerMessage(Product product, string? languageId, Bid bid) + public virtual async Task SendAuctionEndedStoreOwnerMessage(Product product, string? languageId, Bid? bid) { ArgumentNullException.ThrowIfNull(product); diff --git a/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs b/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs index 3d133434d..3aa6d006b 100644 --- a/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs +++ b/src/Business/Grand.Business.Messages/Services/QueuedEmailService.cs @@ -190,10 +190,10 @@ where queuedEmailIds.Contains(qe.Id) /// Page index /// Page size /// Email item list - public virtual async Task> SearchEmails(string fromEmail, - string toEmail, string text, DateTime? createdFromUtc, DateTime? createdToUtc, + public virtual async Task> SearchEmails(string? fromEmail, + string? toEmail, string? text, DateTime? createdFromUtc, DateTime? createdToUtc, bool loadNotSentItemsOnly, bool loadOnlyItemsToBeSent, int maxSendTries, - bool loadNewest, int referenceId = -1, string objectId = "", int pageIndex = 0, int pageSize = int.MaxValue) + bool loadNewest, int referenceId = -1, string? objectId = "", int pageIndex = 0, int pageSize = int.MaxValue) { fromEmail = (fromEmail ?? string.Empty).Trim(); toEmail = (toEmail ?? string.Empty).Trim(); diff --git a/src/Business/Grand.Business.Storage/Services/PictureService.cs b/src/Business/Grand.Business.Storage/Services/PictureService.cs index a55091839..b77e38888 100644 --- a/src/Business/Grand.Business.Storage/Services/PictureService.cs +++ b/src/Business/Grand.Business.Storage/Services/PictureService.cs @@ -405,7 +405,7 @@ protected virtual async Task SaveThumb(string thumbFileName, byte[]? binary) /// /// Picture identifier /// Picture - public virtual async Task GetPictureById(string pictureId) + public virtual async Task GetPictureById(string? pictureId) { var pictureKey = string.Format(CacheKey.PICTURE_BY_ID, pictureId); return await _cacheBase.GetAsync(pictureKey, async () => @@ -517,9 +517,9 @@ public virtual async Task> GetPictures(int pageIndex = 0, in /// Object id for reference /// A value indicating whether to validated provided picture binary /// Picture - public virtual async Task InsertPicture(byte[] pictureBinary, string mimeType, string? seoFilename, + public virtual async Task InsertPicture(byte[] pictureBinary, string? mimeType, string? seoFilename, string? altAttribute = null, string? titleAttribute = null, - bool isNew = true, Reference reference = Reference.None, string objectId = "", bool validateBinary = false) + bool isNew = true, Reference reference = Reference.None, string? objectId = "", bool validateBinary = false) { mimeType = CommonHelper.EnsureNotNull(mimeType); mimeType = CommonHelper.EnsureMaximumLength(mimeType, 20); @@ -564,8 +564,8 @@ public virtual async Task InsertPicture(byte[] pictureBinary, string mi /// A value indicating whether the picture is new /// A value indicating whether to validated provided picture binary /// Picture - public virtual async Task UpdatePicture(string pictureId, byte[] pictureBinary, string mimeType, - string seoFilename, string? altAttribute = null, string? titleAttribute = null, + public virtual async Task UpdatePicture(string pictureId, byte[]? pictureBinary, string? mimeType, + string? seoFilename, string? altAttribute = null, string? titleAttribute = null, string? style = null, string? extraField = null, bool isNew = true, bool validateBinary = true) { @@ -689,7 +689,7 @@ public virtual async Task SavePictureInFile(string pictureId, byte[] pictureBina /// The picture /// The SEO filename /// Picture - public virtual async Task SetSeoFilename(Picture picture, string seoFilename) + public virtual async Task SetSeoFilename(Picture picture, string? seoFilename) { if (picture == null) throw new ArgumentException("No picture found with the specified id"); diff --git a/src/Core/Grand.Infrastructure/Configuration/ScimConfig.cs b/src/Core/Grand.Infrastructure/Configuration/ScimConfig.cs index d6d2ad23f..7d2d401ab 100644 --- a/src/Core/Grand.Infrastructure/Configuration/ScimConfig.cs +++ b/src/Core/Grand.Infrastructure/Configuration/ScimConfig.cs @@ -1,3 +1,5 @@ +using System.Diagnostics.CodeAnalysis; + namespace Grand.Infrastructure.Configuration; /// @@ -29,6 +31,7 @@ public class ScimConfig public int MaxResults { get; set; } = DefaultMaxResults; /// A token shorter than 32 characters is a configuration mistake: the endpoint refuses every request + [MemberNotNullWhen(true, nameof(Token))] public bool TokenUsable => !string.IsNullOrEmpty(Token) && Token.Length >= MinTokenLength; /// The e-mail is in one of (case-insensitive, exact domain) diff --git a/src/Core/Grand.Infrastructure/Migrations/MigrationResult.cs b/src/Core/Grand.Infrastructure/Migrations/MigrationResult.cs index cb46f0633..e14481c36 100644 --- a/src/Core/Grand.Infrastructure/Migrations/MigrationResult.cs +++ b/src/Core/Grand.Infrastructure/Migrations/MigrationResult.cs @@ -2,6 +2,6 @@ public class MigrationResult { - public IBaseMigration? Migration; + public required IBaseMigration Migration; public bool Success; } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductAttributeMappingCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductAttributeMappingCommandHandler.cs index f33dbe721..16d5b26dd 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductAttributeMappingCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductAttributeMappingCommandHandler.cs @@ -20,6 +20,7 @@ public AddProductAttributeMappingCommandHandler(IProductAttributeService product public async Task Handle(AddProductAttributeMappingCommand request, CancellationToken cancellationToken) { + ArgumentException.ThrowIfNullOrEmpty(request.Product.Id); //insert mapping var productAttributeMapping = request.Model.ToEntity(); await _productAttributeService.InsertProductAttributeMapping(productAttributeMapping, request.Product.Id); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductCategoryCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductCategoryCommandHandler.cs index a0e011446..3632926ea 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductCategoryCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductCategoryCommandHandler.cs @@ -16,6 +16,7 @@ public AddProductCategoryCommandHandler(IProductCategoryService productcategoryS public async Task Handle(AddProductCategoryCommand request, CancellationToken cancellationToken) { + ArgumentException.ThrowIfNullOrEmpty(request.Product.Id); var productCategory = new ProductCategory { CategoryId = request.Model.CategoryId, IsFeaturedProduct = request.Model.IsFeaturedProduct diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductCollectionCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductCollectionCommandHandler.cs index d4a345d3d..e993c2ea5 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductCollectionCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductCollectionCommandHandler.cs @@ -16,6 +16,7 @@ public AddProductCollectionCommandHandler(IProductCollectionService productcolle public async Task Handle(AddProductCollectionCommand request, CancellationToken cancellationToken) { + ArgumentException.ThrowIfNullOrEmpty(request.Product.Id); var productCollection = new ProductCollection { CollectionId = request.Model.CollectionId, IsFeaturedProduct = request.Model.IsFeaturedProduct diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductSpecificationCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductSpecificationCommandHandler.cs index a4cef5854..cc30889bb 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductSpecificationCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductSpecificationCommandHandler.cs @@ -16,6 +16,7 @@ public AddProductSpecificationCommandHandler(ISpecificationAttributeService spec public async Task Handle(AddProductSpecificationCommand request, CancellationToken cancellationToken) { + ArgumentException.ThrowIfNullOrEmpty(request.Product.Id); //we allow filtering only for "Option" attribute type if (request.Model.AttributeTypeId != SpecificationAttributeType.Option) { diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductTierPriceCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductTierPriceCommandHandler.cs index c6218fbcb..5fe988a49 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductTierPriceCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductTierPriceCommandHandler.cs @@ -16,6 +16,7 @@ public AddProductTierPriceCommandHandler(IProductService productService) public async Task Handle(AddProductTierPriceCommand request, CancellationToken cancellationToken) { + ArgumentException.ThrowIfNullOrEmpty(request.Product.Id); var tierPrice = request.Model.ToEntity(); await _productService.InsertTierPrice(tierPrice, request.Product.Id); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductAttributeMappingCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductAttributeMappingCommandHandler.cs index 870aa0505..ec5d0fe2b 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductAttributeMappingCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductAttributeMappingCommandHandler.cs @@ -16,6 +16,7 @@ public DeleteProductAttributeMappingCommandHandler(IProductAttributeService prod public async Task Handle(DeleteProductAttributeMappingCommand request, CancellationToken cancellationToken) { + ArgumentException.ThrowIfNullOrEmpty(request.Product.Id); //insert mapping var productAttributeMapping = request.Model.ToEntity(); await _productAttributeService.DeleteProductAttributeMapping(productAttributeMapping, request.Product.Id); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductCategoryCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductCategoryCommandHandler.cs index ec6be2493..59c67d9d8 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductCategoryCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductCategoryCommandHandler.cs @@ -20,7 +20,8 @@ public DeleteProductCategoryCommandHandler( public async Task Handle(DeleteProductCategoryCommand request, CancellationToken cancellationToken) { - var product = await _productService.GetProductById(request.Product.Id, true); + var product = await _productService.GetProductById(request.Product.Id, true) ?? + throw new ArgumentException("No product has the id", nameof(request)); var productCategory = product.ProductCategories.FirstOrDefault(x => x.CategoryId == request.CategoryId); if (productCategory == null) throw new ArgumentException("No product category mapping found with the specified id"); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductCollectionCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductCollectionCommandHandler.cs index 93ae9d4ee..05e6b66e0 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductCollectionCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductCollectionCommandHandler.cs @@ -19,7 +19,8 @@ public DeleteProductCollectionCommandHandler(IProductCollectionService productco public async Task Handle(DeleteProductCollectionCommand request, CancellationToken cancellationToken) { - var product = await _productService.GetProductById(request.Product.Id, true); + var product = await _productService.GetProductById(request.Product.Id, true) ?? + throw new ArgumentException("No product has the id", nameof(request)); var productCollection = product.ProductCollections.FirstOrDefault(x => x.CollectionId == request.CollectionId); if (productCollection == null) throw new ArgumentException("No product collection mapping found with the specified id"); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductPictureCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductPictureCommandHandler.cs index 9eebb32dd..7f2c7ec8d 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductPictureCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductPictureCommandHandler.cs @@ -16,7 +16,8 @@ public DeleteProductPictureCommandHandler( public async Task Handle(DeleteProductPictureCommand request, CancellationToken cancellationToken) { - var product = await _productService.GetProductById(request.Product.Id); + var product = await _productService.GetProductById(request.Product.Id) ?? + throw new ArgumentException("No product has the id", nameof(request)); var productPicture = product.ProductPictures.FirstOrDefault(x => x.PictureId == request.PictureId); if (productPicture == null) diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductSpecificationCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductSpecificationCommandHandler.cs index f84c26598..5dbccb1ef 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductSpecificationCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductSpecificationCommandHandler.cs @@ -18,7 +18,8 @@ public DeleteProductSpecificationCommandHandler(ISpecificationAttributeService s public async Task Handle(DeleteProductSpecificationCommand request, CancellationToken cancellationToken) { - var product = await _productService.GetProductById(request.Product.Id, true); + var product = await _productService.GetProductById(request.Product.Id, true) ?? + throw new ArgumentException("No product has the id", nameof(request)); var psa = product.ProductSpecificationAttributes.FirstOrDefault(x => x.Id == request.Id); if (psa != null) await _specificationAttributeService.DeleteProductSpecificationAttribute(psa, product.Id); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductTierPriceCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductTierPriceCommandHandler.cs index 487eaa52f..1f18462ee 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductTierPriceCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/DeleteProductTierPriceCommandHandler.cs @@ -15,10 +15,12 @@ public DeleteProductTierPriceCommandHandler(IProductService productService) public async Task Handle(DeleteProductTierPriceCommand request, CancellationToken cancellationToken) { - var product = await _productService.GetProductById(request.Product.Id, true); + var product = await _productService.GetProductById(request.Product.Id, true) ?? + throw new ArgumentException("No product has the id", nameof(request)); var tierPrice = product.TierPrices.FirstOrDefault(x => x.Id == request.Id); - await _productService.DeleteTierPrice(tierPrice, product.Id); + if (tierPrice != null) + await _productService.DeleteTierPrice(tierPrice, product.Id); return true; } diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateBrandCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateBrandCommandHandler.cs index 879bc36be..3faf13741 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateBrandCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateBrandCommandHandler.cs @@ -28,7 +28,8 @@ public UpdateBrandCommandHandler( public async Task Handle(UpdateBrandCommand request, CancellationToken cancellationToken) { - var brand = await _brandService.GetBrandById(request.Model.Id); + var brand = await _brandService.GetBrandById(request.Model.Id) ?? + throw new ArgumentException("No brand has the id", nameof(request)); var prevPictureId = brand.PictureId; brand = request.Model.ToEntity(brand); request.Model.SeName = await _seNameService.ValidateSeName(brand, request.Model.SeName, brand.Name, true); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateCategoryCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateCategoryCommandHandler.cs index b558dc776..e0f40034a 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateCategoryCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateCategoryCommandHandler.cs @@ -28,7 +28,8 @@ public UpdateCategoryCommandHandler( public async Task Handle(UpdateCategoryCommand request, CancellationToken cancellationToken) { - var category = await _categoryService.GetCategoryById(request.Model.Id); + var category = await _categoryService.GetCategoryById(request.Model.Id) ?? + throw new ArgumentException("No category has the id", nameof(request)); var prevPictureId = category.PictureId; category = request.Model.ToEntity(category); request.Model.SeName = await _seNameService.ValidateSeName(category, request.Model.SeName, category.Name, true); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateCollectionCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateCollectionCommandHandler.cs index 02d6fac82..a7a671c83 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateCollectionCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateCollectionCommandHandler.cs @@ -28,7 +28,8 @@ public UpdateCollectionCommandHandler( public async Task Handle(UpdateCollectionCommand request, CancellationToken cancellationToken) { - var collection = await _collectionService.GetCollectionById(request.Model.Id); + var collection = await _collectionService.GetCollectionById(request.Model.Id) ?? + throw new ArgumentException("No collection has the id", nameof(request)); var prevPictureId = collection.PictureId; collection = request.Model.ToEntity(collection); request.Model.SeName = await _seNameService.ValidateSeName(collection, request.Model.SeName, collection.Name, true); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductAttributeCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductAttributeCommandHandler.cs index 70b9affa1..c82d6e344 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductAttributeCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductAttributeCommandHandler.cs @@ -18,7 +18,8 @@ public UpdateProductAttributeCommandHandler(IProductAttributeService productAttr public async Task Handle(UpdateProductAttributeCommand request, CancellationToken cancellationToken) { - var productAttribute = await _productAttributeService.GetProductAttributeById(request.Model.Id); + var productAttribute = await _productAttributeService.GetProductAttributeById(request.Model.Id) ?? + throw new ArgumentException("No product attribute has the id", nameof(request)); productAttribute = request.Model.ToEntity(productAttribute); await _productAttributeService.UpdateProductAttribute(productAttribute); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductAttributeMappingCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductAttributeMappingCommandHandler.cs index 55e96a958..5c5c3e226 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductAttributeMappingCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductAttributeMappingCommandHandler.cs @@ -20,6 +20,7 @@ public UpdateProductAttributeMappingCommandHandler(IProductAttributeService prod public async Task Handle(UpdateProductAttributeMappingCommand request, CancellationToken cancellationToken) { + ArgumentException.ThrowIfNullOrEmpty(request.Product.Id); //insert mapping var productAttributeMapping = request.Model.ToEntity(); await _productAttributeService.UpdateProductAttributeMapping(productAttributeMapping, request.Product.Id, true); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductCategoryCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductCategoryCommandHandler.cs index 3e9a6de81..e8495229a 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductCategoryCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductCategoryCommandHandler.cs @@ -20,7 +20,8 @@ public UpdateProductCategoryCommandHandler( public async Task Handle(UpdateProductCategoryCommand request, CancellationToken cancellationToken) { - var product = await _productService.GetProductById(request.Product.Id, true); + var product = await _productService.GetProductById(request.Product.Id, true) ?? + throw new ArgumentException("No product has the id", nameof(request)); var productCategory = product.ProductCategories.FirstOrDefault(x => x.CategoryId == request.Model.CategoryId); if (productCategory == null) throw new ArgumentException("No product category mapping found with the specified id"); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductCollectionCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductCollectionCommandHandler.cs index f2d1a2a10..8554a456c 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductCollectionCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductCollectionCommandHandler.cs @@ -19,7 +19,8 @@ public UpdateProductCollectionCommandHandler(IProductCollectionService productCo public async Task Handle(UpdateProductCollectionCommand request, CancellationToken cancellationToken) { - var product = await _productService.GetProductById(request.Product.Id, true); + var product = await _productService.GetProductById(request.Product.Id, true) ?? + throw new ArgumentException("No product has the id", nameof(request)); var productCollection = product.ProductCollections.FirstOrDefault(x => x.CollectionId == request.Model.CollectionId); if (productCollection == null) diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductCommandHandler.cs index d271f7749..648c6842b 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductCommandHandler.cs @@ -39,7 +39,8 @@ public UpdateProductCommandHandler( public async Task Handle(UpdateProductCommand request, CancellationToken cancellationToken) { //product - var product = await _productService.GetProductById(request.Model.Id); + var product = await _productService.GetProductById(request.Model.Id) ?? + throw new ArgumentException("No product has the id", nameof(request)); var prevStockQuantity = product.StockQuantity; var prevReservedQuantity = product.ReservedQuantity; var prevPublished = product.Published; diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductPictureCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductPictureCommandHandler.cs index b1e73b5d2..240e36d2e 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductPictureCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductPictureCommandHandler.cs @@ -16,7 +16,9 @@ public UpdateProductPictureCommandHandler( public async Task Handle(UpdateProductPictureCommand request, CancellationToken cancellationToken) { - var product = await _productService.GetProductById(request.Product.Id); + ArgumentException.ThrowIfNullOrEmpty(request.Product.Id); + var product = await _productService.GetProductById(request.Product.Id) ?? + throw new ArgumentException("No product has the id", nameof(request)); var pp = product.ProductPictures.FirstOrDefault(x => x.PictureId == request.Model.PictureId); if (pp != null) { diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductSpecificationCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductSpecificationCommandHandler.cs index 9a14ecbf4..41514aafc 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductSpecificationCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductSpecificationCommandHandler.cs @@ -20,7 +20,8 @@ public UpdateProductSpecificationCommandHandler( public async Task Handle(UpdateProductSpecificationCommand request, CancellationToken cancellationToken) { - var product = await _productService.GetProductById(request.Product.Id, true); + var product = await _productService.GetProductById(request.Product.Id, true) ?? + throw new ArgumentException("No product has the id", nameof(request)); var psa = product.ProductSpecificationAttributes.FirstOrDefault(x => x.Id == request.Model.Id); if (psa != null) { diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductTierPriceCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductTierPriceCommandHandler.cs index abaebeea3..0f7feaaef 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductTierPriceCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductTierPriceCommandHandler.cs @@ -16,7 +16,8 @@ public UpdateProductTierPriceCommandHandler(IProductService productService) public async Task Handle(UpdateProductTierPriceCommand request, CancellationToken cancellationToken) { - var product = await _productService.GetProductById(request.Product.Id, true); + var product = await _productService.GetProductById(request.Product.Id, true) ?? + throw new ArgumentException("No product has the id", nameof(request)); var tierPrice = request.Model.ToEntity(); await _productService.UpdateTierPrice(tierPrice, product.Id); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateSpecificationAttributeCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateSpecificationAttributeCommandHandler.cs index 00e57774b..b56361343 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateSpecificationAttributeCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateSpecificationAttributeCommandHandler.cs @@ -21,7 +21,8 @@ public async Task Handle(UpdateSpecificationAttribute CancellationToken cancellationToken) { var specificationAttribute = - await _specificationAttributeService.GetSpecificationAttributeById(request.Model.Id); + await _specificationAttributeService.GetSpecificationAttributeById(request.Model.Id) ?? + throw new ArgumentException("No specification attribute has the id", nameof(request)); foreach (var option in specificationAttribute.SpecificationAttributeOptions) if (request.Model.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == option.Id) == null) await _specificationAttributeService.DeleteSpecificationAttributeOption(option); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Common/AddPictureCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Common/AddPictureCommandHandler.cs index 72f7c1dc8..63f6862e0 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Common/AddPictureCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Common/AddPictureCommandHandler.cs @@ -17,7 +17,10 @@ public AddPictureCommandHandler(IPictureService pictureService) public async Task Handle(AddPictureCommand request, CancellationToken cancellationToken) { - var picture = await _pictureService.InsertPicture(request.PictureDto.PictureBinary, request.PictureDto.MimeType, + //the validator requires the binary of a new picture + var picture = await _pictureService.InsertPicture( + request.PictureDto.PictureBinary ?? throw new ArgumentException("The picture has no binary", nameof(request)), + request.PictureDto.MimeType, request.PictureDto.SeoFilename, request.PictureDto.AltAttribute, request.PictureDto.TitleAttribute, diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/AddCustomerAddressCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/AddCustomerAddressCommandHandler.cs index e78a015d2..21e5af64d 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/AddCustomerAddressCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/AddCustomerAddressCommandHandler.cs @@ -17,6 +17,7 @@ public AddCustomerAddressCommandHandler(ICustomerService customerService) public async Task Handle(AddCustomerAddressCommand request, CancellationToken cancellationToken) { + ArgumentException.ThrowIfNullOrEmpty(request.Customer.Id); var address = request.Address.ToEntity(); address.Id = ""; await _customerService.InsertAddress(address, request.Customer.Id); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/AddCustomerCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/AddCustomerCommandHandler.cs index 64c0ce88d..c8e36bc2c 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/AddCustomerCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/AddCustomerCommandHandler.cs @@ -73,7 +73,7 @@ protected async Task SaveCustomerGroups(CustomerDto model, Customer customer) var group = await _groupService.GetCustomerGroupById(item); if (group != null) { - customer.Groups.Remove(customer.Groups.FirstOrDefault(x => x == item)); + customer.Groups.Remove(item); await _customerService.DeleteCustomerGroupInCustomer(group, customer.Id); } } diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/DeleteCustomerAddressCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/DeleteCustomerAddressCommandHandler.cs index 98c96cf25..b2af7e38a 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/DeleteCustomerAddressCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/DeleteCustomerAddressCommandHandler.cs @@ -15,6 +15,7 @@ public DeleteCustomerAddressCommandHandler(ICustomerService customerService) public async Task Handle(DeleteCustomerAddressCommand request, CancellationToken cancellationToken) { + ArgumentException.ThrowIfNullOrEmpty(request.Customer.Id); var customer = await _customerService.GetCustomerById(request.Customer.Id); if (customer != null) { diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/UpdateCustomerAddressCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/UpdateCustomerAddressCommandHandler.cs index 86ba2601c..246fe7818 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/UpdateCustomerAddressCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/UpdateCustomerAddressCommandHandler.cs @@ -6,7 +6,7 @@ namespace Grand.Module.Api.Commands.Handlers.Customers; -public class UpdateCustomerAddressCommandHandler : IRequestHandler +public class UpdateCustomerAddressCommandHandler : IRequestHandler { private readonly ICustomerService _customerService; @@ -15,8 +15,9 @@ public UpdateCustomerAddressCommandHandler(ICustomerService customerService) _customerService = customerService; } - public async Task Handle(UpdateCustomerAddressCommand request, CancellationToken cancellationToken) + public async Task Handle(UpdateCustomerAddressCommand request, CancellationToken cancellationToken) { + ArgumentException.ThrowIfNullOrEmpty(request.Customer.Id); var customer = await _customerService.GetCustomerById(request.Customer.Id); if (customer != null) { diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/UpdateCustomerCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/UpdateCustomerCommandHandler.cs index 9eca850bc..3668fb2e1 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/UpdateCustomerCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/UpdateCustomerCommandHandler.cs @@ -23,7 +23,8 @@ public UpdateCustomerCommandHandler( public async Task Handle(UpdateCustomerCommand request, CancellationToken cancellationToken) { - var customer = await _customerService.GetCustomerById(request.Model.Id); + var customer = await _customerService.GetCustomerById(request.Model.Id) ?? + throw new ArgumentException("No customer has the id", nameof(request)); customer = request.Model.ToEntity(customer); await _customerService.UpdateCustomer(customer); await SaveCustomerAttributes(request.Model, customer); @@ -69,7 +70,7 @@ protected async Task SaveCustomerGroups(CustomerDto model, Customer customer) var group = await _groupService.GetCustomerGroupById(item); if (group != null) { - customer.Groups.Remove(customer.Groups.FirstOrDefault(x => x == item)); + customer.Groups.Remove(item); await _customerService.DeleteCustomerGroupInCustomer(group, customer.Id); } } diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/UpdateCustomerGroupCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/UpdateCustomerGroupCommandHandler.cs index 22890709f..713728e47 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/UpdateCustomerGroupCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Customers/UpdateCustomerGroupCommandHandler.cs @@ -17,7 +17,8 @@ public UpdateCustomerGroupCommandHandler(IGroupService groupService) public async Task Handle(UpdateCustomerGroupCommand request, CancellationToken cancellationToken) { - var customerGroup = await _groupService.GetCustomerGroupById(request.Model.Id); + var customerGroup = await _groupService.GetCustomerGroupById(request.Model.Id) ?? + throw new ArgumentException("No customer group has the id", nameof(request)); customerGroup = request.Model.ToEntity(customerGroup); await _groupService.UpdateCustomerGroup(customerGroup); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Inventory/ApplyStockCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Inventory/ApplyStockCommandHandler.cs index 9c2146895..4eea69a07 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Inventory/ApplyStockCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Inventory/ApplyStockCommandHandler.cs @@ -41,9 +41,10 @@ public async Task> Handle(ApplyStockCommand request, /// private async Task ReadTargets(IList lines) { - static List Trimmed(IEnumerable values) + static List Trimmed(IEnumerable values) { - return values.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim()).Distinct().ToList(); + return values.OfType().Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim()).Distinct() + .ToList(); } var productIds = Trimmed(lines.Select(x => x.ProductId)); @@ -55,11 +56,11 @@ static List Trimmed(IEnumerable values) : await productRepository.ToListAsync(productRepository.Table.Where(x => productIds.Contains(x.Id))); var bySku = skus.Count == 0 ? [] - : await productRepository.ToListAsync(productRepository.Table.Where(x => skus.Contains(x.Sku))); + : await productRepository.ToListAsync(productRepository.Table.Where(x => x.Sku != null && skus.Contains(x.Sku))); var byCombinationSku = skus.Count == 0 ? [] : await productRepository.ToListAsync(productRepository.Table - .Where(x => x.ProductAttributeCombinations.Any(c => skus.Contains(c.Sku)))); + .Where(x => x.ProductAttributeCombinations.Any(c => c.Sku != null && skus.Contains(c.Sku)))); var warehouses = codes.Count == 0 ? [] : await warehouseRepository.ToListAsync(warehouseRepository.Table.Where(x => codes.Contains(x.Code))); @@ -87,9 +88,10 @@ private async Task ApplyLine(StockApplyLineDto line, string if (!string.IsNullOrWhiteSpace(line.WarehouseId) && !string.IsNullOrWhiteSpace(line.WarehouseCode)) return Rejected(line, StockErrors.WarehouseTargetBoth); + //Resolve gives the product or an error var (product, combination, warehouseId, error) = Resolve(line, hasProductId, targets); - if (error != null) - return Rejected(line, error); + if (product == null) + return Rejected(line, error ?? StockErrors.ProductNotFound); //the stock of a batch- or serial-tracked product names its units; a target is the whole bucket, not one unit if (InventoryTracking.Tracked(product) && setTo) @@ -135,14 +137,14 @@ private async Task ApplyLine(StockApplyLineDto line, string }; } - private static (Product Product, ProductAttributeCombination Combination, string WarehouseId, string Error) + private static (Product? Product, ProductAttributeCombination? Combination, string? WarehouseId, string? Error) Resolve(StockApplyLineDto line, bool hasProductId, Targets targets) { - Product product; - ProductAttributeCombination combination = null; + Product? product; + ProductAttributeCombination? combination = null; if (hasProductId) { - product = targets.ProductsById.GetValueOrDefault(line.ProductId.Trim()); + product = targets.ProductsById.GetValueOrDefault((line.ProductId ?? "").Trim()); if (product == null) return (null, null, null, StockErrors.ProductNotFound); @@ -157,9 +159,9 @@ private static (Product Product, ProductAttributeCombination Combination, string } else { - var sku = line.Sku.Trim(); + var sku = (line.Sku ?? "").Trim(); var matches = targets.BySku.Where(x => x.Sku == sku) - .Select(x => (Product: x, Combination: (ProductAttributeCombination)null)) + .Select(x => (Product: x, Combination: (ProductAttributeCombination?)null)) .ToList(); foreach (var owner in targets.ByCombinationSku) foreach (var ownerCombination in owner.ProductAttributeCombinations.Where(c => c.Sku == sku)) @@ -173,7 +175,7 @@ private static (Product Product, ProductAttributeCombination Combination, string (product, combination) = matches[0]; } - string warehouseId = null; + string? warehouseId = null; if (!string.IsNullOrWhiteSpace(line.WarehouseId)) warehouseId = line.WarehouseId.Trim(); else if (!string.IsNullOrWhiteSpace(line.WarehouseCode)) @@ -207,7 +209,7 @@ private static (Product Product, ProductAttributeCombination Combination, string return (product, combination, warehouseId, null); } - private static int? StockAfter(Product product, ProductAttributeCombination combination, string warehouseId) + private static int? StockAfter(Product? product, ProductAttributeCombination? combination, string? warehouseId) { if (product == null) return null; diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/ChangeMerchandiseReturnStatusCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/ChangeMerchandiseReturnStatusCommandHandler.cs index c1db3cf97..b74048d2e 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/ChangeMerchandiseReturnStatusCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/ChangeMerchandiseReturnStatusCommandHandler.cs @@ -5,7 +5,7 @@ namespace Grand.Module.Api.Commands.Handlers.Orders; -public class ChangeMerchandiseReturnStatusCommandHandler : IRequestHandler +public class ChangeMerchandiseReturnStatusCommandHandler : IRequestHandler { private readonly IMerchandiseReturnWorkflowService _merchandiseReturnWorkflowService; @@ -14,7 +14,7 @@ public ChangeMerchandiseReturnStatusCommandHandler(IMerchandiseReturnWorkflowSer _merchandiseReturnWorkflowService = merchandiseReturnWorkflowService; } - public Task Handle(ChangeMerchandiseReturnStatusCommand request, CancellationToken cancellationToken) + public Task Handle(ChangeMerchandiseReturnStatusCommand request, CancellationToken cancellationToken) { return _merchandiseReturnWorkflowService.ChangeStatus(request.Id, (MerchandiseReturnStatus)request.Status, request.CustomerNote, request.ChangedBy); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/DeleteMerchandiseReturnCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/DeleteMerchandiseReturnCommandHandler.cs index 9ebfa67b3..74ec00ae2 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/DeleteMerchandiseReturnCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/DeleteMerchandiseReturnCommandHandler.cs @@ -4,7 +4,7 @@ namespace Grand.Module.Api.Commands.Handlers.Orders; -public class DeleteMerchandiseReturnCommandHandler : IRequestHandler +public class DeleteMerchandiseReturnCommandHandler : IRequestHandler { private readonly IMerchandiseReturnWorkflowService _merchandiseReturnWorkflowService; @@ -13,7 +13,7 @@ public DeleteMerchandiseReturnCommandHandler(IMerchandiseReturnWorkflowService m _merchandiseReturnWorkflowService = merchandiseReturnWorkflowService; } - public Task Handle(DeleteMerchandiseReturnCommand request, CancellationToken cancellationToken) + public Task Handle(DeleteMerchandiseReturnCommand request, CancellationToken cancellationToken) { return _merchandiseReturnWorkflowService.Delete(request.Id); } diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/UpdateMerchandiseReturnActionCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/UpdateMerchandiseReturnActionCommandHandler.cs index 98b1d9c4e..bde289085 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/UpdateMerchandiseReturnActionCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/UpdateMerchandiseReturnActionCommandHandler.cs @@ -19,7 +19,8 @@ public UpdateMerchandiseReturnActionCommandHandler(IMerchandiseReturnService mer public async Task Handle(UpdateMerchandiseReturnActionCommand request, CancellationToken cancellationToken) { - var action = await _merchandiseReturnService.GetMerchandiseReturnActionById(request.Model.Id); + var action = await _merchandiseReturnService.GetMerchandiseReturnActionById(request.Model.Id) ?? + throw new ArgumentException("No merchandise return action has the id", nameof(request)); action = request.Model.ToEntity(action); await _merchandiseReturnService.UpdateMerchandiseReturnAction(action); return action.ToModel(); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/UpdateMerchandiseReturnCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/UpdateMerchandiseReturnCommandHandler.cs index dacdf0e65..d72d5c13d 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/UpdateMerchandiseReturnCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/UpdateMerchandiseReturnCommandHandler.cs @@ -10,7 +10,7 @@ namespace Grand.Module.Api.Commands.Handlers.Orders; -public class UpdateMerchandiseReturnCommandHandler : IRequestHandler +public class UpdateMerchandiseReturnCommandHandler : IRequestHandler { private readonly IMerchandiseReturnService _merchandiseReturnService; private readonly IMerchandiseReturnWorkflowService _merchandiseReturnWorkflowService; @@ -24,7 +24,7 @@ public UpdateMerchandiseReturnCommandHandler(IMerchandiseReturnWorkflowService m _settingService = settingService; } - public async Task Handle(UpdateMerchandiseReturnCommand request, CancellationToken cancellationToken) + public async Task Handle(UpdateMerchandiseReturnCommand request, CancellationToken cancellationToken) { //a field the client did not send stays as stored: a PUT of the staff notes alone keeps the customer's comment //and the pickup address; an empty string clears a text, an address with no field filled in clears it @@ -64,7 +64,7 @@ public async Task Handle(UpdateMerchandiseReturnCommand request, Cancell }); } - private static bool SameAddress(AddressDto sent, Address stored) + private static bool SameAddress(AddressDto sent, Address? stored) { return stored == null ? IsEmpty(sent) diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/UpdateMerchandiseReturnReasonCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/UpdateMerchandiseReturnReasonCommandHandler.cs index 7846b1d9c..33e797282 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/UpdateMerchandiseReturnReasonCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Orders/UpdateMerchandiseReturnReasonCommandHandler.cs @@ -19,7 +19,8 @@ public UpdateMerchandiseReturnReasonCommandHandler(IMerchandiseReturnService mer public async Task Handle(UpdateMerchandiseReturnReasonCommand request, CancellationToken cancellationToken) { - var reason = await _merchandiseReturnService.GetMerchandiseReturnReasonById(request.Model.Id); + var reason = await _merchandiseReturnService.GetMerchandiseReturnReasonById(request.Model.Id) ?? + throw new ArgumentException("No merchandise return reason has the id", nameof(request)); reason = request.Model.ToEntity(reason); await _merchandiseReturnService.UpdateMerchandiseReturnReason(reason); return reason.ToModel(); diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddBrandCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddBrandCommand.cs index 86bbb4855..e084b7235 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddBrandCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddBrandCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class AddBrandCommand : IRequest { - public BrandDto Model { get; set; } + public required BrandDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddCategoryCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddCategoryCommand.cs index 490c7b123..70decb3c0 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddCategoryCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddCategoryCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class AddCategoryCommand : IRequest { - public CategoryDto Model { get; set; } + public required CategoryDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddCollectionCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddCollectionCommand.cs index bd597bf31..510caf6e9 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddCollectionCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddCollectionCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class AddCollectionCommand : IRequest { - public CollectionDto Model { get; set; } + public required CollectionDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductAttributeCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductAttributeCommand.cs index 4d0dd468d..40da975f4 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductAttributeCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductAttributeCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class AddProductAttributeCommand : IRequest { - public ProductDto Product { get; set; } - public ProductAttributeDto Model { get; set; } + public ProductDto? Product { get; set; } + public required ProductAttributeDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductAttributeMappingCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductAttributeMappingCommand.cs index 42bceec1b..6e056bbd7 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductAttributeMappingCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductAttributeMappingCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class AddProductAttributeMappingCommand : IRequest { - public ProductDto Product { get; set; } - public ProductAttributeMappingDto Model { get; set; } + public required ProductDto Product { get; set; } + public required ProductAttributeMappingDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductCategoryCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductCategoryCommand.cs index 351b4f72a..365f2a5ef 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductCategoryCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductCategoryCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class AddProductCategoryCommand : IRequest { - public ProductDto Product { get; set; } - public ProductCategoryDto Model { get; set; } + public required ProductDto Product { get; set; } + public required ProductCategoryDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductCollectionCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductCollectionCommand.cs index 534dab475..d0b2cbcb7 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductCollectionCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductCollectionCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class AddProductCollectionCommand : IRequest { - public ProductDto Product { get; set; } - public ProductCollectionDto Model { get; set; } + public required ProductDto Product { get; set; } + public required ProductCollectionDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductCommand.cs index ac5b0057c..fe6b56153 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class AddProductCommand : IRequest { - public ProductDto Model { get; set; } + public required ProductDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductPictureCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductPictureCommand.cs index 4d9c7dd18..0979a639d 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductPictureCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductPictureCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class AddProductPictureCommand : IRequest { - public ProductDto Product { get; set; } - public ProductPictureDto Model { get; set; } + public required ProductDto Product { get; set; } + public required ProductPictureDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductSpecificationCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductSpecificationCommand.cs index 3ac29dbeb..d284a0344 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductSpecificationCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductSpecificationCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class AddProductSpecificationCommand : IRequest { - public ProductDto Product { get; set; } - public ProductSpecificationAttributeDto Model { get; set; } + public required ProductDto Product { get; set; } + public required ProductSpecificationAttributeDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductTierPriceCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductTierPriceCommand.cs index d3a83c7af..50c67fffa 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductTierPriceCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddProductTierPriceCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class AddProductTierPriceCommand : IRequest { - public ProductDto Product { get; set; } - public ProductTierPriceDto Model { get; set; } + public required ProductDto Product { get; set; } + public required ProductTierPriceDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddSpecificationAttributeCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddSpecificationAttributeCommand.cs index 59bc6e2e0..2634c855e 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddSpecificationAttributeCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/AddSpecificationAttributeCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class AddSpecificationAttributeCommand : IRequest { - public SpecificationAttributeDto Model { get; set; } + public required SpecificationAttributeDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteBrandCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteBrandCommand.cs index c580781e8..36a607ca6 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteBrandCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteBrandCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class DeleteBrandCommand : IRequest { - public BrandDto Model { get; set; } + public required BrandDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteCategoryCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteCategoryCommand.cs index 3898d5e38..7ddcb581e 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteCategoryCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteCategoryCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class DeleteCategoryCommand : IRequest { - public CategoryDto Model { get; set; } + public required CategoryDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteCollectionCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteCollectionCommand.cs index e8e1a9592..1630b306f 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteCollectionCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteCollectionCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class DeleteCollectionCommand : IRequest { - public CollectionDto Model { get; set; } + public required CollectionDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductAttributeCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductAttributeCommand.cs index 767d9354f..8ea61404b 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductAttributeCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductAttributeCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class DeleteProductAttributeCommand : IRequest { - public ProductAttributeDto Model { get; set; } + public required ProductAttributeDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductAttributeMappingCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductAttributeMappingCommand.cs index 1b0f3327f..77ed533e2 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductAttributeMappingCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductAttributeMappingCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class DeleteProductAttributeMappingCommand : IRequest { - public ProductDto Product { get; set; } - public ProductAttributeMappingDto Model { get; set; } + public required ProductDto Product { get; set; } + public required ProductAttributeMappingDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductCategoryCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductCategoryCommand.cs index 7a68fbc7e..1c3e0a2bb 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductCategoryCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductCategoryCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class DeleteProductCategoryCommand : IRequest { - public ProductDto Product { get; set; } - public string CategoryId { get; set; } + public required ProductDto Product { get; set; } + public required string CategoryId { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductCollectionCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductCollectionCommand.cs index 27724a324..dbf4fb79e 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductCollectionCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductCollectionCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class DeleteProductCollectionCommand : IRequest { - public ProductDto Product { get; set; } - public string CollectionId { get; set; } + public required ProductDto Product { get; set; } + public required string CollectionId { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductCommand.cs index d27c8a836..6ce8a4cb2 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class DeleteProductCommand : IRequest { - public ProductDto Model { get; set; } + public required ProductDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductPictureCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductPictureCommand.cs index 82e51af7d..c60efdff3 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductPictureCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductPictureCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class DeleteProductPictureCommand : IRequest { - public ProductDto Product { get; set; } - public string PictureId { get; set; } + public required ProductDto Product { get; set; } + public required string PictureId { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductSpecificationCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductSpecificationCommand.cs index 827f800b7..725ae432c 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductSpecificationCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductSpecificationCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class DeleteProductSpecificationCommand : IRequest { - public ProductDto Product { get; set; } - public string Id { get; set; } + public required ProductDto Product { get; set; } + public required string Id { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductTierPriceCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductTierPriceCommand.cs index b01d6cca4..9d43a4748 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductTierPriceCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteProductTierPriceCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class DeleteProductTierPriceCommand : IRequest { - public ProductDto Product { get; set; } - public string Id { get; set; } + public required ProductDto Product { get; set; } + public required string Id { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteSpecificationAttributeCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteSpecificationAttributeCommand.cs index baad40af1..0021c1e11 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteSpecificationAttributeCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/DeleteSpecificationAttributeCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class DeleteSpecificationAttributeCommand : IRequest { - public SpecificationAttributeDto Model { get; set; } + public required SpecificationAttributeDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateBrandCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateBrandCommand.cs index d493439c0..c14152578 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateBrandCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateBrandCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class UpdateBrandCommand : IRequest { - public BrandDto Model { get; set; } + public required BrandDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateCategoryCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateCategoryCommand.cs index 035283aa7..50be99398 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateCategoryCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateCategoryCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class UpdateCategoryCommand : IRequest { - public CategoryDto Model { get; set; } + public required CategoryDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateCollectionCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateCollectionCommand.cs index ef473c820..7bc8c932c 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateCollectionCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateCollectionCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class UpdateCollectionCommand : IRequest { - public CollectionDto Model { get; set; } + public required CollectionDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductAttributeCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductAttributeCommand.cs index acafa6b91..e8439b79e 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductAttributeCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductAttributeCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class UpdateProductAttributeCommand : IRequest { - public ProductAttributeDto Model { get; set; } + public required ProductAttributeDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductAttributeMappingCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductAttributeMappingCommand.cs index 3d6a21472..0dfd33d88 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductAttributeMappingCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductAttributeMappingCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class UpdateProductAttributeMappingCommand : IRequest { - public ProductDto Product { get; set; } - public ProductAttributeMappingDto Model { get; set; } + public required ProductDto Product { get; set; } + public required ProductAttributeMappingDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductCategoryCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductCategoryCommand.cs index e0ce0a125..beb5a08dc 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductCategoryCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductCategoryCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class UpdateProductCategoryCommand : IRequest { - public ProductDto Product { get; set; } - public ProductCategoryDto Model { get; set; } + public required ProductDto Product { get; set; } + public required ProductCategoryDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductCollectionCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductCollectionCommand.cs index 66f2cf92a..56427e7ce 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductCollectionCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductCollectionCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class UpdateProductCollectionCommand : IRequest { - public ProductDto Product { get; set; } - public ProductCollectionDto Model { get; set; } + public required ProductDto Product { get; set; } + public required ProductCollectionDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductCommand.cs index 8694b967e..904110365 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class UpdateProductCommand : IRequest { - public ProductDto Model { get; set; } + public required ProductDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductPictureCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductPictureCommand.cs index ba1757c07..811147667 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductPictureCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductPictureCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class UpdateProductPictureCommand : IRequest { - public ProductDto Product { get; set; } - public ProductPictureDto Model { get; set; } + public required ProductDto Product { get; set; } + public required ProductPictureDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductSpecificationCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductSpecificationCommand.cs index 37d98b16d..b1ca2652c 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductSpecificationCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductSpecificationCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class UpdateProductSpecificationCommand : IRequest { - public ProductDto Product { get; set; } - public ProductSpecificationAttributeDto Model { get; set; } + public required ProductDto Product { get; set; } + public required ProductSpecificationAttributeDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductStockCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductStockCommand.cs index 4210e30fc..a95eaccba 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductStockCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductStockCommand.cs @@ -5,7 +5,7 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class UpdateProductStockCommand : IRequest { - public ProductDto Product { get; set; } - public string WarehouseId { get; set; } + public required ProductDto Product { get; set; } + public string? WarehouseId { get; set; } public int Stock { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductTierPriceCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductTierPriceCommand.cs index 0e1a5151c..a915c4ed7 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductTierPriceCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateProductTierPriceCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class UpdateProductTierPriceCommand : IRequest { - public ProductDto Product { get; set; } - public ProductTierPriceDto Model { get; set; } + public required ProductDto Product { get; set; } + public required ProductTierPriceDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateSpecificationAttributeCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateSpecificationAttributeCommand.cs index d367f6ebe..425a11ca1 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateSpecificationAttributeCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Catalog/UpdateSpecificationAttributeCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Catalog; public class UpdateSpecificationAttributeCommand : IRequest { - public SpecificationAttributeDto Model { get; set; } + public required SpecificationAttributeDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Common/AddPictureCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Common/AddPictureCommand.cs index c449df96c..f46651f58 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Common/AddPictureCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Common/AddPictureCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Common; public class AddPictureCommand : IRequest { - public PictureDto PictureDto { get; set; } + public required PictureDto PictureDto { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Common/DeletePictureCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Common/DeletePictureCommand.cs index 1a09d8b53..5af7bdba5 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Common/DeletePictureCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Common/DeletePictureCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Common; public class DeletePictureCommand : IRequest { - public PictureDto PictureDto { get; set; } + public required PictureDto PictureDto { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Common/GenerateTokenCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Common/GenerateTokenCommand.cs index f57a9164c..33595eee2 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Common/GenerateTokenCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Common/GenerateTokenCommand.cs @@ -4,5 +4,5 @@ namespace Grand.Module.Api.Commands.Models.Common; public class GenerateTokenCommand : IRequest { - public Dictionary Claims { get; set; } + public required Dictionary Claims { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Common/GenerateTokenWebCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Common/GenerateTokenWebCommand.cs index fb95cc704..23eceb202 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Common/GenerateTokenWebCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Common/GenerateTokenWebCommand.cs @@ -4,5 +4,5 @@ namespace Grand.Module.Api.Commands.Models.Common; public class GenerateTokenWebCommand : IRequest { - public Dictionary Claims { get; set; } + public required Dictionary Claims { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Common/UpdatePictureCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Common/UpdatePictureCommand.cs index 2ae3626cb..4e77a166a 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Common/UpdatePictureCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Common/UpdatePictureCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Common; public class UpdatePictureCommand : IRequest { - public PictureDto Model { get; set; } + public required PictureDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Customers/AddCustomerAddressCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Customers/AddCustomerAddressCommand.cs index 69618d651..2a69b3e67 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Customers/AddCustomerAddressCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Customers/AddCustomerAddressCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Customers; public class AddCustomerAddressCommand : IRequest { - public CustomerDto Customer { get; set; } - public AddressDto Address { get; set; } + public required CustomerDto Customer { get; set; } + public required AddressDto Address { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Customers/AddCustomerCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Customers/AddCustomerCommand.cs index db532a54a..12111fd00 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Customers/AddCustomerCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Customers/AddCustomerCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Customers; public class AddCustomerCommand : IRequest { - public CustomerDto Model { get; set; } + public required CustomerDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Customers/AddCustomerGroupCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Customers/AddCustomerGroupCommand.cs index 0f6ca9174..de9d0bfd8 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Customers/AddCustomerGroupCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Customers/AddCustomerGroupCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Customers; public class AddCustomerGroupCommand : IRequest { - public CustomerGroupDto Model { get; set; } + public required CustomerGroupDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Customers/DeleteCustomerAddressCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Customers/DeleteCustomerAddressCommand.cs index f39dadb84..738cac164 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Customers/DeleteCustomerAddressCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Customers/DeleteCustomerAddressCommand.cs @@ -5,6 +5,6 @@ namespace Grand.Module.Api.Commands.Models.Customers; public class DeleteCustomerAddressCommand : IRequest { - public CustomerDto Customer { get; set; } - public AddressDto Address { get; set; } + public required CustomerDto Customer { get; set; } + public required AddressDto Address { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Customers/DeleteCustomerCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Customers/DeleteCustomerCommand.cs index 36acf3293..2233c065c 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Customers/DeleteCustomerCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Customers/DeleteCustomerCommand.cs @@ -4,5 +4,5 @@ namespace Grand.Module.Api.Commands.Models.Customers; public class DeleteCustomerCommand : IRequest { - public string Email { get; set; } + public string? Email { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Customers/DeleteCustomerGroupCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Customers/DeleteCustomerGroupCommand.cs index ffe0c2862..285e0cc0b 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Customers/DeleteCustomerGroupCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Customers/DeleteCustomerGroupCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Customers; public class DeleteCustomerGroupCommand : IRequest { - public CustomerGroupDto Model { get; set; } + public required CustomerGroupDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Customers/UpdateCustomerAddressCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Customers/UpdateCustomerAddressCommand.cs index 9f571389c..ab4dac32f 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Customers/UpdateCustomerAddressCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Customers/UpdateCustomerAddressCommand.cs @@ -3,8 +3,8 @@ namespace Grand.Module.Api.Commands.Models.Customers; -public class UpdateCustomerAddressCommand : IRequest +public class UpdateCustomerAddressCommand : IRequest { - public CustomerDto Customer { get; set; } - public AddressDto Address { get; set; } + public required CustomerDto Customer { get; set; } + public required AddressDto Address { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Customers/UpdateCustomerCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Customers/UpdateCustomerCommand.cs index e5004cff9..16de8ba1b 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Customers/UpdateCustomerCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Customers/UpdateCustomerCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Customers; public class UpdateCustomerCommand : IRequest { - public CustomerDto Model { get; set; } + public required CustomerDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Customers/UpdateCustomerGroupCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Customers/UpdateCustomerGroupCommand.cs index 1ece7616f..6cfcca769 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Customers/UpdateCustomerGroupCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Customers/UpdateCustomerGroupCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Customers; public class UpdateCustomerGroupCommand : IRequest { - public CustomerGroupDto Model { get; set; } + public required CustomerGroupDto Model { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Inventory/ApplyStockCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Inventory/ApplyStockCommand.cs index 3d72aa767..e0624f3eb 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Inventory/ApplyStockCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Inventory/ApplyStockCommand.cs @@ -13,5 +13,5 @@ public class ApplyStockCommand : IRequest> /// /// The API customer the entries are booked for /// - public string CustomerId { get; set; } + public required string CustomerId { get; set; } } diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Orders/AddMerchandiseReturnActionCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Orders/AddMerchandiseReturnActionCommand.cs index d841ec27c..48ccefcce 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Orders/AddMerchandiseReturnActionCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Orders/AddMerchandiseReturnActionCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Orders; public class AddMerchandiseReturnActionCommand : IRequest { - public MerchandiseReturnActionDto Model { get; set; } + public required MerchandiseReturnActionDto Model { get; set; } } diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Orders/AddMerchandiseReturnReasonCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Orders/AddMerchandiseReturnReasonCommand.cs index 01c71c78b..d91c34dbd 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Orders/AddMerchandiseReturnReasonCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Orders/AddMerchandiseReturnReasonCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Orders; public class AddMerchandiseReturnReasonCommand : IRequest { - public MerchandiseReturnReasonDto Model { get; set; } + public required MerchandiseReturnReasonDto Model { get; set; } } diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Orders/ChangeMerchandiseReturnStatusCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Orders/ChangeMerchandiseReturnStatusCommand.cs index 94aa264ef..2a2d31f25 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Orders/ChangeMerchandiseReturnStatusCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Orders/ChangeMerchandiseReturnStatusCommand.cs @@ -2,10 +2,10 @@ namespace Grand.Module.Api.Commands.Models.Orders; -public class ChangeMerchandiseReturnStatusCommand : IRequest +public class ChangeMerchandiseReturnStatusCommand : IRequest { - public string Id { get; set; } + public required string Id { get; set; } public int Status { get; set; } - public string CustomerNote { get; set; } - public string ChangedBy { get; set; } + public string? CustomerNote { get; set; } + public string? ChangedBy { get; set; } } diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Orders/DeleteMerchandiseReturnActionCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Orders/DeleteMerchandiseReturnActionCommand.cs index 9e9b7e559..9566fef71 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Orders/DeleteMerchandiseReturnActionCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Orders/DeleteMerchandiseReturnActionCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Orders; public class DeleteMerchandiseReturnActionCommand : IRequest { - public MerchandiseReturnActionDto Model { get; set; } + public required MerchandiseReturnActionDto Model { get; set; } } diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Orders/DeleteMerchandiseReturnCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Orders/DeleteMerchandiseReturnCommand.cs index 8f0ec89db..c128a9fb6 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Orders/DeleteMerchandiseReturnCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Orders/DeleteMerchandiseReturnCommand.cs @@ -2,7 +2,7 @@ namespace Grand.Module.Api.Commands.Models.Orders; -public class DeleteMerchandiseReturnCommand : IRequest +public class DeleteMerchandiseReturnCommand : IRequest { - public string Id { get; set; } + public required string Id { get; set; } } diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Orders/DeleteMerchandiseReturnReasonCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Orders/DeleteMerchandiseReturnReasonCommand.cs index 44fbd9867..10ec40b1b 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Orders/DeleteMerchandiseReturnReasonCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Orders/DeleteMerchandiseReturnReasonCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Orders; public class DeleteMerchandiseReturnReasonCommand : IRequest { - public MerchandiseReturnReasonDto Model { get; set; } + public required MerchandiseReturnReasonDto Model { get; set; } } diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Orders/UpdateMerchandiseReturnActionCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Orders/UpdateMerchandiseReturnActionCommand.cs index 8d835be6a..259c987b5 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Orders/UpdateMerchandiseReturnActionCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Orders/UpdateMerchandiseReturnActionCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Orders; public class UpdateMerchandiseReturnActionCommand : IRequest { - public MerchandiseReturnActionDto Model { get; set; } + public required MerchandiseReturnActionDto Model { get; set; } } diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Orders/UpdateMerchandiseReturnCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Orders/UpdateMerchandiseReturnCommand.cs index 48ee7eabe..cf4bd713d 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Orders/UpdateMerchandiseReturnCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Orders/UpdateMerchandiseReturnCommand.cs @@ -3,8 +3,8 @@ namespace Grand.Module.Api.Commands.Models.Orders; -public class UpdateMerchandiseReturnCommand : IRequest +public class UpdateMerchandiseReturnCommand : IRequest { - public string Id { get; set; } - public MerchandiseReturnDto Model { get; set; } + public required string Id { get; set; } + public required MerchandiseReturnDto Model { get; set; } } diff --git a/src/Modules/Grand.Module.Api/Commands/Models/Orders/UpdateMerchandiseReturnReasonCommand.cs b/src/Modules/Grand.Module.Api/Commands/Models/Orders/UpdateMerchandiseReturnReasonCommand.cs index 568545be1..36c5210dc 100644 --- a/src/Modules/Grand.Module.Api/Commands/Models/Orders/UpdateMerchandiseReturnReasonCommand.cs +++ b/src/Modules/Grand.Module.Api/Commands/Models/Orders/UpdateMerchandiseReturnReasonCommand.cs @@ -5,5 +5,5 @@ namespace Grand.Module.Api.Commands.Models.Orders; public class UpdateMerchandiseReturnReasonCommand : IRequest { - public MerchandiseReturnReasonDto Model { get; set; } + public required MerchandiseReturnReasonDto Model { get; set; } } diff --git a/src/Modules/Grand.Module.Api/Controllers/BaseApiController.cs b/src/Modules/Grand.Module.Api/Controllers/BaseApiController.cs index d333d360e..f795dc7a3 100644 --- a/src/Modules/Grand.Module.Api/Controllers/BaseApiController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/BaseApiController.cs @@ -25,7 +25,7 @@ public abstract class BaseApiController : ControllerBase /// Customer of the current request /// protected Customer CurrentCustomer => - HttpContext.RequestServices.GetRequiredService().WorkContext?.CurrentCustomer; + HttpContext.RequestServices.GetRequiredService().WorkContext.CurrentCustomer; public override ForbidResult Forbid() { diff --git a/src/Modules/Grand.Module.Api/Controllers/BrandController.cs b/src/Modules/Grand.Module.Api/Controllers/BrandController.cs index 6182d76db..ddcc02700 100644 --- a/src/Modules/Grand.Module.Api/Controllers/BrandController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/BrandController.cs @@ -47,10 +47,10 @@ public async Task GetById([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.Brands, CurrentCustomer)) return Forbid(); - var brand = await _mediator.Send(new GetGenericQuery(key)); - if (!brand.Any()) return NotFound(); + var brand = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (brand == null) return NotFound(); - return Ok(brand.FirstOrDefault()); + return Ok(brand); } [EndpointDescription("Add new entity to Brand")] @@ -102,10 +102,10 @@ public async Task Patch([FromRoute] string key, [FromBody] JsonPa if (!await _permissionService.AuthorizeAction(PermissionSystemName.Brands, PermissionActionName.Edit, CurrentCustomer)) return Forbid(); - var brand = await _mediator.Send(new GetGenericQuery(key)); - if (!brand.Any()) return NotFound(); + var brand = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (brand == null) return NotFound(); - var man = brand.FirstOrDefault(); + var man = brand; model.ApplyTo(man); await _mediator.Send(new UpdateBrandCommand { Model = man }); return Ok(); @@ -121,10 +121,10 @@ public async Task Delete([FromRoute] string key) { if (!await _permissionService.AuthorizeAction(PermissionSystemName.Brands, PermissionActionName.Delete, CurrentCustomer)) return Forbid(); - var brand = await _mediator.Send(new GetGenericQuery(key)); - if (!brand.Any()) return NotFound(); + var brand = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (brand == null) return NotFound(); - await _mediator.Send(new DeleteBrandCommand { Model = brand.FirstOrDefault() }); + await _mediator.Send(new DeleteBrandCommand { Model = brand }); return Ok(); } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Controllers/BrandLayoutController.cs b/src/Modules/Grand.Module.Api/Controllers/BrandLayoutController.cs index 9396c2bba..be02f67c3 100644 --- a/src/Modules/Grand.Module.Api/Controllers/BrandLayoutController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/BrandLayoutController.cs @@ -32,10 +32,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.Maintenance, CurrentCustomer)) return Forbid(); - var layout = await _mediator.Send(new GetGenericQuery(key)); - if (!layout.Any()) return NotFound(); + var layout = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (layout == null) return NotFound(); - return Ok(layout.FirstOrDefault()); + return Ok(layout); } [EndpointDescription("Get entities from BrandLayout")] diff --git a/src/Modules/Grand.Module.Api/Controllers/CategoryController.cs b/src/Modules/Grand.Module.Api/Controllers/CategoryController.cs index 4b966730b..f1d5f1c9e 100644 --- a/src/Modules/Grand.Module.Api/Controllers/CategoryController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/CategoryController.cs @@ -36,10 +36,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.Categories, CurrentCustomer)) return Forbid(); - var category = await _mediator.Send(new GetGenericQuery(key)); - if (!category.Any()) return NotFound(); + var category = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (category == null) return NotFound(); - return Ok(category.FirstOrDefault()); + return Ok(category); } [EndpointDescription("Get entities from Category")] @@ -97,10 +97,10 @@ public async Task Patch([FromRoute] string key, [FromBody] JsonPa if (!await _permissionService.AuthorizeAction(PermissionSystemName.Categories, PermissionActionName.Edit, CurrentCustomer)) return Forbid(); - var category = await _mediator.Send(new GetGenericQuery(key)); - if (!category.Any()) return NotFound(); + var category = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (category == null) return NotFound(); - var cat = category.FirstOrDefault(); + var cat = category; model.ApplyTo(cat); await _mediator.Send(new UpdateCategoryCommand { Model = cat }); return Ok(); @@ -116,10 +116,10 @@ public async Task Delete([FromRoute] string key) { if (!await _permissionService.AuthorizeAction(PermissionSystemName.Categories, PermissionActionName.Delete, CurrentCustomer)) return Forbid(); - var category = await _mediator.Send(new GetGenericQuery(key)); - if (!category.Any()) return NotFound(); + var category = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (category == null) return NotFound(); - await _mediator.Send(new DeleteCategoryCommand { Model = category.FirstOrDefault() }); + await _mediator.Send(new DeleteCategoryCommand { Model = category }); return Ok(); } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Controllers/CategoryLayoutController.cs b/src/Modules/Grand.Module.Api/Controllers/CategoryLayoutController.cs index d18a6e75f..f027272fc 100644 --- a/src/Modules/Grand.Module.Api/Controllers/CategoryLayoutController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/CategoryLayoutController.cs @@ -34,10 +34,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.Maintenance, CurrentCustomer)) return Forbid(); - var layout = await _mediator.Send(new GetGenericQuery(key)); - if (!layout.Any()) return NotFound(); + var layout = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (layout == null) return NotFound(); - return Ok(layout.FirstOrDefault()); + return Ok(layout); } [EndpointDescription("Get entities from CategoryLayout")] diff --git a/src/Modules/Grand.Module.Api/Controllers/CollectionController.cs b/src/Modules/Grand.Module.Api/Controllers/CollectionController.cs index 4abc6205b..65cb79796 100644 --- a/src/Modules/Grand.Module.Api/Controllers/CollectionController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/CollectionController.cs @@ -34,10 +34,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.Collections, CurrentCustomer)) return Forbid(); - var collection = await _mediator.Send(new GetGenericQuery(key)); - if (!collection.Any()) return NotFound(); + var collection = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (collection == null) return NotFound(); - return Ok(collection.FirstOrDefault()); + return Ok(collection); } [EndpointDescription("Get entities from Collection")] @@ -95,10 +95,10 @@ public async Task Patch([FromRoute] string key, [FromBody] JsonPa if (!await _permissionService.AuthorizeAction(PermissionSystemName.Collections, PermissionActionName.Edit, CurrentCustomer)) return Forbid(); - var collection = await _mediator.Send(new GetGenericQuery(key)); - if (!collection.Any()) return NotFound(); + var collection = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (collection == null) return NotFound(); - var man = collection.FirstOrDefault(); + var man = collection; model.ApplyTo(man); await _mediator.Send(new UpdateCollectionCommand { Model = man }); return Ok(); @@ -114,10 +114,10 @@ public async Task Delete([FromRoute] string key) { if (!await _permissionService.AuthorizeAction(PermissionSystemName.Collections, PermissionActionName.Delete, CurrentCustomer)) return Forbid(); - var collection = await _mediator.Send(new GetGenericQuery(key)); - if (!collection.Any()) return NotFound(); + var collection = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (collection == null) return NotFound(); - await _mediator.Send(new DeleteCollectionCommand { Model = collection.FirstOrDefault() }); + await _mediator.Send(new DeleteCollectionCommand { Model = collection }); return Ok(); } diff --git a/src/Modules/Grand.Module.Api/Controllers/CollectionLayoutController.cs b/src/Modules/Grand.Module.Api/Controllers/CollectionLayoutController.cs index ffa80203c..25847e923 100644 --- a/src/Modules/Grand.Module.Api/Controllers/CollectionLayoutController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/CollectionLayoutController.cs @@ -32,10 +32,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.Maintenance, CurrentCustomer)) return Forbid(); - var layout = await _mediator.Send(new GetGenericQuery(key)); - if (!layout.Any()) return NotFound(); + var layout = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (layout == null) return NotFound(); - return Ok(layout.FirstOrDefault()); + return Ok(layout); } [EndpointDescription("Get entities from CollectionLayout")] diff --git a/src/Modules/Grand.Module.Api/Controllers/CountryController.cs b/src/Modules/Grand.Module.Api/Controllers/CountryController.cs index af6b8f021..36a0b5c7a 100644 --- a/src/Modules/Grand.Module.Api/Controllers/CountryController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/CountryController.cs @@ -33,10 +33,10 @@ public async Task Get([FromRoute] string key) if (!await _permissionService.Authorize(PermissionSystemName.Countries, CurrentCustomer)) return Forbid(); //Domain.Directory.Country - var country = await _mediator.Send(new GetGenericQuery(key)); - if (!country.Any()) return NotFound(); + var country = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (country == null) return NotFound(); - return Ok(country.FirstOrDefault()); + return Ok(country); } [EndpointDescription("Get entities from Country")] diff --git a/src/Modules/Grand.Module.Api/Controllers/CurrencyController.cs b/src/Modules/Grand.Module.Api/Controllers/CurrencyController.cs index 31e30b1ef..0743afc3d 100644 --- a/src/Modules/Grand.Module.Api/Controllers/CurrencyController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/CurrencyController.cs @@ -32,10 +32,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.Currencies, CurrentCustomer)) return Forbid(); - var currency = await _mediator.Send(new GetGenericQuery(key)); - if (!currency.Any()) return NotFound(); + var currency = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (currency == null) return NotFound(); - return Ok(currency.FirstOrDefault()); + return Ok(currency); } [EndpointDescription("Get entities from Currency")] diff --git a/src/Modules/Grand.Module.Api/Controllers/CustomerController.cs b/src/Modules/Grand.Module.Api/Controllers/CustomerController.cs index 2fd8026d8..3ef550a3d 100644 --- a/src/Modules/Grand.Module.Api/Controllers/CustomerController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/CustomerController.cs @@ -136,9 +136,9 @@ public async Task UpdateAddress([FromRoute] string email, [FromBo var customer = await _mediator.Send(new GetCustomerQuery { Email = email }); if (customer == null) return NotFound(); - address = await _mediator.Send(new UpdateCustomerAddressCommand { Customer = customer, Address = address }); + var updated = await _mediator.Send(new UpdateCustomerAddressCommand { Customer = customer, Address = address }); - return Ok(address); + return Ok(updated); } //api/Customer/email/DeleteAddress diff --git a/src/Modules/Grand.Module.Api/Controllers/CustomerGroupController.cs b/src/Modules/Grand.Module.Api/Controllers/CustomerGroupController.cs index d1a01ce53..3b95fbeb4 100644 --- a/src/Modules/Grand.Module.Api/Controllers/CustomerGroupController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/CustomerGroupController.cs @@ -34,10 +34,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.Customers, CurrentCustomer)) return Forbid(); - var customerGroup = await _mediator.Send(new GetGenericQuery(key)); - if (!customerGroup.Any()) return NotFound(); + var customerGroup = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (customerGroup == null) return NotFound(); - return Ok(customerGroup.FirstOrDefault()); + return Ok(customerGroup); } [EndpointDescription("Get entities from CustomerGroup")] @@ -81,10 +81,10 @@ public async Task Put([FromBody] CustomerGroupDto model) if (!await _permissionService.AuthorizeAction(PermissionSystemName.Customers, PermissionActionName.Edit, CurrentCustomer)) return Forbid(); - var customerGroup = await _mediator.Send(new GetGenericQuery(model.Id)); - if (!customerGroup.Any()) return NotFound(); + var customerGroup = (await _mediator.Send(new GetGenericQuery(model.Id))).FirstOrDefault(); + if (customerGroup == null) return NotFound(); - if (customerGroup.FirstOrDefault()!.IsSystem) return BadRequest(ModelState); + if (customerGroup.IsSystem) return BadRequest(ModelState); model = await _mediator.Send(new UpdateCustomerGroupCommand { Model = model }); return Ok(model); @@ -104,10 +104,10 @@ public async Task Patch([FromRoute] string key, [FromBody] JsonPa if (!await _permissionService.AuthorizeAction(PermissionSystemName.Customers, PermissionActionName.Edit, CurrentCustomer)) return Forbid(); - var customerGroup = await _mediator.Send(new GetGenericQuery(key)); - if (!customerGroup.Any()) return NotFound(); + var customerGroup = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (customerGroup == null) return NotFound(); - var cr = customerGroup.FirstOrDefault(); + var cr = customerGroup; if (cr!.IsSystem) return BadRequest(ModelState); model.ApplyTo(cr); @@ -125,12 +125,12 @@ public async Task Delete([FromRoute] string key) { if (!await _permissionService.AuthorizeAction(PermissionSystemName.Customers, PermissionActionName.Delete, CurrentCustomer)) return Forbid(); - var customerGroup = await _mediator.Send(new GetGenericQuery(key)); - if (!customerGroup.Any()) return NotFound(); + var customerGroup = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (customerGroup == null) return NotFound(); - if (customerGroup.FirstOrDefault()!.IsSystem) return Forbid(); + if (customerGroup.IsSystem) return Forbid(); - await _mediator.Send(new DeleteCustomerGroupCommand { Model = customerGroup.FirstOrDefault() }); + await _mediator.Send(new DeleteCustomerGroupCommand { Model = customerGroup }); return Ok(); } diff --git a/src/Modules/Grand.Module.Api/Controllers/DeliveryDateController.cs b/src/Modules/Grand.Module.Api/Controllers/DeliveryDateController.cs index 3dc88ac0e..823a6d85b 100644 --- a/src/Modules/Grand.Module.Api/Controllers/DeliveryDateController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/DeliveryDateController.cs @@ -32,10 +32,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings, CurrentCustomer)) return Forbid(); - var deliverydate = await _mediator.Send(new GetGenericQuery(key)); - if (!deliverydate.Any()) return NotFound(); + var deliverydate = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (deliverydate == null) return NotFound(); - return Ok(deliverydate.FirstOrDefault()); + return Ok(deliverydate); } [EndpointDescription("Get entities from Delivery Date")] diff --git a/src/Modules/Grand.Module.Api/Controllers/LanguageController.cs b/src/Modules/Grand.Module.Api/Controllers/LanguageController.cs index 9b2365a46..f38c498be 100644 --- a/src/Modules/Grand.Module.Api/Controllers/LanguageController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/LanguageController.cs @@ -32,10 +32,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.Languages, CurrentCustomer)) return Forbid(); - var language = await _mediator.Send(new GetGenericQuery(key)); - if (!language.Any()) return NotFound(); + var language = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (language == null) return NotFound(); - return Ok(language.FirstOrDefault()); + return Ok(language); } [EndpointDescription("Get entities from Languages")] diff --git a/src/Modules/Grand.Module.Api/Controllers/MerchandiseReturnActionController.cs b/src/Modules/Grand.Module.Api/Controllers/MerchandiseReturnActionController.cs index 07f1773c7..4b79bcf65 100644 --- a/src/Modules/Grand.Module.Api/Controllers/MerchandiseReturnActionController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/MerchandiseReturnActionController.cs @@ -46,10 +46,10 @@ public async Task GetById([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.Settings, CurrentCustomer)) return Forbid(); - var action = await _mediator.Send(new GetGenericQuery(key)); - if (!action.Any()) return NotFound(); + var action = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (action == null) return NotFound(); - return Ok(action.FirstOrDefault()); + return Ok(action); } [EndpointDescription("Add new entity to MerchandiseReturnAction")] @@ -90,10 +90,10 @@ public async Task Delete([FromRoute] string key) { if (!await _permissionService.AuthorizeAction(PermissionSystemName.Settings, PermissionActionName.Delete, CurrentCustomer)) return Forbid(); - var action = await _mediator.Send(new GetGenericQuery(key)); - if (!action.Any()) return NotFound(); + var action = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (action == null) return NotFound(); - await _mediator.Send(new DeleteMerchandiseReturnActionCommand { Model = action.FirstOrDefault() }); + await _mediator.Send(new DeleteMerchandiseReturnActionCommand { Model = action }); return Ok(); } } diff --git a/src/Modules/Grand.Module.Api/Controllers/MerchandiseReturnController.cs b/src/Modules/Grand.Module.Api/Controllers/MerchandiseReturnController.cs index e63ae3daa..9982752d0 100644 --- a/src/Modules/Grand.Module.Api/Controllers/MerchandiseReturnController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/MerchandiseReturnController.cs @@ -157,7 +157,7 @@ public async Task ChangeStatus([FromRoute] string key, return Ok(await Load(key)); } - private async Task Load(string id) + private async Task Load(string id) { var merchandiseReturn = await _mediator.Send(new GetMerchandiseReturnQuery { Id = id }); return merchandiseReturn == null ? null : Map(merchandiseReturn, await ReceivedByHand(merchandiseReturn)); diff --git a/src/Modules/Grand.Module.Api/Controllers/MerchandiseReturnReasonController.cs b/src/Modules/Grand.Module.Api/Controllers/MerchandiseReturnReasonController.cs index 8bccf8fe5..ba85c047c 100644 --- a/src/Modules/Grand.Module.Api/Controllers/MerchandiseReturnReasonController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/MerchandiseReturnReasonController.cs @@ -46,10 +46,10 @@ public async Task GetById([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.Settings, CurrentCustomer)) return Forbid(); - var reason = await _mediator.Send(new GetGenericQuery(key)); - if (!reason.Any()) return NotFound(); + var reason = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (reason == null) return NotFound(); - return Ok(reason.FirstOrDefault()); + return Ok(reason); } [EndpointDescription("Add new entity to MerchandiseReturnReason")] @@ -90,10 +90,10 @@ public async Task Delete([FromRoute] string key) { if (!await _permissionService.AuthorizeAction(PermissionSystemName.Settings, PermissionActionName.Delete, CurrentCustomer)) return Forbid(); - var reason = await _mediator.Send(new GetGenericQuery(key)); - if (!reason.Any()) return NotFound(); + var reason = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (reason == null) return NotFound(); - await _mediator.Send(new DeleteMerchandiseReturnReasonCommand { Model = reason.FirstOrDefault() }); + await _mediator.Send(new DeleteMerchandiseReturnReasonCommand { Model = reason }); return Ok(); } } diff --git a/src/Modules/Grand.Module.Api/Controllers/PickupPointController.cs b/src/Modules/Grand.Module.Api/Controllers/PickupPointController.cs index 5bd95f930..8ce153a97 100644 --- a/src/Modules/Grand.Module.Api/Controllers/PickupPointController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/PickupPointController.cs @@ -32,10 +32,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings, CurrentCustomer)) return Forbid(); - var points = await _mediator.Send(new GetGenericQuery(key)); - if (!points.Any()) return NotFound(); + var points = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (points == null) return NotFound(); - return Ok(points.FirstOrDefault()); + return Ok(points); } [EndpointDescription("Get entities from PickupPoint")] diff --git a/src/Modules/Grand.Module.Api/Controllers/PictureController.cs b/src/Modules/Grand.Module.Api/Controllers/PictureController.cs index 825124e15..787aebf35 100644 --- a/src/Modules/Grand.Module.Api/Controllers/PictureController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/PictureController.cs @@ -32,10 +32,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.Pictures, CurrentCustomer)) return Forbid(); - var picture = await _mediator.Send(new GetGenericQuery(key)); - if (picture == null || !picture.Any()) return NotFound(); + var picture = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (picture == null) return NotFound(); - return Ok(picture.FirstOrDefault()); + return Ok(picture); } [EndpointDescription("Add new entity in Picture")] @@ -76,10 +76,10 @@ public async Task Delete([FromRoute] string key) { if (!await _permissionService.AuthorizeAction(PermissionSystemName.Pictures, PermissionActionName.Delete, CurrentCustomer)) return Forbid(); - var picture = await _mediator.Send(new GetGenericQuery(key)); - if (picture == null || !picture.Any()) return NotFound(); + var picture = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (picture == null) return NotFound(); - await _mediator.Send(new DeletePictureCommand { PictureDto = picture.FirstOrDefault() }); + await _mediator.Send(new DeletePictureCommand { PictureDto = picture }); return Ok(); } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Controllers/ProductAttributeController.cs b/src/Modules/Grand.Module.Api/Controllers/ProductAttributeController.cs index 67b4b4b99..fef4132c0 100644 --- a/src/Modules/Grand.Module.Api/Controllers/ProductAttributeController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/ProductAttributeController.cs @@ -36,10 +36,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.ProductAttributes, CurrentCustomer)) return Forbid(); - var productAttribute = await _mediator.Send(new GetGenericQuery(key)); - if (!productAttribute.Any()) return NotFound(); + var productAttribute = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (productAttribute == null) return NotFound(); - return Ok(productAttribute.FirstOrDefault()); + return Ok(productAttribute); } [EndpointDescription("Get entities from ProductAttribute")] @@ -97,10 +97,10 @@ public async Task Patch([FromRoute] string key, [FromBody] JsonPa if (!await _permissionService.AuthorizeAction(PermissionSystemName.ProductAttributes, PermissionActionName.Edit, CurrentCustomer)) return Forbid(); - var productAttribute = await _mediator.Send(new GetGenericQuery(key)); - if (!productAttribute.Any()) return NotFound(); + var productAttribute = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (productAttribute == null) return NotFound(); - var pa = productAttribute.FirstOrDefault(); + var pa = productAttribute; model.ApplyTo(pa); pa = await _mediator.Send(new UpdateProductAttributeCommand { Model = pa }); return Ok(pa); @@ -116,10 +116,10 @@ public async Task Delete([FromRoute] string key) { if (!await _permissionService.AuthorizeAction(PermissionSystemName.ProductAttributes, PermissionActionName.Delete, CurrentCustomer)) return Forbid(); - var productAttribute = await _mediator.Send(new GetGenericQuery(key)); - if (!productAttribute.Any()) return NotFound(); + var productAttribute = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (productAttribute == null) return NotFound(); - await _mediator.Send(new DeleteProductAttributeCommand { Model = productAttribute.FirstOrDefault() }); + await _mediator.Send(new DeleteProductAttributeCommand { Model = productAttribute }); return Ok(); } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Controllers/ProductController.cs b/src/Modules/Grand.Module.Api/Controllers/ProductController.cs index 73b388f0a..13ccce4b5 100644 --- a/src/Modules/Grand.Module.Api/Controllers/ProductController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/ProductController.cs @@ -37,10 +37,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.Products, CurrentCustomer)) return Forbid(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); - return Ok(product.FirstOrDefault()); + return Ok(product); } [EndpointDescription("Get entities from Product")] @@ -98,10 +98,10 @@ public async Task Patch([FromRoute] string key, [FromBody] JsonPa if (string.IsNullOrEmpty(key)) return BadRequest("Key is null or empty"); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); - var pr = product.FirstOrDefault(); + var pr = product; model.ApplyTo(pr); await _mediator.Send(new UpdateProductCommand { Model = pr }); return Ok(); @@ -117,10 +117,10 @@ public async Task Delete([FromRoute] string key) { if (!await _permissionService.AuthorizeAction(PermissionSystemName.Products, PermissionActionName.Delete, CurrentCustomer)) return Forbid(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); - await _mediator.Send(new DeleteProductCommand { Model = product.FirstOrDefault() }); + await _mediator.Send(new DeleteProductCommand { Model = product }); return Ok(); } @@ -138,12 +138,12 @@ public async Task UpdateStock([FromRoute] string key, [FromBody] { if (!await _permissionService.AuthorizeAction(PermissionSystemName.Products, PermissionActionName.Edit, CurrentCustomer)) return Forbid(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); if (model == null) return BadRequest(); - if (!await _mediator.Send(new UpdateProductStockCommand { Product = product.FirstOrDefault(), WarehouseId = model.WarehouseId, Stock = model.Stock })) + if (!await _mediator.Send(new UpdateProductStockCommand { Product = product, WarehouseId = model.WarehouseId, Stock = model.Stock })) return BadRequest(InventoryTracking.StockDocumentsOnlyMessage); return Ok(true); @@ -164,16 +164,16 @@ public async Task CreateProductCategory([FromRoute] string key, [ if (productCategory == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); - var pc = product.FirstOrDefault()!.ProductCategories.FirstOrDefault(x => + var pc = product.ProductCategories.FirstOrDefault(x => x.CategoryId == productCategory.CategoryId); if (pc != null) return BadRequest("Product category mapping found with the specified CategoryId"); if (ModelState.IsValid) { - var result = await _mediator.Send(new AddProductCategoryCommand { Product = product.FirstOrDefault(), Model = productCategory }); + var result = await _mediator.Send(new AddProductCategoryCommand { Product = product, Model = productCategory }); return Ok(result); } @@ -193,16 +193,16 @@ public async Task UpdateProductCategory([FromRoute] string key, [ if (productCategory == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); - var pc = product.FirstOrDefault()!.ProductCategories.FirstOrDefault(x => + var pc = product.ProductCategories.FirstOrDefault(x => x.CategoryId == productCategory.CategoryId); if (pc == null) return BadRequest("No product category mapping found with the specified id"); if (ModelState.IsValid) { - var result = await _mediator.Send(new UpdateProductCategoryCommand { Product = product.FirstOrDefault(), Model = productCategory }); + var result = await _mediator.Send(new UpdateProductCategoryCommand { Product = product, Model = productCategory }); return Ok(result); } @@ -222,18 +222,18 @@ public async Task DeleteProductCategory([FromRoute] string key, [ if (model == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); var categoryId = model.CategoryId; if (!string.IsNullOrEmpty(categoryId)) { - var pc = product.FirstOrDefault()!.ProductCategories.FirstOrDefault(x => x.CategoryId == categoryId); + var pc = product.ProductCategories.FirstOrDefault(x => x.CategoryId == categoryId); if (pc == null) return BadRequest("No product category mapping found with the specified id"); if (ModelState.IsValid) { - _ = await _mediator.Send(new DeleteProductCategoryCommand { Product = product.FirstOrDefault(), CategoryId = categoryId }); + _ = await _mediator.Send(new DeleteProductCategoryCommand { Product = product, CategoryId = categoryId }); return Ok(true); } @@ -260,15 +260,15 @@ public async Task CreateProductCollection([FromRoute] string key, if (productCollection == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); - var pm = product.FirstOrDefault()!.ProductCollections.FirstOrDefault(x => x.CollectionId == productCollection.CollectionId); + var pm = product.ProductCollections.FirstOrDefault(x => x.CollectionId == productCollection.CollectionId); if (pm != null) return BadRequest("Product collection mapping found with the specified CollectionId"); if (ModelState.IsValid) { - var result = await _mediator.Send(new AddProductCollectionCommand { Product = product.FirstOrDefault(), Model = productCollection }); + var result = await _mediator.Send(new AddProductCollectionCommand { Product = product, Model = productCollection }); return Ok(result); } @@ -288,16 +288,16 @@ public async Task UpdateProductCollection([FromRoute] string key, if (productCollection == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); - var pm = product.FirstOrDefault()!.ProductCollections.FirstOrDefault(x => + var pm = product.ProductCollections.FirstOrDefault(x => x.CollectionId == productCollection.CollectionId); if (pm == null) return BadRequest("No product collection mapping found with the specified id"); if (ModelState.IsValid) { - var result = await _mediator.Send(new UpdateProductCollectionCommand { Product = product.FirstOrDefault(), Model = productCollection }); + var result = await _mediator.Send(new UpdateProductCollectionCommand { Product = product, Model = productCollection }); return Ok(result); } @@ -317,18 +317,18 @@ public async Task DeleteProductCollection([FromRoute] string key, if (model == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); var collectionId = model.CollectionId; if (!string.IsNullOrEmpty(collectionId)) { - var pm = product.FirstOrDefault()!.ProductCollections.FirstOrDefault(x => x.CollectionId == collectionId); + var pm = product.ProductCollections.FirstOrDefault(x => x.CollectionId == collectionId); if (pm == null) return BadRequest("No product collection mapping found with the specified id"); if (ModelState.IsValid) { - await _mediator.Send(new DeleteProductCollectionCommand { Product = product.FirstOrDefault(), CollectionId = collectionId }); + await _mediator.Send(new DeleteProductCollectionCommand { Product = product, CollectionId = collectionId }); return Ok(true); } @@ -355,15 +355,15 @@ public async Task CreateProductPicture([FromRoute] string key, [F if (productPicture == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); - var pp = product.FirstOrDefault()!.ProductPictures.FirstOrDefault(x => x.PictureId == productPicture.PictureId); + var pp = product.ProductPictures.FirstOrDefault(x => x.PictureId == productPicture.PictureId); if (pp != null) return BadRequest("Product picture mapping found with the specified pictureid"); if (ModelState.IsValid) { - var result = await _mediator.Send(new AddProductPictureCommand { Product = product.FirstOrDefault(), Model = productPicture }); + var result = await _mediator.Send(new AddProductPictureCommand { Product = product, Model = productPicture }); return Ok(result); } @@ -383,15 +383,15 @@ public async Task UpdateProductPicture([FromRoute] string key, [F if (productPicture == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); - var pp = product.FirstOrDefault()!.ProductPictures.FirstOrDefault(x => x.PictureId == productPicture.PictureId); + var pp = product.ProductPictures.FirstOrDefault(x => x.PictureId == productPicture.PictureId); if (pp == null) return BadRequest("No product picture mapping found with the specified id"); if (ModelState.IsValid) { - var result = await _mediator.Send(new UpdateProductPictureCommand { Product = product.FirstOrDefault(), Model = productPicture }); + var result = await _mediator.Send(new UpdateProductPictureCommand { Product = product, Model = productPicture }); return Ok(result); } @@ -411,18 +411,18 @@ public async Task DeleteProductPicture([FromRoute] string key, [F if (model == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); var pictureId = model.PictureId; if (!string.IsNullOrEmpty(pictureId)) { - var pp = product.FirstOrDefault()!.ProductPictures.FirstOrDefault(x => x.PictureId == pictureId); + var pp = product.ProductPictures.FirstOrDefault(x => x.PictureId == pictureId); if (pp == null) return BadRequest("No product picture mapping found with the specified id"); if (ModelState.IsValid) { - var result = await _mediator.Send(new DeleteProductPictureCommand { Product = product.FirstOrDefault(), PictureId = pictureId }); + var result = await _mediator.Send(new DeleteProductPictureCommand { Product = product, PictureId = pictureId }); return Ok(result); } @@ -449,16 +449,16 @@ public async Task CreateProductSpecification([FromRoute] string k if (productSpecification == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); - var psa = product.FirstOrDefault()!.ProductSpecificationAttributes.FirstOrDefault(x => + var psa = product.ProductSpecificationAttributes.FirstOrDefault(x => x.Id == productSpecification.Id); if (psa != null) return BadRequest("Product specification mapping found with the specified id"); if (ModelState.IsValid) { - var result = await _mediator.Send(new AddProductSpecificationCommand { Product = product.FirstOrDefault(), Model = productSpecification }); + var result = await _mediator.Send(new AddProductSpecificationCommand { Product = product, Model = productSpecification }); return Ok(result); } @@ -478,16 +478,16 @@ public async Task UpdateProductSpecification([FromRoute] string k if (productSpecification == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); - var psa = product.FirstOrDefault()!.ProductSpecificationAttributes.FirstOrDefault(x => + var psa = product.ProductSpecificationAttributes.FirstOrDefault(x => x.Id == productSpecification.Id); if (psa == null) return BadRequest("No product specification mapping found with the specified id"); if (ModelState.IsValid) { - var result = await _mediator.Send(new UpdateProductSpecificationCommand { Product = product.FirstOrDefault(), Model = productSpecification }); + var result = await _mediator.Send(new UpdateProductSpecificationCommand { Product = product, Model = productSpecification }); return Ok(result); } @@ -507,19 +507,19 @@ public async Task DeleteProductSpecification([FromRoute] string k if (model == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); var specificationId = model.Id; if (!string.IsNullOrEmpty(specificationId)) { - var psa = product.FirstOrDefault()!.ProductSpecificationAttributes.FirstOrDefault(x => + var psa = product.ProductSpecificationAttributes.FirstOrDefault(x => x.Id == specificationId); if (psa == null) return BadRequest("No product specification mapping found with the specified id"); if (ModelState.IsValid) { - var result = await _mediator.Send(new DeleteProductSpecificationCommand { Product = product.FirstOrDefault(), Id = specificationId }); + var result = await _mediator.Send(new DeleteProductSpecificationCommand { Product = product, Id = specificationId }); return Ok(result); } @@ -546,15 +546,15 @@ public async Task CreateProductTierPrice([FromRoute] string key, if (productTierPrice == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); - var pt = product.FirstOrDefault()!.TierPrices.FirstOrDefault(x => x.Id == productTierPrice.Id); + var pt = product.TierPrices.FirstOrDefault(x => x.Id == productTierPrice.Id); if (pt != null) return BadRequest("Product tier price mapping found with the specified id"); if (ModelState.IsValid) { - var result = await _mediator.Send(new AddProductTierPriceCommand { Product = product.FirstOrDefault(), Model = productTierPrice }); + var result = await _mediator.Send(new AddProductTierPriceCommand { Product = product, Model = productTierPrice }); return Ok(result); } @@ -574,15 +574,15 @@ public async Task UpdateProductTierPrice([FromRoute] string key, if (productTierPrice == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); - var pt = product.FirstOrDefault()!.TierPrices.FirstOrDefault(x => x.Id == productTierPrice.Id); + var pt = product.TierPrices.FirstOrDefault(x => x.Id == productTierPrice.Id); if (pt == null) return BadRequest("No product tier price mapping found with the specified id"); if (ModelState.IsValid) { - var result = await _mediator.Send(new UpdateProductTierPriceCommand { Product = product.FirstOrDefault(), Model = productTierPrice }); + var result = await _mediator.Send(new UpdateProductTierPriceCommand { Product = product, Model = productTierPrice }); return Ok(result); } @@ -602,18 +602,18 @@ public async Task DeleteProductTierPrice([FromRoute] string key, if (model == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); var tierPriceId = model.Id; if (!string.IsNullOrEmpty(tierPriceId)) { - var pt = product.FirstOrDefault()!.TierPrices.FirstOrDefault(x => x.Id == tierPriceId); + var pt = product.TierPrices.FirstOrDefault(x => x.Id == tierPriceId); if (pt == null) return BadRequest("No product tier price mapping found with the specified id"); if (ModelState.IsValid) { - var result = await _mediator.Send(new DeleteProductTierPriceCommand { Product = product.FirstOrDefault(), Id = tierPriceId }); + var result = await _mediator.Send(new DeleteProductTierPriceCommand { Product = product, Id = tierPriceId }); return Ok(result); } @@ -640,16 +640,16 @@ public async Task CreateProductAttributeMapping([FromRoute] strin if (productAttributeMapping == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); - var pam = product.FirstOrDefault()!.ProductAttributeMappings.FirstOrDefault(x => + var pam = product.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMapping.Id); if (pam != null) return BadRequest("Product attribute mapping found with the specified id"); if (ModelState.IsValid) { - var result = await _mediator.Send(new AddProductAttributeMappingCommand { Product = product.FirstOrDefault(), Model = productAttributeMapping }); + var result = await _mediator.Send(new AddProductAttributeMappingCommand { Product = product, Model = productAttributeMapping }); return Ok(result); } @@ -669,16 +669,16 @@ public async Task UpdateProductAttributeMapping([FromRoute] strin if (productAttributeMapping == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); - var pam = product.FirstOrDefault()!.ProductAttributeMappings.FirstOrDefault(x => + var pam = product.ProductAttributeMappings.FirstOrDefault(x => x.Id == productAttributeMapping.Id); if (pam == null) return BadRequest("No product attribute mapping found with the specified id"); if (ModelState.IsValid) { - var result = await _mediator.Send(new UpdateProductAttributeMappingCommand { Product = product.FirstOrDefault(), Model = productAttributeMapping }); + var result = await _mediator.Send(new UpdateProductAttributeMappingCommand { Product = product, Model = productAttributeMapping }); return Ok(result); } @@ -698,18 +698,18 @@ public async Task DeleteProductAttributeMapping([FromRoute] strin if (model == null) return BadRequest(); - var product = await _mediator.Send(new GetGenericQuery(key)); - if (!product.Any()) return NotFound(); + var product = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (product == null) return NotFound(); var attrId = model.Id; if (string.IsNullOrEmpty(attrId)) return NotFound(); - var pam = product.FirstOrDefault()!.ProductAttributeMappings.FirstOrDefault(x => x.Id == attrId); + var pam = product.ProductAttributeMappings.FirstOrDefault(x => x.Id == attrId); if (pam == null) return BadRequest("No product attribute mapping found with the specified id"); if (!ModelState.IsValid) return BadRequest(ModelState); - var result = await _mediator.Send(new DeleteProductAttributeMappingCommand { Product = product.FirstOrDefault(), Model = pam }); + var result = await _mediator.Send(new DeleteProductAttributeMappingCommand { Product = product, Model = pam }); return Ok(result); } diff --git a/src/Modules/Grand.Module.Api/Controllers/ProductLayoutController.cs b/src/Modules/Grand.Module.Api/Controllers/ProductLayoutController.cs index ed24c8554..a9fa0cf60 100644 --- a/src/Modules/Grand.Module.Api/Controllers/ProductLayoutController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/ProductLayoutController.cs @@ -35,10 +35,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.Maintenance, CurrentCustomer)) return Forbid(); - var layout = await _mediator.Send(new GetGenericQuery(key)); - if (!layout.Any()) return NotFound(); + var layout = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (layout == null) return NotFound(); - return Ok(layout.FirstOrDefault()); + return Ok(layout); } [EndpointDescription("Get entities from ProductTemplate")] diff --git a/src/Modules/Grand.Module.Api/Controllers/ShippingMethodController.cs b/src/Modules/Grand.Module.Api/Controllers/ShippingMethodController.cs index 6a041b434..2da69e56e 100644 --- a/src/Modules/Grand.Module.Api/Controllers/ShippingMethodController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/ShippingMethodController.cs @@ -32,10 +32,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings, CurrentCustomer)) return Forbid(); - var shipping = await _mediator.Send(new GetGenericQuery(key)); - if (!shipping.Any()) return NotFound(); + var shipping = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (shipping == null) return NotFound(); - return Ok(shipping.FirstOrDefault()); + return Ok(shipping); } [EndpointDescription("Get entities from ShippingMethod")] diff --git a/src/Modules/Grand.Module.Api/Controllers/SpecificationAttributeController.cs b/src/Modules/Grand.Module.Api/Controllers/SpecificationAttributeController.cs index 63f13ad3a..6081b66b2 100644 --- a/src/Modules/Grand.Module.Api/Controllers/SpecificationAttributeController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/SpecificationAttributeController.cs @@ -34,10 +34,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.SpecificationAttributes, CurrentCustomer)) return Forbid(); - var specificationAttribute = await _mediator.Send(new GetGenericQuery(key)); - if (!specificationAttribute.Any()) return NotFound(); + var specificationAttribute = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (specificationAttribute == null) return NotFound(); - return Ok(specificationAttribute.FirstOrDefault()); + return Ok(specificationAttribute); } [EndpointDescription("Get entities from SpecificationAttribute")] @@ -95,10 +95,10 @@ public async Task Patch([FromRoute] string key, [FromBody] JsonPa if (!await _permissionService.AuthorizeAction(PermissionSystemName.SpecificationAttributes, PermissionActionName.Edit, CurrentCustomer)) return Forbid(); - var specification = await _mediator.Send(new GetGenericQuery(key)); - if (!specification.Any()) return NotFound(); + var specification = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (specification == null) return NotFound(); - var spec = specification.FirstOrDefault(); + var spec = specification; model.ApplyTo(spec); await _mediator.Send(new UpdateSpecificationAttributeCommand { Model = spec }); return Ok(); @@ -115,10 +115,10 @@ public async Task Delete([FromRoute] string key) if (!await _permissionService.AuthorizeAction(PermissionSystemName.SpecificationAttributes, PermissionActionName.Delete, CurrentCustomer)) return Forbid(); var specification = - await _mediator.Send(new GetGenericQuery(key)); - if (!specification.Any()) return NotFound(); + (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (specification == null) return NotFound(); - await _mediator.Send(new DeleteSpecificationAttributeCommand { Model = specification.FirstOrDefault() }); + await _mediator.Send(new DeleteSpecificationAttributeCommand { Model = specification }); return Ok(); } diff --git a/src/Modules/Grand.Module.Api/Controllers/StockController.cs b/src/Modules/Grand.Module.Api/Controllers/StockController.cs index 83ce3bc92..a7b7a310b 100644 --- a/src/Modules/Grand.Module.Api/Controllers/StockController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/StockController.cs @@ -53,8 +53,8 @@ public async Task Apply([FromBody] StockApplyRequestDto model) [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(StockJournalResultDto))] [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task Journal([FromQuery] string after, [FromQuery] int take = 100, - [FromQuery] string warehouseId = null, [FromQuery] string warehouseCode = null, - [FromQuery] string movementTypes = null, [FromQuery] bool excludeOwn = false) + [FromQuery] string? warehouseId = null, [FromQuery] string? warehouseCode = null, + [FromQuery] string? movementTypes = null, [FromQuery] bool excludeOwn = false) { if (!await _permissionService.Authorize(PermissionSystemName.StockIntegration, CurrentCustomer)) return Forbid(); diff --git a/src/Modules/Grand.Module.Api/Controllers/StoreController.cs b/src/Modules/Grand.Module.Api/Controllers/StoreController.cs index b1317f97f..666efe837 100644 --- a/src/Modules/Grand.Module.Api/Controllers/StoreController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/StoreController.cs @@ -32,10 +32,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.Stores, CurrentCustomer)) return Forbid(); - var store = await _mediator.Send(new GetGenericQuery(key)); - if (!store.Any()) return NotFound(); + var store = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (store == null) return NotFound(); - return Ok(store.FirstOrDefault()); + return Ok(store); } [EndpointDescription("Get entities from Store")] diff --git a/src/Modules/Grand.Module.Api/Controllers/TokenController.cs b/src/Modules/Grand.Module.Api/Controllers/TokenController.cs index 92bda40ca..03f0ffd61 100644 --- a/src/Modules/Grand.Module.Api/Controllers/TokenController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/TokenController.cs @@ -32,7 +32,7 @@ public async Task Create([FromBody] LoginModel model) if (!ModelState.IsValid) return BadRequest(ModelState); - var claims = new Dictionary { + var claims = new Dictionary { { "Email", model.Email } }; var user = await _userApiService.GetUserByEmail(model.Email); diff --git a/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs b/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs index 04e3fae8e..c15a9bd22 100644 --- a/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/TokenWebController.cs @@ -65,7 +65,7 @@ public async Task Guest() customer = await _customerService.InsertGuestCustomer(customer); - var claims = new Dictionary { + var claims = new Dictionary { { "Guid", customer.CustomerGuid.ToString() } }; @@ -83,8 +83,9 @@ public async Task Login([FromBody] LoginWebModel model) try { - var customer = await _customerService.GetCustomerByEmail(model.Email, _contextAccessor.StoreContext.CurrentStore.Id); - var claims = new Dictionary { + var customer = await _customerService.GetCustomerByEmail(model.Email, _contextAccessor.StoreContext.CurrentStore.Id) ?? + throw new ArgumentException("No customer has the e-mail", nameof(model)); + var claims = new Dictionary { { "CustomerId", customer.Id }, { "Email", model.Email }, { "Token", customer.GetUserFieldFromEntity(SystemCustomerFieldNames.PasswordToken) } @@ -106,15 +107,15 @@ public async Task Refresh([FromBody] TokenDto tokenDto) if (!_apiConfig.Enabled) return BadRequest("API is disabled"); - Customer customer = null; - var claims = new Dictionary(); + Customer? customer = null; + var claims = new Dictionary(); ClaimsPrincipal principal; - string customerId; - string email; - string guid; + string? customerId; + string? email; + string? guid; try { - principal = _refreshTokenService.GetPrincipalFromToken(tokenDto.AccessToken); + principal = _refreshTokenService.GetPrincipalFromToken(tokenDto.AccessToken ?? ""); customerId = principal.Claims.FirstOrDefault(x => x.Type == "CustomerId")?.Value; email = principal.Claims.FirstOrDefault(x => x.Type == "Email")?.Value; guid = principal.Claims.FirstOrDefault(x => x.Type == "Guid")?.Value; @@ -155,7 +156,7 @@ public async Task Refresh([FromBody] TokenDto tokenDto) } var customerRefreshToken = await _refreshTokenService.GetCustomerRefreshToken(customer); - if (customerRefreshToken is null || !customerRefreshToken.Token.Equals(tokenDto.RefreshToken)) + if (customerRefreshToken is null || !string.Equals(customerRefreshToken.Token, tokenDto.RefreshToken)) return BadRequest("Invalid refresh token"); if (customerRefreshToken.ValidTo.CompareTo(DateTime.UtcNow) < 0) return BadRequest("Token expired"); @@ -174,7 +175,7 @@ public IActionResult Antiforgery() return Ok(token); } - private async Task GetToken(Dictionary claims, Customer customer) + private async Task GetToken(Dictionary claims, Customer customer) { var refreshTokenValue = _refreshTokenService.GenerateRefreshToken(); var refreshToken = await _refreshTokenService.SaveRefreshTokenToCustomer(customer, refreshTokenValue); diff --git a/src/Modules/Grand.Module.Api/Controllers/VendorController.cs b/src/Modules/Grand.Module.Api/Controllers/VendorController.cs index b79eb44bb..6a818ff6d 100644 --- a/src/Modules/Grand.Module.Api/Controllers/VendorController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/VendorController.cs @@ -32,10 +32,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.Vendors, CurrentCustomer)) return Forbid(); - var vendor = await _mediator.Send(new GetGenericQuery(key)); - if (!vendor.Any()) return NotFound(); + var vendor = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (vendor == null) return NotFound(); - return Ok(vendor.FirstOrDefault()); + return Ok(vendor); } [EndpointDescription("Get entities from Vendor")] diff --git a/src/Modules/Grand.Module.Api/Controllers/WarehouseController.cs b/src/Modules/Grand.Module.Api/Controllers/WarehouseController.cs index 07bbeee56..e7776d839 100644 --- a/src/Modules/Grand.Module.Api/Controllers/WarehouseController.cs +++ b/src/Modules/Grand.Module.Api/Controllers/WarehouseController.cs @@ -32,10 +32,10 @@ public async Task Get([FromRoute] string key) { if (!await _permissionService.Authorize(PermissionSystemName.ShippingSettings, CurrentCustomer)) return Forbid(); - var warehouse = await _mediator.Send(new GetGenericQuery(key)); - if (!warehouse.Any()) return NotFound(); + var warehouse = (await _mediator.Send(new GetGenericQuery(key))).FirstOrDefault(); + if (warehouse == null) return NotFound(); - return Ok(warehouse.FirstOrDefault()); + return Ok(warehouse); } [EndpointDescription("Get entities from Warehouse")] diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/BrandDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/BrandDto.cs index 3a9d8057d..c55667346 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/BrandDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/BrandDto.cs @@ -5,27 +5,27 @@ namespace Grand.Module.Api.DTOs.Catalog; public class BrandDto : BaseApiEntityModel { - public string Name { get; set; } - public string SeName { get; set; } + public string? Name { get; set; } + public string? SeName { get; set; } [SanitizeHtml] - public string Description { get; set; } + public string? Description { get; set; } [SanitizeHtml] - public string BottomDescription { get; set; } - public string BrandLayoutId { get; set; } + public string? BottomDescription { get; set; } + public string? BrandLayoutId { get; set; } [NoHtml] - public string MetaKeywords { get; set; } + public string? MetaKeywords { get; set; } [NoHtml] - public string MetaDescription { get; set; } + public string? MetaDescription { get; set; } [NoHtml] - public string MetaTitle { get; set; } - public string PictureId { get; set; } + public string? MetaTitle { get; set; } + public string? PictureId { get; set; } public int PageSize { get; set; } public bool AllowCustomersToSelectPageSize { get; set; } - public string PageSizeOptions { get; set; } + public string? PageSizeOptions { get; set; } public bool ShowOnHomePage { get; set; } public bool IncludeInMenu { get; set; } - public string Icon { get; set; } + public string? Icon { get; set; } public bool Published { get; set; } - public string ExternalId { get; set; } + public string? ExternalId { get; set; } public int DisplayOrder { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/CategoryDTO.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/CategoryDTO.cs index f66a0b157..3bb506b02 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/CategoryDTO.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/CategoryDTO.cs @@ -5,33 +5,33 @@ namespace Grand.Module.Api.DTOs.Catalog; public class CategoryDto : BaseApiEntityModel { - public string Name { get; set; } + public string? Name { get; set; } [SanitizeHtml] - public string Description { get; set; } + public string? Description { get; set; } [SanitizeHtml] - public string BottomDescription { get; set; } - public string CategoryLayoutId { get; set; } + public string? BottomDescription { get; set; } + public string? CategoryLayoutId { get; set; } [NoHtml] - public string MetaKeywords { get; set; } + public string? MetaKeywords { get; set; } [NoHtml] - public string MetaDescription { get; set; } + public string? MetaDescription { get; set; } [NoHtml] - public string MetaTitle { get; set; } - public string SeName { get; set; } - public string ParentCategoryId { get; set; } - public string PictureId { get; set; } + public string? MetaTitle { get; set; } + public string? SeName { get; set; } + public string? ParentCategoryId { get; set; } + public string? PictureId { get; set; } public int PageSize { get; set; } public bool AllowCustomersToSelectPageSize { get; set; } - public string PageSizeOptions { get; set; } + public string? PageSizeOptions { get; set; } public bool ShowOnHomePage { get; set; } public bool FeaturedProductsOnHomePage { get; set; } public bool IncludeInMenu { get; set; } public bool Published { get; set; } public int DisplayOrder { get; set; } - public string ExternalId { get; set; } - public string Flag { get; set; } - public string FlagStyle { get; set; } - public string Icon { get; set; } + public string? ExternalId { get; set; } + public string? Flag { get; set; } + public string? FlagStyle { get; set; } + public string? Icon { get; set; } public bool HideOnCatalog { get; set; } public bool ShowOnSearchBox { get; set; } public int SearchBoxDisplayOrder { get; set; } diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/CollectionDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/CollectionDto.cs index 7a9ae94f7..4a46f3407 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/CollectionDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/CollectionDto.cs @@ -5,28 +5,28 @@ namespace Grand.Module.Api.DTOs.Catalog; public class CollectionDto : BaseApiEntityModel { - public string Name { get; set; } - public string SeName { get; set; } + public string? Name { get; set; } + public string? SeName { get; set; } [SanitizeHtml] - public string Description { get; set; } + public string? Description { get; set; } [SanitizeHtml] - public string BottomDescription { get; set; } - public string CollectionLayoutId { get; set; } + public string? BottomDescription { get; set; } + public string? CollectionLayoutId { get; set; } [NoHtml] - public string MetaKeywords { get; set; } + public string? MetaKeywords { get; set; } [NoHtml] - public string MetaDescription { get; set; } + public string? MetaDescription { get; set; } [NoHtml] - public string MetaTitle { get; set; } - public string PictureId { get; set; } + public string? MetaTitle { get; set; } + public string? PictureId { get; set; } public int PageSize { get; set; } public bool AllowCustomersToSelectPageSize { get; set; } - public string PageSizeOptions { get; set; } + public string? PageSizeOptions { get; set; } public bool ShowOnHomePage { get; set; } public bool FeaturedProductsOnHomePage { get; set; } public bool IncludeInMenu { get; set; } - public string Icon { get; set; } + public string? Icon { get; set; } public bool Published { get; set; } - public string ExternalId { get; set; } + public string? ExternalId { get; set; } public int DisplayOrder { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductAttributeCombinationDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductAttributeCombinationDto.cs index baffa4af4..09f0d3617 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductAttributeCombinationDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductAttributeCombinationDto.cs @@ -7,11 +7,11 @@ public class ProductAttributeCombinationDto : BaseApiEntityModel public int StockQuantity { get; set; } public int ReservedQuantity { get; set; } public bool AllowOutOfStockOrders { get; set; } - public string Text { get; set; } - public string Sku { get; set; } - public string Mpn { get; set; } - public string Gtin { get; set; } + public string? Text { get; set; } + public string? Sku { get; set; } + public string? Mpn { get; set; } + public string? Gtin { get; set; } public double? OverriddenPrice { get; set; } public int NotifyAdminForQuantityBelow { get; set; } - public string PictureId { get; set; } + public string? PictureId { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductAttributeDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductAttributeDto.cs index f9436ca70..6d5b32123 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductAttributeDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductAttributeDto.cs @@ -5,9 +5,9 @@ namespace Grand.Module.Api.DTOs.Catalog; public class ProductAttributeDto : BaseApiEntityModel { - public string Name { get; set; } + public string? Name { get; set; } [SanitizeHtml] - public string Description { get; set; } + public string? Description { get; set; } public IList PredefinedProductAttributeValues { get; set; } = new List(); @@ -15,7 +15,7 @@ public class ProductAttributeDto : BaseApiEntityModel public class PredefinedProductAttributeValueDto : BaseApiEntityModel { - public string Name { get; set; } + public string? Name { get; set; } public double PriceAdjustment { get; set; } public double WeightAdjustment { get; set; } public double Cost { get; set; } diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductAttributeMappingDeleteDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductAttributeMappingDeleteDto.cs index cded6626b..59f36b5c0 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductAttributeMappingDeleteDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductAttributeMappingDeleteDto.cs @@ -2,5 +2,5 @@ public class ProductAttributeMappingDeleteDto { - public string Id { get; set; } + public string? Id { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductAttributeMappingDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductAttributeMappingDto.cs index 57c034ba4..7aaf15391 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductAttributeMappingDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductAttributeMappingDto.cs @@ -5,16 +5,16 @@ namespace Grand.Module.Api.DTOs.Catalog; public class ProductAttributeMappingDto : BaseApiEntityModel { - public string ProductAttributeId { get; set; } - public string TextPrompt { get; set; } + public string? ProductAttributeId { get; set; } + public string? TextPrompt { get; set; } public bool IsRequired { get; set; } public int DisplayOrder { get; set; } public int? ValidationMinLength { get; set; } public int? ValidationMaxLength { get; set; } - public string ValidationFileAllowedExtensions { get; set; } + public string? ValidationFileAllowedExtensions { get; set; } public int? ValidationFileMaximumSize { get; set; } - public string DefaultValue { get; set; } - public string ConditionAttributeXml { get; set; } + public string? DefaultValue { get; set; } + public string? ConditionAttributeXml { get; set; } public AttributeControlType AttributeControlTypeId { get; set; } public IList ProductAttributeValues { get; set; } = new List(); @@ -22,16 +22,16 @@ public class ProductAttributeMappingDto : BaseApiEntityModel public class ProductAttributeValueDto : BaseApiEntityModel { - public string AssociatedProductId { get; set; } - public string Name { get; set; } - public string ColorSquaresRgb { get; set; } - public string ImageSquaresPictureId { get; set; } + public string? AssociatedProductId { get; set; } + public string? Name { get; set; } + public string? ColorSquaresRgb { get; set; } + public string? ImageSquaresPictureId { get; set; } public double PriceAdjustment { get; set; } public double WeightAdjustment { get; set; } public double Cost { get; set; } public int Quantity { get; set; } public bool IsPreSelected { get; set; } public int DisplayOrder { get; set; } - public string PictureId { get; set; } + public string? PictureId { get; set; } public AttributeValueType AttributeValueTypeId { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductCategoryDeleteDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductCategoryDeleteDto.cs index 802bbb53a..fff91a796 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductCategoryDeleteDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductCategoryDeleteDto.cs @@ -2,5 +2,5 @@ public class ProductCategoryDeleteDto { - public string CategoryId { get; set; } + public string? CategoryId { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductCategoryDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductCategoryDto.cs index cedaebc74..b48903226 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductCategoryDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductCategoryDto.cs @@ -4,7 +4,7 @@ namespace Grand.Module.Api.DTOs.Catalog; public class ProductCategoryDto { - [Key] public string CategoryId { get; set; } + [Key] public string? CategoryId { get; set; } public bool IsFeaturedProduct { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductCollectionDeleteDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductCollectionDeleteDto.cs index b44a3d498..85e4d7294 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductCollectionDeleteDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductCollectionDeleteDto.cs @@ -2,5 +2,5 @@ public class ProductCollectionDeleteDto { - public string CollectionId { get; set; } + public string? CollectionId { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductCollectionDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductCollectionDto.cs index 25eefd2dd..e606e1543 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductCollectionDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductCollectionDto.cs @@ -4,7 +4,7 @@ namespace Grand.Module.Api.DTOs.Catalog; public class ProductCollectionDto { - [Key] public string CollectionId { get; set; } + [Key] public string? CollectionId { get; set; } public bool IsFeaturedProduct { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductDto.cs index 595de72d8..84439b7c2 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductDto.cs @@ -7,52 +7,52 @@ namespace Grand.Module.Api.DTOs.Catalog; public class ProductDto : BaseApiEntityModel { public ProductType ProductTypeId { get; set; } - public string ParentGroupedProductId { get; set; } + public string? ParentGroupedProductId { get; set; } public bool VisibleIndividually { get; set; } - public string Name { get; set; } - public string SeName { get; set; } + public string? Name { get; set; } + public string? SeName { get; set; } [SanitizeHtml] - public string ShortDescription { get; set; } + public string? ShortDescription { get; set; } [SanitizeHtml] - public string FullDescription { get; set; } + public string? FullDescription { get; set; } [NoHtml] - public string AdminComment { get; set; } - public string ProductLayoutId { get; set; } - public string BrandId { get; set; } - public string VendorId { get; set; } + public string? AdminComment { get; set; } + public string? ProductLayoutId { get; set; } + public string? BrandId { get; set; } + public string? VendorId { get; set; } public bool ShowOnHomePage { get; set; } [NoHtml] - public string MetaKeywords { get; set; } + public string? MetaKeywords { get; set; } [NoHtml] - public string MetaDescription { get; set; } + public string? MetaDescription { get; set; } [NoHtml] - public string MetaTitle { get; set; } + public string? MetaTitle { get; set; } public bool AllowCustomerReviews { get; set; } public int ApprovedRatingSum { get; set; } public int NotApprovedRatingSum { get; set; } public int ApprovedTotalReviews { get; set; } public int NotApprovedTotalReviews { get; set; } - public string ExternalId { get; set; } - public string Sku { get; set; } - public string Mpn { get; set; } - public string Gtin { get; set; } + public string? ExternalId { get; set; } + public string? Sku { get; set; } + public string? Mpn { get; set; } + public string? Gtin { get; set; } public bool IsGiftVoucher { get; set; } public GiftVoucherType GiftVoucherTypeId { get; set; } public double? OverGiftAmount { get; set; } public bool RequireOtherProducts { get; set; } - public string RequiredProductIds { get; set; } + public string? RequiredProductIds { get; set; } public bool AutoAddRequiredProducts { get; set; } public bool IsDownload { get; set; } - public string DownloadId { get; set; } + public string? DownloadId { get; set; } public bool UnlimitedDownloads { get; set; } public DownloadActivationType DownloadActivationTypeId { get; set; } public int MaxNumberOfDownloads { get; set; } public int? DownloadExpirationDays { get; set; } public bool HasSampleDownload { get; set; } - public string SampleDownloadId { get; set; } + public string? SampleDownloadId { get; set; } public bool HasUserAgreement { get; set; } [SanitizeHtml] - public string UserAgreementText { get; set; } + public string? UserAgreementText { get; set; } public bool IsRecurring { get; set; } public int RecurringCycleLength { get; set; } public int RecurringTotalCycles { get; set; } @@ -64,12 +64,12 @@ public class ProductDto : BaseApiEntityModel public bool IsFreeShipping { get; set; } public bool ShipSeparately { get; set; } public double AdditionalShippingCharge { get; set; } - public string DeliveryDateId { get; set; } + public string? DeliveryDateId { get; set; } public bool IsTaxExempt { get; set; } - public string TaxCategoryId { get; set; } + public string? TaxCategoryId { get; set; } public bool IsTele { get; set; } public bool UseMultipleWarehouses { get; set; } - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } public int StockQuantity { get; set; } public int ReservedQuantity { get; set; } public ManageInventoryMethod ManageInventoryMethodId { get; set; } @@ -83,7 +83,7 @@ public class ProductDto : BaseApiEntityModel public bool AllowOutOfStockSubscriptions { get; set; } public int OrderMinimumQuantity { get; set; } public int OrderMaximumQuantity { get; set; } - public string AllowedQuantities { get; set; } + public string? AllowedQuantities { get; set; } public bool NotReturnable { get; set; } public bool DisableBuyButton { get; set; } public bool DisableWishlistButton { get; set; } @@ -99,10 +99,10 @@ public class ProductDto : BaseApiEntityModel public double MaxEnteredPrice { get; set; } public bool BasepriceEnabled { get; set; } public double BasepriceAmount { get; set; } - public string BasepriceUnitId { get; set; } + public string? BasepriceUnitId { get; set; } public double BasepriceBaseAmount { get; set; } - public string BasepriceBaseUnitId { get; set; } - public string UnitId { get; set; } + public string? BasepriceBaseUnitId { get; set; } + public string? UnitId { get; set; } public bool MarkAsNew { get; set; } public DateTime? MarkAsNewStartDateTimeUtc { get; set; } public DateTime? MarkAsNewEndDateTimeUtc { get; set; } @@ -122,7 +122,7 @@ public class ProductDto : BaseApiEntityModel public int Sold { get; set; } public long Viewed { get; set; } public int OnSale { get; set; } - public string Flag { get; set; } + public string? Flag { get; set; } public IList ProductCategories { get; set; } = new List(); public IList ProductCollections { get; set; } = new List(); public IList ProductPictures { get; set; } = new List(); diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductPictureDeleteDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductPictureDeleteDto.cs index ceb8e98cb..0a98f0fbc 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductPictureDeleteDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductPictureDeleteDto.cs @@ -2,5 +2,5 @@ public class ProductPictureDeleteDto { - public string PictureId { get; set; } + public string? PictureId { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductPictureDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductPictureDto.cs index 7798e2d55..9543ac131 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductPictureDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductPictureDto.cs @@ -4,7 +4,7 @@ namespace Grand.Module.Api.DTOs.Catalog; public class ProductPictureDto { - [Key] public string PictureId { get; set; } + [Key] public string? PictureId { get; set; } public int DisplayOrder { get; set; } diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductSpecificationAttributeDeleteDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductSpecificationAttributeDeleteDto.cs index a217e4630..202d5ecfb 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductSpecificationAttributeDeleteDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductSpecificationAttributeDeleteDto.cs @@ -2,5 +2,5 @@ public class ProductSpecificationAttributeDeleteDto { - public string Id { get; set; } + public string? Id { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductSpecificationAttributeDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductSpecificationAttributeDto.cs index 6dcb60884..a5176ea4c 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductSpecificationAttributeDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductSpecificationAttributeDto.cs @@ -5,10 +5,10 @@ namespace Grand.Module.Api.DTOs.Catalog; public class ProductSpecificationAttributeDto : BaseApiEntityModel { - public string SpecificationAttributeId { get; set; } - public string SpecificationAttributeOptionId { get; set; } - public string CustomName { get; set; } - public string CustomValue { get; set; } + public string? SpecificationAttributeId { get; set; } + public string? SpecificationAttributeOptionId { get; set; } + public string? CustomName { get; set; } + public string? CustomValue { get; set; } public bool AllowFiltering { get; set; } public bool ShowOnProductPage { get; set; } public int DisplayOrder { get; set; } diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductTierPriceDeleteDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductTierPriceDeleteDto.cs index a3a70dc5a..db9f18ed6 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductTierPriceDeleteDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductTierPriceDeleteDto.cs @@ -2,5 +2,5 @@ public class ProductTierPriceDeleteDto { - public string Id { get; set; } + public string? Id { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductTierPriceDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductTierPriceDto.cs index 95d61fb6a..fd999fbc9 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductTierPriceDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductTierPriceDto.cs @@ -4,8 +4,8 @@ namespace Grand.Module.Api.DTOs.Catalog; public class ProductTierPriceDto : BaseApiEntityModel { - public string StoreId { get; set; } - public string CustomerGroupId { get; set; } + public string? StoreId { get; set; } + public string? CustomerGroupId { get; set; } public int Quantity { get; set; } public double Price { get; set; } public DateTime? StartDateTimeUtc { get; set; } diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductUpdateStock.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductUpdateStock.cs index 55c089c00..a72004b64 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductUpdateStock.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductUpdateStock.cs @@ -2,6 +2,6 @@ public class ProductUpdateStock { - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } public int Stock { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductWarehouseInventoryDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductWarehouseInventoryDto.cs index f6ee484db..1303f2952 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductWarehouseInventoryDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/ProductWarehouseInventoryDto.cs @@ -4,7 +4,7 @@ namespace Grand.Module.Api.DTOs.Catalog; public class ProductWarehouseInventoryDto : BaseApiEntityModel { - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } public int StockQuantity { get; set; } public int ReservedQuantity { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Catalog/SpecificationAttributeDto.cs b/src/Modules/Grand.Module.Api/DTOs/Catalog/SpecificationAttributeDto.cs index e1d9c93c2..86c05a6da 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Catalog/SpecificationAttributeDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Catalog/SpecificationAttributeDto.cs @@ -4,7 +4,7 @@ namespace Grand.Module.Api.DTOs.Catalog; public class SpecificationAttributeDto : BaseApiEntityModel { - public string Name { get; set; } + public string? Name { get; set; } public int DisplayOrder { get; set; } public IList SpecificationAttributeOptions { get; set; } = @@ -13,7 +13,7 @@ public class SpecificationAttributeDto : BaseApiEntityModel public class SpecificationAttributeOptionDto : BaseApiEntityModel { - public string Name { get; set; } + public string? Name { get; set; } public int DisplayOrder { get; set; } - public string ColorSquaresRgb { get; set; } + public string? ColorSquaresRgb { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Common/CountryDto.cs b/src/Modules/Grand.Module.Api/DTOs/Common/CountryDto.cs index e0eb11621..e448af87d 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Common/CountryDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Common/CountryDto.cs @@ -4,13 +4,13 @@ namespace Grand.Module.Api.DTOs.Common; public class CountryDto : BaseApiEntityModel { - private ICollection _stateProvinces; + private ICollection? _stateProvinces; - public string Name { get; set; } + public string? Name { get; set; } public bool AllowsBilling { get; set; } public bool AllowsShipping { get; set; } - public string TwoLetterIsoCode { get; set; } - public string ThreeLetterIsoCode { get; set; } + public string? TwoLetterIsoCode { get; set; } + public string? ThreeLetterIsoCode { get; set; } public int NumericIsoCode { get; set; } public bool SubjectToVat { get; set; } public bool Published { get; set; } @@ -23,8 +23,8 @@ public virtual ICollection StateProvinces { public class StateProvinceDto { - public string Name { get; set; } - public string Abbreviation { get; set; } + public string? Name { get; set; } + public string? Abbreviation { get; set; } public bool Published { get; set; } public int DisplayOrder { get; set; } } diff --git a/src/Modules/Grand.Module.Api/DTOs/Common/CurrencyDto.cs b/src/Modules/Grand.Module.Api/DTOs/Common/CurrencyDto.cs index 5e9bb6497..3676d7845 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Common/CurrencyDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Common/CurrencyDto.cs @@ -4,11 +4,11 @@ namespace Grand.Module.Api.DTOs.Common; public class CurrencyDto : BaseApiEntityModel { - public string Name { get; set; } - public string CurrencyCode { get; set; } + public string? Name { get; set; } + public string? CurrencyCode { get; set; } public double Rate { get; set; } - public string DisplayLocale { get; set; } - public string CustomFormatting { get; set; } + public string? DisplayLocale { get; set; } + public string? CustomFormatting { get; set; } public bool Published { get; set; } public int DisplayOrder { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Common/LanguageDto.cs b/src/Modules/Grand.Module.Api/DTOs/Common/LanguageDto.cs index ae5d72659..6d39d88bf 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Common/LanguageDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Common/LanguageDto.cs @@ -4,12 +4,12 @@ namespace Grand.Module.Api.DTOs.Common; public class LanguageDto : BaseApiEntityModel { - public string Name { get; set; } - public string LanguageCulture { get; set; } - public string UniqueSeoCode { get; set; } - public string FlagImageFileName { get; set; } + public string? Name { get; set; } + public string? LanguageCulture { get; set; } + public string? UniqueSeoCode { get; set; } + public string? FlagImageFileName { get; set; } public bool Rtl { get; set; } - public string DefaultCurrencyId { get; set; } + public string? DefaultCurrencyId { get; set; } public bool Published { get; set; } public int DisplayOrder { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Common/LayoutDto.cs b/src/Modules/Grand.Module.Api/DTOs/Common/LayoutDto.cs index ab01a309d..2c71af930 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Common/LayoutDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Common/LayoutDto.cs @@ -4,7 +4,7 @@ namespace Grand.Module.Api.DTOs.Common; public class LayoutDto : BaseApiEntityModel { - public string Name { get; set; } + public string? Name { get; set; } public int DisplayOrder { get; set; } - public string ViewPath { get; set; } + public string? ViewPath { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Common/PictureDto.cs b/src/Modules/Grand.Module.Api/DTOs/Common/PictureDto.cs index 23ecfd7e1..dbe246773 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Common/PictureDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Common/PictureDto.cs @@ -5,14 +5,14 @@ namespace Grand.Module.Api.DTOs.Common; public class PictureDto : BaseApiEntityModel { - public byte[] PictureBinary { get; set; } - public string MimeType { get; set; } - public string SeoFilename { get; set; } - public string AltAttribute { get; set; } - public string TitleAttribute { get; set; } + public byte[]? PictureBinary { get; set; } + public string? MimeType { get; set; } + public string? SeoFilename { get; set; } + public string? AltAttribute { get; set; } + public string? TitleAttribute { get; set; } public Reference Reference { get; set; } - public string ObjectId { get; set; } - public string Style { get; set; } - public string ExtraField { get; set; } + public string? ObjectId { get; set; } + public string? Style { get; set; } + public string? ExtraField { get; set; } public bool IsNew { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Common/StoreDto.cs b/src/Modules/Grand.Module.Api/DTOs/Common/StoreDto.cs index e939ccc4b..f929b5119 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Common/StoreDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Common/StoreDto.cs @@ -4,15 +4,15 @@ namespace Grand.Module.Api.DTOs.Common; public class StoreDto : BaseApiEntityModel { - public string Name { get; set; } - public string Url { get; set; } - public string Hosts { get; set; } - public string DefaultLanguageId { get; set; } - public string DefaultWarehouseId { get; set; } + public string? Name { get; set; } + public string? Url { get; set; } + public string? Hosts { get; set; } + public string? DefaultLanguageId { get; set; } + public string? DefaultWarehouseId { get; set; } public int DisplayOrder { get; set; } - public string CompanyName { get; set; } - public string CompanyAddress { get; set; } - public string CompanyPhoneNumber { get; set; } - public string CompanyRegNo { get; set; } - public string CompanyVat { get; set; } + public string? CompanyName { get; set; } + public string? CompanyAddress { get; set; } + public string? CompanyPhoneNumber { get; set; } + public string? CompanyRegNo { get; set; } + public string? CompanyVat { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Customers/AddressDto.cs b/src/Modules/Grand.Module.Api/DTOs/Customers/AddressDto.cs index ccbfe78ab..66a430e69 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Customers/AddressDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Customers/AddressDto.cs @@ -2,20 +2,20 @@ public class AddressDto { - public string Id { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public string Email { get; set; } - public string Company { get; set; } - public string VatNumber { get; set; } - public string CountryId { get; set; } - public string StateProvinceId { get; set; } - public string City { get; set; } - public string Address1 { get; set; } - public string Address2 { get; set; } - public string ZipPostalCode { get; set; } - public string PhoneNumber { get; set; } - public string FaxNumber { get; set; } - public string Note { get; set; } + public string? Id { get; set; } + public string? FirstName { get; set; } + public string? LastName { get; set; } + public string? Email { get; set; } + public string? Company { get; set; } + public string? VatNumber { get; set; } + public string? CountryId { get; set; } + public string? StateProvinceId { get; set; } + public string? City { get; set; } + public string? Address1 { get; set; } + public string? Address2 { get; set; } + public string? ZipPostalCode { get; set; } + public string? PhoneNumber { get; set; } + public string? FaxNumber { get; set; } + public string? Note { get; set; } public int AddressType { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Customers/CustomerDto.cs b/src/Modules/Grand.Module.Api/DTOs/Customers/CustomerDto.cs index 6936e161f..dd2c44210 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Customers/CustomerDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Customers/CustomerDto.cs @@ -7,34 +7,34 @@ namespace Grand.Module.Api.DTOs.Customers; public class CustomerDto : BaseApiEntityModel { public Guid CustomerGuid { get; set; } = Guid.NewGuid(); - public string Username { get; set; } + public string? Username { get; set; } - [Key] public string Email { get; set; } + [Key] public string? Email { get; set; } [NoHtml] - public string AdminComment { get; set; } + public string? AdminComment { get; set; } public bool IsTaxExempt { get; set; } public bool FreeShipping { get; set; } - public string AffiliateId { get; set; } - public string VendorId { get; set; } - public string StoreId { get; set; } + public string? AffiliateId { get; set; } + public string? VendorId { get; set; } + public string? StoreId { get; set; } public bool Active { get; set; } public bool Deleted { get; set; } - public string Gender { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } + public string? Gender { get; set; } + public string? FirstName { get; set; } + public string? LastName { get; set; } public DateTime? DateOfBirth { get; set; } - public string Company { get; set; } - public string StreetAddress { get; set; } - public string StreetAddress2 { get; set; } - public string ZipPostalCode { get; set; } - public string City { get; set; } - public string CountryId { get; set; } - public string StateProvinceId { get; set; } - public string Phone { get; set; } - public string Fax { get; set; } - public string VatNumber { get; set; } - public string VatNumberStatusId { get; set; } + public string? Company { get; set; } + public string? StreetAddress { get; set; } + public string? StreetAddress2 { get; set; } + public string? ZipPostalCode { get; set; } + public string? City { get; set; } + public string? CountryId { get; set; } + public string? StateProvinceId { get; set; } + public string? Phone { get; set; } + public string? Fax { get; set; } + public string? VatNumber { get; set; } + public string? VatNumberStatusId { get; set; } public IList Groups { get; set; } = new List(); public IList Addresses { get; set; } = new List(); } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Customers/CustomerGroupDto.cs b/src/Modules/Grand.Module.Api/DTOs/Customers/CustomerGroupDto.cs index 09d7c4926..b72188f25 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Customers/CustomerGroupDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Customers/CustomerGroupDto.cs @@ -4,11 +4,11 @@ namespace Grand.Module.Api.DTOs.Customers; public class CustomerGroupDto : BaseApiEntityModel { - public string Name { get; set; } + public string? Name { get; set; } public bool FreeShipping { get; set; } public bool TaxExempt { get; set; } public bool Active { get; set; } public bool IsSystem { get; set; } - public string SystemName { get; set; } + public string? SystemName { get; set; } public bool EnablePasswordLifetime { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Customers/DeleteAddressDto.cs b/src/Modules/Grand.Module.Api/DTOs/Customers/DeleteAddressDto.cs index 59af4ab9e..2617637e8 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Customers/DeleteAddressDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Customers/DeleteAddressDto.cs @@ -2,5 +2,5 @@ public class DeleteAddressDto { - public string AddressId { get; set; } + public string? AddressId { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Customers/PasswordDto.cs b/src/Modules/Grand.Module.Api/DTOs/Customers/PasswordDto.cs index f87cc8ff4..3534676d6 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Customers/PasswordDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Customers/PasswordDto.cs @@ -2,5 +2,5 @@ public class PasswordDto { - public string Password { get; set; } + public string? Password { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Customers/VendorDto.cs b/src/Modules/Grand.Module.Api/DTOs/Customers/VendorDto.cs index c2be84194..b0029920a 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Customers/VendorDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Customers/VendorDto.cs @@ -5,15 +5,15 @@ namespace Grand.Module.Api.DTOs.Customers; public class VendorDto : BaseApiEntityModel { - public string Name { get; set; } - public string SeName { get; set; } - public string PictureId { get; set; } - public string Email { get; set; } + public string? Name { get; set; } + public string? SeName { get; set; } + public string? PictureId { get; set; } + public string? Email { get; set; } [SanitizeHtml] - public string Description { get; set; } - public string StoreId { get; set; } + public string? Description { get; set; } + public string? StoreId { get; set; } [NoHtml] - public string AdminComment { get; set; } + public string? AdminComment { get; set; } public bool Active { get; set; } public bool Deleted { get; set; } public int DisplayOrder { get; set; } @@ -22,5 +22,5 @@ public class VendorDto : BaseApiEntityModel public int NotApprovedRatingSum { get; set; } public int ApprovedTotalReviews { get; set; } public int NotApprovedTotalReviews { get; set; } - public virtual AddressDto Address { get; set; } + public virtual AddressDto? Address { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Inventory/StockApplyLineDto.cs b/src/Modules/Grand.Module.Api/DTOs/Inventory/StockApplyLineDto.cs index 865134816..af3cad013 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Inventory/StockApplyLineDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Inventory/StockApplyLineDto.cs @@ -10,17 +10,17 @@ public class StockApplyLineDto /// /// The idempotency key; required, at most 100 characters. A retried call with the same key is not applied again /// - public string Key { get; set; } + public string? Key { get; set; } /// /// The product by id; exactly one of ProductId and Sku /// - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// The product or combination by SKU; exactly one of ProductId and Sku /// - public string Sku { get; set; } + public string? Sku { get; set; } /// /// With ProductId, the attributes of a product stocked by attributes @@ -30,17 +30,17 @@ public class StockApplyLineDto /// /// The warehouse by id; at most one of WarehouseId and WarehouseCode /// - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } /// /// The warehouse by code; at most one of WarehouseId and WarehouseCode /// - public string WarehouseCode { get; set; } + public string? WarehouseCode { get; set; } /// /// "Set" or "Change" /// - public string Mode { get; set; } + public string? Mode { get; set; } /// /// The target for Set, the signed difference for Change @@ -50,7 +50,7 @@ public class StockApplyLineDto /// /// A batch-tracked product: the batch the line moves /// - public string BatchNumber { get; set; } + public string? BatchNumber { get; set; } /// /// A batch received: its expiry date @@ -65,10 +65,10 @@ public class StockApplyLineDto /// /// The reference of the journal entry; the SKU when empty /// - public string Reference { get; set; } + public string? Reference { get; set; } /// /// The comment of the journal entry /// - public string Comment { get; set; } + public string? Comment { get; set; } } diff --git a/src/Modules/Grand.Module.Api/DTOs/Inventory/StockApplyResultDto.cs b/src/Modules/Grand.Module.Api/DTOs/Inventory/StockApplyResultDto.cs index 9b9a221d6..5beb0711f 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Inventory/StockApplyResultDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Inventory/StockApplyResultDto.cs @@ -5,17 +5,17 @@ namespace Grand.Module.Api.DTOs.Inventory; /// public class StockApplyResultDto { - public string Key { get; set; } + public string? Key { get; set; } /// /// "Applied", "AlreadyApplied" or "Rejected" /// - public string Status { get; set; } + public string? Status { get; set; } /// /// Why the line was rejected; empty otherwise /// - public string Error { get; set; } + public string? Error { get; set; } /// /// The bucket's stock after the line; empty when rejected diff --git a/src/Modules/Grand.Module.Api/DTOs/Inventory/StockJournalEntryDto.cs b/src/Modules/Grand.Module.Api/DTOs/Inventory/StockJournalEntryDto.cs index 6eb9bc8b9..a64055006 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Inventory/StockJournalEntryDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Inventory/StockJournalEntryDto.cs @@ -7,29 +7,29 @@ namespace Grand.Module.Api.DTOs.Inventory; /// public class StockJournalEntryDto { - public string Id { get; set; } + public string? Id { get; set; } public DateTime CreatedOnUtc { get; set; } - public string ProductId { get; set; } + public string? ProductId { get; set; } /// /// The SKU of the product, or of the combination the entry names /// - public string Sku { get; set; } + public string? Sku { get; set; } - public string CombinationId { get; set; } - public string WarehouseId { get; set; } - public string WarehouseCode { get; set; } + public string? CombinationId { get; set; } + public string? WarehouseId { get; set; } + public string? WarehouseCode { get; set; } public int InQty { get; set; } public int OutQty { get; set; } public InventoryMovementType MovementType { get; set; } - public string ObjectType { get; set; } - public string ObjectId { get; set; } - public string Reference { get; set; } - public string Comments { get; set; } - public string CustomerId { get; set; } - public string StoreId { get; set; } - public string BatchNumber { get; set; } + public string? ObjectType { get; set; } + public string? ObjectId { get; set; } + public string? Reference { get; set; } + public string? Comments { get; set; } + public string? CustomerId { get; set; } + public string? StoreId { get; set; } + public string? BatchNumber { get; set; } public IList SerialNumbers { get; set; } = new List(); public DateTime? ExpiryDateUtc { get; set; } - public string IdempotencyKey { get; set; } + public string? IdempotencyKey { get; set; } } diff --git a/src/Modules/Grand.Module.Api/DTOs/Inventory/StockJournalResultDto.cs b/src/Modules/Grand.Module.Api/DTOs/Inventory/StockJournalResultDto.cs index f4f0b4bc9..6d3c67924 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Inventory/StockJournalResultDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Inventory/StockJournalResultDto.cs @@ -9,7 +9,7 @@ public class StockJournalResultDto /// The cursor to ask with next time: the id of the last entry returned, or the cursor asked with when the page is /// empty. Keep it even when HasMore is false, to poll for new entries later /// - public string Next { get; set; } + public string? Next { get; set; } /// /// Whether more entries follow this page now diff --git a/src/Modules/Grand.Module.Api/DTOs/Orders/MerchandiseReturnActionDto.cs b/src/Modules/Grand.Module.Api/DTOs/Orders/MerchandiseReturnActionDto.cs index 13c74acdd..aeb4885d7 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Orders/MerchandiseReturnActionDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Orders/MerchandiseReturnActionDto.cs @@ -4,7 +4,7 @@ namespace Grand.Module.Api.DTOs.Orders; public class MerchandiseReturnActionDto : BaseApiEntityModel { - public string Name { get; set; } + public string? Name { get; set; } public int DisplayOrder { get; set; } public bool LimitedToStores { get; set; } public IList Stores { get; set; } = new List(); diff --git a/src/Modules/Grand.Module.Api/DTOs/Orders/MerchandiseReturnDto.cs b/src/Modules/Grand.Module.Api/DTOs/Orders/MerchandiseReturnDto.cs index 8f2c5e3c6..672694a77 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Orders/MerchandiseReturnDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Orders/MerchandiseReturnDto.cs @@ -6,15 +6,15 @@ namespace Grand.Module.Api.DTOs.Orders; public class MerchandiseReturnDto : BaseApiEntityModel { public int ReturnNumber { get; set; } - public string ExternalId { get; set; } - public string StoreId { get; set; } - public string OrderId { get; set; } - public string OwnerId { get; set; } - public string SeId { get; set; } - public string CustomerId { get; set; } - public string VendorId { get; set; } - public string CustomerComments { get; set; } - public string StaffNotes { get; set; } + public string? ExternalId { get; set; } + public string? StoreId { get; set; } + public string? OrderId { get; set; } + public string? OwnerId { get; set; } + public string? SeId { get; set; } + public string? CustomerId { get; set; } + public string? VendorId { get; set; } + public string? CustomerComments { get; set; } + public string? StaffNotes { get; set; } /// /// The return status as its stored numeric value; the enum is computed, not stored @@ -31,9 +31,9 @@ public class MerchandiseReturnDto : BaseApiEntityModel /// On update, null keeps the stored address and an address with no field filled in clears it; a new address /// only where the return's store allows a pickup address, else 400 (PickupNotAllowed) /// - public AddressDto PickupAddress { get; set; } - public MerchandiseReturnShippingDto ReturnShipping { get; set; } - public MerchandiseReturnRefundDto Refund { get; set; } + public AddressDto? PickupAddress { get; set; } + public MerchandiseReturnShippingDto? ReturnShipping { get; set; } + public MerchandiseReturnRefundDto? Refund { get; set; } public IList MerchandiseReturnItems { get; set; } = new List(); public IList StatusHistory { get; set; } = new List(); @@ -47,30 +47,30 @@ public class MerchandiseReturnDto : BaseApiEntityModel public class MerchandiseReturnItemDto { - public string Id { get; set; } - public string OrderItemId { get; set; } - public string ReasonId { get; set; } - public string ReasonForReturn { get; set; } + public string? Id { get; set; } + public string? OrderItemId { get; set; } + public string? ReasonId { get; set; } + public string? ReasonForReturn { get; set; } public int Quantity { get; set; } - public string ActionId { get; set; } - public string RequestedAction { get; set; } + public string? ActionId { get; set; } + public string? RequestedAction { get; set; } } public class MerchandiseReturnShippingDto { - public string ProviderSystemName { get; set; } - public string OptionCode { get; set; } - public string OptionName { get; set; } + public string? ProviderSystemName { get; set; } + public string? OptionCode { get; set; } + public string? OptionName { get; set; } public double Cost { get; set; } public double CurrencyRate { get; set; } - public ReturnDropOffPointDto DropOffPoint { get; set; } - public AddressDto ReturnAddress { get; set; } - public string TrackingNumber { get; set; } - public string ReturnCode { get; set; } - public string LabelDownloadId { get; set; } - public string Instructions { get; set; } + public ReturnDropOffPointDto? DropOffPoint { get; set; } + public AddressDto? ReturnAddress { get; set; } + public string? TrackingNumber { get; set; } + public string? ReturnCode { get; set; } + public string? LabelDownloadId { get; set; } + public string? Instructions { get; set; } public int LabelStatusId { get; set; } - public string LabelError { get; set; } + public string? LabelError { get; set; } public Dictionary ProviderData { get; set; } = new(); } @@ -80,9 +80,9 @@ public class MerchandiseReturnRefundDto public double ReturnShippingCost { get; set; } public double Amount { get; set; } public bool Offline { get; set; } - public string PaymentTransactionId { get; set; } + public string? PaymentTransactionId { get; set; } public bool OutcomeUnknown { get; set; } - public string RefundedBy { get; set; } + public string? RefundedBy { get; set; } public DateTime CreatedOnUtc { get; set; } public DateTime? RefundedOnUtc { get; set; } } @@ -95,11 +95,11 @@ public class MerchandiseReturnStatusChangeDto public class ReturnDropOffPointDto { - public string Id { get; set; } - public string Name { get; set; } - public AddressDto Address { get; set; } - public string OpeningHours { get; set; } - public string WarehouseId { get; set; } + public string? Id { get; set; } + public string? Name { get; set; } + public AddressDto? Address { get; set; } + public string? OpeningHours { get; set; } + public string? WarehouseId { get; set; } } public class MerchandiseReturnListModel diff --git a/src/Modules/Grand.Module.Api/DTOs/Orders/MerchandiseReturnReasonDto.cs b/src/Modules/Grand.Module.Api/DTOs/Orders/MerchandiseReturnReasonDto.cs index 729df1a59..a7890eb40 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Orders/MerchandiseReturnReasonDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Orders/MerchandiseReturnReasonDto.cs @@ -4,7 +4,7 @@ namespace Grand.Module.Api.DTOs.Orders; public class MerchandiseReturnReasonDto : BaseApiEntityModel { - public string Name { get; set; } + public string? Name { get; set; } public int DisplayOrder { get; set; } public bool LimitedToStores { get; set; } public IList Stores { get; set; } = new List(); diff --git a/src/Modules/Grand.Module.Api/DTOs/Orders/MerchandiseReturnStatusChangeRequest.cs b/src/Modules/Grand.Module.Api/DTOs/Orders/MerchandiseReturnStatusChangeRequest.cs index 028e13483..f26075e92 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Orders/MerchandiseReturnStatusChangeRequest.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Orders/MerchandiseReturnStatusChangeRequest.cs @@ -7,5 +7,5 @@ namespace Grand.Module.Api.DTOs.Orders; public class MerchandiseReturnStatusChangeRequest { public int? Status { get; set; } - public string CustomerNote { get; set; } + public string? CustomerNote { get; set; } } diff --git a/src/Modules/Grand.Module.Api/DTOs/Shipping/DeliveryDateDto.cs b/src/Modules/Grand.Module.Api/DTOs/Shipping/DeliveryDateDto.cs index 74eae10de..1f7175f45 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Shipping/DeliveryDateDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Shipping/DeliveryDateDto.cs @@ -4,7 +4,7 @@ namespace Grand.Module.Api.DTOs.Shipping; public class DeliveryDateDto : BaseApiEntityModel { - public string Name { get; set; } + public string? Name { get; set; } public int DisplayOrder { get; set; } - public string ColorSquaresRgb { get; set; } + public string? ColorSquaresRgb { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Shipping/PickupPointDto.cs b/src/Modules/Grand.Module.Api/DTOs/Shipping/PickupPointDto.cs index c52e22b36..2713808e0 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Shipping/PickupPointDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Shipping/PickupPointDto.cs @@ -5,13 +5,13 @@ namespace Grand.Module.Api.DTOs.Shipping; public class PickupPointDto : BaseApiEntityModel { - public string Name { get; set; } + public string? Name { get; set; } [SanitizeHtml] - public string Description { get; set; } + public string? Description { get; set; } [NoHtml] - public string AdminComment { get; set; } - public string WarehouseId { get; set; } - public string StoreId { get; set; } + public string? AdminComment { get; set; } + public string? WarehouseId { get; set; } + public string? StoreId { get; set; } public double PickupFee { get; set; } public int DisplayOrder { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Shipping/ShippingMethodDto.cs b/src/Modules/Grand.Module.Api/DTOs/Shipping/ShippingMethodDto.cs index cb68ec09d..058959301 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Shipping/ShippingMethodDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Shipping/ShippingMethodDto.cs @@ -5,8 +5,8 @@ namespace Grand.Module.Api.DTOs.Shipping; public class ShippingMethodDto : BaseApiEntityModel { - public string Name { get; set; } + public string? Name { get; set; } [SanitizeHtml] - public string Description { get; set; } + public string? Description { get; set; } public int DisplayOrder { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/DTOs/Shipping/WarehouseDto.cs b/src/Modules/Grand.Module.Api/DTOs/Shipping/WarehouseDto.cs index 9585d6866..b97eed94b 100644 --- a/src/Modules/Grand.Module.Api/DTOs/Shipping/WarehouseDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/Shipping/WarehouseDto.cs @@ -5,9 +5,9 @@ namespace Grand.Module.Api.DTOs.Shipping; public class WarehouseDto : BaseApiEntityModel { - public string Name { get; set; } + public string? Name { get; set; } [NoHtml] - public string AdminComment { get; set; } + public string? AdminComment { get; set; } /// /// The stock of this warehouse belongs to an external system (ERP/WMS); it changes only through the stock diff --git a/src/Modules/Grand.Module.Api/DTOs/TokenDto.cs b/src/Modules/Grand.Module.Api/DTOs/TokenDto.cs index 98a3c8d13..26ae32e1f 100644 --- a/src/Modules/Grand.Module.Api/DTOs/TokenDto.cs +++ b/src/Modules/Grand.Module.Api/DTOs/TokenDto.cs @@ -2,6 +2,6 @@ public class TokenDto { - public string AccessToken { get; set; } - public string RefreshToken { get; set; } + public string? AccessToken { get; set; } + public string? RefreshToken { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Extensions/OpenApiOptionsExtensions.cs b/src/Modules/Grand.Module.Api/Extensions/OpenApiOptionsExtensions.cs index 455def999..c06423db4 100644 --- a/src/Modules/Grand.Module.Api/Extensions/OpenApiOptionsExtensions.cs +++ b/src/Modules/Grand.Module.Api/Extensions/OpenApiOptionsExtensions.cs @@ -121,7 +121,7 @@ public static void AddClearServerDocumentTransformer(this OpenApiOptions options { options.AddDocumentTransformer((document, context, cancellationToken) => { - document.Servers.Clear(); + document.Servers?.Clear(); return Task.CompletedTask; }); } diff --git a/src/Modules/Grand.Module.Api/Filters/AuthorizeApiAdminAttribute.cs b/src/Modules/Grand.Module.Api/Filters/AuthorizeApiAdminAttribute.cs index a7f9edcc8..aa8fffd71 100644 --- a/src/Modules/Grand.Module.Api/Filters/AuthorizeApiAdminAttribute.cs +++ b/src/Modules/Grand.Module.Api/Filters/AuthorizeApiAdminAttribute.cs @@ -75,7 +75,7 @@ public async Task OnAuthorizationAsync(AuthorizationFilterContext filterContext) if (filterContext.Filters.Any(filter => filter is AuthorizeApiAdminFilter)) { //authorize permission of access to the admin area - var customer = contextAccessor.WorkContext?.CurrentCustomer; + var customer = contextAccessor.WorkContext.CurrentCustomer; if (!await permissionService.Authorize(StandardPermission.ManageAccessAdminPanel, customer)) { filterContext.Result = new ForbidResult(JwtBearerDefaults.AuthenticationScheme); diff --git a/src/Modules/Grand.Module.Api/Grand.Module.Api.csproj b/src/Modules/Grand.Module.Api/Grand.Module.Api.csproj index 6abfa6983..0d4b4516d 100644 --- a/src/Modules/Grand.Module.Api/Grand.Module.Api.csproj +++ b/src/Modules/Grand.Module.Api/Grand.Module.Api.csproj @@ -51,4 +51,7 @@ + + enable + diff --git a/src/Modules/Grand.Module.Api/Infrastructure/ApiSecurityStartup.cs b/src/Modules/Grand.Module.Api/Infrastructure/ApiSecurityStartup.cs index 56a58b6bf..5d7bcf4f6 100644 --- a/src/Modules/Grand.Module.Api/Infrastructure/ApiSecurityStartup.cs +++ b/src/Modules/Grand.Module.Api/Infrastructure/ApiSecurityStartup.cs @@ -7,6 +7,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; +using System.Diagnostics.CodeAnalysis; namespace Grand.Module.Api.Infrastructure; @@ -37,7 +38,7 @@ public void Configure(WebApplication application, IWebHostEnvironment webHostEnv Validate("FrontendAPI", frontend.Enabled, frontend.SecretKey, webHostEnvironment, logger); } - private static void Validate(string section, bool enabled, string secret, IWebHostEnvironment env, ILogger logger) + private static void Validate(string section, bool enabled, string? secret, IWebHostEnvironment env, ILogger logger) { if (!enabled) return; @@ -57,7 +58,7 @@ private static void Validate(string section, bool enabled, string secret, IWebHo throw new InvalidOperationException(message); } - private static bool IsStrong(string secret) + private static bool IsStrong([NotNullWhen(true)] string? secret) { return !string.IsNullOrWhiteSpace(secret) && secret.Length >= MinSecretLength diff --git a/src/Modules/Grand.Module.Api/Infrastructure/Extensions/JwtSecurityKey.cs b/src/Modules/Grand.Module.Api/Infrastructure/Extensions/JwtSecurityKey.cs index ee135a224..cacafd368 100644 --- a/src/Modules/Grand.Module.Api/Infrastructure/Extensions/JwtSecurityKey.cs +++ b/src/Modules/Grand.Module.Api/Infrastructure/Extensions/JwtSecurityKey.cs @@ -1,11 +1,13 @@ -using Microsoft.IdentityModel.Tokens; +using Grand.SharedKernel; +using Microsoft.IdentityModel.Tokens; namespace Grand.Module.Api.Infrastructure.Extensions; public static class JwtSecurityKey { - public static SymmetricSecurityKey Create(string secret) + public static SymmetricSecurityKey Create(string? secret) { - return new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secret)); + return new SymmetricSecurityKey(Encoding.ASCII.GetBytes( + secret ?? throw new GrandException("The API secret key is not configured"))); } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Infrastructure/OpenApiStartup.cs b/src/Modules/Grand.Module.Api/Infrastructure/OpenApiStartup.cs index 746cc2c6d..94f0901f0 100644 --- a/src/Modules/Grand.Module.Api/Infrastructure/OpenApiStartup.cs +++ b/src/Modules/Grand.Module.Api/Infrastructure/OpenApiStartup.cs @@ -33,9 +33,9 @@ public void Configure(WebApplication application, IWebHostEnvironment webHostEnv public void ConfigureServices(IServiceCollection services, IConfiguration configuration) { - var backendApiConfig = services.BuildServiceProvider().GetService(); - var frontApiConfig = services.BuildServiceProvider().GetService(); - var webHostEnvironment = services.BuildServiceProvider().GetService(); + var backendApiConfig = services.BuildServiceProvider().GetRequiredService(); + var frontApiConfig = services.BuildServiceProvider().GetRequiredService(); + var webHostEnvironment = services.BuildServiceProvider().GetRequiredService(); if (webHostEnvironment.IsDevelopment() && (backendApiConfig.Enabled || frontApiConfig.Enabled)) { diff --git a/src/Modules/Grand.Module.Api/Jwt/JwtTokenBuilder.cs b/src/Modules/Grand.Module.Api/Jwt/JwtTokenBuilder.cs index ca57a5329..e82705ce4 100644 --- a/src/Modules/Grand.Module.Api/Jwt/JwtTokenBuilder.cs +++ b/src/Modules/Grand.Module.Api/Jwt/JwtTokenBuilder.cs @@ -7,10 +7,10 @@ namespace Grand.Module.Api.Jwt; public sealed class JwtTokenBuilder { private readonly Dictionary claims = new(); - private string audience = ""; + private string? audience; private int expiryInMinutes = 5; - private string issuer = ""; - private SecurityKey securityKey; + private string? issuer; + private SecurityKey? securityKey; private bool useaudience; private bool useissuer; @@ -27,14 +27,14 @@ public JwtTokenBuilder AddSecurityKey(SecurityKey securityKey) return this; } - public JwtTokenBuilder AddIssuer(string issuer) + public JwtTokenBuilder AddIssuer(string? issuer) { this.issuer = issuer; useissuer = true; return this; } - public JwtTokenBuilder AddAudience(string audience) + public JwtTokenBuilder AddAudience(string? audience) { this.audience = audience; useaudience = true; @@ -47,7 +47,7 @@ public JwtTokenBuilder AddClaim(string type, string value) return this; } - public JwtTokenBuilder AddClaims(Dictionary claims) + public JwtTokenBuilder AddClaims(Dictionary claims) { foreach (var item in claims) if (!this.claims.ContainsKey(item.Key) && !string.IsNullOrEmpty(item.Value)) diff --git a/src/Modules/Grand.Module.Api/Models/BaseApiEntityModel.cs b/src/Modules/Grand.Module.Api/Models/BaseApiEntityModel.cs index 6525ce05b..0f9f98765 100644 --- a/src/Modules/Grand.Module.Api/Models/BaseApiEntityModel.cs +++ b/src/Modules/Grand.Module.Api/Models/BaseApiEntityModel.cs @@ -4,7 +4,7 @@ namespace Grand.Module.Api.Models; public class BaseApiEntityModel { - [Key] public string Id { get; set; } + [Key] public string? Id { get; set; } public DateTime CreatedOnUtc { get; set; } public DateTime? UpdatedOnUtc { get; set; } diff --git a/src/Modules/Grand.Module.Api/Models/Common/LoginModel.cs b/src/Modules/Grand.Module.Api/Models/Common/LoginModel.cs index 9c4faf277..460ef6de5 100644 --- a/src/Modules/Grand.Module.Api/Models/Common/LoginModel.cs +++ b/src/Modules/Grand.Module.Api/Models/Common/LoginModel.cs @@ -2,6 +2,6 @@ public class LoginModel { - public string Email { get; set; } - public string Password { get; set; } + public string Email { get; set; } = null!; + public string Password { get; set; } = null!; } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Models/Common/LoginWebModel.cs b/src/Modules/Grand.Module.Api/Models/Common/LoginWebModel.cs index f60b83220..d656bc1d1 100644 --- a/src/Modules/Grand.Module.Api/Models/Common/LoginWebModel.cs +++ b/src/Modules/Grand.Module.Api/Models/Common/LoginWebModel.cs @@ -2,6 +2,6 @@ public class LoginWebModel { - public string Email { get; set; } - public string Password { get; set; } + public string Email { get; set; } = null!; + public string Password { get; set; } = null!; } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Queries/ApiQueryOptions.cs b/src/Modules/Grand.Module.Api/Queries/ApiQueryOptions.cs index 5c85abae0..5b0427223 100644 --- a/src/Modules/Grand.Module.Api/Queries/ApiQueryOptions.cs +++ b/src/Modules/Grand.Module.Api/Queries/ApiQueryOptions.cs @@ -196,12 +196,12 @@ public Dictionary> GetExtensionMethods() return []; } - public Type ResolveType(string typeName) + public Type? ResolveType(string typeName) { return null; } - public Type ResolveTypeBySimpleName(string simpleTypeName) + public Type? ResolveTypeBySimpleName(string simpleTypeName) { return null; } diff --git a/src/Modules/Grand.Module.Api/Queries/Handlers/Customers/GetCustomerQueryHandler.cs b/src/Modules/Grand.Module.Api/Queries/Handlers/Customers/GetCustomerQueryHandler.cs index 6e1235e93..6eeb56d18 100644 --- a/src/Modules/Grand.Module.Api/Queries/Handlers/Customers/GetCustomerQueryHandler.cs +++ b/src/Modules/Grand.Module.Api/Queries/Handlers/Customers/GetCustomerQueryHandler.cs @@ -6,7 +6,7 @@ namespace Grand.Module.Api.Queries.Handlers.Customers; -public class GetCustomerQueryHandler : IRequestHandler +public class GetCustomerQueryHandler : IRequestHandler { private readonly ICustomerService _customerService; @@ -15,8 +15,9 @@ public GetCustomerQueryHandler(ICustomerService customerService) _customerService = customerService; } - public async Task Handle(GetCustomerQuery request, CancellationToken cancellationToken) + public async Task Handle(GetCustomerQuery request, CancellationToken cancellationToken) { - return (await _customerService.GetCustomerByEmail(request.Email)).ToModel(); + var customer = await _customerService.GetCustomerByEmail(request.Email); + return customer?.ToModel(); } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Queries/Handlers/Inventory/GetStockJournalQueryHandler.cs b/src/Modules/Grand.Module.Api/Queries/Handlers/Inventory/GetStockJournalQueryHandler.cs index 35d8a98b4..e9ed05aa2 100644 --- a/src/Modules/Grand.Module.Api/Queries/Handlers/Inventory/GetStockJournalQueryHandler.cs +++ b/src/Modules/Grand.Module.Api/Queries/Handlers/Inventory/GetStockJournalQueryHandler.cs @@ -89,10 +89,10 @@ private async Task> BuildEntries(IList x.Id); return entries.Select(x => ToDto(x, products.GetValueOrDefault(x.ProductId), - warehouses.GetValueOrDefault(x.WarehouseId))).ToList(); + x.WarehouseId != null ? warehouses.GetValueOrDefault(x.WarehouseId) : null)).ToList(); } - private static StockJournalEntryDto ToDto(InventoryJournal entry, Product product, Warehouse warehouse) + private static StockJournalEntryDto ToDto(InventoryJournal entry, Product? product, Warehouse? warehouse) { var sku = product?.Sku ?? ""; if (product != null && !string.IsNullOrEmpty(entry.CombinationId)) diff --git a/src/Modules/Grand.Module.Api/Queries/Handlers/Orders/GetMerchandiseReturnQueryHandler.cs b/src/Modules/Grand.Module.Api/Queries/Handlers/Orders/GetMerchandiseReturnQueryHandler.cs index 9f34fcf6c..4683a3281 100644 --- a/src/Modules/Grand.Module.Api/Queries/Handlers/Orders/GetMerchandiseReturnQueryHandler.cs +++ b/src/Modules/Grand.Module.Api/Queries/Handlers/Orders/GetMerchandiseReturnQueryHandler.cs @@ -5,7 +5,7 @@ namespace Grand.Module.Api.Queries.Handlers.Orders; -public class GetMerchandiseReturnQueryHandler : IRequestHandler +public class GetMerchandiseReturnQueryHandler : IRequestHandler { private readonly IMerchandiseReturnService _merchandiseReturnService; @@ -14,7 +14,7 @@ public GetMerchandiseReturnQueryHandler(IMerchandiseReturnService merchandiseRet _merchandiseReturnService = merchandiseReturnService; } - public async Task Handle(GetMerchandiseReturnQuery request, + public async Task Handle(GetMerchandiseReturnQuery request, CancellationToken cancellationToken) { return await _merchandiseReturnService.GetMerchandiseReturnById(request.Id); diff --git a/src/Modules/Grand.Module.Api/Queries/Models/Common/GetGenericQuery.cs b/src/Modules/Grand.Module.Api/Queries/Models/Common/GetGenericQuery.cs index 94152c599..d0ae858d1 100644 --- a/src/Modules/Grand.Module.Api/Queries/Models/Common/GetGenericQuery.cs +++ b/src/Modules/Grand.Module.Api/Queries/Models/Common/GetGenericQuery.cs @@ -4,4 +4,4 @@ namespace Grand.Module.Api.Queries.Models.Common; -public record GetGenericQuery(string Id = null) : IRequest> where T : BaseApiEntityModel where C : BaseEntity; \ No newline at end of file +public record GetGenericQuery(string? Id = null) : IRequest> where T : BaseApiEntityModel where C : BaseEntity; \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Queries/Models/Common/GetQuery.cs b/src/Modules/Grand.Module.Api/Queries/Models/Common/GetQuery.cs index 4e5ece0ee..d1409e293 100644 --- a/src/Modules/Grand.Module.Api/Queries/Models/Common/GetQuery.cs +++ b/src/Modules/Grand.Module.Api/Queries/Models/Common/GetQuery.cs @@ -4,5 +4,5 @@ namespace Grand.Module.Api.Queries.Models.Common; public class GetQuery : IRequest> where T : class { - public string Id { get; set; } + public string? Id { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Queries/Models/Customers/GetCustomerQuery.cs b/src/Modules/Grand.Module.Api/Queries/Models/Customers/GetCustomerQuery.cs index f586a312c..b5b5abc32 100644 --- a/src/Modules/Grand.Module.Api/Queries/Models/Customers/GetCustomerQuery.cs +++ b/src/Modules/Grand.Module.Api/Queries/Models/Customers/GetCustomerQuery.cs @@ -3,7 +3,7 @@ namespace Grand.Module.Api.Queries.Models.Customers; -public class GetCustomerQuery : IRequest +public class GetCustomerQuery : IRequest { - public string Email { get; set; } + public string? Email { get; set; } } \ No newline at end of file diff --git a/src/Modules/Grand.Module.Api/Queries/Models/Inventory/GetStockJournalQuery.cs b/src/Modules/Grand.Module.Api/Queries/Models/Inventory/GetStockJournalQuery.cs index cce91fedd..ffbfa5a14 100644 --- a/src/Modules/Grand.Module.Api/Queries/Models/Inventory/GetStockJournalQuery.cs +++ b/src/Modules/Grand.Module.Api/Queries/Models/Inventory/GetStockJournalQuery.cs @@ -12,13 +12,13 @@ public class GetStockJournalQuery : IRequest /// /// The cursor: the id of the last entry of the previous page; empty for the beginning /// - public string After { get; set; } + public string? After { get; set; } public int Take { get; set; } = 100; - public string WarehouseId { get; set; } + public string? WarehouseId { get; set; } - public string WarehouseCode { get; set; } + public string? WarehouseCode { get; set; } /// /// The inventory movement types to include; empty for all @@ -30,5 +30,5 @@ public class GetStockJournalQuery : IRequest /// public bool ExcludeOwn { get; set; } - public string CustomerId { get; set; } + public string? CustomerId { get; set; } } diff --git a/src/Modules/Grand.Module.Api/Queries/Models/Orders/GetMerchandiseReturnQuery.cs b/src/Modules/Grand.Module.Api/Queries/Models/Orders/GetMerchandiseReturnQuery.cs index d93fac458..eb69b2fde 100644 --- a/src/Modules/Grand.Module.Api/Queries/Models/Orders/GetMerchandiseReturnQuery.cs +++ b/src/Modules/Grand.Module.Api/Queries/Models/Orders/GetMerchandiseReturnQuery.cs @@ -3,7 +3,7 @@ namespace Grand.Module.Api.Queries.Models.Orders; -public class GetMerchandiseReturnQuery : IRequest +public class GetMerchandiseReturnQuery : IRequest { - public string Id { get; set; } + public required string Id { get; set; } } diff --git a/src/Modules/Grand.Module.Api/Validators/Common/LoginValidator.cs b/src/Modules/Grand.Module.Api/Validators/Common/LoginValidator.cs index 40d9c6014..1a6837072 100644 --- a/src/Modules/Grand.Module.Api/Validators/Common/LoginValidator.cs +++ b/src/Modules/Grand.Module.Api/Validators/Common/LoginValidator.cs @@ -39,7 +39,7 @@ public LoginValidator( var userapi = await userApiService.GetUserByEmail(x.Email.ToLowerInvariant()); if (userapi is { IsActive: true }) { - var base64EncodedBytes = Convert.FromBase64String(x.Password); + var base64EncodedBytes = Convert.FromBase64String(x.Password ?? ""); var password = Encoding.UTF8.GetString(base64EncodedBytes); //detect the format from the stored password itself: modern records are PBKDF2 hashes, legacy //records are reversibly encrypted with the per-user PrivateKey (verified in constant time) diff --git a/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs b/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs index a444baa6c..b27e4511a 100644 --- a/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs +++ b/src/Modules/Grand.Module.Api/Validators/Common/LoginWebValidator.cs @@ -45,7 +45,7 @@ public LoginWebValidator( string password; try { - password = Encoding.UTF8.GetString(Convert.FromBase64String(x.Password)); + password = Encoding.UTF8.GetString(Convert.FromBase64String(x.Password ?? "")); } catch (FormatException) { diff --git a/src/Modules/Grand.Module.Api/Validators/Customers/CustomerGroupValidator.cs b/src/Modules/Grand.Module.Api/Validators/Customers/CustomerGroupValidator.cs index 9e3013568..045d798e2 100644 --- a/src/Modules/Grand.Module.Api/Validators/Customers/CustomerGroupValidator.cs +++ b/src/Modules/Grand.Module.Api/Validators/Customers/CustomerGroupValidator.cs @@ -37,7 +37,7 @@ public CustomerGroupValidator( if (!string.IsNullOrEmpty(x.Id)) { var customerGroup = await groupService.GetCustomerGroupById(x.Id); - if (customerGroup.IsSystem && !x.Active) return false; + if (customerGroup is { IsSystem: true } && !x.Active) return false; } return true; @@ -47,8 +47,8 @@ public CustomerGroupValidator( if (!string.IsNullOrEmpty(x.Id)) { var customerGroup = await groupService.GetCustomerGroupById(x.Id); - if (customerGroup.IsSystem && - !customerGroup.SystemName.Equals(x.SystemName, StringComparison.OrdinalIgnoreCase)) return false; + if (customerGroup is { IsSystem: true } && + !string.Equals(customerGroup.SystemName, x.SystemName, StringComparison.OrdinalIgnoreCase)) return false; } return true; diff --git a/src/Modules/Grand.Module.Installer/Controllers/InstallController.cs b/src/Modules/Grand.Module.Installer/Controllers/InstallController.cs index 8f9f30605..946180219 100644 --- a/src/Modules/Grand.Module.Installer/Controllers/InstallController.cs +++ b/src/Modules/Grand.Module.Installer/Controllers/InstallController.cs @@ -5,6 +5,7 @@ using Grand.Module.Installer.Interfaces; using Grand.Module.Installer.Models; using Grand.SharedKernel.Extensions; +using Grand.SharedKernel; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; @@ -121,7 +122,7 @@ public virtual async Task Index() return View(installed ? new InstallModel { Installed = true, AdminEmail = "", AdminPassword = "", ConfirmPassword = "" } : PrepareModel(null)); } - private string BuildConnectionString(IInstallationLocalizedService locService, InstallModel model) + private string? BuildConnectionString(IInstallationLocalizedService locService, InstallModel model) { var connectionString = ""; @@ -249,14 +250,15 @@ await installationService.InstallData( await PluginManager.ClearPlugins(); - var pluginsInfo = PluginManager.ReferencedPlugins.ToList(); + var pluginsInfo = PluginManager.ReferencedPlugins?.ToList() ?? []; foreach (var pluginInfo in pluginsInfo) try { - var plugin = pluginInfo.Instance(HttpContext.RequestServices.CreateScope().ServiceProvider); + var plugin = pluginInfo.Instance(HttpContext.RequestServices.CreateScope().ServiceProvider) ?? + throw new GrandException($"Plugin {pluginInfo.SystemName} could not be created"); await plugin.Install(); - _logger.LogInformation($"Plugin {plugin.PluginInfo.FriendlyName} has been installed"); + _logger.LogInformation($"Plugin {pluginInfo.FriendlyName} has been installed"); } catch (Exception ex) { diff --git a/src/Modules/Grand.Module.Installer/Services/InstallDataPages.cs b/src/Modules/Grand.Module.Installer/Services/InstallDataPages.cs index 3cf33fef3..b5ed1f320 100644 --- a/src/Modules/Grand.Module.Installer/Services/InstallDataPages.cs +++ b/src/Modules/Grand.Module.Installer/Services/InstallDataPages.cs @@ -214,6 +214,8 @@ protected virtual async Task InstallPages(bool installSampleData) //search engine names foreach (var page in lpages) { + if (string.IsNullOrEmpty(page.SystemName)) + continue; var seName = page.SystemName.ToLowerInvariant(); await _entityUrlRepository.InsertAsync(new EntityUrl { EntityId = page.Id, diff --git a/src/Modules/Grand.Module.Installer/Services/InstallDataProducts.Fashion.cs b/src/Modules/Grand.Module.Installer/Services/InstallDataProducts.Fashion.cs index 8d0d6f91d..da46fde23 100644 --- a/src/Modules/Grand.Module.Installer/Services/InstallDataProducts.Fashion.cs +++ b/src/Modules/Grand.Module.Installer/Services/InstallDataProducts.Fashion.cs @@ -700,7 +700,7 @@ await AddProductPictures(backpack, // Builds a Color attribute mapping whose values carry a picture (one of the product's own // pictures), for products where the manifest calls out per-color-value pictures. private ProductAttributeMapping ColorAttributeWithPictures(int displayOrder, bool combination, - params (string Name, string Hex, string PictureId)[] values) + params (string Name, string Hex, string? PictureId)[] values) { var mapping = new ProductAttributeMapping { ProductAttributeId = ProductAttributeId("Color"), diff --git a/src/Modules/Grand.Module.Migration/Migrations/1.1/MigrationUpdateMediaSettings.cs b/src/Modules/Grand.Module.Migration/Migrations/1.1/MigrationUpdateMediaSettings.cs index 38404adc0..99fc807c3 100644 --- a/src/Modules/Grand.Module.Migration/Migrations/1.1/MigrationUpdateMediaSettings.cs +++ b/src/Modules/Grand.Module.Migration/Migrations/1.1/MigrationUpdateMediaSettings.cs @@ -29,9 +29,8 @@ public async Task UpgradeProcess(IServiceProvider serviceProvider) try { var mediaSettings = await repository.FirstOrDefaultAsync(repository.Table.Where(x => x.Name == "mediasettings")); - if (mediaSettings != null) + if (mediaSettings is { Metadata: { } metadata }) { - var metadata = mediaSettings.Metadata; var settingsLogo = JsonSerializer.Deserialize(metadata); if (settingsLogo != null) { diff --git a/src/Modules/Grand.Module.Migration/Migrations/2.1/MigrationUpdateAdminSiteMap.cs b/src/Modules/Grand.Module.Migration/Migrations/2.1/MigrationUpdateAdminSiteMap.cs index 67f21ddce..36f410486 100644 --- a/src/Modules/Grand.Module.Migration/Migrations/2.1/MigrationUpdateAdminSiteMap.cs +++ b/src/Modules/Grand.Module.Migration/Migrations/2.1/MigrationUpdateAdminSiteMap.cs @@ -39,10 +39,12 @@ public async Task UpgradeProcess(IServiceProvider serviceProvider) PermissionSystemName.ContactAttributes }; - sitemapSystem.ChildNodes.Remove( - sitemapSystem.ChildNodes.FirstOrDefault(x => x.SystemName == "Customer reminders")); - sitemapSystem.ChildNodes.Remove( - sitemapSystem.ChildNodes.FirstOrDefault(x => x.SystemName == "Customer actions")); + foreach (var name in new[] { "Customer reminders", "Customer actions" }) + { + var removed = sitemapSystem.ChildNodes.FirstOrDefault(x => x.SystemName == name); + if (removed != null) + sitemapSystem.ChildNodes.Remove(removed); + } await repository.UpdateAsync(sitemapSystem); } diff --git a/src/Modules/Grand.Module.Migration/Migrations/2.4/MigrationAddAdminPortalInfoPage.cs b/src/Modules/Grand.Module.Migration/Migrations/2.4/MigrationAddAdminPortalInfoPage.cs index 861833731..93c20dcd2 100644 --- a/src/Modules/Grand.Module.Migration/Migrations/2.4/MigrationAddAdminPortalInfoPage.cs +++ b/src/Modules/Grand.Module.Migration/Migrations/2.4/MigrationAddAdminPortalInfoPage.cs @@ -41,7 +41,7 @@ public async Task UpgradeProcess(IServiceProvider serviceProvider) var entityUrlRepository = serviceProvider.GetRequiredService>(); var systemName = PageSystemName.ToLowerInvariant(); - var page = await pageRepository.FirstOrDefaultAsync(pageRepository.Table.Where(x => x.SystemName.ToLower() == systemName)); + var page = await pageRepository.FirstOrDefaultAsync(pageRepository.Table.Where(x => x.SystemName != null && x.SystemName.ToLower() == systemName)); if (page == null) { var defaultPageLayout = await pageLayoutRepository.FirstOrDefaultAsync(pageLayoutRepository.Table.Where(x => x.Name == "Default layout")); diff --git a/src/Modules/Grand.Module.Migration/Migrations/2.4/MigrationRobotsTxtAiCrawlers.cs b/src/Modules/Grand.Module.Migration/Migrations/2.4/MigrationRobotsTxtAiCrawlers.cs index c1b52f4f1..96dcdf0a3 100644 --- a/src/Modules/Grand.Module.Migration/Migrations/2.4/MigrationRobotsTxtAiCrawlers.cs +++ b/src/Modules/Grand.Module.Migration/Migrations/2.4/MigrationRobotsTxtAiCrawlers.cs @@ -54,7 +54,7 @@ public async Task UpgradeProcess(IServiceProvider serviceProvider) return true; } - public static string AddAiCrawlers(string text) + public static string? AddAiCrawlers(string? text) { if (string.IsNullOrEmpty(text)) return text; diff --git a/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationInventoryLedger.cs b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationInventoryLedger.cs index e31aa2a7f..df04e2f40 100644 --- a/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationInventoryLedger.cs +++ b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationInventoryLedger.cs @@ -183,7 +183,7 @@ private static void Sum(Product product) yield return ("", [], warehouseId, product.StockQuantity); else foreach (var row in product.ProductWarehouseInventory) - yield return ("", [], row.WarehouseId, row.StockQuantity); + yield return ("", [], row.WarehouseId ?? "", row.StockQuantity); yield break; } @@ -192,7 +192,7 @@ private static void Sum(Product product) yield return (combination.Id, combination.Attributes, warehouseId, combination.StockQuantity); else foreach (var row in combination.WarehouseInventory) - yield return (combination.Id, combination.Attributes, row.WarehouseId, row.StockQuantity); + yield return (combination.Id, combination.Attributes, row.WarehouseId ?? "", row.StockQuantity); } private static async Task AddPermission(IServiceProvider serviceProvider) diff --git a/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationInventoryUnits.cs b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationInventoryUnits.cs index 2eb2209e0..aa10f5c1b 100644 --- a/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationInventoryUnits.cs +++ b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationInventoryUnits.cs @@ -115,7 +115,8 @@ await InventoryMenu.Add(repository, var configuration = await repository.FirstOrDefaultAsync(repository.Table.Where(x => x.SystemName == "Configuration")); var shipping = configuration?.ChildNodes.FirstOrDefault(x => x.SystemName == "Shipping"); - if (shipping == null || shipping.ChildNodes.Any(x => x.SystemName == "Warehouse locations")) + if (configuration == null || shipping == null || + shipping.ChildNodes.Any(x => x.SystemName == "Warehouse locations")) return; shipping.ChildNodes.Add(new AdminSiteMap { diff --git a/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationMerchandiseReturnReasonIds.cs b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationMerchandiseReturnReasonIds.cs index 1bf48cb6f..722428a04 100644 --- a/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationMerchandiseReturnReasonIds.cs +++ b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationMerchandiseReturnReasonIds.cs @@ -73,7 +73,7 @@ await returnRepository.UpdateField(merchandiseReturn.Id, x => x.MerchandiseRetur return true; } - private static string Key(string name) + private static string Key(string? name) { return name?.Trim().ToLowerInvariant() ?? ""; } diff --git a/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationReturnShippingMenu.cs b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationReturnShippingMenu.cs index c866c095e..654d755f6 100644 --- a/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationReturnShippingMenu.cs +++ b/src/Modules/Grand.Module.Migration/Migrations/2.5/MigrationReturnShippingMenu.cs @@ -29,7 +29,7 @@ public async Task UpgradeProcess(IServiceProvider serviceProvider) var configuration = await repository.FirstOrDefaultAsync(repository.Table.Where(x => x.SystemName == "Configuration")); var shipping = configuration?.ChildNodes.FirstOrDefault(x => x.SystemName == "Shipping"); - if (shipping == null || shipping.ChildNodes.Any(x => x.SystemName == NodeName)) + if (configuration == null || shipping == null || shipping.ChildNodes.Any(x => x.SystemName == NodeName)) return true; //the display order of the shipping providers; the menu's ordering is stable, so it follows them diff --git a/src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/EndAuctionsTask.cs b/src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/EndAuctionsTask.cs index 055f5f727..5992866a0 100644 --- a/src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/EndAuctionsTask.cs +++ b/src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/EndAuctionsTask.cs @@ -71,7 +71,15 @@ await _catalogMessageProviderService.SendAuctionEndedStoreOwnerMessage(auctionTo continue; } - var warnings = (await _shoppingCartService.AddToCart(await _customerService.GetCustomerById(bid.CustomerId), + var bidder = await _customerService.GetCustomerById(bid.CustomerId); + if (bidder == null) + { + _logger.LogWarning("EndAuctionTask - Product {Name} - the customer of the highest bid does not exist", + auctionToEnd.Name); + continue; + } + + var warnings = (await _shoppingCartService.AddToCart(bidder, language, bid.ProductId, ShoppingCartType.Auctions, bid.StoreId, bid.WarehouseId, customerEnteredPrice: bid.Amount, diff --git a/src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/QueuedMessagesSendScheduleTask.cs b/src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/QueuedMessagesSendScheduleTask.cs index ad0b3c1de..7066d2ce2 100644 --- a/src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/QueuedMessagesSendScheduleTask.cs +++ b/src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/QueuedMessagesSendScheduleTask.cs @@ -1,5 +1,6 @@ using Grand.Business.Core.Interfaces.Messages; using Grand.Business.Core.Interfaces.System.ScheduleTasks; +using Grand.SharedKernel; using Microsoft.Extensions.Logging; namespace Grand.Module.ScheduledTasks.BackgroundServices; @@ -49,13 +50,15 @@ public async Task Execute(CancellationToken cancellationToken) try { - var emailAccount = await _emailAccountService.GetEmailAccountById(queuedEmail.EmailAccountId); + //a message that cannot be sent counts as a failed try, as any other sending error + var emailAccount = await _emailAccountService.GetEmailAccountById(queuedEmail.EmailAccountId) ?? + throw new GrandException("The email account of the message does not exist"); await _emailSender.SendEmail(emailAccount, - queuedEmail.Subject, - queuedEmail.Body, - queuedEmail.From, + queuedEmail.Subject ?? "", + queuedEmail.Body ?? "", + queuedEmail.From ?? throw new GrandException("The message has no sender address"), queuedEmail.FromName, - queuedEmail.To, + queuedEmail.To ?? throw new GrandException("The message has no recipient address"), queuedEmail.ToName, queuedEmail.ReplyTo, queuedEmail.ReplyToName, diff --git a/src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/ScheduleTaskService.cs b/src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/ScheduleTaskService.cs index 8ecc8e488..bfea9f4b0 100644 --- a/src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/ScheduleTaskService.cs +++ b/src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/ScheduleTaskService.cs @@ -29,7 +29,7 @@ public ScheduleTaskService(IRepository taskRepository) /// /// Task identifier /// Task - public virtual Task GetTaskById(string taskId) + public virtual Task GetTaskById(string taskId) { return _taskRepository.GetByIdAsync(taskId); } @@ -38,7 +38,7 @@ public virtual Task GetTaskById(string taskId) /// Gets a task by its name /// /// Task - public virtual async Task GetTaskByName(string name) + public virtual async Task GetTaskByName(string name) { if (string.IsNullOrWhiteSpace(name)) return null; diff --git a/src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/UpdateExchangeRateScheduleTask.cs b/src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/UpdateExchangeRateScheduleTask.cs index 8e307db9a..f86ce30a7 100644 --- a/src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/UpdateExchangeRateScheduleTask.cs +++ b/src/Modules/Grand.Module.ScheduledTasks/BackgroundServices/UpdateExchangeRateScheduleTask.cs @@ -2,6 +2,7 @@ using Grand.Business.Core.Interfaces.System.ScheduleTasks; using Grand.Domain.Directory; using Grand.Domain.Tasks; +using Grand.SharedKernel; namespace Grand.Module.ScheduledTasks.BackgroundServices; @@ -32,7 +33,9 @@ public async Task Execute(CancellationToken cancellationToken) if (!_currencySettings.AutoUpdateEnabled) return; - var primaryCurrencyCode = (await _currencyService.GetPrimaryExchangeRateCurrency()).CurrencyCode; + var primaryCurrency = await _currencyService.GetPrimaryExchangeRateCurrency() ?? + throw new GrandException("The primary exchange rate currency is not set"); + var primaryCurrencyCode = primaryCurrency.CurrencyCode; var exchangeRates = await _exchangeRateService.GetCurrencyLiveRates(primaryCurrencyCode, cancellationToken); foreach (var exchangeRate in exchangeRates) diff --git a/src/Modules/Grand.Module.ScheduledTasks/Grand.Module.ScheduledTasks.csproj b/src/Modules/Grand.Module.ScheduledTasks/Grand.Module.ScheduledTasks.csproj index 5018356d4..54ec9ffb3 100644 --- a/src/Modules/Grand.Module.ScheduledTasks/Grand.Module.ScheduledTasks.csproj +++ b/src/Modules/Grand.Module.ScheduledTasks/Grand.Module.ScheduledTasks.csproj @@ -38,4 +38,7 @@ ..\..\Web\Grand.Web\Modules\Grand.Module.ScheduledTasks\ $(OutputPath) + + enable + diff --git a/src/Modules/Grand.Module.Scim/Controllers/ScimControllerBase.cs b/src/Modules/Grand.Module.Scim/Controllers/ScimControllerBase.cs index 58f0c088d..d71647c9a 100644 --- a/src/Modules/Grand.Module.Scim/Controllers/ScimControllerBase.cs +++ b/src/Modules/Grand.Module.Scim/Controllers/ScimControllerBase.cs @@ -25,17 +25,16 @@ public abstract class ScimControllerBase : ControllerBase protected string BaseUrl => $"{Request.Scheme}://{Request.Host}{Request.PathBase}/scim/v2"; - /// The body, or the 400 response to return when it is missing or is not JSON of the expected shape - protected async Task<(T Body, IActionResult Error)> ReadBody() where T : class + /// The body, or null when it is missing or is not JSON of the expected shape + protected async Task ReadBody() where T : class { try { - var body = await JsonSerializer.DeserializeAsync(Request.Body, ScimJson.Options, HttpContext.RequestAborted); - return body == null ? (null, InvalidSyntax()) : (body, null); + return await JsonSerializer.DeserializeAsync(Request.Body, ScimJson.Options, HttpContext.RequestAborted); } catch (JsonException) { - return (null, InvalidSyntax()); + return null; } } @@ -46,7 +45,7 @@ protected static (int StartIndex, int Skip, int Take) Page(int? startIndex, int? return (start, start - 1, config.PageSize(count)); } - protected static IActionResult Refused(ScimOutcome outcome, string detail) => outcome switch { + protected static IActionResult Refused(ScimOutcome outcome, string? detail) => outcome switch { ScimOutcome.NotFound => ScimResponse.Error(StatusCodes.Status404NotFound, null, detail ?? "Resource not found"), ScimOutcome.Conflict => ScimResponse.Error(StatusCodes.Status409Conflict, "uniqueness", detail), _ => ScimResponse.Error(StatusCodes.Status400BadRequest, "invalidValue", detail) @@ -55,6 +54,6 @@ protected static (int StartIndex, int Skip, int Take) Page(int? startIndex, int? protected static IActionResult InvalidFilter(string detail) => ScimResponse.Error(StatusCodes.Status400BadRequest, "invalidFilter", detail); - private static IActionResult InvalidSyntax() => + protected static IActionResult InvalidSyntax() => ScimResponse.Error(StatusCodes.Status400BadRequest, "invalidSyntax", "The request body is not valid SCIM JSON"); } diff --git a/src/Modules/Grand.Module.Scim/Controllers/ScimGroupsController.cs b/src/Modules/Grand.Module.Scim/Controllers/ScimGroupsController.cs index 27e049b2a..5177efde8 100644 --- a/src/Modules/Grand.Module.Scim/Controllers/ScimGroupsController.cs +++ b/src/Modules/Grand.Module.Scim/Controllers/ScimGroupsController.cs @@ -16,7 +16,7 @@ public class ScimGroupsController(IScimGroupService groupService, ScimConfig con public async Task List([FromQuery] string filter, [FromQuery] int? startIndex, [FromQuery] int? count, [FromQuery] string excludedAttributes) { - string displayName = null, externalId = null; + string? displayName = null, externalId = null; if (!string.IsNullOrWhiteSpace(filter)) { if (!ScimFilter.TryParse(filter, out var parsed) || parsed.Attribute is not ("displayname" or "externalid")) @@ -45,48 +45,48 @@ public async Task List([FromQuery] string filter, [FromQuery] int public async Task Get(string id, [FromQuery] string excludedAttributes) { var result = await groupService.Get(id); - return result.Outcome == ScimOutcome.Ok - ? ScimResponse.Json(ToResource(result.Group, !ExcludesMembers(excludedAttributes))) + return result is { Outcome: ScimOutcome.Ok, Group: { } okGroup } + ? ScimResponse.Json(ToResource(okGroup, !ExcludesMembers(excludedAttributes))) : Refused(result.Outcome, null); } [HttpPost("Groups")] public async Task Create() { - var (body, error) = await ReadBody(); - if (error != null) - return error; + var body = await ReadBody(); + if (body == null) + return InvalidSyntax(); var result = await groupService.Create(ToData(body)); - if (result.Outcome != ScimOutcome.Created) + if (result is not { Outcome: ScimOutcome.Created, Group: { } created }) return Refused(result.Outcome, result.Detail); - var resource = ToResource(result.Group, true); - Response.Headers.Location = resource.Meta.Location; + var resource = ToResource(created, true); + Response.Headers.Location = resource.Meta?.Location; return ScimResponse.Json(resource, StatusCodes.Status201Created); } [HttpPut("Groups/{id}")] public async Task Replace(string id) { - var (body, error) = await ReadBody(); - if (error != null) - return error; + var body = await ReadBody(); + if (body == null) + return InvalidSyntax(); var result = await groupService.Replace(id, ToData(body)); - return result.Outcome == ScimOutcome.Ok - ? ScimResponse.Json(ToResource(result.Group, true)) + return result is { Outcome: ScimOutcome.Ok, Group: { } okGroup } + ? ScimResponse.Json(ToResource(okGroup, true)) : Refused(result.Outcome, result.Detail); } [HttpPatch("Groups/{id}")] public async Task Patch(string id) { - var (body, error) = await ReadBody(); - if (error != null) - return error; + var body = await ReadBody(); + if (body == null) + return InvalidSyntax(); - if (!ScimGroupPatch.TryApply(body.Operations, out var changes, out var patchError)) + if (!ScimGroupPatch.TryApply(body.Operations ?? [], out var changes, out var patchError)) return Refused(ScimOutcome.Invalid, patchError); var result = await groupService.Get(id); @@ -95,8 +95,8 @@ public async Task Patch(string id) if (result.Outcome == ScimOutcome.Ok && changes.MembersChanged) result = await groupService.ModifyMembers(id, changes.Add, changes.Remove, changes.ReplaceAll); - return result.Outcome == ScimOutcome.Ok - ? ScimResponse.Json(ToResource(result.Group, true)) + return result is { Outcome: ScimOutcome.Ok, Group: { } okGroup } + ? ScimResponse.Json(ToResource(okGroup, true)) : Refused(result.Outcome, result.Detail); } @@ -113,7 +113,7 @@ private static bool ExcludesMembers(string excludedAttributes) => private static ScimGroupData ToData(ScimGroupResource body) => new(body.DisplayName, body.ExternalId, - body.Members?.Select(x => x.Value).Where(x => !string.IsNullOrEmpty(x)).ToList() ?? []); + body.Members?.Select(x => x.Value).OfType().Where(x => x.Length > 0).ToList() ?? []); private ScimGroupResource ToResource(ScimGroupView group, bool withMembers) => new() { diff --git a/src/Modules/Grand.Module.Scim/Controllers/ScimUsersController.cs b/src/Modules/Grand.Module.Scim/Controllers/ScimUsersController.cs index cd7fc284e..87ccd770b 100644 --- a/src/Modules/Grand.Module.Scim/Controllers/ScimUsersController.cs +++ b/src/Modules/Grand.Module.Scim/Controllers/ScimUsersController.cs @@ -15,7 +15,7 @@ public class ScimUsersController(IScimUserService userService, ScimConfig config [HttpGet("Users")] public async Task List([FromQuery] string filter, [FromQuery] int? startIndex, [FromQuery] int? count) { - string userName = null, externalId = null; + string? userName = null, externalId = null; if (!string.IsNullOrWhiteSpace(filter)) { if (!ScimFilter.TryParse(filter, out var parsed) || parsed.Attribute is not ("username" or "externalid")) @@ -44,62 +44,62 @@ public async Task List([FromQuery] string filter, [FromQuery] int public async Task Get(string id) { var result = await userService.Get(id); - return result.Outcome == ScimOutcome.Ok ? ScimResponse.Json(ToResource(result.User)) : Refused(result.Outcome, null); + return result is { Outcome: ScimOutcome.Ok, User: { } okUser } ? ScimResponse.Json(ToResource(okUser)) : Refused(result.Outcome, null); } [HttpPost("Users")] public async Task Create() { - var (body, error) = await ReadBody(); - if (error != null) - return error; + var body = await ReadBody(); + if (body == null) + return InvalidSyntax(); var result = await userService.Create(ToData(body, true)); - if (result.Outcome != ScimOutcome.Created) + if (result is not { Outcome: ScimOutcome.Created, User: { } created }) return Refused(result.Outcome, result.Detail); - var resource = ToResource(result.User); - Response.Headers.Location = resource.Meta.Location; + var resource = ToResource(created); + Response.Headers.Location = resource.Meta?.Location; return ScimResponse.Json(resource, StatusCodes.Status201Created); } [HttpPut("Users/{id}")] public async Task Replace(string id) { - var (body, error) = await ReadBody(); - if (error != null) - return error; + var body = await ReadBody(); + if (body == null) + return InvalidSyntax(); var current = await userService.Get(id); - if (current.Outcome != ScimOutcome.Ok) + if (current is not { Outcome: ScimOutcome.Ok, User: { } currentUser }) return Refused(current.Outcome, null); //a replace without active keeps the state: it must not activate a deactivated account - var result = await userService.Replace(id, ToData(body, current.User.Active)); - return result.Outcome == ScimOutcome.Ok - ? ScimResponse.Json(ToResource(result.User)) + var result = await userService.Replace(id, ToData(body, currentUser.Active)); + return result is { Outcome: ScimOutcome.Ok, User: { } okUser } + ? ScimResponse.Json(ToResource(okUser)) : Refused(result.Outcome, result.Detail); } [HttpPatch("Users/{id}")] public async Task Patch(string id) { - var (body, error) = await ReadBody(); - if (error != null) - return error; + var body = await ReadBody(); + if (body == null) + return InvalidSyntax(); var current = await userService.Get(id); - if (current.Outcome != ScimOutcome.Ok) + if (current is not { Outcome: ScimOutcome.Ok, User: { } currentUser }) return Refused(current.Outcome, null); - var user = current.User; + var user = currentUser; var data = new ScimUserData(user.UserName, user.ExternalId, user.Email, user.GivenName, user.FamilyName, user.Active); - if (!ScimUserPatch.TryApply(data, body.Operations, out var patched, out var patchError)) + if (!ScimUserPatch.TryApply(data, body.Operations ?? [], out var patched, out var patchError)) return Refused(ScimOutcome.Invalid, patchError); var result = await userService.Replace(id, patched); - return result.Outcome == ScimOutcome.Ok - ? ScimResponse.Json(ToResource(result.User)) + return result is { Outcome: ScimOutcome.Ok, User: { } okUser } + ? ScimResponse.Json(ToResource(okUser)) : Refused(result.Outcome, result.Detail); } @@ -115,7 +115,7 @@ private static ScimUserData ToData(ScimUserResource body, bool activeWhenMissing body.Active ?? activeWhenMissing); //the primary e-mail, else the work e-mail, else the first one - private static string PickEmail(List emails) => + private static string? PickEmail(List? emails) => (emails?.FirstOrDefault(x => x.Primary == true) ?? emails?.FirstOrDefault(x => string.Equals(x.Type, "work", StringComparison.OrdinalIgnoreCase)) ?? emails?.FirstOrDefault())?.Value; diff --git a/src/Modules/Grand.Module.Scim/Grand.Module.Scim.csproj b/src/Modules/Grand.Module.Scim/Grand.Module.Scim.csproj index e980a0455..0032fda5f 100644 --- a/src/Modules/Grand.Module.Scim/Grand.Module.Scim.csproj +++ b/src/Modules/Grand.Module.Scim/Grand.Module.Scim.csproj @@ -43,4 +43,7 @@ ..\..\Web\Grand.Web\Modules\Grand.Module.Scim\ $(OutputPath) + + enable + diff --git a/src/Modules/Grand.Module.Scim/Infrastructure/ScimAuthorizeFilter.cs b/src/Modules/Grand.Module.Scim/Infrastructure/ScimAuthorizeFilter.cs index c3eac20e4..f1b3c57ac 100644 --- a/src/Modules/Grand.Module.Scim/Infrastructure/ScimAuthorizeFilter.cs +++ b/src/Modules/Grand.Module.Scim/Infrastructure/ScimAuthorizeFilter.cs @@ -29,7 +29,7 @@ public void OnAuthorization(AuthorizationFilterContext context) return; } - string authorization = context.HttpContext.Request.Headers.Authorization; + string? authorization = context.HttpContext.Request.Headers.Authorization; if (authorization == null || !authorization.StartsWith(Scheme, StringComparison.OrdinalIgnoreCase) || !Matches(authorization[Scheme.Length..].Trim(), config.Token)) { diff --git a/src/Modules/Grand.Module.Scim/Infrastructure/ScimResponse.cs b/src/Modules/Grand.Module.Scim/Infrastructure/ScimResponse.cs index e5aeed0c8..251618b9f 100644 --- a/src/Modules/Grand.Module.Scim/Infrastructure/ScimResponse.cs +++ b/src/Modules/Grand.Module.Scim/Infrastructure/ScimResponse.cs @@ -16,7 +16,7 @@ public static ContentResult Json(object body, int status = 200) => }; /// RFC 7644 error type (invalidFilter, uniqueness, invalidValue...), null for none - public static ContentResult Error(int status, string scimType, string detail) => + public static ContentResult Error(int status, string? scimType, string? detail) => Json(new ScimError { Status = status.ToString(CultureInfo.InvariantCulture), ScimType = scimType, diff --git a/src/Modules/Grand.Module.Scim/Models/ScimResources.cs b/src/Modules/Grand.Module.Scim/Models/ScimResources.cs index 57f543815..111eabcc1 100644 --- a/src/Modules/Grand.Module.Scim/Models/ScimResources.cs +++ b/src/Modules/Grand.Module.Scim/Models/ScimResources.cs @@ -18,56 +18,56 @@ public static class ScimSchemas public class ScimMeta { - public string ResourceType { get; set; } + public string? ResourceType { get; set; } public DateTime? Created { get; set; } public DateTime? LastModified { get; set; } - public string Location { get; set; } + public string? Location { get; set; } } public class ScimName { - public string GivenName { get; set; } - public string FamilyName { get; set; } - public string Formatted { get; set; } + public string? GivenName { get; set; } + public string? FamilyName { get; set; } + public string? Formatted { get; set; } } /// A multi-valued attribute item: an e-mail, a group of a user, a member of a group public class ScimMultiValue { - public string Value { get; set; } - public string Type { get; set; } + public string? Value { get; set; } + public string? Type { get; set; } public bool? Primary { get; set; } - public string Display { get; set; } + public string? Display { get; set; } [JsonPropertyName("$ref")] - public string Ref { get; set; } + public string? Ref { get; set; } } public class ScimUserResource { - public List Schemas { get; set; } - public string Id { get; set; } - public string ExternalId { get; set; } - public string UserName { get; set; } - public ScimName Name { get; set; } - public string DisplayName { get; set; } - public List Emails { get; set; } + public List? Schemas { get; set; } + public string? Id { get; set; } + public string? ExternalId { get; set; } + public string? UserName { get; set; } + public ScimName? Name { get; set; } + public string? DisplayName { get; set; } + public List? Emails { get; set; } [JsonConverter(typeof(ScimBooleanConverter))] public bool? Active { get; set; } - public List Groups { get; set; } - public ScimMeta Meta { get; set; } + public List? Groups { get; set; } + public ScimMeta? Meta { get; set; } } public class ScimGroupResource { - public List Schemas { get; set; } - public string Id { get; set; } - public string ExternalId { get; set; } - public string DisplayName { get; set; } - public List Members { get; set; } - public ScimMeta Meta { get; set; } + public List? Schemas { get; set; } + public string? Id { get; set; } + public string? ExternalId { get; set; } + public string? DisplayName { get; set; } + public List? Members { get; set; } + public ScimMeta? Meta { get; set; } } public class ScimListResponse @@ -86,21 +86,21 @@ public class ScimError public List Schemas { get; set; } = [ScimSchemas.Error]; /// The HTTP status as a string (RFC 7644, 3.12) - public string Status { get; set; } + public string? Status { get; set; } - public string ScimType { get; set; } - public string Detail { get; set; } + public string? ScimType { get; set; } + public string? Detail { get; set; } } public class ScimPatchRequest { - public List Schemas { get; set; } + public List? Schemas { get; set; } public List Operations { get; set; } = []; } public class ScimPatchOperation { - public string Op { get; set; } - public string Path { get; set; } + public string? Op { get; set; } + public string? Path { get; set; } public JsonElement? Value { get; set; } } diff --git a/src/Modules/Grand.Module.Scim/Protocol/ScimFilter.cs b/src/Modules/Grand.Module.Scim/Protocol/ScimFilter.cs index a23cb1a92..a2aba4cf8 100644 --- a/src/Modules/Grand.Module.Scim/Protocol/ScimFilter.cs +++ b/src/Modules/Grand.Module.Scim/Protocol/ScimFilter.cs @@ -1,3 +1,4 @@ +using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; namespace Grand.Module.Scim.Protocol; @@ -15,7 +16,7 @@ public partial record ScimFilter(string Attribute, string Value) [GeneratedRegex("""\\(.)""")] private static partial Regex Escape(); - public static bool TryParse(string filter, out ScimFilter result) + public static bool TryParse(string filter, [NotNullWhen(true)] out ScimFilter? result) { result = null; if (string.IsNullOrWhiteSpace(filter)) diff --git a/src/Modules/Grand.Module.Scim/Protocol/ScimGroupPatch.cs b/src/Modules/Grand.Module.Scim/Protocol/ScimGroupPatch.cs index 7e330b0b5..12a1b7fd9 100644 --- a/src/Modules/Grand.Module.Scim/Protocol/ScimGroupPatch.cs +++ b/src/Modules/Grand.Module.Scim/Protocol/ScimGroupPatch.cs @@ -15,10 +15,10 @@ public class ScimGroupChanges public bool MembersChanged { get; set; } /// New name; null keeps it - public string DisplayName { get; set; } + public string? DisplayName { get; set; } /// New externalId; null keeps it - public string ExternalId { get; set; } + public string? ExternalId { get; set; } } /// @@ -30,7 +30,7 @@ public static partial class ScimGroupPatch [GeneratedRegex("""^members\[value eq "((?:[^"\\]|\\.)*)"\]$""", RegexOptions.IgnoreCase)] private static partial Regex MemberPath(); - public static bool TryApply(IList operations, out ScimGroupChanges changes, out string error) + public static bool TryApply(IList operations, out ScimGroupChanges changes, out string? error) { changes = new ScimGroupChanges(); error = null; @@ -176,7 +176,8 @@ private static List MemberIds(JsonElement? value) .Where(x => x.ValueKind == JsonValueKind.Object && x.TryGetProperty("value", out var v) && v.ValueKind == JsonValueKind.String) .Select(x => x.GetProperty("value").GetString()) - .Where(x => !string.IsNullOrEmpty(x)) + .OfType() + .Where(x => x.Length > 0) .ToList(); } } diff --git a/src/Modules/Grand.Module.Scim/Protocol/ScimUserPatch.cs b/src/Modules/Grand.Module.Scim/Protocol/ScimUserPatch.cs index eb4d4ad8f..3d9042d98 100644 --- a/src/Modules/Grand.Module.Scim/Protocol/ScimUserPatch.cs +++ b/src/Modules/Grand.Module.Scim/Protocol/ScimUserPatch.cs @@ -19,7 +19,7 @@ public static partial class ScimUserPatch private static partial Regex TypedEmailPath(); public static bool TryApply(ScimUserData user, IList operations, out ScimUserData result, - out string error) + out string? error) { result = user; error = null; @@ -54,7 +54,7 @@ public static bool TryApply(ScimUserData user, IList operati } /// Null for a remove - private static bool TryApplyPath(ref ScimUserData user, string path, JsonElement? value, out string error) + private static bool TryApplyPath(ref ScimUserData user, string path, JsonElement? value, out string? error) { error = null; if (path.StartsWith(UserSchemaPrefix, StringComparison.OrdinalIgnoreCase)) @@ -104,7 +104,7 @@ private static bool TryApplyPath(ref ScimUserData user, string path, JsonElement } //the primary e-mail, else the work e-mail, else the first one - private static string PickEmail(JsonElement? value) + private static string? PickEmail(JsonElement? value) { if (value is not { ValueKind: JsonValueKind.Array } emails) return null; @@ -121,7 +121,7 @@ private static string PickEmail(JsonElement? value) : null; } - private static bool TryString(JsonElement? value, string name, out string result, out string error) + private static bool TryString(JsonElement? value, string name, out string? result, out string? error) { error = null; result = null; diff --git a/src/Tests/Grand.Module.Api.Tests/Commands/Inventory/ApplyStockCommandHandlerTests.cs b/src/Tests/Grand.Module.Api.Tests/Commands/Inventory/ApplyStockCommandHandlerTests.cs index 62dccf7a2..b3145cf16 100644 --- a/src/Tests/Grand.Module.Api.Tests/Commands/Inventory/ApplyStockCommandHandlerTests.cs +++ b/src/Tests/Grand.Module.Api.Tests/Commands/Inventory/ApplyStockCommandHandlerTests.cs @@ -36,7 +36,7 @@ public void Init() [TestMethod] public async Task Handle_MissingKey_Rejected() { - var result = await _handler.Handle(new ApplyStockCommand { + var result = await _handler.Handle(new ApplyStockCommand { CustomerId = "c1", Lines = [new StockApplyLineDto { ProductId = "p1", Mode = "Set", Quantity = 3 }] }, default); @@ -47,7 +47,7 @@ public async Task Handle_MissingKey_Rejected() [TestMethod] public async Task Handle_InvalidMode_Rejected() { - var result = await _handler.Handle(new ApplyStockCommand { + var result = await _handler.Handle(new ApplyStockCommand { CustomerId = "c1", Lines = [new StockApplyLineDto { Key = "k1", ProductId = "p1", Mode = "Adjust", Quantity = 3 }] }, default); @@ -58,7 +58,7 @@ public async Task Handle_InvalidMode_Rejected() [TestMethod] public async Task Handle_ProductIdAndSku_Rejected() { - var result = await _handler.Handle(new ApplyStockCommand { + var result = await _handler.Handle(new ApplyStockCommand { CustomerId = "c1", Lines = [new StockApplyLineDto { Key = "k1", ProductId = "p1", Sku = "s1", Mode = "Set", Quantity = 3 }] }, default); @@ -75,7 +75,7 @@ await _productRepositoryMock.Object.InsertAsync(new Product { InventoryTrackingModeId = InventoryTrackingMode.SerialNumber }); - var result = await _handler.Handle(new ApplyStockCommand { + var result = await _handler.Handle(new ApplyStockCommand { CustomerId = "c1", Lines = [new StockApplyLineDto { Key = "k1", ProductId = "p1", Mode = "Set", Quantity = 3 }] }, default); @@ -94,7 +94,7 @@ await _productRepositoryMock.Object.InsertAsync(new Product { InventoryTrackingModeId = InventoryTrackingMode.SerialNumber }); - var result = await _handler.Handle(new ApplyStockCommand { + var result = await _handler.Handle(new ApplyStockCommand { CustomerId = "c1", Lines = [new StockApplyLineDto { Key = "k1", ProductId = "p1", Mode = "Change", Quantity = 2, SerialNumbers = ["s1"] }] @@ -113,7 +113,7 @@ await _productRepositoryMock.Object.InsertAsync(new Product { InventoryTrackingModeId = InventoryTrackingMode.Batch }); - var result = await _handler.Handle(new ApplyStockCommand { + var result = await _handler.Handle(new ApplyStockCommand { CustomerId = "c1", Lines = [new StockApplyLineDto { Key = "k1", ProductId = "p1", Mode = "Change", Quantity = 3 }] }, default); @@ -128,7 +128,7 @@ await _productRepositoryMock.Object.InsertAsync(new Product { Id = "p1", ManageInventoryMethodId = ManageInventoryMethod.ManageStock, WarehouseId = "w1" }); - var result = await _handler.Handle(new ApplyStockCommand { + var result = await _handler.Handle(new ApplyStockCommand { CustomerId = "c1", Lines = [new StockApplyLineDto { Key = "k1", ProductId = "p1", WarehouseId = "w2", Mode = "Change", Quantity = 1 }] }, default); @@ -165,7 +165,7 @@ await _productRepositoryMock.Object.InsertAsync(new Product { _stockMovementServiceMock.Setup(x => x.Apply("p1", It.IsAny>())) .ReturnsAsync([StockErrors.AlreadyApplied]); - var result = await _handler.Handle(new ApplyStockCommand { + var result = await _handler.Handle(new ApplyStockCommand { CustomerId = "c1", Lines = [new StockApplyLineDto { Key = "k1", ProductId = "p1", Mode = "Set", Quantity = 10 }] }, default); @@ -180,7 +180,7 @@ await _productRepositoryMock.Object.InsertAsync(new Product { Id = "p1", ManageInventoryMethodId = ManageInventoryMethod.ManageStock, StockQuantity = 10 }); - var result = await _handler.Handle(new ApplyStockCommand { + var result = await _handler.Handle(new ApplyStockCommand { CustomerId = "c1", Lines = [ new StockApplyLineDto { Key = "k1", ProductId = "p1", Mode = "Set", Quantity = 10 }, new StockApplyLineDto { ProductId = "p1", Mode = "Set", Quantity = 20 } @@ -200,7 +200,7 @@ await _productRepositoryMock.Object.InsertAsync(new Product { Id = "p1", Sku = "S-1", ManageInventoryMethodId = ManageInventoryMethod.ManageStock }); - var result = await _handler.Handle(new ApplyStockCommand { + var result = await _handler.Handle(new ApplyStockCommand { CustomerId = "c1", Lines = [new StockApplyLineDto { Key = "k1", Sku = " S-1 ", Mode = "Change", Quantity = 2 }] }, default); @@ -222,7 +222,7 @@ await _productRepositoryMock.Object.InsertAsync(new Product { } }); - var result = await _handler.Handle(new ApplyStockCommand { + var result = await _handler.Handle(new ApplyStockCommand { CustomerId = "c1", Lines = [new StockApplyLineDto { Key = "k1", Sku = "C-1", Mode = "Set", Quantity = 4 }] }, default); @@ -243,7 +243,7 @@ await _productRepositoryMock.Object.InsertAsync(new Product { ProductAttributeCombinations = { new ProductAttributeCombination { Id = "c1", Sku = "S-1" } } }); - var result = await _handler.Handle(new ApplyStockCommand { + var result = await _handler.Handle(new ApplyStockCommand { CustomerId = "c1", Lines = [new StockApplyLineDto { Key = "k1", Sku = "S-1", Mode = "Change", Quantity = 1 }] }, default); @@ -255,7 +255,7 @@ await _productRepositoryMock.Object.InsertAsync(new Product { [TestMethod] public async Task Handle_UnknownSku_Rejected() { - var result = await _handler.Handle(new ApplyStockCommand { + var result = await _handler.Handle(new ApplyStockCommand { CustomerId = "c1", Lines = [new StockApplyLineDto { Key = "k1", Sku = "NONE", Mode = "Change", Quantity = 1 }] }, default); @@ -273,7 +273,7 @@ await _productRepositoryMock.Object.InsertAsync(new Product { ProductWarehouseInventory = { new ProductWarehouseInventory { WarehouseId = "w1", StockQuantity = 7 } } }); - var result = await _handler.Handle(new ApplyStockCommand { + var result = await _handler.Handle(new ApplyStockCommand { CustomerId = "c1", Lines = [new StockApplyLineDto { Key = "k1", ProductId = "p1", WarehouseCode = "WH-1", Mode = "Set", Quantity = 7 }] }, default); @@ -289,7 +289,7 @@ public async Task Handle_UnknownWarehouseCode_Rejected() await _productRepositoryMock.Object.InsertAsync(new Product { Id = "p1", ManageInventoryMethodId = ManageInventoryMethod.ManageStock }); - var result = await _handler.Handle(new ApplyStockCommand { + var result = await _handler.Handle(new ApplyStockCommand { CustomerId = "c1", Lines = [new StockApplyLineDto { Key = "k1", ProductId = "p1", WarehouseCode = "NONE", Mode = "Set", Quantity = 1 }] }, default); @@ -303,7 +303,7 @@ public async Task Handle_ManyLines_ResolvesSkusInOneQueryEach() await _productRepositoryMock.Object.InsertAsync(new Product { Id = $"p{i}", Sku = $"S-{i}", ManageInventoryMethodId = ManageInventoryMethod.ManageStock }); - var result = await _handler.Handle(new ApplyStockCommand { + var result = await _handler.Handle(new ApplyStockCommand { CustomerId = "c1", Lines = Enumerable.Range(0, 50).Select(i => new StockApplyLineDto { Key = $"k{i}", Sku = $"S-{i}", Mode = "Change", Quantity = 1 }).ToList() }, default); diff --git a/src/Tests/Grand.Modules.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs b/src/Tests/Grand.Modules.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs index 2e4140309..c599e5b50 100644 --- a/src/Tests/Grand.Modules.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs +++ b/src/Tests/Grand.Modules.Tests/Services/BackgroundService/EndAuctionsTaskTests.cs @@ -36,6 +36,8 @@ public void Init() _messageProviderMock = new Mock(); _shoppingCartMock = new Mock(); _customerServiceMock = new Mock(); + //the customer of the highest bid + _customerServiceMock.Setup(c => c.GetCustomerById(It.IsAny())).ReturnsAsync(new Customer()); _loggerMock = new Mock>(); _settings = new LanguageSettings { DefaultAdminLanguageId = "admin-lang" }; _languageServiceMock = new Mock(); diff --git a/src/Tests/Grand.Modules.Tests/Services/BackgroundService/QueuedMessagesSendScheduleTaskTests.cs b/src/Tests/Grand.Modules.Tests/Services/BackgroundService/QueuedMessagesSendScheduleTaskTests.cs index 710398f0f..72ca6644b 100644 --- a/src/Tests/Grand.Modules.Tests/Services/BackgroundService/QueuedMessagesSendScheduleTaskTests.cs +++ b/src/Tests/Grand.Modules.Tests/Services/BackgroundService/QueuedMessagesSendScheduleTaskTests.cs @@ -36,7 +36,7 @@ public async Task Execute_InovekExpectedMethods() It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(() => new PagedList - { new() { Bcc = "bcc", CC = "cc", EmailAccountId = "id" } }); + { new() { Bcc = "bcc", CC = "cc", EmailAccountId = "id", From = "store@shop.example", To = "customer@shop.example" } }); _emailAccountServiceMock.Setup(c => c.GetEmailAccountById(It.IsAny())).ReturnsAsync(new EmailAccount()); await _task.Execute(CancellationToken.None); @@ -56,7 +56,7 @@ public async Task Execute_ThrowExecption_InovekExpectedMethodsAndInsertLog() It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(() => new PagedList - { new() { Bcc = "bcc", CC = "cc", EmailAccountId = "id" } }); + { new() { Bcc = "bcc", CC = "cc", EmailAccountId = "id", From = "store@shop.example", To = "customer@shop.example" } }); _emailAccountServiceMock.Setup(c => c.GetEmailAccountById(It.IsAny())).ReturnsAsync(new EmailAccount()); _emailSenderMock.Setup(c => c.SendEmail(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny() @@ -76,9 +76,9 @@ public async Task Execute_ThrowExecption_InovekExpectedMethodsAndInsertLog() [TestMethod] public async Task Execute_CancelledAfterTheFirstMail_LeavesTheRestQueuedWithUnchangedTries() { - var first = new QueuedEmail { Id = "1", EmailAccountId = "id" }; - var second = new QueuedEmail { Id = "2", EmailAccountId = "id", SentTries = 1 }; - var third = new QueuedEmail { Id = "3", EmailAccountId = "id" }; + var first = new QueuedEmail { Id = "1", EmailAccountId = "id", From = "store@shop.example", To = "customer@shop.example" }; + var second = new QueuedEmail { Id = "2", EmailAccountId = "id", From = "store@shop.example", To = "customer@shop.example", SentTries = 1 }; + var third = new QueuedEmail { Id = "3", EmailAccountId = "id", From = "store@shop.example", To = "customer@shop.example" }; SetupQueue(first, second, third); using var cts = new CancellationTokenSource(); _emailSenderMock.Setup(c => c.SendEmail(It.IsAny(), It.IsAny(), It.IsAny(), @@ -106,7 +106,7 @@ public async Task Execute_CancelledAfterTheFirstMail_LeavesTheRestQueuedWithUnch [TestMethod] public async Task Execute_CancelledMidSend_DoesNotCountTheInterruptedTry() { - var queuedEmail = new QueuedEmail { Id = "1", EmailAccountId = "id", SentTries = 2 }; + var queuedEmail = new QueuedEmail { Id = "1", EmailAccountId = "id", From = "store@shop.example", To = "customer@shop.example", SentTries = 2 }; SetupQueue(queuedEmail); using var cts = new CancellationTokenSource(); _emailSenderMock.Setup(c => c.SendEmail(It.IsAny(), It.IsAny(), It.IsAny(), @@ -131,7 +131,7 @@ public async Task Execute_CancelledMidSend_DoesNotCountTheInterruptedTry() public async Task Execute_EmailWithInvoice_SendsItWithTheOtherAttachments() { var attachments = await SentAttachments(new QueuedEmail { - EmailAccountId = "id", InvoiceDownloadId = "invoice", AttachedDownloads = ["template-attachment"] + EmailAccountId = "id", From = "store@shop.example", To = "customer@shop.example", InvoiceDownloadId = "invoice", AttachedDownloads = ["template-attachment"] }); CollectionAssert.AreEqual(new[] { "template-attachment", "invoice" }, attachments); @@ -141,7 +141,7 @@ public async Task Execute_EmailWithInvoice_SendsItWithTheOtherAttachments() public async Task Execute_EmailWithoutInvoice_SendsOnlyTheOtherAttachments() { var attachments = await SentAttachments(new QueuedEmail { - EmailAccountId = "id", AttachedDownloads = ["template-attachment"] + EmailAccountId = "id", From = "store@shop.example", To = "customer@shop.example", AttachedDownloads = ["template-attachment"] }); CollectionAssert.AreEqual(new[] { "template-attachment" }, attachments); From 4c6d2d9383dbd7685b2dfa5720feea1c0304c5fc Mon Sep 17 00:00:00 2001 From: support Date: Wed, 25 Nov 2026 22:39:08 +0100 Subject: [PATCH 11/30] Enable nullable reference types in Web.Common and Web.Models Both projects build with no nullable warnings. - IContextAccessor.WorkContext and StoreContext stay not null: the getter throws when no context is set, as outside a request. Code that also runs without one (settings resolved by the container, the culture middleware, the request translation and permission services, the admin component texts) reads the new nullable CurrentWorkContext/CurrentStoreContext and behaves as before. - IWorkContext: only CurrentVendor, StoreManager and OriginalCustomerIfImpersonated are nullable; the work context is built in one go, in the same order. No store, language or currency throws "could not be loaded", as the language and currency already did. - Tag helpers: ViewContext and the attributes an element is matched on are set by the framework (= null!, with the reason next to each). - The MVC helpers copied for the admin templates follow the annotations of the originals (template and field names nullable, the buffered writer's inner writer known once it stops buffering). - Lookups that cope with null take it (permission check of a missing customer, slug and active-slug lookups, audit actor fields); missing configuration of an enabled feature (Redis, Azure key vault) throws a message naming the setting. - The specification filter looks its option up once instead of four times with a forgiving operator. --- .../Services/OidcSessionService.cs | 2 +- .../Services/OidcTokenRevocationService.cs | 2 +- .../Services/KnowledgebaseService.cs | 2 +- .../Services/Security/PermissionService.cs | 4 +- .../Services/Seo/SlugService.cs | 4 +- .../IExternalSignInPathProvider.cs | 2 +- .../IExternalSignOutProvider.cs | 2 +- .../Authentication/IOidcSessionService.cs | 2 +- .../IOidcTokenRevocationService.cs | 2 +- .../Interfaces/Cms/IKnowledgebaseService.cs | 2 +- .../Common/Security/IPermissionService.cs | 4 +- .../Interfaces/Common/Seo/ISlugService.cs | 4 +- .../Authentication/OidcRefreshResult.cs | 2 +- .../Services/MediaFileStoreFactory.cs | 2 +- src/Core/Grand.Data/Audit/AuditActor.cs | 18 +-- .../Grand.Domain/Stores/StoreExtensions.cs | 2 +- .../Extensions/CommonExtensions.cs | 2 +- .../Grand.Infrastructure/IContextAccessor.cs | 18 ++- src/Core/Grand.Infrastructure/IWorkContext.cs | 6 +- .../Captcha/IGoogleReCaptchaValidator.cs | 2 +- .../Catalog/AddProductCommandHandler.cs | 2 +- .../Catalog/UpdateProductCommandHandler.cs | 2 +- .../UpdateProductStockCommandHandler.cs | 2 +- .../Extensions/ContextAccessorExtensions.cs | 2 +- .../RequestTranslationServiceTests.cs | 6 +- .../RequestPermissionServiceTests.cs | 6 +- .../StoreContextSetterTests.cs | 6 +- .../AdminComponentTagHelperTests.cs | 1 + .../TagHelpers/AdminCultureTagHelperTests.cs | 1 + .../TagHelpers/AdminGridTagHelperTests.cs | 1 + .../AdminImportWindowTagHelperTests.cs | 1 + .../MerchandiseReturnViewModelService.cs | 2 +- .../Audit/AuditEventRecorder.cs | 10 +- .../Grand.Web.Common/Audit/AuditRequest.cs | 10 +- .../Audit/IAuditEventRecorder.cs | 4 +- .../Binders/CustomAttributesBinder.cs | 4 +- .../Binders/CustomAttributesBinderProvider.cs | 2 +- .../Handlers/GetSitemapXMLCommandHandler.cs | 16 ++- .../Components/WidgetViewComponent.cs | 2 +- src/Web/Grand.Web.Common/ContextAccessor.cs | 17 ++- .../Controllers/BaseController.cs | 20 ++- .../Controllers/BasePublicController.cs | 2 +- .../Controllers/ControllerExtensions.cs | 2 +- .../DataSource/DataSourceRequestFilter.cs | 14 +- .../DataSource/DataSourceResult.cs | 6 +- .../Extensions/HttpContextExtensions.cs | 2 +- .../Extensions/KeyedServiceHelper.cs | 8 +- .../Extensions/ModelStateExtensions.cs | 9 +- .../Extensions/SessionExtensions.cs | 2 +- .../Filters/AffiliateAttribute.cs | 2 +- .../Filters/ArgumentNameFilterAttribute.cs | 6 +- .../Filters/AuditExportAttribute.cs | 4 +- .../Filters/AuditScopeFilter.cs | 2 +- .../Filters/AuthorizeMenuAttribute.cs | 12 +- .../Filters/LanguageAttribute.cs | 6 +- .../Grand.Web.Common/Grand.Web.Common.csproj | 3 + .../Helpers/AdminStoreService.cs | 4 +- .../IRequestCustomerResolver.cs | 2 +- .../ApplicationBuilderExtensions.cs | 7 +- .../Infrastructure/BackgroundServiceTask.cs | 8 +- .../Infrastructure/MediaRootFileProvider.cs | 2 +- .../Infrastructure/PluginAssetContentTypes.cs | 5 +- .../ServiceCollectionExtensions.cs | 20 +-- .../Localization/IEnumTranslationService.cs | 6 +- .../Localization/LocService.cs | 6 +- .../Localization/RequestTranslationService.cs | 2 +- src/Web/Grand.Web.Common/Menu/SiteMap.cs | 2 +- src/Web/Grand.Web.Common/Menu/SiteMapNode.cs | 12 +- .../Middleware/ContextLoggingMiddleware.cs | 2 +- .../Middleware/CultureSettingMiddleware.cs | 5 +- .../Middleware/InstallUrlMiddleware.cs | 2 +- .../Models/Cms/WidgetModel.cs | 6 +- .../Models/CustomAttributeModel.cs | 4 +- .../Models/CustomerGroupModel.cs | 4 +- .../Models/DatePickerDropDownsModel.cs | 8 +- .../Models/DeleteConfirmationModel.cs | 6 +- .../Models/ImportWindowModel.cs | 24 ++-- src/Web/Grand.Web.Common/Models/StoreModel.cs | 4 +- .../Grand.Web.Common/Page/IPageHeadBuilder.cs | 8 +- .../Grand.Web.Common/Page/PageHeadBuilder.cs | 10 +- .../AllowAnonymousCustomerResolver.cs | 2 +- .../ApiUserCustomerResolver.cs | 4 +- .../CookieCustomerResolver.cs | 2 +- .../GuestCookieCustomerResolver.cs | 2 +- .../GuestCustomerPersistence.cs | 6 +- .../GuestCustomerRules.cs | 2 +- .../IGuestCustomerPersistence.cs | 4 +- .../SearchEngineCustomerResolver.cs | 2 +- src/Web/Grand.Web.Common/RequestStorePin.cs | 2 +- .../Routing/LanguageParameterTransformer.cs | 2 +- .../Routing/SlugRouteTransformer.cs | 8 +- .../ApiAuthenticationService.cs | 12 +- .../CookieAuthenticationService.cs | 30 ++-- .../Authentication/CookieOptionsFactory.cs | 2 +- .../Authentication/ExternalSignInService.cs | 13 +- .../IApiAuthenticationService.cs | 2 +- .../Authentication/ICookieOptionsFactory.cs | 2 +- .../Authentication/IExternalSignInService.cs | 2 +- .../IGrandAuthenticationService.cs | 6 +- .../PermissionAuthorizeActionAttribute.cs | 2 +- .../Authorization/RequestPermissionService.cs | 4 +- .../Captcha/GoogleReCaptchaValidator.cs | 8 +- .../Captcha/GoogleRecaptchaControl.cs | 8 +- .../ExternalRegistrationContext.cs | 2 +- .../ExternalRegistrationIdentity.cs | 4 +- .../IExternalRegistrationContext.cs | 2 +- .../ExternalRegistration/ProviderSignOut.cs | 8 +- .../Oidc/IOidcProtectedResourceRegistry.cs | 2 +- .../OidcAuthenticationBuilderExtensions.cs | 2 +- .../Oidc/OidcAuthenticationFailure.cs | 6 +- .../Oidc/OidcBackChannelLogoutEndpoint.cs | 11 +- .../Security/Oidc/OidcCanonicalUri.cs | 6 +- .../Security/Oidc/OidcChallengeWriter.cs | 8 +- .../Security/Oidc/OidcJwtBearerEvents.cs | 4 +- .../Security/Oidc/OidcLoginIdentityMapper.cs | 4 +- .../Security/Oidc/OidcLoginProvider.cs | 2 +- .../Security/Oidc/OidcLoginSessionData.cs | 8 +- .../Security/Oidc/OidcLogoutToken.cs | 4 +- .../Security/Oidc/OidcLogoutTokenValidator.cs | 6 +- .../Security/Oidc/OidcPath.cs | 2 +- .../Security/Oidc/OidcProfileSynchronizer.cs | 2 +- .../Oidc/OidcProtectedResourceMetadata.cs | 26 ++-- .../Oidc/OidcProtectedResourceRegistry.cs | 8 +- .../Oidc/OidcRequestCustomerResolver.cs | 2 +- .../Security/Oidc/OidcResourceAccess.cs | 2 +- .../Security/Oidc/OidcSchemeSelector.cs | 8 +- .../Security/Oidc/OidcSignOutProvider.cs | 4 +- .../Security/Oidc/OidcTokenChecks.cs | 10 +- .../Security/Oidc/OidcTokenRefresher.cs | 4 +- .../Startup/OidcLoginStartup.cs | 4 +- .../Startup/StartupApplication.cs | 3 +- .../Grand.Web.Common/StoreContextSetter.cs | 27 ++-- .../Admin/AdminActionMenuTagHelper.cs | 12 +- .../TagHelpers/Admin/AdminBulkBarTagHelper.cs | 2 +- .../TagHelpers/Admin/AdminCardTagHelper.cs | 8 +- .../TagHelpers/Admin/AdminCultureTagHelper.cs | 2 +- .../Admin/AdminDeleteConfirmationTagHelper.cs | 9 +- .../TagHelpers/Admin/AdminFieldTagHelper.cs | 32 +++-- .../TagHelpers/Admin/AdminFiltersTagHelper.cs | 2 +- .../TagHelpers/Admin/AdminGridTagHelper.cs | 66 ++++----- .../Admin/AdminImportWindowTagHelper.cs | 33 ++--- .../TagHelpers/Admin/AdminInputTagHelper.cs | 30 ++-- .../TagHelpers/Admin/AdminPageTagHelper.cs | 10 +- .../TagHelpers/Admin/AdminPopupTagHelper.cs | 4 +- .../Admin/AdminTabAppendTagHelper.cs | 7 +- .../Admin/AdminTabContentTagHelper.cs | 11 +- .../Admin/AdminTabStripItemTagHelper.cs | 11 +- .../Admin/AdminTabStripTagHelper.cs | 18 +-- .../TagHelpers/Admin/AdminText.cs | 8 +- .../Admin/AdminTextAreaTagHelper.cs | 4 +- .../TagHelpers/Admin/AuditHistoryTagHelper.cs | 9 +- .../Admin/Extend/DefaultDisplayTemplates.cs | 12 +- .../Admin/Extend/DefaultEditorTemplates.cs | 14 +- .../Admin/Extend/DefaultHtmlGenerator.cs | 112 ++++++++------- .../Extend/ExpressionMetadataProvider.cs | 2 +- .../Admin/Extend/NameAndIdProvider.cs | 28 ++-- .../Admin/Extend/TemplateBuilder.cs | 14 +- .../Admin/Extend/TemplateRenderer.cs | 6 +- .../Admin/Extend/ValidationHelpers.cs | 4 +- .../TagHelpers/Admin/Extend/ViewBuffer.cs | 21 +-- .../Admin/Extend/ViewBufferTextWriter.cs | 23 +-- .../TagHelpers/Admin/Grid/GridCulture.cs | 54 +++---- .../TagHelpers/Admin/Grid/GridDefinition.cs | 104 +++++++------- .../TagHelpers/Admin/GridColumnTagHelper.cs | 26 ++-- .../TagHelpers/Admin/GridCommandsTagHelper.cs | 63 +++++---- .../DatePickerDropDownsTagHelper.cs | 16 ++- .../TagHelpers/GenerateCaptchaTagHelper.cs | 3 +- .../TagHelpers/GrandTextAreaTagHelper.cs | 2 +- .../TagHelpers/HtmlClassTagHelper.cs | 2 +- .../TagHelpers/InputTagHelper.cs | 2 +- .../Grand.Web.Common/TagHelpers/LinkEntry.cs | 24 ++-- .../TagHelpers/LinkTagHelper.cs | 10 +- .../TagHelpers/LocalizedEditorTagHelper.cs | 23 +-- .../TagHelpers/MetaKeywordsTagHelper.cs | 2 +- .../TagHelpers/PageNavigationTagHelper.cs | 58 ++++---- .../TagHelpers/PictureSourceTagHelper.cs | 2 +- .../TagHelpers/ResourceManager.cs | 4 +- .../TagHelpers/ScriptTagHelper.cs | 2 +- .../TagHelpers/TabsTagHelper.cs | 26 ++-- .../TagHelpers/TitleTagHelper.cs | 2 +- .../Grand.Web.Common/Themes/IThemeContext.cs | 2 +- .../Themes/IThemeContextFactory.cs | 2 +- .../Grand.Web.Common/Themes/ThemeContext.cs | 4 +- .../Themes/ThemeContextBase.cs | 2 +- .../Themes/ThemeContextFactory.cs | 2 +- .../Validators/CaptchaValidator.cs | 24 ++-- .../View/DefaultAreaViewFactory.cs | 2 +- .../View/ViewLocationExpander.cs | 2 +- src/Web/Grand.Web.Common/WorkContextSetter.cs | 102 +++++++------- .../Blogs/AddBlogCommentModel.cs | 2 +- .../Blogs/BlogCommentModel.cs | 6 +- .../Blogs/BlogPagingFilteringModel.cs | 8 +- .../Blogs/BlogPostCategoryModel.cs | 6 +- .../Blogs/BlogPostListModel.cs | 4 +- .../Grand.Web.Models/Blogs/BlogPostModel.cs | 14 +- .../Blogs/BlogPostTagModel.cs | 2 +- .../Blogs/HomePageBlogItemsModel.cs | 12 +- .../Grand.Web.Models/Catalog/BrandModel.cs | 20 +-- .../Catalog/CatalogPagingFilteringModel.cs | 55 ++++---- .../Grand.Web.Models/Catalog/CategoryModel.cs | 32 ++--- .../Catalog/CategoryNavigationModel.cs | 6 +- .../Catalog/CategorySimpleModel.cs | 12 +- .../Catalog/CollectionModel.cs | 16 +-- .../Catalog/CollectionNavigationModel.cs | 6 +- .../CustomerOutOfStockSubscriptionsModel.cs | 8 +- src/Web/Grand.Web.Models/Catalog/MenuModel.cs | 18 +-- .../Catalog/OutOfStockSubscribeModel.cs | 6 +- .../Catalog/ProductAskQuestionModel.cs | 16 +-- .../Catalog/ProductAskQuestionSimpleModel.cs | 8 +- .../ProductDetailsAttributeChangeModel.cs | 16 +-- .../Catalog/ProductDetailsModel.cs | 132 +++++++++--------- .../Catalog/ProductEmailAFriendModel.cs | 14 +- .../Grand.Web.Models/Catalog/ProductModel.cs | 10 +- .../Catalog/ProductOverviewModel.cs | 50 +++---- .../Catalog/ProductReviewModel.cs | 36 ++--- .../Catalog/ProductSpecificationModel.cs | 8 +- .../Catalog/ProductStructuredDataModel.cs | 4 +- .../Catalog/ProductTagModel.cs | 4 +- .../Catalog/ProductsByTagModel.cs | 4 +- .../Catalog/SearchAutoCompleteModel.cs | 14 +- .../Catalog/SearchBoxModel.cs | 2 +- .../Grand.Web.Models/Catalog/SearchModel.cs | 18 +-- .../Grand.Web.Models/Catalog/VendorModel.cs | 16 +-- .../Catalog/VendorNavigationModel.cs | 4 +- .../Checkout/CheckoutBillingAddressModel.cs | 2 +- .../Checkout/CheckoutCompletedModel.cs | 4 +- .../Checkout/CheckoutConfirmModel.cs | 14 +- .../Checkout/CheckoutModel.cs | 4 +- .../Checkout/CheckoutPaymentInfoModel.cs | 4 +- .../Checkout/CheckoutPaymentMethodModel.cs | 18 +-- .../Checkout/CheckoutPickupPointModel.cs | 10 +- .../Checkout/CheckoutShippingAddressModel.cs | 4 +- .../Checkout/CheckoutShippingMethodModel.cs | 14 +- .../Checkout/UpdateSectionJsonModel.cs | 4 +- .../Common/AddressAttributeModel.cs | 6 +- .../Grand.Web.Models/Common/AddressModel.cs | 38 ++--- .../Grand.Web.Models/Common/CurrencyModel.cs | 6 +- .../Grand.Web.Models/Common/FooterModel.cs | 32 ++--- .../Grand.Web.Models/Common/LanguageModel.cs | 6 +- .../Common/PrivacyPreferenceModel.cs | 6 +- .../Common/SiteStructuredDataModel.cs | 10 +- .../Common/StateProvinceModel.cs | 4 +- src/Web/Grand.Web.Models/Common/StoreModel.cs | 4 +- .../Common/StoreThemeModel.cs | 4 +- .../Contact/ContactUsModel.cs | 22 +-- .../Grand.Web.Models/Course/CourseModel.cs | 28 ++-- .../Grand.Web.Models/Course/LessonModel.cs | 24 ++-- .../Customer/AccountActivationModel.cs | 2 +- .../Customer/ChangePasswordModel.cs | 8 +- .../Grand.Web.Models/Customer/CoursesModel.cs | 10 +- .../Customer/CustomerAttributeModel.cs | 6 +- .../Customer/CustomerAuctionsModel.cs | 12 +- .../CustomerDownloadableProductsModel.cs | 16 +-- .../Customer/CustomerInfoModel.cs | 46 +++--- .../Customer/CustomerNotesModel.cs | 10 +- .../Customer/CustomerProductReviewModel.cs | 20 +-- .../Customer/DeleteAccountModel.cs | 2 +- .../Customer/DocumentsModel.cs | 16 +-- .../ExternalAuthenticationMethodModel.cs | 2 +- .../Grand.Web.Models/Customer/LoginModel.cs | 6 +- .../Customer/OidcLinkModel.cs | 4 +- .../Customer/PasswordRecoveryConfirmModel.cs | 10 +- .../Customer/PaswordRecoveryModel.cs | 4 +- .../Customer/RegisterModel.cs | 38 ++--- .../Customer/RegisterResultModel.cs | 2 +- .../Customer/SubAccountCreateModel.cs | 8 +- .../Customer/SubAccountEditModel.cs | 10 +- .../Customer/SubAccountSimpleModel.cs | 6 +- .../Grand.Web.Models/Grand.Web.Models.csproj | 3 + .../AddKnowledgebaseArticleCommentModel.cs | 2 +- .../KnowledgebaseArticleCommentModel.cs | 6 +- .../KnowledgebaseArticleModel.cs | 16 +-- .../KnowledgebaseCategoryModel.cs | 10 +- .../KnowledgebaseHomePageModel.cs | 16 +-- .../Knowledgebase/KnowledgebaseItemModel.cs | 6 +- .../Grand.Web.Models/Media/PictureModel.cs | 14 +- .../News/AddNewsCommentModel.cs | 6 +- .../News/HomePageNewsItemsModel.cs | 10 +- .../Grand.Web.Models/News/NewsCommentModel.cs | 8 +- .../News/NewsItemListModel.cs | 12 +- .../Grand.Web.Models/News/NewsItemModel.cs | 16 +-- .../Newsletter/NewsletterCategoryModel.cs | 10 +- .../SubscribeNewsletterResultModel.cs | 6 +- .../Newsletter/SubscriptionActivationModel.cs | 2 +- .../Orders/AddOrderNoteModel.cs | 4 +- .../Orders/CustomerLoyaltyPointsModel.cs | 6 +- .../Orders/CustomerMerchandiseReturnsModel.cs | 8 +- .../Orders/CustomerOrderListModel.cs | 20 +-- .../Orders/GuestOrderModel.cs | 6 +- .../Orders/MerchandiseReturnDetailsModel.cs | 46 +++--- .../Orders/MerchandiseReturnEstimateModel.cs | 6 +- .../MerchandiseReturnInStorePointModel.cs | 6 +- .../Orders/MerchandiseReturnModel.cs | 38 ++--- .../Orders/OrderApprovalListModel.cs | 8 +- .../Orders/OrderApprovalModel.cs | 32 ++--- .../Orders/OrderDetailsModel.cs | 78 +++++------ .../Orders/RecurringPaymentListModel.cs | 8 +- .../Orders/ReturnShippingOfferModel.cs | 14 +- .../Orders/ShipmentDetailsModel.cs | 40 +++--- .../Pages/AuthenticateModel.cs | 4 +- src/Web/Grand.Web.Models/Pages/PageModel.cs | 18 +-- .../PushNotifications/PublicInfoModel.cs | 14 +- .../ShoppingCart/AddBidModel.cs | 6 +- .../ShoppingCart/AddCartFromWishlistModel.cs | 2 +- .../ShoppingCart/AddToCartModel.cs | 20 +-- .../ShoppingCart/ChangeTypeCartItemModel.cs | 2 +- .../ShoppingCart/DeleteCartItemModel.cs | 2 +- .../ShoppingCart/DiscountCouponModel.cs | 2 +- .../ShoppingCart/EstimateShippingModel.cs | 12 +- .../ShoppingCart/GiftVoucherCouponModel.cs | 2 +- .../ShoppingCart/MiniShoppingCartModel.cs | 14 +- .../ShoppingCart/MiniWishlistModel.cs | 14 +- .../ShoppingCart/OrderTotalsModel.cs | 28 ++-- .../ShoppingCart/ProductCatalogCart.cs | 2 +- .../ShoppingCart/ProductDetailsCart.cs | 26 ++-- .../ShoppingCart/ShoppingCartModel.cs | 62 ++++---- .../ShoppingCart/UpdateQuantityModel.cs | 2 +- .../ShoppingCart/WishlistEmailAFriendModel.cs | 8 +- .../ShoppingCart/WishlistModel.cs | 24 ++-- .../Vendors/ApplyVendorModel.cs | 8 +- .../Vendors/ContactVendorModel.cs | 14 +- .../Vendors/VendorAddressModel.cs | 24 ++-- .../Vendors/VendorReviewOverviewModel.cs | 32 ++--- 323 files changed, 1918 insertions(+), 1811 deletions(-) diff --git a/src/Business/Grand.Business.Authentication/Services/OidcSessionService.cs b/src/Business/Grand.Business.Authentication/Services/OidcSessionService.cs index 83aae4b19..c4a4efa32 100644 --- a/src/Business/Grand.Business.Authentication/Services/OidcSessionService.cs +++ b/src/Business/Grand.Business.Authentication/Services/OidcSessionService.cs @@ -252,7 +252,7 @@ await _sessionRepository.UpdateOneAsync(x => x.Id == sessionId && x.EndedUtc == _logger.LogInformation("OpenID Connect session {SessionId} ended: {Reason}", sessionId, reason); } - public virtual async Task> EndBySid(string subject, string sid) + public virtual async Task> EndBySid(string? subject, string sid) { ArgumentException.ThrowIfNullOrEmpty(sid); var query = _sessionRepository.Table.Where(x => x.Sid == sid && x.EndedUtc == null); diff --git a/src/Business/Grand.Business.Authentication/Services/OidcTokenRevocationService.cs b/src/Business/Grand.Business.Authentication/Services/OidcTokenRevocationService.cs index ae7b3494e..1881ebefe 100644 --- a/src/Business/Grand.Business.Authentication/Services/OidcTokenRevocationService.cs +++ b/src/Business/Grand.Business.Authentication/Services/OidcTokenRevocationService.cs @@ -42,7 +42,7 @@ await revocationRepository.UpdateOneAsync(x => x.Id == id && x.RevokedBeforeUtc UpdateBuilder.Create().Set(x => x.RevokedBeforeUtc, now)); } - public async Task IsRevoked(string subject, DateTime issuedUtc) + public async Task IsRevoked(string? subject, DateTime issuedUtc) { if (string.IsNullOrEmpty(subject)) return false; diff --git a/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs b/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs index fc211bedb..5ffe67186 100644 --- a/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs +++ b/src/Business/Grand.Business.Cms/Services/KnowledgebaseService.cs @@ -282,7 +282,7 @@ public virtual async Task> GetPublicKnowledgebaseArti /// Customer groups the articles must be visible to /// List of public knowledge base articles public virtual async Task> GetPublicKnowledgebaseArticles(string storeId, - IList customerGroupIds) + IList? customerGroupIds) { var query = from p in _knowledgebaseArticleRepository.Table select p; diff --git a/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs b/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs index 76f495b0d..f866f8dfd 100644 --- a/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs +++ b/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs @@ -162,7 +162,7 @@ public virtual async Task UpdatePermission(Permission permission) /// Permission /// Customer /// true - authorized; otherwise, false - public virtual async Task Authorize(Permission permission, Customer customer) + public virtual async Task Authorize(Permission permission, Customer? customer) { if (permission == null) return false; @@ -179,7 +179,7 @@ public virtual async Task Authorize(Permission permission, Customer custom /// Permission system name /// Customer /// true - authorized; otherwise, false - public virtual async Task Authorize(string? permissionSystemName, Customer customer) + public virtual async Task Authorize(string? permissionSystemName, Customer? customer) { if (string.IsNullOrEmpty(permissionSystemName)) return false; diff --git a/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs b/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs index 09c36f287..0ef3438e3 100644 --- a/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs +++ b/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs @@ -117,7 +117,7 @@ orderby ur.IsActive /// /// Slug /// Found URL Entity - public virtual async Task GetBySlugCached(string slug) + public virtual async Task GetBySlugCached(string? slug) { if (string.IsNullOrEmpty(slug)) return null; @@ -165,7 +165,7 @@ public virtual async Task> GetAllEntityUrl(string slug = " /// Entity name /// Language identifier /// Found slug - public virtual async Task GetActiveSlug(string entityId, string entityName, string languageId) + public virtual async Task GetActiveSlug(string? entityId, string? entityName, string? languageId) { var key = string.Format(CacheKey.URLEntity_ACTIVE_BY_ID_NAME_LANGUAGE_KEY, entityId, entityName, languageId); return await _cacheBase.GetAsync(key, async () => diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalSignInPathProvider.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalSignInPathProvider.cs index 2f4877e1c..3779cfc17 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalSignInPathProvider.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalSignInPathProvider.cs @@ -10,5 +10,5 @@ public interface IExternalSignInPathProvider : IExternalAuthenticationProvider /// Path (from the application root, starting with "/") that signs in and returns to ; /// null when the provider cannot sign in now (for example, not configured) /// - Task GetSignInPath(string returnUrl); + Task GetSignInPath(string returnUrl); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalSignOutProvider.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalSignOutProvider.cs index 55960e44d..b94e49537 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalSignOutProvider.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IExternalSignOutProvider.cs @@ -7,5 +7,5 @@ public interface IExternalSignOutProvider /// Absolute URL that ends the session at the provider and returns to /// (registered at the provider); null when the provider cannot do it now /// - Task GetSignOutUrl(string postLogoutRedirectUri); + Task GetSignOutUrl(string postLogoutRedirectUri); } diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcSessionService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcSessionService.cs index 116839ea5..100a8132f 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcSessionService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcSessionService.cs @@ -22,7 +22,7 @@ public interface IOidcSessionService Task End(string sessionId, OidcSessionEndReason reason); /// Ends the open sessions with the provider session id (and the subject, when given); returns them - Task> EndBySid(string subject, string sid); + Task> EndBySid(string? subject, string sid); /// Ends every open session of the subject; returns them Task> EndBySubject(string subject); diff --git a/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcTokenRevocationService.cs b/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcTokenRevocationService.cs index 904669fe6..8f30b7dc9 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcTokenRevocationService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Authentication/IOidcTokenRevocationService.cs @@ -10,7 +10,7 @@ public interface IOidcTokenRevocationService Task RevokeTokens(string? subject); /// The token of the subject issued at is refused - Task IsRevoked(string subject, DateTime issuedUtc); + Task IsRevoked(string? subject, DateTime issuedUtc); /// Deletes revocations older than any access token they could still refuse Task DeleteExpired(); diff --git a/src/Business/Grand.Business.Core/Interfaces/Cms/IKnowledgebaseService.cs b/src/Business/Grand.Business.Core/Interfaces/Cms/IKnowledgebaseService.cs index a9363eb2e..d86fd646b 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Cms/IKnowledgebaseService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Cms/IKnowledgebaseService.cs @@ -87,7 +87,7 @@ public interface IKnowledgebaseService /// Store ident /// Customer groups the articles must be visible to /// List of public knowledge base articles - Task> GetPublicKnowledgebaseArticles(string storeId, IList customerGroupIds); + Task> GetPublicKnowledgebaseArticles(string storeId, IList? customerGroupIds); /// /// Gets homepage knowledge base articles diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Security/IPermissionService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Security/IPermissionService.cs index 26b939f4c..5e7b8da13 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Security/IPermissionService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Security/IPermissionService.cs @@ -52,7 +52,7 @@ public interface IPermissionService /// Permission /// Customer /// true - authorized; otherwise, false - Task Authorize(Permission permission, Customer customer); + Task Authorize(Permission permission, Customer? customer); /// /// Authorize permission @@ -60,7 +60,7 @@ public interface IPermissionService /// Permission system name /// Customer /// true - authorized; otherwise, false - Task Authorize(string permissionSystemName, Customer customer); + Task Authorize(string permissionSystemName, Customer? customer); /// /// Gets a permission actions diff --git a/src/Business/Grand.Business.Core/Interfaces/Common/Seo/ISlugService.cs b/src/Business/Grand.Business.Core/Interfaces/Common/Seo/ISlugService.cs index 0c32d044c..ebff7c4fa 100644 --- a/src/Business/Grand.Business.Core/Interfaces/Common/Seo/ISlugService.cs +++ b/src/Business/Grand.Business.Core/Interfaces/Common/Seo/ISlugService.cs @@ -45,7 +45,7 @@ public interface ISlugService /// /// Slug /// Found URL Entity - Task GetBySlugCached(string slug); + Task GetBySlugCached(string? slug); /// /// Gets all URL Entity @@ -65,7 +65,7 @@ Task> GetAllEntityUrl(string slug = "", bool? active = nul /// Entity name /// Language identifier /// Found slug - Task GetActiveSlug(string entityId, string entityName, string languageId); + Task GetActiveSlug(string? entityId, string? entityName, string? languageId); /// /// Save slug diff --git a/src/Business/Grand.Business.Core/Utilities/Authentication/OidcRefreshResult.cs b/src/Business/Grand.Business.Core/Utilities/Authentication/OidcRefreshResult.cs index 436fc085c..1ad973874 100644 --- a/src/Business/Grand.Business.Core/Utilities/Authentication/OidcRefreshResult.cs +++ b/src/Business/Grand.Business.Core/Utilities/Authentication/OidcRefreshResult.cs @@ -22,7 +22,7 @@ public enum OidcRefreshOutcome /// The rotated refresh token, or null when the provider keeps the old one public sealed record OidcRefreshResult(OidcRefreshOutcome Outcome, string? RefreshToken = null) { - public static OidcRefreshResult Refreshed(string refreshToken) => new(OidcRefreshOutcome.Refreshed, refreshToken); + public static OidcRefreshResult Refreshed(string? refreshToken) => new(OidcRefreshOutcome.Refreshed, refreshToken); public static OidcRefreshResult Refused() => new(OidcRefreshOutcome.Refused); public static OidcRefreshResult Unavailable() => new(OidcRefreshOutcome.Unavailable); public static OidcRefreshResult NotAsked() => new(OidcRefreshOutcome.NotAsked); diff --git a/src/Business/Grand.Business.Storage/Services/MediaFileStoreFactory.cs b/src/Business/Grand.Business.Storage/Services/MediaFileStoreFactory.cs index 703576ee4..1827cb231 100644 --- a/src/Business/Grand.Business.Storage/Services/MediaFileStoreFactory.cs +++ b/src/Business/Grand.Business.Storage/Services/MediaFileStoreFactory.cs @@ -20,7 +20,7 @@ public static class MediaFileStoreFactory /// Runs once per request scope, so it does not touch the file system; the media directory is created /// at startup (MediaRootFileProvider.Apply) /// - public static IFileStore Create(string webRootPath, string mediaRootPath, string directory) + public static IFileStore Create(string webRootPath, string? mediaRootPath, string? directory) { var webRootStore = new FileSystemStore(Path.Combine(webRootPath, directory ?? "")); if (string.IsNullOrEmpty(mediaRootPath)) return webRootStore; diff --git a/src/Core/Grand.Data/Audit/AuditActor.cs b/src/Core/Grand.Data/Audit/AuditActor.cs index 1edc41a91..4e3d87949 100644 --- a/src/Core/Grand.Data/Audit/AuditActor.cs +++ b/src/Core/Grand.Data/Audit/AuditActor.cs @@ -7,15 +7,15 @@ namespace Grand.Data.Audit; /// public record AuditActor( AuditSource Source, - string CustomerId, - string Email, - string ImpersonatedCustomerId, - string StoreId, - string VendorId, - string IpAddress, - string UserAgent, - string Action, - string OperationId) + string? CustomerId, + string? Email, + string? ImpersonatedCustomerId, + string? StoreId, + string? VendorId, + string? IpAddress, + string? UserAgent, + string? Action, + string? OperationId) { public void Stamp(AuditEntry entry) { diff --git a/src/Core/Grand.Domain/Stores/StoreExtensions.cs b/src/Core/Grand.Domain/Stores/StoreExtensions.cs index d4ec39b5d..b6b3e0632 100644 --- a/src/Core/Grand.Domain/Stores/StoreExtensions.cs +++ b/src/Core/Grand.Domain/Stores/StoreExtensions.cs @@ -26,7 +26,7 @@ public static bool ContainsHostValue(this Store store, string host) /// Store /// Host /// DomainHost - public static DomainHost? HostValue(this Store store, string host) + public static DomainHost? HostValue(this Store store, string? host) { ArgumentNullException.ThrowIfNull(store); return string.IsNullOrEmpty(host) diff --git a/src/Core/Grand.Infrastructure/Extensions/CommonExtensions.cs b/src/Core/Grand.Infrastructure/Extensions/CommonExtensions.cs index 3253dae78..8e7c751a2 100644 --- a/src/Core/Grand.Infrastructure/Extensions/CommonExtensions.cs +++ b/src/Core/Grand.Infrastructure/Extensions/CommonExtensions.cs @@ -5,7 +5,7 @@ namespace Grand.Infrastructure.Extensions; public static class CommonExtensions { - public static string ModifyQueryString(string url, string key, string value) + public static string ModifyQueryString(string url, string? key, string? value) { if (string.IsNullOrEmpty(url)) return string.Empty; diff --git a/src/Core/Grand.Infrastructure/IContextAccessor.cs b/src/Core/Grand.Infrastructure/IContextAccessor.cs index 7fff7cf67..19c808aff 100644 --- a/src/Core/Grand.Infrastructure/IContextAccessor.cs +++ b/src/Core/Grand.Infrastructure/IContextAccessor.cs @@ -2,7 +2,23 @@ public interface IContextAccessor { + /// + /// The work context of the current request; throws when none is set, as outside a request + /// IWorkContext WorkContext { get; set; } + /// + /// The store context of the current request; throws when none is set, as outside a request + /// IStoreContext StoreContext { get; set; } -} + + /// + /// The work context, or null when none is set: for code that also runs outside a request + /// + IWorkContext? CurrentWorkContext { get; } + + /// + /// The store context, or null when none is set: for code that also runs outside a request + /// + IStoreContext? CurrentStoreContext { get; } +} \ No newline at end of file diff --git a/src/Core/Grand.Infrastructure/IWorkContext.cs b/src/Core/Grand.Infrastructure/IWorkContext.cs index b0571c19f..58be60a18 100644 --- a/src/Core/Grand.Infrastructure/IWorkContext.cs +++ b/src/Core/Grand.Infrastructure/IWorkContext.cs @@ -20,12 +20,12 @@ public interface IWorkContext /// /// Gets or sets the original customer (in case the current one is impersonated) /// - Customer OriginalCustomerIfImpersonated { get; } + Customer? OriginalCustomerIfImpersonated { get; } /// /// Gets the current vendor (logged-in manager) /// - Vendor CurrentVendor { get; } + Vendor? CurrentVendor { get; } /// /// Get or set current user working language @@ -40,7 +40,7 @@ public interface IWorkContext /// /// Get the store manager /// - Store StoreManager { get; } + Store? StoreManager { get; } /// /// Get current tax display type diff --git a/src/Core/Grand.SharedKernel/Captcha/IGoogleReCaptchaValidator.cs b/src/Core/Grand.SharedKernel/Captcha/IGoogleReCaptchaValidator.cs index f21719956..aed3a7a9f 100644 --- a/src/Core/Grand.SharedKernel/Captcha/IGoogleReCaptchaValidator.cs +++ b/src/Core/Grand.SharedKernel/Captcha/IGoogleReCaptchaValidator.cs @@ -1,5 +1,5 @@ namespace Grand.SharedKernel.Captcha; public interface IGoogleReCaptchaValidator { - Task Validate(string response, CancellationToken cancellationToken = default); + Task Validate(string response, CancellationToken cancellationToken = default); } diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductCommandHandler.cs index b95737f6a..5c0d434a6 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/AddProductCommandHandler.cs @@ -38,7 +38,7 @@ public async Task Handle(AddProductCommand request, CancellationToke //the stock the product starts with goes into the journal before the product exists await _stockMovementService.JournalNewProduct(product, InventoryMovementType.Api, new StockSource("Api", product.Id, Reference: product.Sku ?? "", - CustomerId: _contextAccessor.WorkContext?.CurrentCustomer?.Id ?? "")); + CustomerId: _contextAccessor.WorkContext.CurrentCustomer.Id ?? "")); await _productService.InsertProduct(product); request.Model.SeName = await _seNameService.ValidateSeName(product, request.Model.SeName, product.Name, true); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductCommandHandler.cs index 648c6842b..69776bb85 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductCommandHandler.cs @@ -62,7 +62,7 @@ await _stockMovementService.Apply(product.Id, [ new StockChange([], "", stockChanged ? product.StockQuantity : 0, stockChanged, InventoryMovementType.Api, new StockSource("Api", product.Id, Reference: product.Sku ?? "", - CustomerId: _contextAccessor.WorkContext?.CurrentCustomer?.Id ?? "")) { + CustomerId: _contextAccessor.WorkContext.CurrentCustomer.Id ?? "")) { ReservedQuantity = reservedChanged ? product.ReservedQuantity : null } ]); diff --git a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductStockCommandHandler.cs b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductStockCommandHandler.cs index 84ee45ecc..0160a84fc 100644 --- a/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductStockCommandHandler.cs +++ b/src/Modules/Grand.Module.Api/Commands/Handlers/Catalog/UpdateProductStockCommandHandler.cs @@ -53,7 +53,7 @@ public async Task Handle(UpdateProductStockCommand request, CancellationTo var errors = await _stockMovementService.Apply(product.Id, [ new StockChange([], request.WarehouseId ?? "", request.Stock, true, InventoryMovementType.Api, new StockSource("Api", product.Id, Reference: product.Sku ?? "", - CustomerId: _contextAccessor.WorkContext?.CurrentCustomer?.Id ?? "")) + CustomerId: _contextAccessor.WorkContext.CurrentCustomer.Id ?? "")) ]); if (errors.Count > 0) throw new ArgumentException(errors[0]); diff --git a/src/Modules/Grand.Module.Api/Extensions/ContextAccessorExtensions.cs b/src/Modules/Grand.Module.Api/Extensions/ContextAccessorExtensions.cs index 9729e20e7..26de38b6f 100644 --- a/src/Modules/Grand.Module.Api/Extensions/ContextAccessorExtensions.cs +++ b/src/Modules/Grand.Module.Api/Extensions/ContextAccessorExtensions.cs @@ -9,6 +9,6 @@ public static class ContextAccessorExtensions /// public static string WorkingLanguageId(this IContextAccessor contextAccessor) { - return contextAccessor.WorkContext?.WorkingLanguage?.Id ?? string.Empty; + return contextAccessor.CurrentWorkContext?.WorkingLanguage?.Id ?? string.Empty; } } diff --git a/src/Tests/Grand.Web.Common.Tests/Localization/RequestTranslationServiceTests.cs b/src/Tests/Grand.Web.Common.Tests/Localization/RequestTranslationServiceTests.cs index 2398c4cb8..c5f3059f6 100644 --- a/src/Tests/Grand.Web.Common.Tests/Localization/RequestTranslationServiceTests.cs +++ b/src/Tests/Grand.Web.Common.Tests/Localization/RequestTranslationServiceTests.cs @@ -27,7 +27,7 @@ public void Init() [TestMethod] public void GetResource_UsesWorkingLanguageOfTheRequest() { - _contextAccessorMock.Setup(c => c.WorkContext.WorkingLanguage).Returns(new Language { Id = "pl" }); + _contextAccessorMock.Setup(c => c.CurrentWorkContext.WorkingLanguage).Returns(new Language { Id = "pl" }); _serviceMock.Setup(x => x.GetResource("name", "pl", "", false)).Returns("nazwa"); var result = _service.GetResource("name"); @@ -38,7 +38,7 @@ public void GetResource_UsesWorkingLanguageOfTheRequest() [TestMethod] public void GetResource_WithoutWorkingLanguage_ReturnsEmpty() { - _contextAccessorMock.Setup(c => c.WorkContext.WorkingLanguage).Returns((Language)null); + _contextAccessorMock.Setup(c => c.CurrentWorkContext.WorkingLanguage).Returns((Language)null); var result = _service.GetResource("name"); @@ -51,7 +51,7 @@ public void GetResource_WithoutWorkingLanguage_ReturnsEmpty() [TestMethod] public void GetResource_WithoutWorkContext_ReturnsEmpty() { - _contextAccessorMock.Setup(c => c.WorkContext).Returns((IWorkContext)null); + _contextAccessorMock.Setup(c => c.CurrentWorkContext).Returns((IWorkContext)null); var result = _service.GetResource("name"); diff --git a/src/Tests/Grand.Web.Common.Tests/Security/Authorization/RequestPermissionServiceTests.cs b/src/Tests/Grand.Web.Common.Tests/Security/Authorization/RequestPermissionServiceTests.cs index a0db48c08..c3ccf0fb2 100644 --- a/src/Tests/Grand.Web.Common.Tests/Security/Authorization/RequestPermissionServiceTests.cs +++ b/src/Tests/Grand.Web.Common.Tests/Security/Authorization/RequestPermissionServiceTests.cs @@ -27,7 +27,7 @@ public void Init() public async Task Authorize_SystemName_UsesCustomerOfTheRequest() { var customer = new Customer(); - _contextAccessorMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(customer); + _contextAccessorMock.Setup(c => c.CurrentWorkContext.CurrentCustomer).Returns(customer); _permissionServiceMock.Setup(x => x.Authorize("ManageProducts", customer)).ReturnsAsync(true); Assert.IsTrue(await _service.Authorize("ManageProducts")); @@ -38,7 +38,7 @@ public async Task Authorize_Permission_UsesCustomerOfTheRequest() { var customer = new Customer(); var permission = new Permission { SystemName = "ManageProducts" }; - _contextAccessorMock.Setup(c => c.WorkContext.CurrentCustomer).Returns(customer); + _contextAccessorMock.Setup(c => c.CurrentWorkContext.CurrentCustomer).Returns(customer); _permissionServiceMock.Setup(x => x.Authorize(permission, customer)).ReturnsAsync(true); Assert.IsTrue(await _service.Authorize(permission)); @@ -47,7 +47,7 @@ public async Task Authorize_Permission_UsesCustomerOfTheRequest() [TestMethod] public async Task Authorize_WithoutWorkContext_PassesNoCustomer() { - _contextAccessorMock.Setup(c => c.WorkContext).Returns((IWorkContext)null); + _contextAccessorMock.Setup(c => c.CurrentWorkContext).Returns((IWorkContext)null); Assert.IsFalse(await _service.Authorize("ManageProducts")); Assert.IsFalse(await _service.Authorize(new Permission { SystemName = "ManageProducts" })); diff --git a/src/Tests/Grand.Web.Common.Tests/StoreContextSetterTests.cs b/src/Tests/Grand.Web.Common.Tests/StoreContextSetterTests.cs index a98b5e811..c941b2c49 100644 --- a/src/Tests/Grand.Web.Common.Tests/StoreContextSetterTests.cs +++ b/src/Tests/Grand.Web.Common.Tests/StoreContextSetterTests.cs @@ -36,11 +36,11 @@ public async Task InitializeStoreContext_LoadsTheSettingsOfTheStore() } [TestMethod] - public async Task InitializeStoreContext_NoStore_LoadsNoSettings() + public async Task InitializeStoreContext_NoStore_ThrowsAndLoadsNoSettings() { - var storeContext = await _setter.InitializeStoreContext("missing"); + //a request always has a store; without any there is no store context to build + await Assert.ThrowsExactlyAsync(() => _setter.InitializeStoreContext("missing")); - Assert.IsNull(storeContext.CurrentStore); _settingServiceMock.Verify(s => s.LoadStoreSettings(It.IsAny()), Times.Never); } } diff --git a/src/Tests/Grand.Web.Common.Tests/TagHelpers/AdminComponentTagHelperTests.cs b/src/Tests/Grand.Web.Common.Tests/TagHelpers/AdminComponentTagHelperTests.cs index a1ccaafaa..3e5662121 100644 --- a/src/Tests/Grand.Web.Common.Tests/TagHelpers/AdminComponentTagHelperTests.cs +++ b/src/Tests/Grand.Web.Common.Tests/TagHelpers/AdminComponentTagHelperTests.cs @@ -30,6 +30,7 @@ public void Init() workContextMock.Setup(x => x.WorkingLanguage).Returns(new Language { Id = "lang1" }); _contextAccessorMock = new Mock(); _contextAccessorMock.Setup(x => x.WorkContext).Returns(workContextMock.Object); + _contextAccessorMock.Setup(x => x.CurrentWorkContext).Returns(workContextMock.Object); _translationServiceMock = new Mock(); _translationServiceMock .Setup(x => x.GetResource(It.IsAny(), "lang1", string.Empty, true)) diff --git a/src/Tests/Grand.Web.Common.Tests/TagHelpers/AdminCultureTagHelperTests.cs b/src/Tests/Grand.Web.Common.Tests/TagHelpers/AdminCultureTagHelperTests.cs index 03bf29211..001fe3c72 100644 --- a/src/Tests/Grand.Web.Common.Tests/TagHelpers/AdminCultureTagHelperTests.cs +++ b/src/Tests/Grand.Web.Common.Tests/TagHelpers/AdminCultureTagHelperTests.cs @@ -33,6 +33,7 @@ public void Init() workContextMock.Setup(x => x.WorkingLanguage).Returns(() => _workingLanguage); _contextAccessorMock = new Mock(); _contextAccessorMock.Setup(x => x.WorkContext).Returns(workContextMock.Object); + _contextAccessorMock.Setup(x => x.CurrentWorkContext).Returns(workContextMock.Object); _translationServiceMock = new Mock(); _translationServiceMock .Setup(x => x.GetResource(It.IsAny(), "lang1", string.Empty, true)) diff --git a/src/Tests/Grand.Web.Common.Tests/TagHelpers/AdminGridTagHelperTests.cs b/src/Tests/Grand.Web.Common.Tests/TagHelpers/AdminGridTagHelperTests.cs index 33036697b..318348afc 100644 --- a/src/Tests/Grand.Web.Common.Tests/TagHelpers/AdminGridTagHelperTests.cs +++ b/src/Tests/Grand.Web.Common.Tests/TagHelpers/AdminGridTagHelperTests.cs @@ -43,6 +43,7 @@ public void Init() workContextMock.Setup(x => x.WorkingLanguage).Returns(() => _workingLanguage); _contextAccessorMock = new Mock(); _contextAccessorMock.Setup(x => x.WorkContext).Returns(workContextMock.Object); + _contextAccessorMock.Setup(x => x.CurrentWorkContext).Returns(workContextMock.Object); _translationServiceMock = new Mock(); _translationServiceMock.Setup(x => x.GetResource(It.IsAny())).Returns((string key) => $"[{key}]"); _translationServiceMock diff --git a/src/Tests/Grand.Web.Common.Tests/TagHelpers/AdminImportWindowTagHelperTests.cs b/src/Tests/Grand.Web.Common.Tests/TagHelpers/AdminImportWindowTagHelperTests.cs index ba9bbed82..01273ce72 100644 --- a/src/Tests/Grand.Web.Common.Tests/TagHelpers/AdminImportWindowTagHelperTests.cs +++ b/src/Tests/Grand.Web.Common.Tests/TagHelpers/AdminImportWindowTagHelperTests.cs @@ -37,6 +37,7 @@ public void Init() workContextMock.Setup(x => x.WorkingLanguage).Returns(new Language { Id = "lang1" }); _contextAccessorMock = new Mock(); _contextAccessorMock.Setup(x => x.WorkContext).Returns(workContextMock.Object); + _contextAccessorMock.Setup(x => x.CurrentWorkContext).Returns(workContextMock.Object); _translationServiceMock = new Mock(); _htmlHelperMock = new Mock(); _htmlHelperMock diff --git a/src/Web/Grand.Web.AdminShared/Services/MerchandiseReturnViewModelService.cs b/src/Web/Grand.Web.AdminShared/Services/MerchandiseReturnViewModelService.cs index 7c8c5c95b..f377c8f6e 100644 --- a/src/Web/Grand.Web.AdminShared/Services/MerchandiseReturnViewModelService.cs +++ b/src/Web/Grand.Web.AdminShared/Services/MerchandiseReturnViewModelService.cs @@ -549,7 +549,7 @@ public virtual async Task ResolveRefund(MerchandiseReturn merchandiseRet /// private async Task RefundsPayments() { - var customer = contextAccessor.WorkContext?.CurrentCustomer; + var customer = contextAccessor.WorkContext.CurrentCustomer; return customer != null && await actionPermissionService.AuthorizeAction( PermissionSystemName.PaymentTransactions, PermissionActionName.Edit, customer); } diff --git a/src/Web/Grand.Web.Common/Audit/AuditEventRecorder.cs b/src/Web/Grand.Web.Common/Audit/AuditEventRecorder.cs index 4d566a999..6dcc78450 100644 --- a/src/Web/Grand.Web.Common/Audit/AuditEventRecorder.cs +++ b/src/Web/Grand.Web.Common/Audit/AuditEventRecorder.cs @@ -22,7 +22,7 @@ public Task SignIn(Customer customer) return RecordSignInEvent(AuditKind.SignIn, customer, null); } - public Task SignInFailed(Customer customer, string reason) + public Task SignInFailed(Customer customer, string? reason) { return RecordSignInEvent(AuditKind.SignInFailed, customer, reason); } @@ -70,7 +70,7 @@ public Task AuditLogExported(string filterSummary, int rowCount) entry => entry.Details = $"filter: {filterSummary}; rows: {rowCount}"); } - public Task AccessDenied(string permission, string permissionAction) + public Task AccessDenied(string permission, string? permissionAction) { var details = string.IsNullOrEmpty(permissionAction) ? $"permission: {permission}" @@ -88,7 +88,7 @@ public Task Plugin(string pluginName, string change) }); } - private async Task RecordSignInEvent(AuditKind kind, Customer customer, string reason) + private async Task RecordSignInEvent(AuditKind kind, Customer? customer, string? reason) { try { @@ -119,7 +119,7 @@ private async Task IsStaff(Customer customer) } //the staff member behind the request, also while impersonating a customer - private Customer CurrentStaff() + private Customer? CurrentStaff() { var workContext = contextAccessor.WorkContext; return workContext?.OriginalCustomerIfImpersonated ?? workContext?.CurrentCustomer; @@ -133,7 +133,7 @@ private static void Target(AuditEntry entry, Customer target) entry.ImpersonatedCustomerId = target?.Id; } - private async Task Record(AuditKind kind, Customer actor, Action fill) + private async Task Record(AuditKind kind, Customer? actor, Action? fill) { try { diff --git a/src/Web/Grand.Web.Common/Audit/AuditRequest.cs b/src/Web/Grand.Web.Common/Audit/AuditRequest.cs index aa8310c03..bdce71d1f 100644 --- a/src/Web/Grand.Web.Common/Audit/AuditRequest.cs +++ b/src/Web/Grand.Web.Common/Audit/AuditRequest.cs @@ -16,13 +16,13 @@ public static class AuditRequest /// /// The source of a panel, API or SCIM request: an [AuditSource] mark wins over the area. Null otherwise. /// - public static AuditSource? StaffSource(IEnumerable endpointMetadata, RouteValueDictionary routeValues) + public static AuditSource? StaffSource(IEnumerable? endpointMetadata, RouteValueDictionary? routeValues) { var marked = endpointMetadata?.OfType().LastOrDefault(); if (marked != null) return marked.Source; - return routeValues?["area"] as string switch { + return (routeValues?["area"] as string) switch { "Admin" => AuditSource.Admin, "Store" => AuditSource.Store, "Vendor" => AuditSource.Vendor, @@ -30,8 +30,8 @@ public static class AuditRequest }; } - public static AuditActor Actor(HttpContext httpContext, RouteValueDictionary routeValues, AuditSource source, - string customerId, string email, string impersonatedCustomerId, string storeId, string vendorId) + public static AuditActor Actor(HttpContext? httpContext, RouteValueDictionary? routeValues, AuditSource source, + string? customerId, string? email, string? impersonatedCustomerId, string? storeId, string? vendorId) { return new AuditActor( source, @@ -42,7 +42,7 @@ public static AuditActor Actor(HttpContext httpContext, RouteValueDictionary rou vendorId, httpContext?.Connection.RemoteIpAddress?.ToString(), httpContext?.Request.Headers.UserAgent.ToString(), - httpContext == null ? null : $"{source} / {routeValues["controller"]} / {routeValues["action"]}", + httpContext == null ? null : $"{source} / {routeValues?["controller"]} / {routeValues?["action"]}", httpContext == null ? null : Activity.Current?.TraceId.ToString() ?? httpContext.TraceIdentifier); } } diff --git a/src/Web/Grand.Web.Common/Audit/IAuditEventRecorder.cs b/src/Web/Grand.Web.Common/Audit/IAuditEventRecorder.cs index 551471153..0226fd236 100644 --- a/src/Web/Grand.Web.Common/Audit/IAuditEventRecorder.cs +++ b/src/Web/Grand.Web.Common/Audit/IAuditEventRecorder.cs @@ -9,7 +9,7 @@ public interface IAuditEventRecorder { Task SignIn(Customer customer); - Task SignInFailed(Customer customer, string reason); + Task SignInFailed(Customer customer, string? reason); Task SignOut(Customer customer); @@ -34,7 +34,7 @@ public interface IAuditEventRecorder /// /// Records that the current staff member was refused an admin page or action for lack of a permission /// - Task AccessDenied(string permission, string permissionAction); + Task AccessDenied(string permission, string? permissionAction); /// /// Records a plugin installed, uninstalled, removed or uploaded by the current staff member diff --git a/src/Web/Grand.Web.Common/Binders/CustomAttributesBinder.cs b/src/Web/Grand.Web.Common/Binders/CustomAttributesBinder.cs index 0b01f8dac..09515ea8e 100644 --- a/src/Web/Grand.Web.Common/Binders/CustomAttributesBinder.cs +++ b/src/Web/Grand.Web.Common/Binders/CustomAttributesBinder.cs @@ -24,10 +24,10 @@ public Task BindModelAsync(ModelBindingContext bindingContext) return Task.CompletedTask; } - private static string GetKey(string key) + private static string? GetKey(string key) { var regex = new Regex("\\[(?\\w+)\\]", RegexOptions.Compiled, TimeSpan.FromSeconds(1)); - string value = null; + string? value = null; var match = regex.Match(key); if (match.Success) value = match.Groups["Value"].Value; diff --git a/src/Web/Grand.Web.Common/Binders/CustomAttributesBinderProvider.cs b/src/Web/Grand.Web.Common/Binders/CustomAttributesBinderProvider.cs index 8de9ba1c8..764b6c282 100644 --- a/src/Web/Grand.Web.Common/Binders/CustomAttributesBinderProvider.cs +++ b/src/Web/Grand.Web.Common/Binders/CustomAttributesBinderProvider.cs @@ -6,7 +6,7 @@ namespace Grand.Web.Common.Binders; public class CustomAttributesBinderProvider : IModelBinderProvider { - public IModelBinder GetBinder(ModelBinderProviderContext context) + public IModelBinder? GetBinder(ModelBinderProviderContext context) { ArgumentNullException.ThrowIfNull(context); return context.Metadata.ModelType == typeof(IList) diff --git a/src/Web/Grand.Web.Common/Commands/Handlers/GetSitemapXMLCommandHandler.cs b/src/Web/Grand.Web.Common/Commands/Handlers/GetSitemapXMLCommandHandler.cs index 6b6cdf93b..ba6d839bf 100644 --- a/src/Web/Grand.Web.Common/Commands/Handlers/GetSitemapXMLCommandHandler.cs +++ b/src/Web/Grand.Web.Common/Commands/Handlers/GetSitemapXMLCommandHandler.cs @@ -48,8 +48,10 @@ public class GetSitemapXmlCommandHandler : IRequestHandler> GetProductUrls(Language language, St var products = new List(); //a large catalog is read in batches of the few fields an entry needs, never as whole documents at once IList batch; - string afterId = null; + string? afterId = null; do { _cancellationToken.ThrowIfCancellationRequested(); @@ -411,7 +413,7 @@ private IEnumerable GetCustomUrls() DateTime.UtcNow)); } - private string XmlEncode(string str) + private string? XmlEncode(string? str) { if (str == null) return null; @@ -480,7 +482,7 @@ await writer.WriteAttributeStringAsync("xsi", "schemaLocation", null, /// private class SitemapUrl { - public SitemapUrl(string location, string image, UpdateFrequency frequency, DateTime updatedOn) + public SitemapUrl(string? location, string? image, UpdateFrequency frequency, DateTime updatedOn) { Location = location; Image = image; @@ -491,12 +493,12 @@ public SitemapUrl(string location, string image, UpdateFrequency frequency, Date /// /// Gets or sets URL of the page /// - public string Location { get; } + public string? Location { get; } /// /// Gets or sets URL of the image /// - public string Image { get; } + public string? Image { get; } /// /// Gets or sets a value indicating how frequently the page is likely to change diff --git a/src/Web/Grand.Web.Common/Components/WidgetViewComponent.cs b/src/Web/Grand.Web.Common/Components/WidgetViewComponent.cs index dfce08dd3..7694ac14d 100644 --- a/src/Web/Grand.Web.Common/Components/WidgetViewComponent.cs +++ b/src/Web/Grand.Web.Common/Components/WidgetViewComponent.cs @@ -21,7 +21,7 @@ public WidgetViewComponent(IContextAccessor contextAccessor, ICacheBase cacheBas _widgetService = widgetService; } - public async Task InvokeAsync(string widgetZone, object additionalData = null) + public async Task InvokeAsync(string widgetZone, object? additionalData = null) { var cacheKey = string.Format(CacheKey.WIDGET_MODEL_KEY, _contextAccessor.StoreContext.CurrentStore.Id, _contextAccessor.WorkContext.CurrentCustomer.GetCustomerGroupsCacheKey(), diff --git a/src/Web/Grand.Web.Common/ContextAccessor.cs b/src/Web/Grand.Web.Common/ContextAccessor.cs index c1bd8b79d..73d804b95 100644 --- a/src/Web/Grand.Web.Common/ContextAccessor.cs +++ b/src/Web/Grand.Web.Common/ContextAccessor.cs @@ -4,15 +4,22 @@ namespace Grand.Web.Common; public class ContextAccessor : IContextAccessor { - private static readonly AsyncLocal _asyncLocalWorkContext = new(); - private static readonly AsyncLocal _asyncLocalStoreContext = new(); + private static readonly AsyncLocal _asyncLocalWorkContext = new(); + private static readonly AsyncLocal _asyncLocalStoreContext = new(); public IWorkContext WorkContext { - get => _asyncLocalWorkContext.Value; + get => _asyncLocalWorkContext.Value ?? + throw new InvalidOperationException("No work context is set: ContextMiddleware sets it for a request"); set => _asyncLocalWorkContext.Value = value; } + public IStoreContext StoreContext { - get => _asyncLocalStoreContext.Value; + get => _asyncLocalStoreContext.Value ?? + throw new InvalidOperationException("No store context is set: ContextMiddleware sets it for a request"); set => _asyncLocalStoreContext.Value = value; } -} + + public IWorkContext? CurrentWorkContext => _asyncLocalWorkContext.Value; + + public IStoreContext? CurrentStoreContext => _asyncLocalStoreContext.Value; +} \ No newline at end of file diff --git a/src/Web/Grand.Web.Common/Controllers/BaseController.cs b/src/Web/Grand.Web.Common/Controllers/BaseController.cs index 8e7a10fbf..94c2704fd 100644 --- a/src/Web/Grand.Web.Common/Controllers/BaseController.cs +++ b/src/Web/Grand.Web.Common/Controllers/BaseController.cs @@ -141,17 +141,23 @@ protected void Notification(NotifyType type, string message, bool persistNextReq if (persistNextRequest) { - if (TempData[dataKey] == null || TempData[dataKey] is not List) - TempData[dataKey] = new List(); - ((List)TempData[dataKey]).Add(message); + if (TempData[dataKey] is not List list) + { + list = new List(); + TempData[dataKey] = list; + } + list.Add(message); } else { //1. Compare with null (first usage) //2. For some unknown reasons sometimes List is converted to string[]. And it throws exceptions. That's why we reset it - if (ViewData[dataKey] == null || ViewData[dataKey] is not List) - ViewData[dataKey] = new List(); - ((List)ViewData[dataKey]).Add(message); + if (ViewData[dataKey] is not List list) + { + list = new List(); + ViewData[dataKey] = list; + } + list.Add(message); } } @@ -216,7 +222,7 @@ protected virtual async Task AddLocales(ILanguageService l /// Configure action /// https://github.com/smartstore/Smartstore/blob/98494cd31f5a376bf67010264e10c37a657f6ee9/src/Smartstore.Web.Common/Controllers/ManageController.cs protected virtual async Task AddLocales(ILanguageService languageService, - IList locales, Action configure) + IList locales, Action? configure) where TLocalizedModelLocal : ILocalizedModelLocal { foreach (var language in await languageService.GetAllLanguages(true)) diff --git a/src/Web/Grand.Web.Common/Controllers/BasePublicController.cs b/src/Web/Grand.Web.Common/Controllers/BasePublicController.cs index 6521f45ef..225dc6f47 100644 --- a/src/Web/Grand.Web.Common/Controllers/BasePublicController.cs +++ b/src/Web/Grand.Web.Common/Controllers/BasePublicController.cs @@ -43,7 +43,7 @@ private bool IsJsonResponseView() return base.View(viewName, model); } - public override RedirectToRouteResult RedirectToRoute(string routeName) + public override RedirectToRouteResult RedirectToRoute(string? routeName) { return IsJsonResponseView() ? RedirectToRoute("Route", new { routeName }) : base.RedirectToRoute(routeName); } diff --git a/src/Web/Grand.Web.Common/Controllers/ControllerExtensions.cs b/src/Web/Grand.Web.Common/Controllers/ControllerExtensions.cs index 2d7fc693d..ef8d84b80 100644 --- a/src/Web/Grand.Web.Common/Controllers/ControllerExtensions.cs +++ b/src/Web/Grand.Web.Common/Controllers/ControllerExtensions.cs @@ -15,7 +15,7 @@ public static async Task RenderPartialViewToString(this Controll controller.ViewData.Model = model; await using var writer = new StringWriter(); - IViewEngine viewEngine = + IViewEngine? viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine; if (viewEngine == null) return writer.GetStringBuilder().ToString(); var viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial); diff --git a/src/Web/Grand.Web.Common/DataSource/DataSourceRequestFilter.cs b/src/Web/Grand.Web.Common/DataSource/DataSourceRequestFilter.cs index 3bad0593b..c187deef3 100644 --- a/src/Web/Grand.Web.Common/DataSource/DataSourceRequestFilter.cs +++ b/src/Web/Grand.Web.Common/DataSource/DataSourceRequestFilter.cs @@ -6,22 +6,22 @@ namespace Grand.Web.Common.DataSource; [ModelBinder(BinderType = typeof(DataSourceRequestFilterBinder))] public class DataSourceRequestFilter { - public string Logic { get; set; } - public List Filters { get; set; } + public string? Logic { get; set; } + public List? Filters { get; set; } public class FilterDescriptor { - public string Field { get; set; } - public string Operator { get; set; } - public string Value { get; set; } + public string? Field { get; set; } + public string? Operator { get; set; } + public string? Value { get; set; } public bool IgnoreCase { get; set; } } } public static class DataSourceRequestFilterExtensions { - public static string GetNameFilterValue(this DataSourceRequestFilter filter) + public static string? GetNameFilterValue(this DataSourceRequestFilter filter) { - return filter.Filters.FirstOrDefault(x => x.Field == "Name")?.Value; + return filter.Filters?.FirstOrDefault(x => x.Field == "Name")?.Value; } } \ No newline at end of file diff --git a/src/Web/Grand.Web.Common/DataSource/DataSourceResult.cs b/src/Web/Grand.Web.Common/DataSource/DataSourceResult.cs index 15e809e27..834ab6d0a 100644 --- a/src/Web/Grand.Web.Common/DataSource/DataSourceResult.cs +++ b/src/Web/Grand.Web.Common/DataSource/DataSourceResult.cs @@ -4,11 +4,11 @@ namespace Grand.Web.Common.DataSource; public class DataSourceResult { - public object ExtraData { get; set; } + public object? ExtraData { get; set; } - public IEnumerable Data { get; set; } + public IEnumerable? Data { get; set; } - public object Errors { get; set; } + public object? Errors { get; set; } public int Total { get; set; } } \ No newline at end of file diff --git a/src/Web/Grand.Web.Common/Extensions/HttpContextExtensions.cs b/src/Web/Grand.Web.Common/Extensions/HttpContextExtensions.cs index f48590309..056988738 100644 --- a/src/Web/Grand.Web.Common/Extensions/HttpContextExtensions.cs +++ b/src/Web/Grand.Web.Common/Extensions/HttpContextExtensions.cs @@ -5,7 +5,7 @@ namespace Grand.Web.Common.Extensions; public static class HttpContextExtensions { - public static string GetStoreCookie(this HttpContext httpContext) + public static string? GetStoreCookie(this HttpContext httpContext) { return httpContext?.Request.Cookies[CommonHelper.StoreCookieName]; } diff --git a/src/Web/Grand.Web.Common/Extensions/KeyedServiceHelper.cs b/src/Web/Grand.Web.Common/Extensions/KeyedServiceHelper.cs index 22bbde9df..102362014 100644 --- a/src/Web/Grand.Web.Common/Extensions/KeyedServiceHelper.cs +++ b/src/Web/Grand.Web.Common/Extensions/KeyedServiceHelper.cs @@ -9,11 +9,9 @@ public static IList GetKeyedServicesForInterface(IServiceCol ArgumentNullException.ThrowIfNull(services); return services - .Where(service => - service.ServiceType == typeof(TInterface) && - service.IsKeyedService && - service.ServiceKey != null) - .Select(service => service.ServiceKey.ToString()) + .Where(service => service.ServiceType == typeof(TInterface) && service.IsKeyedService) + .Select(service => service.ServiceKey?.ToString()) + .OfType() .ToList(); } } \ No newline at end of file diff --git a/src/Web/Grand.Web.Common/Extensions/ModelStateExtensions.cs b/src/Web/Grand.Web.Common/Extensions/ModelStateExtensions.cs index 7ba43244f..92a149ecd 100644 --- a/src/Web/Grand.Web.Common/Extensions/ModelStateExtensions.cs +++ b/src/Web/Grand.Web.Common/Extensions/ModelStateExtensions.cs @@ -6,8 +6,11 @@ public static class ModelStateExtensions { public static object SerializeErrors(this ModelStateDictionary modelStateDictionary) { - return modelStateDictionary.Where(entry => entry.Value != null && entry.Value.Errors.Any()) - .ToDictionary(entry => entry.Key, entry => SerializeModelState(entry.Value)); + var errors = new Dictionary>(); + foreach (var (key, entry) in modelStateDictionary) + if (entry is { Errors.Count: > 0 }) + errors[key] = SerializeModelState(entry); + return errors; } private static Dictionary SerializeModelState(ModelStateEntry modelState) @@ -19,7 +22,7 @@ private static Dictionary SerializeModelState(ModelStateEntry mo return dictionary; } - public static object ToDataSourceResult(this ModelStateDictionary modelState) + public static object? ToDataSourceResult(this ModelStateDictionary modelState) { return !modelState.IsValid ? modelState.SerializeErrors() : null; } diff --git a/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs b/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs index bf20dbfba..87a6c8c98 100644 --- a/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs +++ b/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs @@ -27,7 +27,7 @@ public static void Set(this ISession session, string key, T value) /// Session /// Key /// Value - public static T Get(this ISession session, string key) + public static T? Get(this ISession session, string key) { var value = session.GetString(key); return value == null ? default : JsonSerializer.Deserialize(value); diff --git a/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs b/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs index 4b7b164b7..65e163b51 100644 --- a/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs +++ b/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs @@ -83,7 +83,7 @@ private async Task SetAffiliateFromQuery(HttpRequest request) /// Set the affiliate identifier of current customer /// /// Affiliate - private async Task SetCustomerAffiliateId(Affiliate affiliate) + private async Task SetCustomerAffiliateId(Affiliate? affiliate) { if (affiliate is not { Active: true }) return; diff --git a/src/Web/Grand.Web.Common/Filters/ArgumentNameFilterAttribute.cs b/src/Web/Grand.Web.Common/Filters/ArgumentNameFilterAttribute.cs index 4080bd93c..34e1f02f5 100644 --- a/src/Web/Grand.Web.Common/Filters/ArgumentNameFilterAttribute.cs +++ b/src/Web/Grand.Web.Common/Filters/ArgumentNameFilterAttribute.cs @@ -4,11 +4,13 @@ namespace Grand.Web.Common.Filters; public class ArgumentNameFilterAttribute : ActionFilterAttribute { - public string KeyName { get; set; } - public string Argument { get; set; } + public string? KeyName { get; set; } + public string? Argument { get; set; } public override void OnActionExecuting(ActionExecutingContext context) { + if (string.IsNullOrEmpty(Argument)) + return; context.ActionArguments[Argument] = context.HttpContext.Request.Form.Keys.Any(key => key.Equals(KeyName)); } } \ No newline at end of file diff --git a/src/Web/Grand.Web.Common/Filters/AuditExportAttribute.cs b/src/Web/Grand.Web.Common/Filters/AuditExportAttribute.cs index 7a921e667..c08384e4d 100644 --- a/src/Web/Grand.Web.Common/Filters/AuditExportAttribute.cs +++ b/src/Web/Grand.Web.Common/Filters/AuditExportAttribute.cs @@ -39,7 +39,7 @@ public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionE await recorder.Export(entityType, summary, null); } - private static string Summarize(IDictionary arguments) + private static string Summarize(IDictionary arguments) { var parts = new List(); foreach (var (name, value) in arguments) @@ -58,7 +58,7 @@ private static string Summarize(IDictionary arguments) return summary.Length > MaxSummaryLength ? summary[..MaxSummaryLength] : summary; } - private static void Add(List parts, string name, object value) + private static void Add(List parts, string name, object? value) { if (value == null || AuditDiff.IsSensitive(name)) return; diff --git a/src/Web/Grand.Web.Common/Filters/AuditScopeFilter.cs b/src/Web/Grand.Web.Common/Filters/AuditScopeFilter.cs index b12b28d48..d8ac990e9 100644 --- a/src/Web/Grand.Web.Common/Filters/AuditScopeFilter.cs +++ b/src/Web/Grand.Web.Common/Filters/AuditScopeFilter.cs @@ -33,7 +33,7 @@ public async Task OnResourceExecutionAsync(ResourceExecutingContext context, Res } } - private AuditActor ResolveActor(ResourceExecutingContext context) + private AuditActor? ResolveActor(ResourceExecutingContext context) { var httpContext = context.HttpContext; var workContext = contextAccessor.WorkContext; diff --git a/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs b/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs index 8f33194bc..070965a00 100644 --- a/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs +++ b/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs @@ -94,8 +94,8 @@ public async Task OnAuthorizationAsync(AuthorizationFilterContext filterContext) } private async Task ValidateMenuSiteMapPermissions(AuthorizationFilterContext filterContext, - string controllerName, - string actionName) + string? controllerName, + string? actionName) { var menuSiteMap = await FindSiteMap(controllerName, actionName); if (menuSiteMap != null && menuSiteMap.PermissionNames.Any()) @@ -115,8 +115,8 @@ await _permissionService.Authorize(x, _contextAccessor.WorkContext.CurrentCustom } } - private async Task FindSiteMap(string controllerName, - string actionName) + private async Task FindSiteMap(string? controllerName, + string? actionName) { var adminSiteMap = await _adminSiteMapService.GetSiteMap(); return adminSiteMap.Select(siteMap => @@ -124,8 +124,8 @@ private async Task FindSiteMap(string controllerName, .FirstOrDefault(siteMap => siteMap != null); } - private static AdminSiteMap FindSiteMapByControllerAndActionName(AdminSiteMap siteMap, - string controllerName, string actionName) + private static AdminSiteMap? FindSiteMapByControllerAndActionName(AdminSiteMap siteMap, + string? controllerName, string? actionName) { if (siteMap.ControllerName == controllerName && siteMap.ActionName == actionName) return siteMap; diff --git a/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs b/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs index c1210bc01..e3d37f937 100644 --- a/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs +++ b/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs @@ -70,7 +70,7 @@ public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionE } //check whether current page URL is already localized URL - var pageUrl = context.HttpContext.Request?.GetEncodedPathAndQuery(); + var pageUrl = context.HttpContext.Request.GetEncodedPathAndQuery(); if (await IsLocalized(pageUrl, context.HttpContext.Request.PathBase)) { await next(); @@ -81,7 +81,7 @@ public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionE context.Result = new RedirectResult(pageUrl, false); } - private async Task IsLocalized(string url, PathString pathBase) + private async Task IsLocalized(string? url, PathString pathBase) { _ = new PathString(url).StartsWithSegments(pathBase, out var result); url = WebUtility.UrlDecode(result); @@ -99,7 +99,7 @@ private async Task IsLocalized(string url, PathString pathBase) return language?.Published ?? false; } - private static string AddLanguageSeo(string url, Language language) + private static string AddLanguageSeo(string? url, Language language) { ArgumentNullException.ThrowIfNull(language); diff --git a/src/Web/Grand.Web.Common/Grand.Web.Common.csproj b/src/Web/Grand.Web.Common/Grand.Web.Common.csproj index a71fb5633..409d74aef 100644 --- a/src/Web/Grand.Web.Common/Grand.Web.Common.csproj +++ b/src/Web/Grand.Web.Common/Grand.Web.Common.csproj @@ -34,4 +34,7 @@ + + enable + \ No newline at end of file diff --git a/src/Web/Grand.Web.Common/Helpers/AdminStoreService.cs b/src/Web/Grand.Web.Common/Helpers/AdminStoreService.cs index eccf0beb4..ed8dad178 100644 --- a/src/Web/Grand.Web.Common/Helpers/AdminStoreService.cs +++ b/src/Web/Grand.Web.Common/Helpers/AdminStoreService.cs @@ -7,7 +7,7 @@ namespace Grand.Web.Common.Helpers; public interface IAdminStoreService { - Task GetActiveStore(); + Task GetActiveStore(); } public class AdminStoreService : IAdminStoreService @@ -21,7 +21,7 @@ public AdminStoreService(IStoreService storeService, IContextAccessor contextAcc _contextAccessor = contextAccessor; } - public async Task GetActiveStore() + public async Task GetActiveStore() { var stores = await _storeService.GetAllStores(); if (stores.Count < 2) diff --git a/src/Web/Grand.Web.Common/IRequestCustomerResolver.cs b/src/Web/Grand.Web.Common/IRequestCustomerResolver.cs index 2679c810a..9ae7b5d20 100644 --- a/src/Web/Grand.Web.Common/IRequestCustomerResolver.cs +++ b/src/Web/Grand.Web.Common/IRequestCustomerResolver.cs @@ -29,5 +29,5 @@ public interface IRequestCustomerResolver /// null when the request is not this resolver's, so the next resolver is asked. A customer stops the chain /// (for example the Anonymous system customer when the credential is recognised but rejected). /// - Task Resolve(); + Task Resolve(); } diff --git a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs index a80a4ac5e..63e61466c 100644 --- a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs +++ b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs @@ -32,7 +32,7 @@ public static class ApplicationBuilderExtensions internal static bool IsApiRequest(HttpRequest request) { - string authHeader = request.Headers[HeaderNames.Authorization]; + string? authHeader = request.Headers[HeaderNames.Authorization]; return authHeader != null && authHeader.StartsWith(JwtBearerDefaults.AuthenticationScheme + " ", StringComparison.OrdinalIgnoreCase); } @@ -142,8 +142,9 @@ public static void UseGrandEndpoints(this WebApplication application) var endpointProviders = typeSearcher.ClassesOfType(); var instances = endpointProviders .Where(PluginExtensions.OnlyInstalledPlugins) - .Select(endpointProvider => (IEndpointProvider)Activator.CreateInstance(endpointProvider)) - .OrderByDescending(endpointProvider => endpointProvider!.Priority); + .Select(endpointProvider => Activator.CreateInstance(endpointProvider)) + .OfType() + .OrderByDescending(endpointProvider => endpointProvider.Priority); foreach (var endpointProvider in instances) endpointProvider.RegisterEndpoint(endpoints); diff --git a/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs b/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs index 99bcb6e24..6fb50062d 100644 --- a/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs +++ b/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs @@ -65,7 +65,7 @@ internal enum ScheduleAction /// Name of the machine (container hostname, pod name) /// Configured Application:InstanceName, empty when not set /// Current time - internal static ScheduleDecision Decide(ScheduleTask task, string machineName, string instanceName, + internal static ScheduleDecision Decide(ScheduleTask? task, string machineName, string? instanceName, DateTime utcNow) { if (task == null) @@ -99,7 +99,7 @@ internal static ScheduleDecision Decide(ScheduleTask task, string machineName, s /// change on every deployment, so the configured instance name is accepted too - and it can be /// shared by several instances, which then compete for the run like unpinned ones. /// - private static bool IsPinnedToThisInstance(string leasedByMachineName, string machineName, string instanceName) + private static bool IsPinnedToThisInstance(string? leasedByMachineName, string machineName, string? instanceName) { if (string.IsNullOrEmpty(leasedByMachineName)) return true; @@ -113,7 +113,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) { //resolved once from the root provider (not the per-iteration scope) so it also //survives to log failures raised before/around a scope, e.g. in the outer catch - var logger = _serviceProvider.GetService>(); + var logger = _serviceProvider.GetRequiredService>(); var instanceName = _serviceProvider.GetService()?.InstanceName; while (!stoppingToken.IsCancellationRequested) @@ -121,7 +121,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) { using var scope = _serviceProvider.CreateScope(); var serviceProvider = scope.ServiceProvider; - var scheduleTaskService = serviceProvider.GetService(); + var scheduleTaskService = serviceProvider.GetRequiredService(); var task = await scheduleTaskService.GetTaskByName(Name); var decision = Decide(task, Environment.MachineName, instanceName, DateTime.UtcNow); diff --git a/src/Web/Grand.Web.Common/Infrastructure/MediaRootFileProvider.cs b/src/Web/Grand.Web.Common/Infrastructure/MediaRootFileProvider.cs index 650958edd..80ac73f6f 100644 --- a/src/Web/Grand.Web.Common/Infrastructure/MediaRootFileProvider.cs +++ b/src/Web/Grand.Web.Common/Infrastructure/MediaRootFileProvider.cs @@ -14,7 +14,7 @@ public static class MediaRootFileProvider /// Host environment whose WebRootFileProvider is layered /// Media physical path; null or empty leaves wwwroot alone /// Optional per-installation subdirectory (the "Directory" config value) - public static void Apply(IWebHostEnvironment webHostEnvironment, string mediaRootPath, string directory) + public static void Apply(IWebHostEnvironment webHostEnvironment, string? mediaRootPath, string? directory) { if (string.IsNullOrEmpty(mediaRootPath)) return; diff --git a/src/Web/Grand.Web.Common/Infrastructure/PluginAssetContentTypes.cs b/src/Web/Grand.Web.Common/Infrastructure/PluginAssetContentTypes.cs index fe8583dab..6d0a46ffc 100644 --- a/src/Web/Grand.Web.Common/Infrastructure/PluginAssetContentTypes.cs +++ b/src/Web/Grand.Web.Common/Infrastructure/PluginAssetContentTypes.cs @@ -1,4 +1,5 @@ using Microsoft.AspNetCore.StaticFiles; +using System.Diagnostics.CodeAnalysis; namespace Grand.Web.Common.Infrastructure; @@ -24,7 +25,7 @@ public static class PluginAssetContentTypes /// their deps.json and pdb files, which are never served, whatever the configuration says. /// /// Extensions to serve on top of the built-in ones, with or without the dot - public static IContentTypeProvider Create(IEnumerable additionalExtensions) + public static IContentTypeProvider Create(IEnumerable? additionalExtensions) { var defaults = new FileExtensionContentTypeProvider().Mappings; var mappings = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -49,7 +50,7 @@ public static IContentTypeProvider Create(IEnumerable additionalExtensio private sealed class PluginContentTypeProvider(IContentTypeProvider inner) : IContentTypeProvider { - public bool TryGetContentType(string subpath, out string contentType) + public bool TryGetContentType(string subpath, [MaybeNullWhen(false)] out string contentType) { if (NeverServedFileSuffixes.Any(suffix => subpath.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))) { diff --git a/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs b/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs index abc426ed3..29376f134 100644 --- a/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs +++ b/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs @@ -104,7 +104,8 @@ public static void AddGrandDataProtection(this IServiceCollection services, ICon if (redisConfig.PersistKeysToRedis) { services.AddDataProtection(opt => opt.ApplicationDiscriminator = "grandnode") - .PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(redisConfig.PersistKeysToRedisUrl)); + .PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(redisConfig.PersistKeysToRedisUrl ?? + throw new InvalidOperationException("Redis:PersistKeysToRedisUrl is not set"))); } else if (azureConfig.PersistKeysToAzureKeyVault || azureConfig.PersistKeysToAzureBlobStorage) { @@ -113,7 +114,8 @@ public static void AddGrandDataProtection(this IServiceCollection services, ICon // This blob must already exist before the application is run .PersistKeysToAzureBlobStorage(azureConfig.PersistKeysAzureBlobStorageConnectionString, azureConfig.DataProtectionContainerName, azureConfig.DataProtectionBlobName) - .ProtectKeysWithAzureKeyVault(new Uri(azureConfig.KeyIdentifier), + .ProtectKeysWithAzureKeyVault(new Uri(azureConfig.KeyIdentifier ?? + throw new InvalidOperationException("Azure:KeyIdentifier is not set")), new DefaultAzureCredential()); else services.AddDataProtection() @@ -190,8 +192,9 @@ public static void AddGrandAuthentication(this IServiceCollection services, ICon var externalAuthConfigurations = typeSearcher.ClassesOfType(); var externalAuthInstances = externalAuthConfigurations .Where(PluginExtensions.OnlyInstalledPlugins) - .Select(x => (IAuthenticationBuilder)Activator.CreateInstance(x)) - .OrderBy(x => x?.Priority); + .Select(x => Activator.CreateInstance(x)) + .OfType() + .OrderBy(x => x.Priority); //add new Authentication foreach (var instance in externalAuthInstances) @@ -264,16 +267,17 @@ public static void AddSettings(this IServiceCollection services) { var typeSearcher = new TypeSearcher(); var settings = typeSearcher.ClassesOfType(); - var instances = settings.Select(x => (ISettings)Activator.CreateInstance(x)); + var instances = settings.Select(x => Activator.CreateInstance(x)).OfType(); foreach (var item in instances) - services.AddScoped(item!.GetType(), x => + services.AddScoped(item.GetType(), x => { var type = item.GetType(); var storeId = ""; var settingService = x.GetRequiredService(); var contextAccessor = x.GetRequiredService(); - if (contextAccessor.StoreContext != null) - storeId = contextAccessor.StoreContext.CurrentStore.Id; + //settings are also resolved outside a request, where no store context is set + if (contextAccessor.CurrentStoreContext is { } storeContext) + storeId = storeContext.CurrentStore.Id; return settingService.LoadSetting(type, storeId); }); diff --git a/src/Web/Grand.Web.Common/Localization/IEnumTranslationService.cs b/src/Web/Grand.Web.Common/Localization/IEnumTranslationService.cs index f000d653a..532b775e5 100644 --- a/src/Web/Grand.Web.Common/Localization/IEnumTranslationService.cs +++ b/src/Web/Grand.Web.Common/Localization/IEnumTranslationService.cs @@ -8,13 +8,13 @@ namespace Grand.Web.Common.Localization; public interface IEnumTranslationService { - SelectList ToSelectList(TEnum enumObj, bool markCurrentAsSelected = true, int[] valuesToExclude = null) where TEnum : struct; + SelectList ToSelectList(TEnum enumObj, bool markCurrentAsSelected = true, int[]? valuesToExclude = null) where TEnum : struct; string GetTranslationEnum(T enumValue) where T : struct; } public class EnumTranslationService(ITranslationService translationService, IContextAccessor contextAccessor) : IEnumTranslationService { - public SelectList ToSelectList(TEnum enumObj, bool markCurrentAsSelected = true, int[] valuesToExclude = null) + public SelectList ToSelectList(TEnum enumObj, bool markCurrentAsSelected = true, int[]? valuesToExclude = null) where TEnum : struct { if (!typeof(TEnum).GetTypeInfo().IsEnum) @@ -28,7 +28,7 @@ public SelectList ToSelectList(TEnum enumObj, bool markCurrentAsSelected Name = GetTranslationEnum(enumValue) }; - object selectedValue = null; + object? selectedValue = null; if (markCurrentAsSelected) selectedValue = Convert.ToInt32(enumObj); diff --git a/src/Web/Grand.Web.Common/Localization/LocService.cs b/src/Web/Grand.Web.Common/Localization/LocService.cs index 7a2bd7632..0332cad7b 100644 --- a/src/Web/Grand.Web.Common/Localization/LocService.cs +++ b/src/Web/Grand.Web.Common/Localization/LocService.cs @@ -4,7 +4,7 @@ namespace Grand.Web.Common.Localization; public class LocService : StringLocalizer { - private readonly IRequestTranslationService _translationService; + private readonly IRequestTranslationService? _translationService; public LocService(IStringLocalizerFactory factory) : base(factory) { @@ -17,14 +17,14 @@ public LocService(IStringLocalizerFactory factory, IRequestTranslationService tr public override LocalizedString this[string name] { get { - var resFormat = _translationService.GetResource(name.ToLowerInvariant()); + var resFormat = _translationService?.GetResource(name.ToLowerInvariant()); return new LocalizedString(name, resFormat ?? name, resFormat == null); } } public override LocalizedString this[string name, params object[] arguments] { get { - var resFormat = _translationService.GetResource(name.ToLowerInvariant()); + var resFormat = _translationService?.GetResource(name.ToLowerInvariant()); if (string.IsNullOrEmpty(resFormat)) return new LocalizedString(name, string.Empty, resFormat == null); try { diff --git a/src/Web/Grand.Web.Common/Localization/RequestTranslationService.cs b/src/Web/Grand.Web.Common/Localization/RequestTranslationService.cs index 5a8a32bf1..8969fce5c 100644 --- a/src/Web/Grand.Web.Common/Localization/RequestTranslationService.cs +++ b/src/Web/Grand.Web.Common/Localization/RequestTranslationService.cs @@ -14,7 +14,7 @@ public class RequestTranslationService( { public string GetResource(string name) { - var language = contextAccessor.WorkContext?.WorkingLanguage; + var language = contextAccessor.CurrentWorkContext?.WorkingLanguage; return language != null ? GetResource(name, language.Id) : ""; } } diff --git a/src/Web/Grand.Web.Common/Menu/SiteMap.cs b/src/Web/Grand.Web.Common/Menu/SiteMap.cs index dcbe9e45e..eac9c5a02 100644 --- a/src/Web/Grand.Web.Common/Menu/SiteMap.cs +++ b/src/Web/Grand.Web.Common/Menu/SiteMap.cs @@ -17,7 +17,7 @@ public SiteMap( _permissionService = permissionService; } - public SiteMapNode RootNode { get; set; } + public SiteMapNode? RootNode { get; set; } public virtual async Task Load() { diff --git a/src/Web/Grand.Web.Common/Menu/SiteMapNode.cs b/src/Web/Grand.Web.Common/Menu/SiteMapNode.cs index 077103025..dd0e233f8 100644 --- a/src/Web/Grand.Web.Common/Menu/SiteMapNode.cs +++ b/src/Web/Grand.Web.Common/Menu/SiteMapNode.cs @@ -16,28 +16,28 @@ public SiteMapNode() /// /// Gets or sets the system name. /// - public string SystemName { get; set; } + public string? SystemName { get; set; } /// /// Gets or sets the resource name. /// - public string ResourceName { get; set; } + public string? ResourceName { get; set; } /// /// Gets or sets the name of the controller. /// - public string ControllerName { get; set; } + public string? ControllerName { get; set; } /// /// Gets or sets the name of the action. /// - public string ActionName { get; set; } + public string? ActionName { get; set; } /// /// Gets or sets the URL. /// - public string Url { get; set; } + public string? Url { get; set; } /// /// Gets or sets the child nodes. @@ -47,7 +47,7 @@ public SiteMapNode() /// /// Gets or sets the icon class (bootstrap-icons: https://icons.getbootstrap.com/, e.g. "bi bi-house") /// - public string IconClass { get; set; } + public string? IconClass { get; set; } /// /// Gets or sets the item is visible diff --git a/src/Web/Grand.Web.Common/Middleware/ContextLoggingMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/ContextLoggingMiddleware.cs index e9b0f9ece..e0139eeab 100644 --- a/src/Web/Grand.Web.Common/Middleware/ContextLoggingMiddleware.cs +++ b/src/Web/Grand.Web.Common/Middleware/ContextLoggingMiddleware.cs @@ -21,7 +21,7 @@ public async Task InvokeAsync(HttpContext context, IContextAccessor contextAcces { var workContext = contextAccessor.WorkContext; var storeContext = contextAccessor.StoreContext; - Activity activity = Activity.Current; + Activity? activity = Activity.Current; if (activity != null) { activity.AddTag(CustomerPropertyName, workContext?.CurrentCustomer?.Email); diff --git a/src/Web/Grand.Web.Common/Middleware/CultureSettingMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/CultureSettingMiddleware.cs index c999e0a47..673b03464 100644 --- a/src/Web/Grand.Web.Common/Middleware/CultureSettingMiddleware.cs +++ b/src/Web/Grand.Web.Common/Middleware/CultureSettingMiddleware.cs @@ -15,9 +15,10 @@ public CultureSettingMiddleware(RequestDelegate next) public async Task InvokeAsync(HttpContext context, IContextAccessor contextAccessor) { - if (contextAccessor.WorkContext?.WorkingLanguage != null) + //runs for every request, also for one ContextMiddleware gave no context + if (contextAccessor.CurrentWorkContext?.WorkingLanguage.LanguageCulture is { } languageCulture) { - var culture = new CultureInfo(contextAccessor.WorkContext.WorkingLanguage.LanguageCulture); + var culture = new CultureInfo(languageCulture); CultureInfo.CurrentCulture = culture; CultureInfo.CurrentUICulture = culture; diff --git a/src/Web/Grand.Web.Common/Middleware/InstallUrlMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/InstallUrlMiddleware.cs index ad7386291..29613e940 100644 --- a/src/Web/Grand.Web.Common/Middleware/InstallUrlMiddleware.cs +++ b/src/Web/Grand.Web.Common/Middleware/InstallUrlMiddleware.cs @@ -54,7 +54,7 @@ public async Task InvokeAsync(HttpContext context) } else { - if (!version.DataBaseVersion.Equals(GrandVersion.SupportedDBVersion)) + if (!string.Equals(version.DataBaseVersion, GrandVersion.SupportedDBVersion)) { await context.Response.WriteAsync("The database version is not supported in this software version. " + $"Supported version: {GrandVersion.SupportedDBVersion} , your version: {version.DataBaseVersion}"); diff --git a/src/Web/Grand.Web.Common/Models/Cms/WidgetModel.cs b/src/Web/Grand.Web.Common/Models/Cms/WidgetModel.cs index 318b4debb..f7c43b230 100644 --- a/src/Web/Grand.Web.Common/Models/Cms/WidgetModel.cs +++ b/src/Web/Grand.Web.Common/Models/Cms/WidgetModel.cs @@ -5,7 +5,7 @@ namespace Grand.Web.Models.Cms; public class WidgetModel : BaseModel { - public string WidgetZone { get; set; } - public string ViewComponentName { get; set; } - public object AdditionalData { get; set; } + public string? WidgetZone { get; set; } + public string? ViewComponentName { get; set; } + public object? AdditionalData { get; set; } } diff --git a/src/Web/Grand.Web.Common/Models/CustomAttributeModel.cs b/src/Web/Grand.Web.Common/Models/CustomAttributeModel.cs index 7b796dcfa..c795cf0d7 100644 --- a/src/Web/Grand.Web.Common/Models/CustomAttributeModel.cs +++ b/src/Web/Grand.Web.Common/Models/CustomAttributeModel.cs @@ -2,6 +2,6 @@ public class CustomAttributeModel { - public string Key { get; set; } - public string Value { get; set; } + public string? Key { get; set; } + public string? Value { get; set; } } \ No newline at end of file diff --git a/src/Web/Grand.Web.Common/Models/CustomerGroupModel.cs b/src/Web/Grand.Web.Common/Models/CustomerGroupModel.cs index 1d75e796b..a0b8dc466 100644 --- a/src/Web/Grand.Web.Common/Models/CustomerGroupModel.cs +++ b/src/Web/Grand.Web.Common/Models/CustomerGroupModel.cs @@ -2,6 +2,6 @@ public class CustomerGroupModel { - public string Id { get; set; } - public string Name { get; set; } + public string? Id { get; set; } + public string? Name { get; set; } } \ No newline at end of file diff --git a/src/Web/Grand.Web.Common/Models/DatePickerDropDownsModel.cs b/src/Web/Grand.Web.Common/Models/DatePickerDropDownsModel.cs index 97d65729d..c3bf8cff9 100644 --- a/src/Web/Grand.Web.Common/Models/DatePickerDropDownsModel.cs +++ b/src/Web/Grand.Web.Common/Models/DatePickerDropDownsModel.cs @@ -5,16 +5,16 @@ namespace Grand.Web.Common.Models; public class DatePickerDropDownsModel : BaseEntityModel { - public string Attribute { get; set; } + public string? Attribute { get; set; } - public string Day { get; set; } + public string? Day { get; set; } public IList SelectListDay { get; set; } = new List(); - public string Month { get; set; } + public string? Month { get; set; } public IList SelectListMonth { get; set; } = new List(); - public string Year { get; set; } + public string? Year { get; set; } public IList SelectListYear { get; set; } = new List(); public int Begin_Year { get; set; } diff --git a/src/Web/Grand.Web.Common/Models/DeleteConfirmationModel.cs b/src/Web/Grand.Web.Common/Models/DeleteConfirmationModel.cs index 45cabb682..a6bf5e380 100644 --- a/src/Web/Grand.Web.Common/Models/DeleteConfirmationModel.cs +++ b/src/Web/Grand.Web.Common/Models/DeleteConfirmationModel.cs @@ -4,7 +4,7 @@ namespace Grand.Web.Common.Models; public class DeleteConfirmationModel : BaseEntityModel { - public string ControllerName { get; set; } - public string ActionName { get; set; } - public string WindowId { get; set; } + public string? ControllerName { get; set; } + public string? ActionName { get; set; } + public string? WindowId { get; set; } } \ No newline at end of file diff --git a/src/Web/Grand.Web.Common/Models/ImportWindowModel.cs b/src/Web/Grand.Web.Common/Models/ImportWindowModel.cs index e2cac53be..ea3a2fc1c 100644 --- a/src/Web/Grand.Web.Common/Models/ImportWindowModel.cs +++ b/src/Web/Grand.Web.Common/Models/ImportWindowModel.cs @@ -10,35 +10,35 @@ namespace Grand.Web.Common.Models; public class ImportWindowModel { /// Id of the hidden element the modal is opened on. - public string WindowId { get; set; } + public string? WindowId { get; set; } /// Area, controller and action the form posts to. - public string AreaName { get; set; } + public string? AreaName { get; set; } - public string ControllerName { get; set; } + public string? ControllerName { get; set; } - public string ActionName { get; set; } + public string? ActionName { get; set; } /// Route id of the edited record, for an import that belongs to one. - public string RouteId { get; set; } + public string? RouteId { get; set; } /// Posted name of the file field - part of the server contract. - public string FileName { get; set; } + public string? FileName { get; set; } /// Element id of the file field; defaults to . - public string FileId { get; set; } + public string? FileId { get; set; } /// Label of the file field. - public string FileLabel { get; set; } + public string? FileLabel { get; set; } /// Value of the field's accept attribute, when the import takes one format. - public string Accept { get; set; } + public string? Accept { get; set; } /// Caption and element id of the submit button. - public string SubmitText { get; set; } + public string? SubmitText { get; set; } - public string SubmitId { get; set; } + public string? SubmitId { get; set; } /// Whatever the view puts above the field: the tip, the notes. - public IHtmlContent Notes { get; set; } + public IHtmlContent? Notes { get; set; } } diff --git a/src/Web/Grand.Web.Common/Models/StoreModel.cs b/src/Web/Grand.Web.Common/Models/StoreModel.cs index 9ce625cdd..968c12686 100644 --- a/src/Web/Grand.Web.Common/Models/StoreModel.cs +++ b/src/Web/Grand.Web.Common/Models/StoreModel.cs @@ -2,6 +2,6 @@ public class StoreModel { - public string Id { get; set; } - public string Name { get; set; } + public string? Id { get; set; } + public string? Name { get; set; } } \ No newline at end of file diff --git a/src/Web/Grand.Web.Common/Page/IPageHeadBuilder.cs b/src/Web/Grand.Web.Common/Page/IPageHeadBuilder.cs index d282c76d5..d6ec48ffa 100644 --- a/src/Web/Grand.Web.Common/Page/IPageHeadBuilder.cs +++ b/src/Web/Grand.Web.Common/Page/IPageHeadBuilder.cs @@ -7,17 +7,17 @@ namespace Grand.Web.Common.Page; /// public interface IPageHeadBuilder { - string EditPageUrl { get; set; } + string? EditPageUrl { get; set; } void AddTitleParts(string part); void AppendTitleParts(string part); - string GenerateTitle(bool addDefaultTitle); + string? GenerateTitle(bool addDefaultTitle); void AddMetaDescriptionParts(string part); void AppendMetaDescriptionParts(string part); - string GenerateMetaDescription(); + string? GenerateMetaDescription(); void AddMetaKeywordParts(string part); void AppendMetaKeywordParts(string part); - string GenerateMetaKeywords(); + string? GenerateMetaKeywords(); void AddCanonicalUrlParts(string part); void AppendCanonicalUrlParts(string part); diff --git a/src/Web/Grand.Web.Common/Page/PageHeadBuilder.cs b/src/Web/Grand.Web.Common/Page/PageHeadBuilder.cs index 7259ef4b4..08427ff1e 100644 --- a/src/Web/Grand.Web.Common/Page/PageHeadBuilder.cs +++ b/src/Web/Grand.Web.Common/Page/PageHeadBuilder.cs @@ -66,9 +66,9 @@ public virtual void AppendTitleParts(string part) _title.Insert(0, part); } - public virtual string GenerateTitle(bool addDefaultTitle) + public virtual string? GenerateTitle(bool addDefaultTitle) { - string result; + string? result; var titleParts = string.Join(_seoSettings.PageTitleSeparator, _title.AsEnumerable().Reverse().ToList()); if (!string.IsNullOrEmpty(titleParts)) { @@ -103,7 +103,7 @@ public virtual void AppendMetaDescriptionParts(string part) _metaDescription.Insert(0, part); } - public virtual string GenerateMetaDescription() + public virtual string? GenerateMetaDescription() { var description = string.Join(", ", _metaDescription.AsEnumerable().Reverse().ToList()); var result = !string.IsNullOrEmpty(description) ? description : _seoSettings.DefaultMetaDescription; @@ -126,7 +126,7 @@ public virtual void AppendMetaKeywordParts(string part) _metaKeyword.Insert(0, part); } - public virtual string GenerateMetaKeywords() + public virtual string? GenerateMetaKeywords() { var keyword = string.Join(", ", _metaKeyword.AsEnumerable().Reverse().ToList()); var result = !string.IsNullOrEmpty(keyword) ? keyword : _seoSettings.DefaultMetaKeywords; @@ -215,7 +215,7 @@ public virtual string GeneratePageCssClasses() return result; } - public virtual string EditPageUrl { get; set; } + public virtual string? EditPageUrl { get; set; } #endregion } \ No newline at end of file diff --git a/src/Web/Grand.Web.Common/RequestCustomerResolvers/AllowAnonymousCustomerResolver.cs b/src/Web/Grand.Web.Common/RequestCustomerResolvers/AllowAnonymousCustomerResolver.cs index 8c261733c..26ef2a1bb 100644 --- a/src/Web/Grand.Web.Common/RequestCustomerResolvers/AllowAnonymousCustomerResolver.cs +++ b/src/Web/Grand.Web.Common/RequestCustomerResolvers/AllowAnonymousCustomerResolver.cs @@ -14,7 +14,7 @@ public class AllowAnonymousCustomerResolver( { public int Order => RequestCustomerResolverOrder.AllowAnonymous; - public async Task Resolve() + public async Task Resolve() { var endpoint = httpContextAccessor.HttpContext?.GetEndpoint(); if (endpoint?.Metadata.GetMetadata() == null) return null; diff --git a/src/Web/Grand.Web.Common/RequestCustomerResolvers/ApiUserCustomerResolver.cs b/src/Web/Grand.Web.Common/RequestCustomerResolvers/ApiUserCustomerResolver.cs index 55d1c995a..72c874a42 100644 --- a/src/Web/Grand.Web.Common/RequestCustomerResolvers/ApiUserCustomerResolver.cs +++ b/src/Web/Grand.Web.Common/RequestCustomerResolvers/ApiUserCustomerResolver.cs @@ -16,14 +16,14 @@ public class ApiUserCustomerResolver( { public int Order => RequestCustomerResolverOrder.ApiUser; - public async Task Resolve() + public async Task Resolve() { var customer = await apiAuthenticationService.GetAuthenticatedCustomer(); if (customer != null) return customer; //an API call with an invalid or expired token must not insert a new guest (and set its cookie) on every call; //other schemes (Basic in front of a staging site) still fall through to a new guest - string authorization = httpContextAccessor.HttpContext?.Request.Headers[HeaderNames.Authorization]; + string? authorization = httpContextAccessor.HttpContext?.Request.Headers[HeaderNames.Authorization]; if (authorization == null || !authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) return null; diff --git a/src/Web/Grand.Web.Common/RequestCustomerResolvers/CookieCustomerResolver.cs b/src/Web/Grand.Web.Common/RequestCustomerResolvers/CookieCustomerResolver.cs index c5d11782a..58bea27d0 100644 --- a/src/Web/Grand.Web.Common/RequestCustomerResolvers/CookieCustomerResolver.cs +++ b/src/Web/Grand.Web.Common/RequestCustomerResolvers/CookieCustomerResolver.cs @@ -13,7 +13,7 @@ public sealed class CookieCustomerResolver(IGrandAuthenticationService authentic { public int Order => RequestCustomerResolverOrder.Cookie; - public async Task Resolve() + public async Task Resolve() { return await authenticationService.GetAuthenticatedCustomer(); } diff --git a/src/Web/Grand.Web.Common/RequestCustomerResolvers/GuestCookieCustomerResolver.cs b/src/Web/Grand.Web.Common/RequestCustomerResolvers/GuestCookieCustomerResolver.cs index a42b7e859..fcd54cdfc 100644 --- a/src/Web/Grand.Web.Common/RequestCustomerResolvers/GuestCookieCustomerResolver.cs +++ b/src/Web/Grand.Web.Common/RequestCustomerResolvers/GuestCookieCustomerResolver.cs @@ -15,7 +15,7 @@ public class GuestCookieCustomerResolver( { public int Order => RequestCustomerResolverOrder.GuestCookie; - public async Task Resolve() + public async Task Resolve() { var cookie = await authenticationService.GetCustomerGuid(); //transition, removed in 2.6: a cookie written before it was protected still finds its existing guest diff --git a/src/Web/Grand.Web.Common/RequestCustomerResolvers/GuestCustomerPersistence.cs b/src/Web/Grand.Web.Common/RequestCustomerResolvers/GuestCustomerPersistence.cs index de5964e99..874586f6d 100644 --- a/src/Web/Grand.Web.Common/RequestCustomerResolvers/GuestCustomerPersistence.cs +++ b/src/Web/Grand.Web.Common/RequestCustomerResolvers/GuestCustomerPersistence.cs @@ -10,9 +10,9 @@ public class GuestCustomerPersistence( IGroupService groupService, ILogger logger) : IGuestCustomerPersistence { - private Task _persisting; + private Task? _persisting; - public Customer Transient { get; private set; } + public Customer? Transient { get; private set; } public async Task SetTransient(Customer customer) { @@ -47,7 +47,7 @@ private async Task Persist(Customer guest) Transient = null; } - public async Task Promote(Customer guest) + public async Task Promote(Customer guest) { try { diff --git a/src/Web/Grand.Web.Common/RequestCustomerResolvers/GuestCustomerRules.cs b/src/Web/Grand.Web.Common/RequestCustomerResolvers/GuestCustomerRules.cs index bb175ca7f..d0f25ccfa 100644 --- a/src/Web/Grand.Web.Common/RequestCustomerResolvers/GuestCustomerRules.cs +++ b/src/Web/Grand.Web.Common/RequestCustomerResolvers/GuestCustomerRules.cs @@ -11,7 +11,7 @@ public static class GuestCustomerRules /// /// The cookie holds a GUID in the format the store writes ("D"), never Guid.Empty /// - public static bool TryParseCookie(string value, out Guid customerGuid) + public static bool TryParseCookie(string? value, out Guid customerGuid) { return Guid.TryParseExact(value, "D", out customerGuid) && customerGuid != Guid.Empty; } diff --git a/src/Web/Grand.Web.Common/RequestCustomerResolvers/IGuestCustomerPersistence.cs b/src/Web/Grand.Web.Common/RequestCustomerResolvers/IGuestCustomerPersistence.cs index d6d1f9ffc..671a214c2 100644 --- a/src/Web/Grand.Web.Common/RequestCustomerResolvers/IGuestCustomerPersistence.cs +++ b/src/Web/Grand.Web.Common/RequestCustomerResolvers/IGuestCustomerPersistence.cs @@ -11,7 +11,7 @@ public interface IGuestCustomerPersistence /// /// The unsaved guest of this request; null once saved or when the customer came from the database /// - Customer Transient { get; } + Customer? Transient { get; } Task SetTransient(Customer customer); @@ -26,5 +26,5 @@ public interface IGuestCustomerPersistence /// Saves a guest for a returned cookie whose GUID no customer has. Returns the saved guest, the guest a /// parallel request saved first, or null when the GUID turned out to belong to a customer that is not a guest /// - Task Promote(Customer guest); + Task Promote(Customer guest); } diff --git a/src/Web/Grand.Web.Common/RequestCustomerResolvers/SearchEngineCustomerResolver.cs b/src/Web/Grand.Web.Common/RequestCustomerResolvers/SearchEngineCustomerResolver.cs index 9d68f737e..c03da3c37 100644 --- a/src/Web/Grand.Web.Common/RequestCustomerResolvers/SearchEngineCustomerResolver.cs +++ b/src/Web/Grand.Web.Common/RequestCustomerResolvers/SearchEngineCustomerResolver.cs @@ -15,7 +15,7 @@ public class SearchEngineCustomerResolver( { public int Order => RequestCustomerResolverOrder.SearchEngine; - public async Task Resolve() + public async Task Resolve() { //an authenticated API client is never treated as a crawler var request = httpContextAccessor.HttpContext?.Request; diff --git a/src/Web/Grand.Web.Common/RequestStorePin.cs b/src/Web/Grand.Web.Common/RequestStorePin.cs index 8878ea279..9ecb4948c 100644 --- a/src/Web/Grand.Web.Common/RequestStorePin.cs +++ b/src/Web/Grand.Web.Common/RequestStorePin.cs @@ -24,6 +24,6 @@ public static void Set(HttpContext context, string storeId) /// /// The pinned store id, or null when the request is not pinned /// - public static string Get(HttpContext context) => + public static string? Get(HttpContext context) => context?.Items.TryGetValue(ItemKey, out var storeId) == true ? storeId as string : null; } diff --git a/src/Web/Grand.Web.Common/Routing/LanguageParameterTransformer.cs b/src/Web/Grand.Web.Common/Routing/LanguageParameterTransformer.cs index 304d8e4f2..97ca39bbb 100644 --- a/src/Web/Grand.Web.Common/Routing/LanguageParameterTransformer.cs +++ b/src/Web/Grand.Web.Common/Routing/LanguageParameterTransformer.cs @@ -12,7 +12,7 @@ public LanguageParameterTransformer(IHttpContextAccessor httpContextAccessor) _httpContextAccessor = httpContextAccessor; } - public string TransformOutbound(object value) + public string? TransformOutbound(object? value) { var lang = _httpContextAccessor.HttpContext?.Request.RouteValues["language"]; return lang != null ? lang.ToString() : value?.ToString(); diff --git a/src/Web/Grand.Web.Common/Routing/SlugRouteTransformer.cs b/src/Web/Grand.Web.Common/Routing/SlugRouteTransformer.cs index 941587548..5d844dac4 100644 --- a/src/Web/Grand.Web.Common/Routing/SlugRouteTransformer.cs +++ b/src/Web/Grand.Web.Common/Routing/SlugRouteTransformer.cs @@ -24,7 +24,7 @@ public SlugRouteTransformer( _config = config; } - private async ValueTask GetSeName(string entityId, string entityName, string languageId) + private async ValueTask GetSeName(string? entityId, string? entityName, string? languageId) { var result = string.Empty; if (!string.IsNullOrEmpty(languageId)) @@ -35,6 +35,8 @@ private async ValueTask GetSeName(string entityId, string entityName, st return result; } + //null skips the route: the endpoint matcher (DynamicControllerEndpointMatcherPolicy) treats it so, though the + //signature of the base class does not say it public override async ValueTask TransformAsync(HttpContext context, RouteValueDictionary values) { @@ -46,7 +48,7 @@ public override async ValueTask TransformAsync(HttpContext //no URL Entity found if (entityUrl == null) - return null; + return null!; //if URL Entity is not active find the latest one if (!entityUrl.IsActive) @@ -54,7 +56,7 @@ public override async ValueTask TransformAsync(HttpContext var activeSlug = await _slugService.GetActiveSlug(entityUrl.EntityId, entityUrl.EntityName, entityUrl.LanguageId); if (string.IsNullOrEmpty(activeSlug)) - return null; + return null!; values["controller"] = "Common"; values["action"] = "InternalRedirect"; diff --git a/src/Web/Grand.Web.Common/Security/Authentication/ApiAuthenticationService.cs b/src/Web/Grand.Web.Common/Security/Authentication/ApiAuthenticationService.cs index eea79cfcc..04ddad35c 100644 --- a/src/Web/Grand.Web.Common/Security/Authentication/ApiAuthenticationService.cs +++ b/src/Web/Grand.Web.Common/Security/Authentication/ApiAuthenticationService.cs @@ -30,12 +30,12 @@ public ApiAuthenticationService( _httpContextAccessor = httpContextAccessor; } - public virtual async Task GetAuthenticatedCustomer() + public virtual async Task GetAuthenticatedCustomer() { - Customer customer = null; + Customer? customer = null; if (_httpContextAccessor.HttpContext == null) return null; - string authHeader = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Authorization]; + string? authHeader = _httpContextAccessor.HttpContext.Request.Headers[HeaderNames.Authorization]; if (string.IsNullOrEmpty(authHeader)) return null; @@ -81,7 +81,7 @@ public virtual async Task GetAuthenticatedCustomer() } private bool IsApiFrontAuthenticated() { - var endpoint = _httpContextAccessor.HttpContext.GetEndpoint(); + var endpoint = _httpContextAccessor.HttpContext?.GetEndpoint(); if (endpoint == null) return false; var apiGroupAttr = endpoint.Metadata.GetOrderedMetadata(); @@ -89,9 +89,9 @@ private bool IsApiFrontAuthenticated() } - private async Task ApiCustomer() + private async Task ApiCustomer() { - Customer customer = null; + Customer? customer = null; var authResult = await _httpContextAccessor.HttpContext!.AuthenticateAsync(FrontendAPIConfig.AuthenticationScheme); if (!authResult.Succeeded) return await _customerService.GetCustomerBySystemName(SystemCustomerNames.Anonymous); diff --git a/src/Web/Grand.Web.Common/Security/Authentication/CookieAuthenticationService.cs b/src/Web/Grand.Web.Common/Security/Authentication/CookieAuthenticationService.cs index f1f15250e..dbabe62fa 100644 --- a/src/Web/Grand.Web.Common/Security/Authentication/CookieAuthenticationService.cs +++ b/src/Web/Grand.Web.Common/Security/Authentication/CookieAuthenticationService.cs @@ -110,7 +110,7 @@ public virtual async Task SignIn(Customer customer, bool isPersistent) await SignIn(customer, isPersistent, await CurrentOidcSessionIdOf(customer)); } - private async Task CurrentOidcSessionIdOf(Customer customer) + private async Task CurrentOidcSessionIdOf(Customer customer) { if (_httpContextAccessor.HttpContext == null || string.IsNullOrEmpty(customer.Id)) return null; @@ -133,7 +133,7 @@ private async Task CurrentOidcSessionIdOf(Customer customer) /// Customer /// Whether the authentication session is persisted across multiple requests /// Id of the OidcSession; null or empty = an ordinary sign-in - public virtual async Task SignIn(Customer customer, bool isPersistent, string oidcSessionId) + public virtual async Task SignIn(Customer customer, bool isPersistent, string? oidcSessionId) { ArgumentNullException.ThrowIfNull(customer); @@ -241,9 +241,13 @@ public virtual async Task HasOidcSession() /// Get an authenticated customer /// /// Customer - public virtual async Task GetAuthenticatedCustomer() + public virtual async Task GetAuthenticatedCustomer() { - var authenticateResult = await _httpContextAccessor.HttpContext.AuthenticateAsync(GrandCookieAuthenticationDefaults.AuthenticationScheme); + var httpContext = _httpContextAccessor.HttpContext; + if (httpContext == null) + return null; + + var authenticateResult = await httpContext.AuthenticateAsync(GrandCookieAuthenticationDefaults.AuthenticationScheme); if (!authenticateResult.Succeeded) return null; @@ -254,7 +258,7 @@ public virtual async Task GetAuthenticatedCustomer() return customer; } - private async Task RetrieveCustomer(ClaimsPrincipal principal) + private async Task RetrieveCustomer(ClaimsPrincipal principal) { //prefer the stable customer id - unambiguous even with per-store customer identity var customerId = principal.FindFirst(claim => @@ -322,14 +326,14 @@ private async Task ReplacePasswordToken(ClaimsPrincipal principal) var customer = await RetrieveCustomer(principal); var passwordToken = customer?.GetUserFieldFromEntity(SystemCustomerFieldNames.PasswordToken); //an old cookie, whose token was replaced already, does not end the sign-ins made after it - if (string.IsNullOrEmpty(passwordToken) || PasswordTokenOf(principal) != passwordToken) + if (customer == null || string.IsNullOrEmpty(passwordToken) || PasswordTokenOf(principal) != passwordToken) return; await _customerService.UpdateUserField(customer, SystemCustomerFieldNames.PasswordToken, Guid.NewGuid().ToString()); } - private string PasswordTokenOf(ClaimsPrincipal principal) => + private string? PasswordTokenOf(ClaimsPrincipal principal) => principal.FindFirst(claim => claim.Type == ClaimTypes.UserData && claim.Issuer.Equals(_securityConfig.CookieClaimsIssuer, StringComparison.InvariantCultureIgnoreCase))?.Value; @@ -347,7 +351,7 @@ private async Task EndOidcSession(string sessionId) } } - private string OidcSessionId(ClaimsPrincipal principal) => + private string? OidcSessionId(ClaimsPrincipal? principal) => principal?.FindFirst(claim => claim.Type == OidcSessionDefaults.SessionIdClaimType && claim.Issuer.Equals(_securityConfig.CookieClaimsIssuer, StringComparison.InvariantCultureIgnoreCase))?.Value; @@ -356,20 +360,20 @@ private string OidcSessionId(ClaimsPrincipal principal) => /// Get customer cookie /// /// String value of cookie - public virtual Task GetCustomerGuid() + public virtual Task GetCustomerGuid() { var cookie = _httpContextAccessor.HttpContext?.Request.Cookies[CustomerCookieName]; if (string.IsNullOrEmpty(cookie)) - return Task.FromResult(null); + return Task.FromResult(null); try { - return Task.FromResult(_customerCookieProtector.Unprotect(cookie)); + return Task.FromResult(_customerCookieProtector.Unprotect(cookie)); } catch (CryptographicException) { //not issued by the store (a bare GUID included), or protected with a key that is gone - return Task.FromResult(null); + return Task.FromResult(null); } } @@ -377,7 +381,7 @@ public virtual Task GetCustomerGuid() /// The bare GUID of a guest cookie written before the cookie was protected; null otherwise. /// Transition only, removed in 2.6 /// - public virtual Task GetLegacyCustomerGuid() + public virtual Task GetLegacyCustomerGuid() { var cookie = _httpContextAccessor.HttpContext?.Request.Cookies[CustomerCookieName]; return Task.FromResult(GuestCustomerRules.TryParseCookie(cookie, out _) ? cookie : null); diff --git a/src/Web/Grand.Web.Common/Security/Authentication/CookieOptionsFactory.cs b/src/Web/Grand.Web.Common/Security/Authentication/CookieOptionsFactory.cs index 80984f7a0..3b18560df 100644 --- a/src/Web/Grand.Web.Common/Security/Authentication/CookieOptionsFactory.cs +++ b/src/Web/Grand.Web.Common/Security/Authentication/CookieOptionsFactory.cs @@ -8,7 +8,7 @@ namespace Grand.Web.Common.Security.Authentication; /// public class CookieOptionsFactory(SecurityConfig securityConfig) : ICookieOptionsFactory { - public string CookiePrefix => securityConfig.CookiePrefix; + public string? CookiePrefix => securityConfig.CookiePrefix; /// /// Creates cookie options with proper security settings diff --git a/src/Web/Grand.Web.Common/Security/Authentication/ExternalSignInService.cs b/src/Web/Grand.Web.Common/Security/Authentication/ExternalSignInService.cs index da4c3f116..44ea396df 100644 --- a/src/Web/Grand.Web.Common/Security/Authentication/ExternalSignInService.cs +++ b/src/Web/Grand.Web.Common/Security/Authentication/ExternalSignInService.cs @@ -15,17 +15,18 @@ public class ExternalSignInService( ITranslationService translationService) : IExternalSignInService { public virtual async Task Authenticate(ExternalAuthParam parameters, Customer customer, - Store store, Language language, string returnUrl = null) + Store store, Language language, string? returnUrl = null) { //the logged-in or registered event is already published; sign in after it, as before var result = await externalAuthenticationService.Authenticate(parameters, customer, store, language); switch (result.Status) { - case ExternalAuthStatus.LoggedIn: - await authenticationService.SignIn(result.Customer, false); + //a logged-in or registered result carries its customer + case ExternalAuthStatus.LoggedIn when result.Customer is { } loggedIn: + await authenticationService.SignIn(loggedIn, false); return ReturnUrl(returnUrl); - case ExternalAuthStatus.Registered: - await authenticationService.SignIn(result.Customer, false); + case ExternalAuthStatus.Registered when result.Customer is { } registered: + await authenticationService.SignIn(registered, false); return RegisterResult(UserRegistrationType.Standard); case ExternalAuthStatus.Associated: return ReturnUrl(returnUrl); @@ -55,7 +56,7 @@ public virtual async Task Authenticate(ExternalAuthParam paramete } } - protected virtual IActionResult ReturnUrl(string returnUrl) + protected virtual IActionResult ReturnUrl(string? returnUrl) { //the return URL comes from the query string of the login request; never leave the store with it if (string.IsNullOrEmpty(returnUrl) || !RedirectHttpResult.IsLocalUrl(returnUrl)) diff --git a/src/Web/Grand.Web.Common/Security/Authentication/IApiAuthenticationService.cs b/src/Web/Grand.Web.Common/Security/Authentication/IApiAuthenticationService.cs index 777874940..706662f78 100644 --- a/src/Web/Grand.Web.Common/Security/Authentication/IApiAuthenticationService.cs +++ b/src/Web/Grand.Web.Common/Security/Authentication/IApiAuthenticationService.cs @@ -8,5 +8,5 @@ public interface IApiAuthenticationService /// Get authenticated customer /// /// Customer - Task GetAuthenticatedCustomer(); + Task GetAuthenticatedCustomer(); } \ No newline at end of file diff --git a/src/Web/Grand.Web.Common/Security/Authentication/ICookieOptionsFactory.cs b/src/Web/Grand.Web.Common/Security/Authentication/ICookieOptionsFactory.cs index 7ca656812..07f90801f 100644 --- a/src/Web/Grand.Web.Common/Security/Authentication/ICookieOptionsFactory.cs +++ b/src/Web/Grand.Web.Common/Security/Authentication/ICookieOptionsFactory.cs @@ -17,5 +17,5 @@ public interface ICookieOptionsFactory /// /// Gets the cookie prefix /// - string CookiePrefix { get; } + string? CookiePrefix { get; } } diff --git a/src/Web/Grand.Web.Common/Security/Authentication/IExternalSignInService.cs b/src/Web/Grand.Web.Common/Security/Authentication/IExternalSignInService.cs index 3e564b3a1..98988022a 100644 --- a/src/Web/Grand.Web.Common/Security/Authentication/IExternalSignInService.cs +++ b/src/Web/Grand.Web.Common/Security/Authentication/IExternalSignInService.cs @@ -21,5 +21,5 @@ public interface IExternalSignInService /// Defines the URL of user return, when successfully authenticated /// Result of an authentication Task Authenticate(ExternalAuthParam parameters, Customer customer, Store store, Language language, - string returnUrl = null); + string? returnUrl = null); } diff --git a/src/Web/Grand.Web.Common/Security/Authentication/IGrandAuthenticationService.cs b/src/Web/Grand.Web.Common/Security/Authentication/IGrandAuthenticationService.cs index 93a0d20a7..ffcad2a5e 100644 --- a/src/Web/Grand.Web.Common/Security/Authentication/IGrandAuthenticationService.cs +++ b/src/Web/Grand.Web.Common/Security/Authentication/IGrandAuthenticationService.cs @@ -38,19 +38,19 @@ public interface IGrandAuthenticationService /// Get authenticated customer /// /// Customer - Task GetAuthenticatedCustomer(); + Task GetAuthenticatedCustomer(); /// /// Get customer guid /// /// Customer - Task GetCustomerGuid(); + Task GetCustomerGuid(); /// /// The customer guid of a guest cookie written before the cookie was protected (a bare GUID); null otherwise. /// Transition only, removed in 2.6 /// - Task GetLegacyCustomerGuid() => Task.FromResult(null); + Task GetLegacyCustomerGuid() => Task.FromResult(null); /// /// Set customer guid diff --git a/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeActionAttribute.cs b/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeActionAttribute.cs index a247419c2..4461cf5c1 100644 --- a/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeActionAttribute.cs +++ b/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeActionAttribute.cs @@ -40,7 +40,7 @@ public async Task OnAuthorizationAsync(AuthorizationFilterContext context) var contextAccessor = context.HttpContext.RequestServices.GetRequiredService(); //check whether current customer has access to a public store - var customer = contextAccessor.WorkContext?.CurrentCustomer; + var customer = contextAccessor.WorkContext.CurrentCustomer; if (customer != null && await permissionService.AuthorizeAction(permissionAuthorize.Permission, PermissionAction, customer)) return; diff --git a/src/Web/Grand.Web.Common/Security/Authorization/RequestPermissionService.cs b/src/Web/Grand.Web.Common/Security/Authorization/RequestPermissionService.cs index 6eb1969d3..84551d579 100644 --- a/src/Web/Grand.Web.Common/Security/Authorization/RequestPermissionService.cs +++ b/src/Web/Grand.Web.Common/Security/Authorization/RequestPermissionService.cs @@ -10,11 +10,11 @@ public class RequestPermissionService( { public Task Authorize(Permission permission) { - return permissionService.Authorize(permission, contextAccessor.WorkContext?.CurrentCustomer); + return permissionService.Authorize(permission, contextAccessor.CurrentWorkContext?.CurrentCustomer); } public Task Authorize(string permissionSystemName) { - return permissionService.Authorize(permissionSystemName, contextAccessor.WorkContext?.CurrentCustomer); + return permissionService.Authorize(permissionSystemName, contextAccessor.CurrentWorkContext?.CurrentCustomer); } } diff --git a/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaValidator.cs b/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaValidator.cs index 19f51f9a0..d900b943d 100644 --- a/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaValidator.cs +++ b/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaValidator.cs @@ -28,10 +28,10 @@ public GoogleReCaptchaValidator(CaptchaSettings captchaSettings, _logger = logger; } - public async Task Validate(string response, + public async Task Validate(string response, CancellationToken cancellationToken = default) { - GoogleReCaptchaResponse result; + GoogleReCaptchaResponse? result; if (_httpContextAccessor.HttpContext == null) return null; var requestUri = string.Format(RecaptchaVerifyUrl, _captchaSettings.ReCaptchaPrivateKey, response, _httpContextAccessor.HttpContext.Connection.RemoteIpAddress); @@ -54,11 +54,11 @@ public async Task Validate(string response, return result; } - private GoogleReCaptchaResponse ParseResponseResult(string responseString) + private GoogleReCaptchaResponse? ParseResponseResult(string responseString) { var result = JsonSerializer.Deserialize(responseString, ProviderExtensions.JsonSerializerOptionsProvider.Options); - if (_captchaSettings.ReCaptchaVersion != GoogleReCaptchaVersion.V3) return result; + if (result == null || _captchaSettings.ReCaptchaVersion != GoogleReCaptchaVersion.V3) return result; if (_captchaSettings.ReCaptchaScore > 0) result.Success = result.Success && result.Score >= _captchaSettings.ReCaptchaScore; diff --git a/src/Web/Grand.Web.Common/Security/Captcha/GoogleRecaptchaControl.cs b/src/Web/Grand.Web.Common/Security/Captcha/GoogleRecaptchaControl.cs index d564b0df7..06a4d2300 100644 --- a/src/Web/Grand.Web.Common/Security/Captcha/GoogleRecaptchaControl.cs +++ b/src/Web/Grand.Web.Common/Security/Captcha/GoogleRecaptchaControl.cs @@ -16,10 +16,10 @@ public GoogleRecaptchaControl(GoogleReCaptchaVersion version = GoogleReCaptchaVe _version = version; } - public string Id { get; set; } - public string Theme { get; set; } - public string PublicKey { get; set; } - public string Language { get; set; } + public string? Id { get; set; } + public string? Theme { get; set; } + public string? PublicKey { get; set; } + public string? Language { get; set; } public string RenderControl() { diff --git a/src/Web/Grand.Web.Common/Security/ExternalRegistration/ExternalRegistrationContext.cs b/src/Web/Grand.Web.Common/Security/ExternalRegistration/ExternalRegistrationContext.cs index 68e842b3d..10821b82e 100644 --- a/src/Web/Grand.Web.Common/Security/ExternalRegistration/ExternalRegistrationContext.cs +++ b/src/Web/Grand.Web.Common/Security/ExternalRegistration/ExternalRegistrationContext.cs @@ -48,7 +48,7 @@ public static ClaimsPrincipal CreatePrincipal(ExternalRegistrationIdentity ident return new ClaimsPrincipal(new ClaimsIdentity(claims, AuthenticationType)); } - public async Task GetPending() + public async Task GetPending() { var result = await HttpContext.AuthenticateAsync(GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme); var principal = result.Succeeded ? result.Principal : null; diff --git a/src/Web/Grand.Web.Common/Security/ExternalRegistration/ExternalRegistrationIdentity.cs b/src/Web/Grand.Web.Common/Security/ExternalRegistration/ExternalRegistrationIdentity.cs index 9c56380ca..520052039 100644 --- a/src/Web/Grand.Web.Common/Security/ExternalRegistration/ExternalRegistrationIdentity.cs +++ b/src/Web/Grand.Web.Common/Security/ExternalRegistration/ExternalRegistrationIdentity.cs @@ -9,5 +9,5 @@ public record ExternalRegistrationIdentity( string Subject, string Email, bool EmailVerified, - string FirstName, - string LastName); + string? FirstName, + string? LastName); diff --git a/src/Web/Grand.Web.Common/Security/ExternalRegistration/IExternalRegistrationContext.cs b/src/Web/Grand.Web.Common/Security/ExternalRegistration/IExternalRegistrationContext.cs index b0325fca4..f63e56f76 100644 --- a/src/Web/Grand.Web.Common/Security/ExternalRegistration/IExternalRegistrationContext.cs +++ b/src/Web/Grand.Web.Common/Security/ExternalRegistration/IExternalRegistrationContext.cs @@ -6,7 +6,7 @@ namespace Grand.Web.Common.Security.ExternalRegistration; public interface IExternalRegistrationContext { /// The pending identity of this browser, or null - Task GetPending(); + Task GetPending(); Task Clear(); diff --git a/src/Web/Grand.Web.Common/Security/ExternalRegistration/ProviderSignOut.cs b/src/Web/Grand.Web.Common/Security/ExternalRegistration/ProviderSignOut.cs index a854309ae..269ffcd27 100644 --- a/src/Web/Grand.Web.Common/Security/ExternalRegistration/ProviderSignOut.cs +++ b/src/Web/Grand.Web.Common/Security/ExternalRegistration/ProviderSignOut.cs @@ -14,7 +14,7 @@ public interface IProviderSignOut /// Signs out locally; returns the URL to redirect to so the session at the identity provider ends too, or null /// when the sign-in did not come from a provider (or the provider cannot end it) /// - Task SignOut(); + Task SignOut(); } public class ProviderSignOut( @@ -25,9 +25,9 @@ public class ProviderSignOut( IHttpContextAccessor httpContextAccessor, ILogger logger) : IProviderSignOut { - public async Task SignOut() + public async Task SignOut() { - string providerUrl = null; + string? providerUrl = null; try { //the cookie is what tells whether the sign-in came from the provider: look before it is removed @@ -52,7 +52,7 @@ private bool IsCrossSite() return !string.IsNullOrEmpty(site) && site != "same-origin" && site != "none"; } - private async Task GetProviderUrl() + private async Task GetProviderUrl() { //the canonical store address, never the Host header var postLogoutRedirectUri = contextAccessor.StoreContext.CurrentStore.Url.TrimEnd('/') + "/"; diff --git a/src/Web/Grand.Web.Common/Security/Oidc/IOidcProtectedResourceRegistry.cs b/src/Web/Grand.Web.Common/Security/Oidc/IOidcProtectedResourceRegistry.cs index 7738f321f..df25ff657 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/IOidcProtectedResourceRegistry.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/IOidcProtectedResourceRegistry.cs @@ -15,5 +15,5 @@ public interface IOidcProtectedResourceRegistry IReadOnlyList Withdrawn { get; } /// The resource covering the path, or null - OidcProtectedResource Match(PathString path); + OidcProtectedResource? Match(PathString path); } diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcAuthenticationBuilderExtensions.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcAuthenticationBuilderExtensions.cs index 49f7706ef..d9af87984 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcAuthenticationBuilderExtensions.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcAuthenticationBuilderExtensions.cs @@ -29,7 +29,7 @@ public static class OidcAuthenticationBuilderExtensions /// Resource server configuration /// Applied last when enabled (tests inject a static OpenID configuration) public static AuthenticationBuilder AddOidcResourceServer(this AuthenticationBuilder builder, - OidcResourceServerConfig config, Action configure = null) + OidcResourceServerConfig config, Action? configure = null) { ArgumentNullException.ThrowIfNull(config); var enabled = config.Enabled; diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcAuthenticationFailure.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcAuthenticationFailure.cs index e45d82310..fa2a15e25 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcAuthenticationFailure.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcAuthenticationFailure.cs @@ -11,15 +11,15 @@ public class OidcAuthenticationFailure public OidcFailureKind Kind { get; init; } /// Fixed, token-independent text - public string Description { get; init; } + public string? Description { get; init; } /// Space-separated scopes for insufficient_scope - public string Scope { get; init; } + public string? Scope { get; init; } public static void Set(HttpContext context, OidcAuthenticationFailure failure) => context.Items[OidcResourceServerDefaults.FailureItemKey] = failure; - public static OidcAuthenticationFailure Get(HttpContext context) => + public static OidcAuthenticationFailure? Get(HttpContext context) => context.Items.TryGetValue(OidcResourceServerDefaults.FailureItemKey, out var value) ? value as OidcAuthenticationFailure : null; diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcBackChannelLogoutEndpoint.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcBackChannelLogoutEndpoint.cs index 2ce330c5a..2f9b0bff1 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcBackChannelLogoutEndpoint.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcBackChannelLogoutEndpoint.cs @@ -70,7 +70,7 @@ public static async Task Handle(HttpContext context) if (!logout.IsValid) { logger.LogWarning("Back-channel logout refused: {Reason}", logout.Error); - return Error(logout.Error); + return Error(logout.Error ?? "The logout token is invalid"); } try @@ -82,9 +82,12 @@ public static async Task Handle(HttpContext context) if (await services.GetRequiredService().LinksMatchProvider()) { var sessionService = services.GetRequiredService(); + //a valid logout token names a sid, a subject or both ended = logout.Sid != null ? await sessionService.EndBySid(logout.Subject, logout.Sid) - : await sessionService.EndBySubject(logout.Subject); + : logout.Subject != null + ? await sessionService.EndBySubject(logout.Subject) + : []; } else logger.LogWarning("Back-channel logout: no session ended, the identity provider changed and the account " + @@ -112,7 +115,7 @@ public static async Task Handle(HttpContext context) return Results.Ok(); } - private static async Task Configuration( + private static async Task Configuration( OpenIdConnectOptions options, HttpContext context, ILogger logger) { try @@ -130,7 +133,7 @@ public static async Task Handle(HttpContext context) /// The configuration manager refreshes in the background and answers with the cached metadata meanwhile, so /// wait (briefly) for a new instance; a refresh requested too soon after the last one is ignored by the manager /// - private static async Task RefreshedConfiguration( + private static async Task RefreshedConfiguration( OpenIdConnectOptions options, Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfiguration cached, HttpContext context, ILogger logger) { diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcCanonicalUri.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcCanonicalUri.cs index 2ce084520..bcd706015 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcCanonicalUri.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcCanonicalUri.cs @@ -20,7 +20,7 @@ public static class OidcCanonicalUri /// request. The store cookie and the ambient store context are never used: they can name another store than /// the one whose host the request reached, and a token issued for that store would then pass the audience check. /// - public static async Task RequestStore(HttpContext context) + public static async Task RequestStore(HttpContext context) { if (context.Items.TryGetValue(StoreItemKey, out var cached)) return cached as Store; @@ -44,7 +44,7 @@ public static async Task RequestStore(HttpContext context) /// /// Normalized URL of ; null when no store is resolved or it has no URL /// - public static async Task StoreBaseUrl(HttpContext context) + public static async Task StoreBaseUrl(HttpContext context) { var store = await RequestStore(context); return string.IsNullOrWhiteSpace(store?.Url) ? null : Normalize(store.Url.Trim()); @@ -52,7 +52,7 @@ public static async Task StoreBaseUrl(HttpContext context) /// Protected resource /// Store base URL (), used when the resource has no configured URI - public static string ResourceFor(OidcProtectedResource resource, string baseUrl) + public static string? ResourceFor(OidcProtectedResource resource, string? baseUrl) { if (!string.IsNullOrWhiteSpace(resource.Resource)) return Normalize(resource.Resource.Trim()); diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcChallengeWriter.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcChallengeWriter.cs index 615029d6e..3db10fb05 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcChallengeWriter.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcChallengeWriter.cs @@ -16,8 +16,8 @@ public static class OidcChallengeWriter /// Retry-After of the 503 answered while the authorization server is unreachable public const int RetryAfterSeconds = 30; - public static async Task Write(HttpContext context, OidcAuthenticationFailure failure, string resourceMetadataUrl, - string scope) + public static async Task Write(HttpContext context, OidcAuthenticationFailure? failure, string? resourceMetadataUrl, + string? scope) { var status = failure?.Kind switch { OidcFailureKind.Forbidden or OidcFailureKind.InsufficientScope => StatusCodes.Status403Forbidden, @@ -46,11 +46,11 @@ public static async Task Write(HttpContext context, OidcAuthenticationFailure fa //written directly: IProblemDetailsService picks MVC's writer first on controller endpoints, and that writer //writes nothing for controllers without [ApiController] while still reporting the body as written - await context.Response.WriteAsJsonAsync(problem, (JsonSerializerOptions)null, "application/problem+json"); + await context.Response.WriteAsJsonAsync(problem, (JsonSerializerOptions?)null, "application/problem+json"); } /// Scopes of the initial 401 (no failure); a failure carries its own - public static string BuildHeader(OidcAuthenticationFailure failure, string resourceMetadataUrl, string scope) + public static string BuildHeader(OidcAuthenticationFailure? failure, string? resourceMetadataUrl, string? scope) { var parameters = new List(); if (failure != null) diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcJwtBearerEvents.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcJwtBearerEvents.cs index 28b67bc19..76f2029e4 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcJwtBearerEvents.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcJwtBearerEvents.cs @@ -90,7 +90,7 @@ protected virtual async Task AfterTokenChecks(TokenValidatedContext contex var result = await services.GetRequiredService().Resolve(context.Principal!, storeId); if (!result.Succeeded) { - Reject(context, result.Failure ?? OidcFailureKind.InvalidToken, result.Description); + Reject(context, result.Failure ?? OidcFailureKind.InvalidToken, result.Description ?? "The token is not accepted"); return false; } @@ -174,7 +174,7 @@ public override async Task Challenge(JwtBearerChallengeContext context) await OidcChallengeWriter.Write(http, failure, metadataUrl, scope); } - protected void Reject(TokenValidatedContext context, OidcFailureKind kind, string description, string scope = null) + protected void Reject(TokenValidatedContext context, OidcFailureKind kind, string description, string? scope = null) { var principal = context.Principal; Logger(context.HttpContext).LogWarning("Access token refused for subject {Subject} of {Issuer}: {Reason}", diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcLoginIdentityMapper.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcLoginIdentityMapper.cs index c557eeab3..8d01a4fee 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcLoginIdentityMapper.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcLoginIdentityMapper.cs @@ -12,11 +12,11 @@ public static class OidcLoginIdentityMapper /// The provider identity as a pending identity, by the claim names of the resource server configuration; /// null without a subject or an e-mail /// - public static ExternalRegistrationIdentity Map(ClaimsPrincipal principal, OidcClaimNames claims) + public static ExternalRegistrationIdentity? Map(ClaimsPrincipal? principal, OidcClaimNames claims) { var sub = principal?.FindFirst(claims.Subject)?.Value; var email = principal?.FindFirst(claims.Email)?.Value; - if (string.IsNullOrEmpty(sub) || string.IsNullOrWhiteSpace(email)) + if (principal == null || string.IsNullOrEmpty(sub) || string.IsNullOrWhiteSpace(email)) return null; return new ExternalRegistrationIdentity(OidcLoginDefaults.ProviderSystemName, sub, email.Trim(), diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcLoginProvider.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcLoginProvider.cs index 7564af17b..7849509eb 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcLoginProvider.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcLoginProvider.cs @@ -24,7 +24,7 @@ public class OidcLoginProvider(OidcLoginConfig config, IAuthenticationSchemeProv /// public Task GetPublicViewComponentName() => Task.FromResult("OidcLogin"); - public async Task GetSignInPath(string returnUrl) => + public async Task GetSignInPath(string returnUrl) => await authenticationSchemeProvider.GetSchemeAsync(OidcLoginDefaults.AuthenticationScheme) == null ? null : OidcLoginDefaults.LoginPath + "?returnUrl=" + Uri.EscapeDataString(returnUrl ?? "/"); diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcLoginSessionData.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcLoginSessionData.cs index 39b329753..d46dcc285 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcLoginSessionData.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcLoginSessionData.cs @@ -15,7 +15,7 @@ public static class OidcLoginSessionData public const string RefreshTokenItem = ".Grand.OidcLogin.RefreshToken"; public const string SidItem = ".Grand.OidcLogin.Sid"; - public static void Capture(AuthenticationProperties properties, OpenIdConnectMessage tokenResponse) + public static void Capture(AuthenticationProperties? properties, OpenIdConnectMessage? tokenResponse) { if (properties == null || tokenResponse == null) return; @@ -27,7 +27,7 @@ public static void Capture(AuthenticationProperties properties, OpenIdConnectMes } /// The sid claim of an ID token already validated by the handler; null when absent or unreadable - public static string Sid(string idToken) + public static string? Sid(string idToken) { if (string.IsNullOrEmpty(idToken)) return null; @@ -44,11 +44,11 @@ public static string Sid(string idToken) } } - public static async Task<(string RefreshToken, string Sid)> Read(HttpContext context) + public static async Task<(string? RefreshToken, string? Sid)> Read(HttpContext context) { var result = await context.AuthenticateAsync(GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme); var items = result?.Succeeded == true ? result.Properties?.Items : null; - string refreshToken = null, sid = null; + string? refreshToken = null, sid = null; items?.TryGetValue(RefreshTokenItem, out refreshToken); items?.TryGetValue(SidItem, out sid); return (refreshToken, sid); diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcLogoutToken.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcLogoutToken.cs index 1edab7b80..221ba6b44 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcLogoutToken.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcLogoutToken.cs @@ -1,10 +1,10 @@ namespace Grand.Web.Common.Security.Oidc; /// The token is signed with a key the metadata does not list (yet): the provider may have rotated its keys -public sealed record OidcLogoutToken(bool IsValid, string Subject, string Sid, string Error, string ReplayKey = null, +public sealed record OidcLogoutToken(bool IsValid, string? Subject, string? Sid, string? Error, string? ReplayKey = null, bool SigningKeyNotFound = false) { - public static OidcLogoutToken Valid(string subject, string sid, string replayKey = null) => + public static OidcLogoutToken Valid(string? subject, string? sid, string? replayKey = null) => new(true, subject, sid, null, replayKey); public static OidcLogoutToken Invalid(string error, bool signingKeyNotFound = false) => new(false, null, null, error, SigningKeyNotFound: signingKeyNotFound); diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcLogoutTokenValidator.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcLogoutTokenValidator.cs index 698b70d0d..0ad61a4d4 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcLogoutTokenValidator.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcLogoutTokenValidator.cs @@ -26,7 +26,7 @@ public static bool TypeAccepted(string typ) => string.IsNullOrEmpty(typ) || typ.Equals("logout+jwt", StringComparison.OrdinalIgnoreCase) || typ.Equals("JWT", StringComparison.OrdinalIgnoreCase); - public async Task Validate(string token, OpenIdConnectConfiguration configuration, string clientId, + public async Task Validate(string token, OpenIdConnectConfiguration configuration, string? clientId, TimeSpan clockSkew) { if (string.IsNullOrEmpty(token) || configuration == null || string.IsNullOrEmpty(clientId)) @@ -68,7 +68,7 @@ public async Task Validate(string token, OpenIdConnectConfigura if (subject == null && sid == null) return OidcLogoutToken.Invalid("The logout token names no subject and no session"); - string key = null; + string? key = null; if (!string.IsNullOrEmpty(jwt.Id)) { key = "Grand.OidcLogin.LogoutJti." + jwt.Issuer + "|" + jwt.Id; @@ -84,7 +84,7 @@ public async Task Validate(string token, OpenIdConnectConfigura } /// Lets a token be validated again, when the work it asked for failed and the provider retries - public void Release(string replayKey) + public void Release(string? replayKey) { if (replayKey != null) cache.Remove(replayKey); diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcPath.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcPath.cs index 19c54e97a..a3330d3fc 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcPath.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcPath.cs @@ -7,7 +7,7 @@ public static class OidcPath /// /// "/api/" -> "/api"; null when empty, relative or the site root (a root prefix would capture the storefront) /// - public static string Normalize(string prefix) + public static string? Normalize(string? prefix) { var trimmed = prefix?.Trim(); if (string.IsNullOrEmpty(trimmed) || !trimmed.StartsWith('/')) diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcProfileSynchronizer.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcProfileSynchronizer.cs index 557b867a0..996b3aa31 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcProfileSynchronizer.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcProfileSynchronizer.cs @@ -27,7 +27,7 @@ public async Task Sync(Customer customer, ExternalRegistrationIdentity identity, await SyncEmail(customer, identity, storeId); } - private async Task SyncUserField(Customer customer, string key, string value) + private async Task SyncUserField(Customer customer, string key, string? value) { if (string.IsNullOrEmpty(value)) return; diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcProtectedResourceMetadata.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcProtectedResourceMetadata.cs index 8ccafa911..86aa95c37 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcProtectedResourceMetadata.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcProtectedResourceMetadata.cs @@ -36,19 +36,19 @@ public static void Map(IEndpointRouteBuilder endpoints) }).AllowAnonymous(); } - private static bool HasPath(string url) => + private static bool HasPath(string? url) => Uri.TryCreate(url, UriKind.Absolute, out var uri) && uri.AbsolutePath.TrimEnd('/').Length > 0; /// /// The resource whose canonical URI has the requested path: a protected resource, or the store base URL itself /// (null resource). When several have that path, the one on the authority the request reached. /// - private static (bool Found, OidcProtectedResource Resource) Find(HttpContext context, string path, string baseUrl) + private static (bool Found, OidcProtectedResource? Resource) Find(HttpContext context, string path, string? baseUrl) { var registry = context.RequestServices.GetRequiredService(); var wanted = path.TrimEnd('/'); var candidates = registry.Resources - .Select(r => (Resource: r, Uri: OidcCanonicalUri.ResourceFor(r, baseUrl))) + .Select(r => (Resource: (OidcProtectedResource?)r, Uri: OidcCanonicalUri.ResourceFor(r, baseUrl))) .Append((Resource: null, Uri: baseUrl)) .Select(x => (x.Resource, Uri: Uri.TryCreate(x.Uri, UriKind.Absolute, out var uri) ? uri : null)) .ToList(); @@ -67,7 +67,7 @@ private static (bool Found, OidcProtectedResource Resource) Find(HttpContext con if (matches.Count > 1) { var authority = OidcCanonicalUri.Normalize($"{context.Request.Scheme}://{context.Request.Host}"); - matches = matches.Where(x => OidcCanonicalUri.Equal(x.Uri.GetLeftPart(UriPartial.Authority), authority)) + matches = matches.Where(x => x.Uri != null && OidcCanonicalUri.Equal(x.Uri.GetLeftPart(UriPartial.Authority), authority)) .ToList(); } @@ -79,7 +79,7 @@ private static (bool Found, OidcProtectedResource Resource) Find(HttpContext con /// audience to match). A warning when a store serves the host but has no URL (a configuration to fix); only a /// debug message when no store serves the host, which any anonymous request can cause with its Host header. /// - private static async Task Document(HttpContext context, OidcProtectedResource resource, string baseUrl) + private static async Task Document(HttpContext context, OidcProtectedResource? resource, string? baseUrl) { var config = context.RequestServices.GetRequiredService(); var resourceUri = resource != null ? OidcCanonicalUri.ResourceFor(resource, baseUrl) : baseUrl; @@ -110,7 +110,7 @@ private static async Task Document(HttpContext context, OidcProtectedRe /// /// Canonical resource URI () /// Null when the resource URI is not an absolute http(s) URI - public static string MetadataUrl(string resourceUri) + public static string? MetadataUrl(string? resourceUri) { if (!Uri.TryCreate(resourceUri, UriKind.Absolute, out var uri) || (uri.Scheme != Uri.UriSchemeHttps && uri.Scheme != Uri.UriSchemeHttp)) @@ -120,11 +120,11 @@ public static string MetadataUrl(string resourceUri) } public static object Build(OidcResourceServerConfig config, IReadOnlyList all, - OidcProtectedResource resource, string baseUrl) => + OidcProtectedResource? resource, string? baseUrl) => new MetadataDocument { Resource = resource != null ? OidcCanonicalUri.ResourceFor(resource, baseUrl) : baseUrl, ResourceName = resource?.Name, - AuthorizationServers = [config.Authority], + AuthorizationServers = config.Authority is { } authority ? [authority] : [], ScopesSupported = OidcTokenChecks.PublicScopes(resource != null ? resource.ScopesSupported : all.SelectMany(r => r.ScopesSupported ?? [])), @@ -133,13 +133,13 @@ public static object Build(OidcResourceServerConfig config, IReadOnlyList providers, - IEnumerable disabledPaths = null) + IEnumerable? disabledPaths = null) { if (config is not { Enabled: true }) return; @@ -30,7 +30,7 @@ public OidcProtectedResourceRegistry(OidcResourceServerConfig config, try { _disabledPrefixes.AddRange((provider.GetDisabledPaths() ?? []).Select(OidcPath.Normalize) - .Where(x => x != null)); + .OfType()); } catch (Exception ex) { @@ -55,7 +55,7 @@ public OidcProtectedResourceRegistry(OidcResourceServerConfig config, } foreach (var resource in resources) - Add(resource, provider.GetType().FullName); + Add(resource, provider.GetType().FullName ?? provider.GetType().Name); } _resources = _entries.Select(x => x.Resource).ToList().AsReadOnly(); @@ -65,7 +65,7 @@ public OidcProtectedResourceRegistry(OidcResourceServerConfig config, public IReadOnlyList Errors => _errors; public IReadOnlyList Withdrawn => _withdrawn; - public OidcProtectedResource Match(PathString path) + public OidcProtectedResource? Match(PathString path) { foreach (var (prefix, resource) in _entries) if (OidcPath.Covers(prefix, path)) diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcRequestCustomerResolver.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcRequestCustomerResolver.cs index ab5c1baf7..cd821bc38 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcRequestCustomerResolver.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcRequestCustomerResolver.cs @@ -28,7 +28,7 @@ public OidcRequestCustomerResolver(IHttpContextAccessor httpContextAccessor, Oid public int Order => ResolverOrder; - public async Task Resolve() + public async Task Resolve() { var httpContext = _httpContextAccessor.HttpContext; //the decision the Bearer scheme forwards by: a protected path, and no token or one an identity provider signed diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcResourceAccess.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcResourceAccess.cs index 3279fb491..8fc0ec828 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcResourceAccess.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcResourceAccess.cs @@ -21,7 +21,7 @@ public OidcResourceAccess(IPermissionService permissionService, IGroupService gr } /// null when allowed, otherwise a fixed description - public async Task Refusal(OidcProtectedResource resource, Customer customer) + public async Task Refusal(OidcProtectedResource resource, Customer customer) { if (resource.DenyVendors && (!string.IsNullOrEmpty(customer.VendorId) || await _groupService.IsVendor(customer))) return "Vendor accounts cannot use this resource"; diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcSchemeSelector.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcSchemeSelector.cs index e7baffe6d..65d084881 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcSchemeSelector.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcSchemeSelector.cs @@ -23,7 +23,7 @@ public OidcSchemeSelector(IOidcProtectedResourceRegistry registry) _registry = registry; } - public void PostConfigure(string name, JwtBearerOptions options) + public void PostConfigure(string? name, JwtBearerOptions options) { //registered only while the resource server is enabled (OidcAuthenticationBuilderExtensions); only the Web //API's scheme: other JwtBearer schemes (FrontendAPI, plugins) keep their own validation and challenge @@ -39,7 +39,7 @@ public void PostConfigure(string name, JwtBearerOptions options) /// Decided once per request (the selector runs for every authenticate, challenge and forbid, and the work /// context asks too) and kept in HttpContext.Items with the path it was made for. /// - public string Select(HttpContext context) + public string? Select(HttpContext context) { var path = context.Request.Path; if (context.Items.TryGetValue(OidcResourceServerDefaults.RouteItemKey, out var cached) && @@ -59,7 +59,7 @@ public string Select(HttpContext context) /// private static bool IsOidcRequest(HttpRequest request) { - string authorization = request.Headers[HeaderNames.Authorization]; + string? authorization = request.Headers[HeaderNames.Authorization]; if (string.IsNullOrEmpty(authorization) || !authorization.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) return true; @@ -85,5 +85,5 @@ private static bool IsOidcRequest(HttpRequest request) return algorithm != null && OidcAuthenticationBuilderExtensions.AsymmetricAlgorithms.Contains(algorithm); } - private sealed record Route(PathString Path, string Scheme); + private sealed record Route(PathString Path, string? Scheme); } diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcSignOutProvider.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcSignOutProvider.cs index fb182a083..fb36a70b8 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcSignOutProvider.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcSignOutProvider.cs @@ -18,7 +18,7 @@ public class OidcSignOutProvider( IContextAccessor contextAccessor, ILogger logger) : IExternalSignOutProvider { - public async Task GetSignOutUrl(string postLogoutRedirectUri) + public async Task GetSignOutUrl(string postLogoutRedirectUri) { //called before the local sign-out: the customer is still the signed-in one if (!externalAuthenticationService.AuthenticationProviderIsAvailable(OidcLoginDefaults.ProviderSystemName, @@ -36,7 +36,7 @@ public async Task GetSignOutUrl(string postLogoutRedirectUri) return null; var separator = configuration.EndSessionEndpoint.Contains('?') ? '&' : '?'; - return $"{configuration.EndSessionEndpoint}{separator}client_id={Uri.EscapeDataString(config.ClientId)}" + + return $"{configuration.EndSessionEndpoint}{separator}client_id={Uri.EscapeDataString(config.ClientId ?? "")}" + $"&post_logout_redirect_uri={Uri.EscapeDataString(postLogoutRedirectUri)}"; } catch (Exception ex) diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcTokenChecks.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcTokenChecks.cs index 6ab20da32..79e3608e5 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcTokenChecks.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcTokenChecks.cs @@ -12,9 +12,11 @@ public static class OidcTokenChecks /// /// RFC 8707: the token must name this resource (or a configured alternative) in "aud" /// - public static bool HasAudience(ClaimsPrincipal principal, string canonicalResource, IEnumerable audiences) + public static bool HasAudience(ClaimsPrincipal principal, string? canonicalResource, IEnumerable audiences) { - var accepted = (audiences ?? []).Where(a => !string.IsNullOrWhiteSpace(a)).Append(canonicalResource).ToList(); + var accepted = (audiences ?? []).Where(a => !string.IsNullOrWhiteSpace(a)).ToList(); + if (canonicalResource != null) + accepted.Add(canonicalResource); return principal.FindAll("aud").Any(aud => accepted.Any(a => OidcCanonicalUri.Equal(aud.Value, a))); } @@ -59,7 +61,7 @@ public static bool IsTooOld(DateTime issuedUtc, int? maxTokenAgeMinutes, int clo /// /// Scopes that may be advertised or required: distinct, non-empty, never offline_access /// - public static string[] PublicScopes(IEnumerable scopes) => - (scopes ?? []).Select(s => s?.Trim()).Where(s => !string.IsNullOrEmpty(s) && s != OfflineAccess) + public static string[] PublicScopes(IEnumerable? scopes) => + (scopes ?? []).Select(s => s?.Trim()).OfType().Where(s => s.Length > 0 && s != OfflineAccess) .Distinct(StringComparer.Ordinal).ToArray(); } diff --git a/src/Web/Grand.Web.Common/Security/Oidc/OidcTokenRefresher.cs b/src/Web/Grand.Web.Common/Security/Oidc/OidcTokenRefresher.cs index 3cc7f48c8..7777688e1 100644 --- a/src/Web/Grand.Web.Common/Security/Oidc/OidcTokenRefresher.cs +++ b/src/Web/Grand.Web.Common/Security/Oidc/OidcTokenRefresher.cs @@ -38,7 +38,7 @@ public async Task Refresh(string refreshToken, CancellationTo return OidcRefreshResult.Unavailable(); } - var form = new Dictionary { + var form = new Dictionary { ["grant_type"] = "refresh_token", ["refresh_token"] = refreshToken, ["client_id"] = config.ClientId }; if (!string.IsNullOrEmpty(config.ClientSecret)) @@ -78,7 +78,7 @@ public async Task Refresh(string refreshToken, CancellationTo } } - private static string ErrorCode(string body) + private static string? ErrorCode(string body) { try { diff --git a/src/Web/Grand.Web.Common/Startup/OidcLoginStartup.cs b/src/Web/Grand.Web.Common/Startup/OidcLoginStartup.cs index f3c9bef7c..4a1777443 100644 --- a/src/Web/Grand.Web.Common/Startup/OidcLoginStartup.cs +++ b/src/Web/Grand.Web.Common/Startup/OidcLoginStartup.cs @@ -40,8 +40,8 @@ public void ConfigureServices(IServiceCollection services, IConfiguration config public void Configure(WebApplication application, IWebHostEnvironment webHostEnvironment) { - var problem = OidcSignInModeCheck.Problem(application.Services.GetService(), - application.Services.GetService()); + var problem = OidcSignInModeCheck.Problem(application.Services.GetRequiredService(), + application.Services.GetRequiredService()); if (problem != null) application.Services.GetRequiredService>().LogError( "ProviderOnly sign-in mode without a working OpenID Connect login ({Problem}): only break-glass accounts can sign in", diff --git a/src/Web/Grand.Web.Common/Startup/StartupApplication.cs b/src/Web/Grand.Web.Common/Startup/StartupApplication.cs index babff8ac6..ead825825 100644 --- a/src/Web/Grand.Web.Common/Startup/StartupApplication.cs +++ b/src/Web/Grand.Web.Common/Startup/StartupApplication.cs @@ -75,7 +75,8 @@ private static void RegisterCache(IServiceCollection serviceCollection, IConfigu { //AbortOnConnectFail=false lets the multiplexer keep retrying in the background //instead of crashing the instance when Redis is temporarily unavailable at startup - var options = ConfigurationOptions.Parse(config.RedisPubSubConnectionString); + var options = ConfigurationOptions.Parse(config.RedisPubSubConnectionString ?? + throw new InvalidOperationException("Redis:RedisPubSubConnectionString is not set")); options.AbortOnConnectFail = false; var redis = ConnectionMultiplexer.Connect(options); serviceCollection.AddSingleton(redis); diff --git a/src/Web/Grand.Web.Common/StoreContextSetter.cs b/src/Web/Grand.Web.Common/StoreContextSetter.cs index 497f1d1e5..7a2e5a425 100644 --- a/src/Web/Grand.Web.Common/StoreContextSetter.cs +++ b/src/Web/Grand.Web.Common/StoreContextSetter.cs @@ -20,14 +20,13 @@ public StoreContextSetter(IStoreService storeService, ISettingService settingSer _httpContextAccessor = httpContextAccessor; } - public async Task InitializeStoreContext(string storeId = null) + public async Task InitializeStoreContext(string? storeId = null) { var store = await CurrentStore(storeId); //the settings injected for this store are resolved by the container, which cannot wait for a query, //so they are read here; the work context setter is the first to resolve them - if (store != null) - await _settingService.LoadStoreSettings(store.Id); + await _settingService.LoadStoreSettings(store.Id); var storeContext = new CurrentStoreContext { CurrentStore = store, @@ -36,7 +35,7 @@ public async Task InitializeStoreContext(string storeId = null) return storeContext; } - protected async Task CurrentStore(string id = null) + protected async Task CurrentStore(string? id = null) { var httpContext = _httpContextAccessor.HttpContext; @@ -67,7 +66,8 @@ protected async Task CurrentStore(string id = null) } // Fallback: return the first available store - return (await _storeService.GetAllStores()).FirstOrDefault(); + return (await _storeService.GetAllStores()).FirstOrDefault() ?? + throw new Exception("No store could be loaded"); } /// @@ -77,24 +77,17 @@ protected DomainHost CurrentHost(Store store) { //try to determine the current HOST header var host = _httpContextAccessor.HttpContext?.Request.GetTypedHeaders().Host.ToString(); - if (store != null) - return store.HostValue(host) ?? new DomainHost { - Id = int.MinValue.ToString(), - Url = store.Url, - HostName = "temporary-store" - }; - - return new DomainHost { + return store.HostValue(host) ?? new DomainHost { Id = int.MinValue.ToString(), - Url = host, - HostName = "temporary" + Url = store.Url, + HostName = "temporary-store" }; } private sealed class CurrentStoreContext : IStoreContext { - public Store CurrentStore { get; set; } + public required Store CurrentStore { get; init; } - public DomainHost CurrentHost { get; set; } + public required DomainHost CurrentHost { get; init; } } } diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminActionMenuTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminActionMenuTagHelper.cs index 259d5efb8..285eba961 100644 --- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminActionMenuTagHelper.cs +++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminActionMenuTagHelper.cs @@ -28,7 +28,7 @@ public AdminActionMenuTagHelper(IContextAccessor contextAccessor, ITranslationSe /// The trigger's text. Empty leaves the icon alone, as an overflow button. [HtmlAttributeName("text")] - public string Text { get; set; } + public string? Text { get; set; } public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { @@ -68,23 +68,23 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu [HtmlTargetElement("admin-action", ParentTag = "admin-action-menu")] public class AdminActionTagHelper : TagHelper { - [HtmlAttributeName("text")] public string Text { get; set; } + [HtmlAttributeName("text")] public string? Text { get; set; } /// A bootstrap-icons name ("bi-download"). [HtmlAttributeName("icon")] - public string Icon { get; set; } + public string? Icon { get; set; } /// Where the entry goes: an href, or the form action when . [HtmlAttributeName("url")] - public string Url { get; set; } + public string? Url { get; set; } /// Posts the surrounding form to instead of following it. [HtmlAttributeName("submit")] public bool Submit { get; set; } - [HtmlAttributeName("name")] public string Name { get; set; } + [HtmlAttributeName("name")] public string? Name { get; set; } - [HtmlAttributeName("id")] public string Id { get; set; } + [HtmlAttributeName("id")] public string? Id { get; set; } /// Draws the entry as destructive. [HtmlAttributeName("destructive")] diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminBulkBarTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminBulkBarTagHelper.cs index bf1bd2180..74cfa855f 100644 --- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminBulkBarTagHelper.cs +++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminBulkBarTagHelper.cs @@ -28,7 +28,7 @@ public AdminBulkBarTagHelper(IContextAccessor contextAccessor, ITranslationServi /// Id of the grid whose selection drives the bar. [HtmlAttributeName("grid-id")] - public string GridId { get; set; } + public string? GridId { get; set; } public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminCardTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminCardTagHelper.cs index df136e6ad..c11e49636 100644 --- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminCardTagHelper.cs +++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminCardTagHelper.cs @@ -15,17 +15,17 @@ public class AdminCardTagHelper : TagHelper { internal static readonly object ActionsKey = typeof(CardActionsTagHelper); - [HtmlAttributeName("title")] public string Title { get; set; } + [HtmlAttributeName("title")] public string? Title { get; set; } /// A bootstrap-icons name ("bi-box-seam") shown before the title. [HtmlAttributeName("icon")] - public string Icon { get; set; } + public string? Icon { get; set; } /// A link at the end of the header ("see all"), with . [HtmlAttributeName("action-url")] - public string ActionUrl { get; set; } + public string? ActionUrl { get; set; } - [HtmlAttributeName("action-text")] public string ActionText { get; set; } + [HtmlAttributeName("action-text")] public string? ActionText { get; set; } /// Drops the body padding, for a card holding nothing but a grid. [HtmlAttributeName("flush")] diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminCultureTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminCultureTagHelper.cs index e792d127c..a70013da8 100644 --- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminCultureTagHelper.cs +++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminCultureTagHelper.cs @@ -74,7 +74,7 @@ public override void Process(TagHelperContext context, TagHelperOutput output) /// private IDictionary Texts() { - var languageId = _contextAccessor.WorkContext?.WorkingLanguage?.Id; + var languageId = _contextAccessor.CurrentWorkContext?.WorkingLanguage?.Id; var texts = new Dictionary(); if (languageId is null) return texts; foreach (var (name, key) in TextResources) diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminDeleteConfirmationTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminDeleteConfirmationTagHelper.cs index 0972602aa..faef95d59 100644 --- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminDeleteConfirmationTagHelper.cs +++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminDeleteConfirmationTagHelper.cs @@ -22,13 +22,14 @@ public AdminDeleteConfirmationTagHelper(IHtmlHelper htmlHelper, IRequestTranslat _translationService = translationService; } - [ViewContext] public ViewContext ViewContext { get; set; } + //set by the framework before the tag helper runs + [ViewContext] public ViewContext ViewContext { get; set; } = null!; - [HtmlAttributeName("action-name")] public string Action { get; set; } + [HtmlAttributeName("action-name")] public string? Action { get; set; } - [HtmlAttributeName("button-id")] public string ButtonId { get; set; } + [HtmlAttributeName("button-id")] public string? ButtonId { get; set; } - [HtmlAttributeName("id")] public string ModelId { get; set; } + [HtmlAttributeName("id")] public string? ModelId { get; set; } public override async Task ProcessAsync(TagHelperContext tagHelperContext, TagHelperOutput output) { diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminFieldTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminFieldTagHelper.cs index 03ef4757e..253f2ffde 100644 --- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminFieldTagHelper.cs +++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminFieldTagHelper.cs @@ -39,7 +39,8 @@ public AdminFieldTagHelper(IHtmlHelper htmlHelper, IContextAccessor contextAcces _translationService = translationService; } - [HtmlAttributeName(ForAttributeName)] public ModelExpression For { get; set; } + //the element matches only with asp-for, so it is always set + [HtmlAttributeName(ForAttributeName)] public ModelExpression For { get; set; } = null!; /// /// The property whose display name (and hint) labels the field, when it is not the bound @@ -47,11 +48,11 @@ public AdminFieldTagHelper(IHtmlHelper htmlHelper, IContextAccessor contextAcces /// property that carries the resource. /// [HtmlAttributeName("asp-label-for")] - public ModelExpression LabelFor { get; set; } + public ModelExpression? LabelFor { get; set; } /// The control's width: sm, md, lg, or full (the default). [HtmlAttributeName("size")] - public string Size { get; set; } + public string? Size { get; set; } /// Marks the label with an asterisk. [HtmlAttributeName("asp-required")] @@ -61,15 +62,15 @@ public AdminFieldTagHelper(IHtmlHelper htmlHelper, IContextAccessor contextAcces /// IEnumerable, because a SelectList - what EnumTranslationService.ToSelectList returns - /// is not an IList. [HtmlAttributeName("asp-items")] - public IEnumerable Items { get; set; } + public IEnumerable? Items { get; set; } /// An editor template name, when the metadata's own choice is not wanted. [HtmlAttributeName("asp-template")] - public string Template { get; set; } + public string? Template { get; set; } /// Text under the control, in place of the field's .Hint resource. [HtmlAttributeName("hint")] - public string Hint { get; set; } + public string? Hint { get; set; } /// /// The unit the value is in, shown at the end of the control: a currency code, kg, %. The @@ -77,9 +78,10 @@ public AdminFieldTagHelper(IHtmlHelper htmlHelper, IContextAccessor contextAcces /// field. /// [HtmlAttributeName("suffix")] - public string Suffix { get; set; } + public string? Suffix { get; set; } - [HtmlAttributeNotBound] [ViewContext] public ViewContext ViewContext { get; set; } + //set by the framework before the tag helper runs + [HtmlAttributeNotBound] [ViewContext] public ViewContext ViewContext { get; set; } = null!; public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { @@ -156,7 +158,7 @@ private string Text() } /// The hint given on the element, else the field's .Hint resource. - private string HintText() + private string? HintText() { if (!string.IsNullOrEmpty(Hint)) return Hint; var displayName = (LabelFor ?? For).Metadata.GetDisplayName(); @@ -180,11 +182,13 @@ private async Task BuildControl() if (Items != null) return _htmlHelper.DropDownList(For.Name, Items, new { @class = "form-select" }); - var viewEngine = GetPrivateFieldValue(_htmlHelper, "_viewEngine") as IViewEngine; - var bufferScope = GetPrivateFieldValue(_htmlHelper, "_bufferScope") as IViewBufferScope; + var viewEngine = GetPrivateFieldValue(_htmlHelper, "_viewEngine") as IViewEngine ?? + throw new InvalidOperationException("The html helper has no view engine"); + var bufferScope = GetPrivateFieldValue(_htmlHelper, "_bufferScope") as IViewBufferScope ?? + throw new InvalidOperationException("The html helper has no buffer scope"); var isString = For.Metadata.ModelType == typeof(string); - object htmlAttributes = isString ? new { @class = "form-control" } : null; + object? htmlAttributes = isString ? new { @class = "form-control" } : null; var templateBuilder = new TemplateBuilder( viewEngine, @@ -195,12 +199,12 @@ private async Task BuildControl() For.Name, Template, false, - new { htmlAttributes, postfix = (string)null }); + new { htmlAttributes, postfix = (string?)null }); return await templateBuilder.Build(); } - private static object GetPrivateFieldValue(object target, string fieldName) + private static object? GetPrivateFieldValue(object target, string fieldName) { var type = target.GetType(); while (type != null) diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminFiltersTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminFiltersTagHelper.cs index 019b63606..b133daff2 100644 --- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminFiltersTagHelper.cs +++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminFiltersTagHelper.cs @@ -34,7 +34,7 @@ public AdminFiltersTagHelper(IContextAccessor contextAccessor, ITranslationServi /// The id the search button gets, so a view's script can click it. [HtmlAttributeName("submit-id")] - public string SubmitId { get; set; } + public string? SubmitId { get; set; } /// Opens the advanced panel on load, for a screen arriving with filters applied. [HtmlAttributeName("expanded")] diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminGridTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminGridTagHelper.cs index e89ddcf03..863e48a76 100644 --- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminGridTagHelper.cs +++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminGridTagHelper.cs @@ -48,29 +48,30 @@ public AdminGridTagHelper( _urlHelperFactory = urlHelperFactory; } - [HtmlAttributeName("id")] public string Id { get; set; } + //the element matches only with an id, so it is always set + [HtmlAttributeName("id")] public string Id { get; set; } = null!; /// Id field of the rows (schema.model.id). Default "Id". public string Key { get; set; } = "Id"; - public string ReadUrl { get; set; } - public string CreateUrl { get; set; } - public string UpdateUrl { get; set; } - public string DestroyUrl { get; set; } + public string? ReadUrl { get; set; } + public string? CreateUrl { get; set; } + public string? UpdateUrl { get; set; } + public string? DestroyUrl { get; set; } /// Controller for the *-action attributes; the area comes from the current route. - public string Controller { get; set; } + public string? Controller { get; set; } - public string ReadAction { get; set; } - public string CreateAction { get; set; } - public string UpdateAction { get; set; } - public string DestroyAction { get; set; } + public string? ReadAction { get; set; } + public string? CreateAction { get; set; } + public string? UpdateAction { get; set; } + public string? DestroyAction { get; set; } /// Page size; defaults to AdminAreaSettings.DefaultGridPageSize for the Full pager. public int? PageSize { get; set; } /// Comma separated page sizes; defaults to AdminAreaSettings.GridPageSizes. - public string PageSizes { get; set; } + public string? PageSizes { get; set; } public GridPager Pager { get; set; } = GridPager.Full; @@ -97,22 +98,22 @@ public AdminGridTagHelper( /// Name of the checkbox inputs of selectable="Checkbox", so the ticked rows of the page are /// posted with the surrounding form (e.g. SelectedProductIds). /// - public string SelectionName { get; set; } + public string? SelectionName { get; set; } /// /// edit-mode="Batch": posts all changed rows in one request as prefix[i].Field (the /// Kendo batch parameterMap pattern). Without it each row is posted on its own. /// - public string BatchPrefix { get; set; } + public string? BatchPrefix { get; set; } /// Rows rendered with the page for a grid without read-url (Kendo dataSource.data). - public object Data { get; set; } + public object? Data { get; set; } /// Name of a global function returning extra read data (Kendo transport.read.data). - public string AdditionalData { get; set; } + public string? AdditionalData { get; set; } /// Selector of a container whose fields are posted with every read. - public string SearchForm { get; set; } + public string? SearchForm { get; set; } /// /// Renders the grid for viewing only: no Edit/Delete commands, no toolbar, no editors and no @@ -122,16 +123,17 @@ public AdminGridTagHelper( /// public bool ReadOnly { get; set; } - public string OnDataBound { get; set; } - public string OnEdit { get; set; } - public string OnSave { get; set; } - public string OnChange { get; set; } - public string OnRequestStart { get; set; } - public string OnRequestEnd { get; set; } - public string OnError { get; set; } - public string OnDetailInit { get; set; } + public string? OnDataBound { get; set; } + public string? OnEdit { get; set; } + public string? OnSave { get; set; } + public string? OnChange { get; set; } + public string? OnRequestStart { get; set; } + public string? OnRequestEnd { get; set; } + public string? OnError { get; set; } + public string? OnDetailInit { get; set; } - [ViewContext] [HtmlAttributeNotBound] public ViewContext ViewContext { get; set; } + //set by the framework before the tag helper runs + [ViewContext] [HtmlAttributeNotBound] public ViewContext ViewContext { get; set; } = null!; public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { @@ -201,7 +203,7 @@ internal static void MakeReadOnly(GridDefinition grid) MakeReadOnly(grid.Detail); } - internal static IList ParsePageSizes(string pageSizes) + internal static IList? ParsePageSizes(string? pageSizes) { if (string.IsNullOrWhiteSpace(pageSizes)) return null; @@ -213,7 +215,7 @@ internal static IList ParsePageSizes(string pageSizes) return sizes.Count > 0 ? sizes : null; } - internal string ResolveUrl(string url, string controller, string action) + internal string? ResolveUrl(string? url, string? controller, string? action) { if (!string.IsNullOrEmpty(url) || string.IsNullOrEmpty(action)) return string.IsNullOrEmpty(url) ? null : url; @@ -224,15 +226,15 @@ internal string ResolveUrl(string url, string controller, string action) private bool IsRtl() { - var language = _contextAccessor.WorkContext?.WorkingLanguage; + var language = _contextAccessor.CurrentWorkContext?.WorkingLanguage; //same condition as HeadAdmin/HeadStore/HeadVendor return language is { Rtl: true } && !_languageSettings.IgnoreRtlPropertyForAdminArea; } - private IDictionary Events() + private IDictionary? Events() { var events = new Dictionary(); - void Add(string name, string handler) + void Add(string name, string? handler) { if (!string.IsNullOrWhiteSpace(handler)) events[name] = handler; } @@ -269,7 +271,7 @@ private IDictionary Texts(IDictionary custom) ["selectAll"] = "Admin.Common.Grid.SelectAll", ["selectRow"] = "Admin.Common.Grid.SelectRow" }; - var languageId = _contextAccessor.WorkContext?.WorkingLanguage?.Id; + var languageId = _contextAccessor.CurrentWorkContext?.WorkingLanguage?.Id; var texts = new Dictionary(); foreach (var (name, key) in keys) { @@ -296,7 +298,7 @@ internal class GridBuilder { private int _templateCount; - public GridBuilder(GridDefinition grid, string id, GridBuilder root = null) + public GridBuilder(GridDefinition grid, string id, GridBuilder? root = null) { Grid = grid; Id = id; diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminImportWindowTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminImportWindowTagHelper.cs index 209a7ee01..fdb29ce57 100644 --- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminImportWindowTagHelper.cs +++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminImportWindowTagHelper.cs @@ -34,39 +34,40 @@ public AdminImportWindowTagHelper(IHtmlHelper htmlHelper, ITranslationService tr _contextAccessor = contextAccessor; } - [ViewContext] public ViewContext ViewContext { get; set; } + //set by the framework before the tag helper runs + [ViewContext] public ViewContext ViewContext { get; set; } = null!; /// Id of the window element; defaults to "{file-name}-window". [HtmlAttributeName("id")] - public string WindowId { get; set; } + public string? WindowId { get; set; } /// Id of the toolbar button that opens it. [HtmlAttributeName("button-id")] - public string ButtonId { get; set; } + public string? ButtonId { get; set; } /// Title of the window. [HtmlAttributeName("title")] - public string Title { get; set; } + public string? Title { get; set; } /// Controller the form posts to; defaults to the current one. [HtmlAttributeName("controller")] - public string Controller { get; set; } + public string? Controller { get; set; } - [HtmlAttributeName("action")] public string Action { get; set; } + [HtmlAttributeName("action")] public string? Action { get; set; } /// Route id of the edited record, for an import that belongs to one. [HtmlAttributeName("route-id")] - public string RouteId { get; set; } + public string? RouteId { get; set; } /// Posted name of the file field - part of the server contract. [HtmlAttributeName("file-name")] - public string FileName { get; set; } + public string? FileName { get; set; } /// Element id of the file field; defaults to the posted name. [HtmlAttributeName("file-id")] - public string FileId { get; set; } + public string? FileId { get; set; } - [HtmlAttributeName("file-label")] public string FileLabel { get; set; } + [HtmlAttributeName("file-label")] public string? FileLabel { get; set; } /// /// Resource key of the label, for a resource an existing installation may not have @@ -75,18 +76,18 @@ public AdminImportWindowTagHelper(IHtmlHelper htmlHelper, ITranslationService tr /// makes for the widget texts. /// [HtmlAttributeName("file-label-key")] - public string FileLabelKey { get; set; } + public string? FileLabelKey { get; set; } - [HtmlAttributeName("accept")] public string Accept { get; set; } + [HtmlAttributeName("accept")] public string? Accept { get; set; } - [HtmlAttributeName("submit-text")] public string SubmitText { get; set; } + [HtmlAttributeName("submit-text")] public string? SubmitText { get; set; } - [HtmlAttributeName("submit-id")] public string SubmitId { get; set; } + [HtmlAttributeName("submit-id")] public string? SubmitId { get; set; } - private string ResolveFileLabel() + private string? ResolveFileLabel() { if (string.IsNullOrEmpty(FileLabelKey)) return FileLabel; - var languageId = _contextAccessor?.WorkContext?.WorkingLanguage?.Id; + var languageId = _contextAccessor?.CurrentWorkContext?.WorkingLanguage?.Id; var resource = string.IsNullOrEmpty(languageId) ? null : _translationService.GetResource(FileLabelKey, languageId, string.Empty, true); diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminInputTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminInputTagHelper.cs index 0f2ff389e..04f4ddf23 100644 --- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminInputTagHelper.cs +++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminInputTagHelper.cs @@ -37,47 +37,49 @@ public AdminInputTagHelper(IHtmlHelper htmlHelper) /// /// An expression to be evaluated against the current model /// + //the element matches only with asp-for, so it is always set [HtmlAttributeName(ForAttributeName)] - public ModelExpression For { get; set; } + public ModelExpression For { get; set; } = null!; /// /// Indicates whether the field is disabled /// [HtmlAttributeName(DisabledAttributeName)] - public string IsDisabled { set; get; } + public string? IsDisabled { set; get; } /// /// Indicates whether the field is required /// [HtmlAttributeName(RequiredAttributeName)] - public string IsRequired { set; get; } + public string? IsRequired { set; get; } /// /// Indicates whether the "form-control" class shold be added to the input /// [HtmlAttributeName(RenderFormControlClassAttributeName)] - public string RenderFormControlClass { set; get; } + public string? RenderFormControlClass { set; get; } /// /// Editor template for the field /// [HtmlAttributeName(TemplateAttributeName)] - public string Template { set; get; } + public string? Template { set; get; } - [HtmlAttributeName(PostSelectItem)] public IList SelectItems { set; get; } + [HtmlAttributeName(PostSelectItem)] public IList? SelectItems { set; get; } /// /// Postfix /// [HtmlAttributeName(PostfixAttributeName)] - public string Postfix { set; get; } + public string? Postfix { set; get; } /// /// ViewContext /// [HtmlAttributeNotBound] + //set by the framework before the tag helper runs [ViewContext] - public ViewContext ViewContext { get; set; } + public ViewContext ViewContext { get; set; } = null!; /// /// Process @@ -108,7 +110,7 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu //add form-control class bool.TryParse(RenderFormControlClass, out var renderFormControlClass); - object htmlAttributes = null; + object? htmlAttributes = null; if ((string.IsNullOrEmpty(RenderFormControlClass) && For.Metadata.ModelType.Name.Equals("String")) || renderFormControlClass) htmlAttributes = new { @class = "form-control" }; @@ -123,8 +125,10 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu htmlAttributes = new { @class = "form-control", disabled = "disabled" }; } - var viewEngine = GetPrivateFieldValue(_htmlHelper, "_viewEngine") as IViewEngine; - var bufferScope = GetPrivateFieldValue(_htmlHelper, "_bufferScope") as IViewBufferScope; + var viewEngine = GetPrivateFieldValue(_htmlHelper, "_viewEngine") as IViewEngine ?? + throw new InvalidOperationException("The html helper has no view engine"); + var bufferScope = GetPrivateFieldValue(_htmlHelper, "_bufferScope") as IViewBufferScope ?? + throw new InvalidOperationException("The html helper has no buffer scope"); if (SelectItems != null) { if (SelectItems.Any()) @@ -156,13 +160,13 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu } - private static object GetPrivateFieldValue(object target, string fieldName) + private static object? GetPrivateFieldValue(object target, string fieldName) { ArgumentNullException.ThrowIfNull(target); ArgumentNullException.ThrowIfNullOrEmpty(fieldName); var t = target.GetType(); - FieldInfo fi = null; + FieldInfo? fi = null; while (t != null) { diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminPageTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminPageTagHelper.cs index 353c97a0d..b42446730 100644 --- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminPageTagHelper.cs +++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminPageTagHelper.cs @@ -19,21 +19,21 @@ public class AdminPageTagHelper : TagHelper /// The page title. Localized by the view, like every other text. [HtmlAttributeName("title")] - public string Title { get; set; } + public string? Title { get; set; } /// A bootstrap-icons name ("bi-boxes") shown before the title. [HtmlAttributeName("icon")] - public string Icon { get; set; } + public string? Icon { get; set; } /// What the screen is about: the entity being edited, a count, a store name. [HtmlAttributeName("meta")] - public string Meta { get; set; } + public string? Meta { get; set; } /// Href of the back link; the view builds it with Url.Action. [HtmlAttributeName("back-url")] - public string BackUrl { get; set; } + public string? BackUrl { get; set; } - [HtmlAttributeName("back-text")] public string BackText { get; set; } + [HtmlAttributeName("back-text")] public string? BackText { get; set; } /// /// Keeps the header and the tab strip in view while a long tab scrolls, so the one primary diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminPopupTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminPopupTagHelper.cs index 6e1446041..b18a4c572 100644 --- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminPopupTagHelper.cs +++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminPopupTagHelper.cs @@ -18,11 +18,11 @@ namespace Grand.Web.Common.TagHelpers.Admin; [HtmlTargetElement("admin-popup")] public class AdminPopupTagHelper : TagHelper { - [HtmlAttributeName("title")] public string Title { get; set; } + [HtmlAttributeName("title")] public string? Title { get; set; } /// A bootstrap-icons name ("bi-image") shown before the title. [HtmlAttributeName("icon")] - public string Icon { get; set; } + public string? Icon { get; set; } public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabAppendTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabAppendTagHelper.cs index 522be8bbc..021b2b5f0 100644 --- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabAppendTagHelper.cs +++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabAppendTagHelper.cs @@ -18,11 +18,12 @@ public class AdminTabAppendTagHelper : TagHelper private const string TabContent = "tab-content"; - [HtmlAttributeName(TabName)] public string Name { get; set; } + //the element matches only with all three attributes, so they are always set + [HtmlAttributeName(TabName)] public string Name { get; set; } = null!; - [HtmlAttributeName(TabContent)] public string Content { get; set; } + [HtmlAttributeName(TabContent)] public string Content { get; set; } = null!; - [HtmlAttributeName(TabStripName)] public string StripName { get; set; } + [HtmlAttributeName(TabStripName)] public string StripName { get; set; } = null!; /// The template a tab strip picks up for one appended tab. internal static TagBuilder Template(string stripName, string tabName, IHtmlContent content) diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabContentTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabContentTagHelper.cs index a442e6aaa..ef1aea7ca 100644 --- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabContentTagHelper.cs +++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabContentTagHelper.cs @@ -7,13 +7,18 @@ namespace Grand.Web.Common.TagHelpers.Admin; [HtmlTargetElement("content", ParentTag = "tabstrip-item")] public class AdminTabContentTagHelper : TagHelper { - [ViewContext] public ViewContext ViewContext { get; set; } + //the view data key of the contents the strip collects: the type's full name + internal const string ContentsKey = "Grand.Web.Common.TagHelpers.Admin.AdminTabContentTagHelper"; + + //set by the framework before the tag helper runs + [ViewContext] public ViewContext ViewContext { get; set; } = null!; public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { var content = await output.GetChildContentAsync(); - var list = (List)ViewContext.ViewData[typeof(AdminTabContentTagHelper).FullName]; - list.Add(content.GetContent()); + //outside a tab strip there is no list to collect the content in + if (ViewContext.ViewData[ContentsKey] is List list) + list.Add(content.GetContent()); output.SuppressOutput(); } } \ No newline at end of file diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemTagHelper.cs index 09577e57f..7d180ab9a 100644 --- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemTagHelper.cs +++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemTagHelper.cs @@ -7,9 +7,10 @@ namespace Grand.Web.Common.TagHelpers.Admin; [HtmlTargetElement("tabstrip-item")] public class AdminTabStripItemTagHelper : TagHelper { - [ViewContext] public ViewContext ViewContext { get; set; } + //set by the framework before the tag helper runs + [ViewContext] public ViewContext ViewContext { get; set; } = null!; - [HtmlAttributeName("Text")] public string Text { get; set; } + [HtmlAttributeName("Text")] public string? Text { get; set; } [HtmlAttributeName("tab-index")] public int CurrentIndex { set; get; } @@ -17,8 +18,8 @@ private int GetSelectedTabIndex() { var index = 0; var dataKey = "Grand.selected-tab-index"; - if (ViewContext.ViewData[dataKey] is int) index = (int)ViewContext.ViewData[dataKey]; - if (ViewContext.TempData[dataKey] is int) index = (int)ViewContext.TempData[dataKey]; + if (ViewContext.ViewData[dataKey] is int viewDataIndex) index = viewDataIndex; + if (ViewContext.TempData[dataKey] is int tempDataIndex) index = tempDataIndex; if (index < 0) index = 0; @@ -52,7 +53,7 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu link.Attributes["aria-selected"] = selected ? "true" : "false"; link.Attributes["tabindex"] = selected ? "0" : "-1"; //Text is view-authored (a localized resource), rendered as it was before - link.InnerHtml.AppendHtml(Text); + link.InnerHtml.AppendHtml(Text ?? ""); output.Content.AppendHtml(link); } } diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripTagHelper.cs index 31e66c0eb..5c8944e00 100644 --- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripTagHelper.cs +++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripTagHelper.cs @@ -31,15 +31,16 @@ public AdminTabStripTagHelper(IMediator mediator, IUserAgentClassifier userAgent [HtmlAttributeName("BindGrid")] public bool BindGrid { get; set; } = false; - [HtmlAttributeName("Name")] public string Name { get; set; } + [HtmlAttributeName("Name")] public string? Name { get; set; } - [ViewContext] public ViewContext ViewContext { get; set; } + //set by the framework before the tag helper runs + [ViewContext] public ViewContext ViewContext { get; set; } = null!; public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { - ViewContext.ViewData[typeof(AdminTabContentTagHelper).FullName] = new List(); + ViewContext.ViewData[AdminTabContentTagHelper.ContentsKey] = new List(); _ = await output.GetChildContentAsync(); - var list = (List)ViewContext.ViewData[typeof(AdminTabContentTagHelper).FullName]; + var list = ViewContext.ViewData[AdminTabContentTagHelper.ContentsKey] as List ?? []; if (_userAgentClassifier.IsMobileOrTablet) SetTabPos = false; @@ -68,10 +69,11 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu //literal, which broke on an apostrophe and let markup from a plugin run as script. //They are markup now, handed to the runtime in a