diff --git a/.ai/knowledge/dotnet.md b/.ai/knowledge/dotnet.md
index de5beadc0a..d16d777ea5 100644
--- a/.ai/knowledge/dotnet.md
+++ b/.ai/knowledge/dotnet.md
@@ -80,11 +80,26 @@ switch (cartItem.ShoppingCartTypeId)
## Nullable Reference Types
-The project has nullable reference types enabled. Follow these conventions:
-
-- `string` — the property/parameter is never null; calling code must not pass null.
-- `string?` — explicitly nullable; caller or callee handles null.
-- Do not suppress warnings with `!` unless you are certain the value cannot be null at that point.
+Nullable reference types are enabled, with nullable warnings as errors, in every project except the plugins
+(`src/Plugins`) and the test projects (`src/Tests`), which come in a later step. Each enabled project sets
+`enable` and `nullable` in its own `.csproj`; there are
+no `#nullable` directives. Razor views compile under their project's setting.
+
+- `string` — never null; calling code must not pass null.
+- `string?` — may be null; the callee copes with it.
+- Domain entity strings are `string?`; a field every validator requires and every creation site sets is
+ `string X { get; set; } = null!`. Do not use `= string.Empty` (it changes what MongoDB stores) or `required` on
+ entities (System.Text.Json enforces it).
+- Mediator requests: a property every creation site sets is `required`. A handler that can return null declares it
+ in the request (`IRequest`); never annotate `IRequestHandler.Handle` itself.
+- A lookup by id takes `string?` and returns `T?`. A value-or-error result is read through its value
+ (`x is { Outcome: Ok, User: { } user }`), not by testing the error.
+- Use `[NotNullWhen]`, `[MemberNotNullWhen]` and `[NotNullIfNotNull]` to say what a check or a mapper guarantees.
+ `[NotNullWhen]` does nothing on `Task`: write `x == null || !await Check(x)` instead.
+- A field a validator requires gets `ArgumentException.ThrowIfNullOrEmpty(model.X)` where it is used, with a comment
+ naming the validator.
+- Do not suppress warnings: no `#pragma`, no `NoWarn`, no `warnings`. A `!` is allowed only
+ with a comment that names the invariant the compiler cannot see.
---
diff --git a/src/Business/Grand.Business.Authentication/Grand.Business.Authentication.csproj b/src/Business/Grand.Business.Authentication/Grand.Business.Authentication.csproj
index 2ac20c3e91..84c0463269 100644
--- a/src/Business/Grand.Business.Authentication/Grand.Business.Authentication.csproj
+++ b/src/Business/Grand.Business.Authentication/Grand.Business.Authentication.csproj
@@ -7,4 +7,8 @@
+
+ enable
+ nullable
+
diff --git a/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs b/src/Business/Grand.Business.Authentication/Services/ExternalAuthenticationService.cs
index 9600424297..39153d6f8d 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));
@@ -236,7 +242,7 @@ public virtual IList LoadAllAuthenticationProvi
/// Customer whose groups the provider may be limited to
/// Store the provider may be limited to
/// True if is available; otherwise false
- public virtual bool AuthenticationProviderIsAvailable(string systemName, Customer customer, Store store)
+ public virtual bool AuthenticationProviderIsAvailable(string? systemName, Customer customer, Store store)
{
ArgumentNullException.ThrowIfNull(customer);
ArgumentNullException.ThrowIfNull(store);
@@ -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 8707367f40..20f807c226 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)
@@ -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);
@@ -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 ca480e95a0..b6dfb63829 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,
@@ -32,14 +32,14 @@ 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;
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 55cfb931fe..c8ef4dd742 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 5358b9647f..5a5d8f6c41 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 0e9a716344..0c61ed324e 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);
@@ -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);
@@ -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 c36510fea4..5bf341e83f 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 e4b87351e2..d886efdb82 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 1ccd8c3964..1881ebefe0 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);
@@ -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.Authentication/Services/RefreshTokenService.cs b/src/Business/Grand.Business.Authentication/Services/RefreshTokenService.cs
index 269ee82b32..c96d0bfab9 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 b0c47bc10c..0b573cd983 100644
--- a/src/Business/Grand.Business.Authentication/Services/Scim/ScimGroupService.cs
+++ b/src/Business/Grand.Business.Authentication/Services/Scim/ScimGroupService.cs
@@ -68,13 +68,13 @@ public virtual async Task Replace(string id, ScimGroupData data
return await ChangeMembers(group, await ManagedOnly(data.MemberIds), [], true);
}
- public virtual async Task Get(string id)
+ public virtual async Task Get(string? id)
{
var group = await Load(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))
@@ -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);
@@ -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)
@@ -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));
}
@@ -143,7 +146,7 @@ public virtual async Task> GetMappings() =>
public virtual async Task> GetMappableGroups() =>
(await groupService.GetAllCustomerGroups(showHidden: true)).Where(ScimRoleSync.IsMappable).ToList();
- public virtual async Task SetMapping(string groupId, string customerGroupId, string staffStoreId,
+ public virtual async Task SetMapping(string groupId, string? customerGroupId, string staffStoreId,
string vendorId)
{
var group = await Load(groupId);
@@ -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 b698791138..85b06e5fc8 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 e39d7db179..ad59a8ec9c 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 a7f04a7968..893584dae9 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 5378d1e1e9..b8d4f2607a 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,13 +168,12 @@ 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)
+ 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))
@@ -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 f8ea4aa560..5accf03f06 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 31aac4ca38..5fbfa5f1d2 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 8287b3943c..ab76517d27 100644
--- a/src/Business/Grand.Business.Catalog/Grand.Business.Catalog.csproj
+++ b/src/Business/Grand.Business.Catalog/Grand.Business.Catalog.csproj
@@ -6,4 +6,8 @@
+
+ enable
+ nullable
+
diff --git a/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountAmountProviderHandler.cs b/src/Business/Grand.Business.Catalog/Queries/Handlers/GetDiscountAmountProviderHandler.cs
index e432592446..50c434b002 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 e9ca46e3fa..f5b1fd115e 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 750efd03f7..0e41228ce0 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)
@@ -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 180ee47713..5ad0257703 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 ce8bdf5da4..1189b15a93 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 4867b423d5..45fec4ccc2 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 3702dd9580..152de53c5e 100644
--- a/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Brands/BrandService.cs
@@ -53,7 +53,7 @@ public BrandService(ICacheBase cacheBase,
/// Page index
/// Page size
/// Brands
- public virtual async Task> GetAllBrands(string brandName,
+ public virtual async Task> GetAllBrands(string? brandName,
CatalogAccess access,
int pageIndex = 0,
int pageSize = int.MaxValue)
@@ -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 ab5a71ab92..a91437058c 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 db5ac783a5..f4092db874 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 3f252f6da0..bb046d00d4 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 e78d132655..3f63fc7165 100644
--- a/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs
+++ b/src/Business/Grand.Business.Catalog/Services/Collections/CollectionService.cs
@@ -57,7 +57,7 @@ public CollectionService(ICacheBase cacheBase,
/// Page index
/// Page size
/// Collections
- public virtual async Task> GetAllCollections(string collectionName,
+ public virtual async Task> GetAllCollections(string? collectionName,
CatalogAccess access,
int pageIndex = 0,
int pageSize = int.MaxValue)
@@ -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 ccb43e003c..0f7341c6d1 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 664a77b8b9..6b1294a170 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 250293664b..b0c20b34e7 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 14b83aa1f6..70cf9fa633 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));
@@ -87,9 +87,9 @@ public virtual async Task> GetActiveDiscountsByContext(DiscountT
return filteredDiscounts.ToList();
}
- public virtual async Task> GetDiscountsQuery(DiscountType? discountType, string storeId = "",
- string currencyCode = "",
- string couponCode = "", string discountName = "")
+ public virtual async Task> GetDiscountsQuery(DiscountType? discountType, string? storeId = "",
+ string? currencyCode = "",
+ string? couponCode = "", string? discountName = "")
{
var query = _discountRepository.Table.AsQueryable();
@@ -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 530335039e..dee7df7bf9 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 00d2a24291..d1752f3cea 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 90f8b96263..b2c1f77c1e 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 fa58a96b18..9658db0fb1 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 fa2f22d22b..7794d1c42d 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 3f05795559..be9fed9c45 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 c4bd38b531..ddc8aefd55 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 4967a22ba3..809de90a73 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 30f4e566fb..28c092cb05 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 ecc2a0c702..cd0faa118a 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