Skip to content

Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.

Grand.Business.Common - Code cleanup (ReSharper)

support8eb0ca1820b1
diff --git a/src/Business/Grand.Business.Common/Events/GroupDeletedEventHandler.cs b/src/Business/Grand.Business.Common/Events/GroupDeletedEventHandler.cs
index 3b11f03bb..4ec3eafc5 100644
--- a/src/Business/Grand.Business.Common/Events/GroupDeletedEventHandler.cs
+++ b/src/Business/Grand.Business.Common/Events/GroupDeletedEventHandler.cs
@@ -1,39 +1,39 @@
-using Grand.Domain.Catalog;
+using Grand.Data;
+using Grand.Domain.Catalog;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Events;
using MediatR;
-namespace Grand.Business.Common.Events
+namespace Grand.Business.Common.Events;
+
+public class GroupDeletedEventHandler : INotificationHandler<EntityDeleted<CustomerGroup>>
{
- public class GroupDeletedEventHandler : INotificationHandler<EntityDeleted<CustomerGroup>>
+ private readonly ICacheBase _cacheBase;
+ private readonly IRepository<Customer> _customerRepository;
+ private readonly IRepository<Product> _productRepository;
+
+ public GroupDeletedEventHandler(
+ IRepository<Customer> customerRepository,
+ IRepository<Product> productRepository,
+ ICacheBase cacheBase)
+ {
+ _customerRepository = customerRepository;
+ _productRepository = productRepository;
+ _cacheBase = cacheBase;
+ }
+
+ public async Task Handle(EntityDeleted<CustomerGroup> notification, CancellationToken cancellationToken)
{
- private readonly IRepository<Customer> _customerRepository;
- private readonly IRepository<Product> _productRepository;
- private readonly ICacheBase _cacheBase;
-
- public GroupDeletedEventHandler(
- IRepository<Customer> customerRepository,
- IRepository<Product> productRepository,
- ICacheBase cacheBase)
- {
- _customerRepository = customerRepository;
- _productRepository = productRepository;
- _cacheBase = cacheBase;
- }
+ //delete from customers
+ await _customerRepository.Pull(string.Empty, x => x.Groups, notification.Entity.Id);
- public async Task Handle(EntityDeleted<CustomerGroup> notification, CancellationToken cancellationToken)
- {
- //delete from customers
- await _customerRepository.Pull(string.Empty, x => x.Groups, notification.Entity.Id);
-
- //delete tier prices on the product
- await _productRepository.PullFilter(string.Empty, x => x.TierPrices, z => z.CustomerGroupId, notification.Entity.Id);
+ //delete tier prices on the product
+ await _productRepository.PullFilter(string.Empty, x => x.TierPrices, z => z.CustomerGroupId,
+ notification.Entity.Id);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
- }
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PRODUCTS_PATTERN_KEY);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Events/LanguageDeletedEventHandler.cs b/src/Business/Grand.Business.Common/Events/LanguageDeletedEventHandler.cs
index 3bc44b7b8..309eb5084 100644
--- a/src/Business/Grand.Business.Common/Events/LanguageDeletedEventHandler.cs
+++ b/src/Business/Grand.Business.Common/Events/LanguageDeletedEventHandler.cs
@@ -1,42 +1,39 @@
using Grand.Business.Core.Interfaces.Common.Configuration;
using Grand.Business.Core.Interfaces.Common.Localization;
-using Grand.Infrastructure.Events;
using Grand.Domain.Localization;
+using Grand.Infrastructure.Events;
using MediatR;
-namespace Grand.Business.Common.Events
+namespace Grand.Business.Common.Events;
+
+public class LanguageDeletedEventHandler : INotificationHandler<EntityDeleted<Language>>
{
- public class LanguageDeletedEventHandler : INotificationHandler<EntityDeleted<Language>>
- {
- private readonly ILanguageService _languageService;
- private readonly ISettingService _settingService;
+ private readonly ILanguageService _languageService;
- private readonly LanguageSettings _languageSettings;
+ private readonly LanguageSettings _languageSettings;
+ private readonly ISettingService _settingService;
- public LanguageDeletedEventHandler(
- ILanguageService languageService,
- ISettingService settingService,
- LanguageSettings languageSettings
- )
- {
- _languageService = languageService;
- _settingService = settingService;
- _languageSettings = languageSettings;
- }
- public async Task Handle(EntityDeleted<Language> notification, CancellationToken cancellationToken)
- {
- //update default admin area language (if required)
- if (_languageSettings.DefaultAdminLanguageId == notification.Entity.Id)
+ public LanguageDeletedEventHandler(
+ ILanguageService languageService,
+ ISettingService settingService,
+ LanguageSettings languageSettings
+ )
+ {
+ _languageService = languageService;
+ _settingService = settingService;
+ _languageSettings = languageSettings;
+ }
+
+ public async Task Handle(EntityDeleted<Language> notification, CancellationToken cancellationToken)
+ {
+ //update default admin area language (if required)
+ if (_languageSettings.DefaultAdminLanguageId == notification.Entity.Id)
+ foreach (var activeLanguage in await _languageService.GetAllLanguages())
{
- foreach (var activeLanguage in await _languageService.GetAllLanguages())
- {
- if (activeLanguage.Id == notification.Entity.Id) continue;
- _languageSettings.DefaultAdminLanguageId = activeLanguage.Id;
- await _settingService.SaveSetting(_languageSettings);
- break;
- }
+ if (activeLanguage.Id == notification.Entity.Id) continue;
+ _languageSettings.DefaultAdminLanguageId = activeLanguage.Id;
+ await _settingService.SaveSetting(_languageSettings);
+ break;
}
-
- }
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeParser.cs b/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeParser.cs
index bd8dd8650..a6a88e6b9 100644
--- a/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeParser.cs
+++ b/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeParser.cs
@@ -6,195 +6,196 @@ using Grand.Domain.Localization;
using Grand.SharedKernel.Extensions;
using System.Net;
-namespace Grand.Business.Common.Services.Addresses
+namespace Grand.Business.Common.Services.Addresses;
+
+/// <summary>
+/// Address attribute parser
+/// </summary>
+public class AddressAttributeParser : IAddressAttributeParser
{
+ private readonly IAddressAttributeService _addressAttributeService;
+
+ public AddressAttributeParser(
+ IAddressAttributeService addressAttributeService)
+ {
+ _addressAttributeService = addressAttributeService;
+ }
+
/// <summary>
- /// Address attribute parser
+ /// Gets selected address attributes
/// </summary>
- public class AddressAttributeParser : IAddressAttributeParser
+ /// <param name="customAttributes">Attributes</param>
+ /// <returns>Selected address attributes</returns>
+ public virtual async Task<IList<AddressAttribute>> ParseAddressAttributes(IList<CustomAttribute> customAttributes)
{
- private readonly IAddressAttributeService _addressAttributeService;
-
- public AddressAttributeParser(
- IAddressAttributeService addressAttributeService)
- {
- _addressAttributeService = addressAttributeService;
- }
-
- /// <summary>
- /// Gets selected address attributes
- /// </summary>
- /// <param name="customAttributes">Attributes</param>
- /// <returns>Selected address attributes</returns>
- public virtual async Task<IList<AddressAttribute>> ParseAddressAttributes(IList<CustomAttribute> customAttributes)
- {
- var result = new List<AddressAttribute>();
- if (!customAttributes.Any())
- return result;
-
- foreach (var customAttribute in customAttributes.GroupBy(x => x.Key))
- {
- var attribute = await _addressAttributeService.GetAddressAttributeById(customAttribute.Key);
- if (attribute != null)
- {
- result.Add(attribute);
- }
- }
+ var result = new List<AddressAttribute>();
+ if (!customAttributes.Any())
return result;
- }
- /// <summary>
- /// Get address attribute values
- /// </summary>
- /// <param name="customAttributes">Attributes</param>
- /// <returns>Address attribute values</returns>
- public virtual async Task<IList<AddressAttributeValue>> ParseAddressAttributeValues(IList<CustomAttribute> customAttributes)
+ foreach (var customAttribute in customAttributes.GroupBy(x => x.Key))
{
- var values = new List<AddressAttributeValue>();
- if (!customAttributes.Any())
- return values;
+ var attribute = await _addressAttributeService.GetAddressAttributeById(customAttribute.Key);
+ if (attribute != null) result.Add(attribute);
+ }
- var attributes = await ParseAddressAttributes(customAttributes);
- foreach (var attribute in attributes)
- {
- if (!attribute.ShouldHaveValues())
- continue;
+ return result;
+ }
- var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value);
- values.AddRange(from valueStr in valuesStr where !string.IsNullOrEmpty(valueStr) select attribute.AddressAttributeValues.FirstOrDefault(x => x.Id == valueStr) into value where value != null select value);
- }
+ /// <summary>
+ /// Get address attribute values
+ /// </summary>
+ /// <param name="customAttributes">Attributes</param>
+ /// <returns>Address attribute values</returns>
+ public virtual async Task<IList<AddressAttributeValue>> ParseAddressAttributeValues(
+ IList<CustomAttribute> customAttributes)
+ {
+ var values = new List<AddressAttributeValue>();
+ if (!customAttributes.Any())
return values;
- }
- /// <summary>
- /// Adds an attribute
- /// </summary>
- /// <param name="customAttributes">Attributes</param>
- /// <param name="attribute">Address attribute</param>
- /// <param name="value">Value</param>
- /// <returns>Attributes</returns>
- public virtual IList<CustomAttribute> AddAddressAttribute(IList<CustomAttribute> customAttributes, AddressAttribute attribute, string value)
+ var attributes = await ParseAddressAttributes(customAttributes);
+ foreach (var attribute in attributes)
{
- customAttributes ??= new List<CustomAttribute>();
- customAttributes.Add(new CustomAttribute { Key = attribute.Id, Value = value });
- return customAttributes;
+ if (!attribute.ShouldHaveValues())
+ continue;
+
+ var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value);
+ values.AddRange(from valueStr in valuesStr
+ where !string.IsNullOrEmpty(valueStr)
+ select attribute.AddressAttributeValues.FirstOrDefault(x => x.Id == valueStr)
+ into value
+ where value != null
+ select value);
}
- /// <summary>
- /// Validates address attributes
- /// </summary>
- /// <param name="customAttributes">Attributes</param>
- /// <returns>Warnings</returns>
- public virtual async Task<IList<string>> GetAttributeWarnings(IList<CustomAttribute> customAttributes)
- {
- var warnings = new List<string>();
+ return values;
+ }
- //ensure it's our attributes
- var attributes1 = await ParseAddressAttributes(customAttributes);
+ /// <summary>
+ /// Adds an attribute
+ /// </summary>
+ /// <param name="customAttributes">Attributes</param>
+ /// <param name="attribute">Address attribute</param>
+ /// <param name="value">Value</param>
+ /// <returns>Attributes</returns>
+ public virtual IList<CustomAttribute> AddAddressAttribute(IList<CustomAttribute> customAttributes,
+ AddressAttribute attribute, string value)
+ {
+ customAttributes ??= new List<CustomAttribute>();
+ customAttributes.Add(new CustomAttribute { Key = attribute.Id, Value = value });
+ return customAttributes;
+ }
- //validate required address attributes (whether they're chosen/selected/entered)
- var attributes2 = await _addressAttributeService.GetAllAddressAttributes();
- foreach (var a2 in attributes2)
- {
- if (!a2.IsRequired) continue;
- var found = false;
- //selected address attributes
- foreach (var a1 in attributes1)
- {
- if (a1.Id != a2.Id) continue;
- var valuesStr = customAttributes.Where(x => x.Key == a1.Id).Select(x => x.Value);
- if (valuesStr.Any(str1 => !string.IsNullOrEmpty(str1.Trim())))
- {
- found = true;
- }
- }
+ /// <summary>
+ /// Validates address attributes
+ /// </summary>
+ /// <param name="customAttributes">Attributes</param>
+ /// <returns>Warnings</returns>
+ public virtual async Task<IList<string>> GetAttributeWarnings(IList<CustomAttribute> customAttributes)
+ {
+ var warnings = new List<string>();
+
+ //ensure it's our attributes
+ var attributes1 = await ParseAddressAttributes(customAttributes);
- //if not found
- if (found) continue;
- warnings.Add("Selected attribute not found");
+ //validate required address attributes (whether they're chosen/selected/entered)
+ var attributes2 = await _addressAttributeService.GetAllAddressAttributes();
+ foreach (var a2 in attributes2)
+ {
+ if (!a2.IsRequired) continue;
+ var found = false;
+ //selected address attributes
+ foreach (var a1 in attributes1)
+ {
+ if (a1.Id != a2.Id) continue;
+ var valuesStr = customAttributes.Where(x => x.Key == a1.Id).Select(x => x.Value);
+ if (valuesStr.Any(str1 => !string.IsNullOrEmpty(str1.Trim()))) found = true;
}
- return warnings;
+ //if not found
+ if (found) continue;
+ warnings.Add("Selected attribute not found");
}
- /// <summary>
- /// Formats attributes
- /// </summary>
- /// <param name="language">Languages</param>
- /// <param name="customAttributes">Attributes</param>
- /// <param name="separator">Separator</param>
- /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>
- /// <returns>Attributes</returns>
- public virtual async Task<string> FormatAttributes(
- Language language,
- IList<CustomAttribute> customAttributes,
- string separator = "<br />",
- bool htmlEncode = true)
- {
- var result = new StringBuilder();
- if (customAttributes == null)
- return result.ToString();
+ return warnings;
+ }
- var attributes = await ParseAddressAttributes(customAttributes);
- for (var i = 0; i < attributes.Count; i++)
+ /// <summary>
+ /// Formats attributes
+ /// </summary>
+ /// <param name="language">Languages</param>
+ /// <param name="customAttributes">Attributes</param>
+ /// <param name="separator">Separator</param>
+ /// <param name="htmlEncode">A value indicating whether to encode (HTML) values</param>
+ /// <returns>Attributes</returns>
+ public virtual async Task<string> FormatAttributes(
+ Language language,
+ IList<CustomAttribute> customAttributes,
+ string separator = "<br />",
+ bool htmlEncode = true)
+ {
+ var result = new StringBuilder();
+ if (customAttributes == null)
+ return result.ToString();
+
+ var attributes = await ParseAddressAttributes(customAttributes);
+ for (var i = 0; i < attributes.Count; i++)
+ {
+ var attribute = attributes[i];
+ var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value).ToList();
+ for (var j = 0; j < valuesStr.Count; j++)
{
- var attribute = attributes[i];
- var valuesStr = customAttributes.Where(x => x.Key == attribute.Id).Select(x => x.Value).ToList();
- for (var j = 0; j < valuesStr.Count; j++)
+ var valueStr = valuesStr[j];
+ var formattedAttribute = "";
+ if (!attribute.ShouldHaveValues())
{
- var valueStr = valuesStr[j];
- var formattedAttribute = "";
- if (!attribute.ShouldHaveValues())
+ switch (attribute.AttributeControlType)
{
- switch (attribute.AttributeControlType)
+ //no values
+ case AttributeControlType.MultilineTextbox:
{
- //no values
- case AttributeControlType.MultilineTextbox:
- {
- //multiline text box
- var attributeName = attribute.GetTranslation(a => a.Name, language.Id);
- //encode (if required)
- if (htmlEncode)
- attributeName = WebUtility.HtmlEncode(attributeName);
- formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";
- break;
- }
- case AttributeControlType.FileUpload:
- //file upload
- //not supported for address attributes
- break;
- default:
- {
- //other attributes (text box, datepicker)
- formattedAttribute = $"{attribute.GetTranslation(a => a.Name, language.Id)}: {valueStr}";
- //encode (if required)
- if (htmlEncode)
- formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
- break;
- }
+ //multiline text box
+ var attributeName = attribute.GetTranslation(a => a.Name, language.Id);
+ //encode (if required)
+ if (htmlEncode)
+ attributeName = WebUtility.HtmlEncode(attributeName);
+ formattedAttribute = $"{attributeName}: {FormatText.ConvertText(valueStr)}";
+ break;
}
- }
- else
- {
- var attributeValueId = valueStr;
- var attributeValue = attribute.AddressAttributeValues.FirstOrDefault(x => x.Id == attributeValueId);
- if (attributeValue != null)
+ case AttributeControlType.FileUpload:
+ //file upload
+ //not supported for address attributes
+ break;
+ default:
{
- formattedAttribute =
- $"{attribute.GetTranslation(a => a.Name, language.Id)}: {attributeValue.GetTranslation(a => a.Name, language.Id)}";
+ //other attributes (text box, datepicker)
+ formattedAttribute = $"{attribute.GetTranslation(a => a.Name, language.Id)}: {valueStr}";
+ //encode (if required)
+ if (htmlEncode)
+ formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
+ break;
}
- //encode (if required)
- if (htmlEncode)
- formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
}
-
- if (string.IsNullOrEmpty(formattedAttribute)) continue;
- if (i != 0 || j != 0)
- result.Append(separator);
- result.Append(formattedAttribute);
}
+ else
+ {
+ var attributeValueId = valueStr;
+ 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)}";
+ //encode (if required)
+ if (htmlEncode)
+ formattedAttribute = WebUtility.HtmlEncode(formattedAttribute);
+ }
+
+ if (string.IsNullOrEmpty(formattedAttribute)) continue;
+ if (i != 0 || j != 0)
+ result.Append(separator);
+ result.Append(formattedAttribute);
}
- return result.ToString();
}
+
+ return result.ToString();
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeService.cs b/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeService.cs
index aa29c4c83..d806fdd9e 100644
--- a/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeService.cs
+++ b/src/Business/Grand.Business.Common/Services/Addresses/AddressAttributeService.cs
@@ -1,180 +1,181 @@
using Grand.Business.Core.Interfaces.Common.Addresses;
+using Grand.Data;
+using Grand.Domain.Common;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
-using Grand.Domain.Common;
-using Grand.Data;
using MediatR;
-namespace Grand.Business.Common.Services.Addresses
+namespace Grand.Business.Common.Services.Addresses;
+
+/// <summary>
+/// Address attribute service
+/// </summary>
+public class AddressAttributeService : IAddressAttributeService
{
+ #region Ctor
+
/// <summary>
- /// Address attribute service
+ /// Ctor
/// </summary>
- public class AddressAttributeService : IAddressAttributeService
+ /// <param name="cacheBase">Cache manager</param>
+ /// <param name="addressAttributeRepository">Address attribute repository</param>
+ /// <param name="mediator">Mediator</param>
+ public AddressAttributeService(ICacheBase cacheBase,
+ IRepository<AddressAttribute> addressAttributeRepository,
+ IMediator mediator)
{
- #region Fields
+ _cacheBase = cacheBase;
+ _addressAttributeRepository = addressAttributeRepository;
+ _mediator = mediator;
+ }
- private readonly IRepository<AddressAttribute> _addressAttributeRepository;
- private readonly IMediator _mediator;
- private readonly ICacheBase _cacheBase;
+ #endregion
- #endregion
+ #region Fields
- #region Ctor
+ private readonly IRepository<AddressAttribute> _addressAttributeRepository;
+ private readonly IMediator _mediator;
+ private readonly ICacheBase _cacheBase;
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="cacheBase">Cache manager</param>
- /// <param name="addressAttributeRepository">Address attribute repository</param>
- /// <param name="mediator">Mediator</param>
- public AddressAttributeService(ICacheBase cacheBase,
- IRepository<AddressAttribute> addressAttributeRepository,
- IMediator mediator)
+ #endregion
+
+ #region Methods
+
+ /// <summary>
+ /// Gets all address attributes
+ /// </summary>
+ /// <returns>Address attributes</returns>
+ public virtual async Task<IList<AddressAttribute>> GetAllAddressAttributes()
+ {
+ var key = CacheKey.ADDRESSATTRIBUTES_ALL_KEY;
+ return await _cacheBase.GetAsync(key, async () =>
{
- _cacheBase = cacheBase;
- _addressAttributeRepository = addressAttributeRepository;
- _mediator = mediator;
- }
+ var query = from aa in _addressAttributeRepository.Table
+ orderby aa.DisplayOrder
+ select aa;
+ return await Task.FromResult(query.ToList());
+ });
+ }
- #endregion
+ /// <summary>
+ /// Gets an address attribute
+ /// </summary>
+ /// <param name="addressAttributeId">Address attribute identifier</param>
+ /// <returns>Address attribute</returns>
+ public virtual async Task<AddressAttribute> GetAddressAttributeById(string addressAttributeId)
+ {
+ if (string.IsNullOrEmpty(addressAttributeId))
+ return null;
- #region Methods
+ var key = string.Format(CacheKey.ADDRESSATTRIBUTES_BY_ID_KEY, addressAttributeId);
+ return await _cacheBase.GetAsync(key, () => _addressAttributeRepository.GetByIdAsync(addressAttributeId));
+ }
-
- /// <summary>
- /// Gets all address attributes
- /// </summary>
- /// <returns>Address attributes</returns>
- public virtual async Task<IList<AddressAttribute>> GetAllAddressAttributes()
- {
- var key = CacheKey.ADDRESSATTRIBUTES_ALL_KEY;
- return await _cacheBase.GetAsync(key, async () =>
- {
- var query = from aa in _addressAttributeRepository.Table
- orderby aa.DisplayOrder
- select aa;
- return await Task.FromResult(query.ToList());
- });
- }
-
- /// <summary>
- /// Gets an address attribute
- /// </summary>
- /// <param name="addressAttributeId">Address attribute identifier</param>
- /// <returns>Address attribute</returns>
- public virtual async Task<AddressAttribute> GetAddressAttributeById(string addressAttributeId)
- {
- if (string.IsNullOrEmpty(addressAttributeId))
- return null;
-
- var key = string.Format(CacheKey.ADDRESSATTRIBUTES_BY_ID_KEY, addressAttributeId);
- return await _cacheBase.GetAsync(key, () => _addressAttributeRepository.GetByIdAsync(addressAttributeId));
- }
-
- /// <summary>
- /// Inserts an address attribute
- /// </summary>
- /// <param name="addressAttribute">Address attribute</param>
- public virtual async Task InsertAddressAttribute(AddressAttribute addressAttribute)
- {
- ArgumentNullException.ThrowIfNull(addressAttribute);
+ /// <summary>
+ /// Inserts an address attribute
+ /// </summary>
+ /// <param name="addressAttribute">Address attribute</param>
+ public virtual async Task InsertAddressAttribute(AddressAttribute addressAttribute)
+ {
+ ArgumentNullException.ThrowIfNull(addressAttribute);
- await _addressAttributeRepository.InsertAsync(addressAttribute);
+ await _addressAttributeRepository.InsertAsync(addressAttribute);
- await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
- //event notification
- await _mediator.EntityInserted(addressAttribute);
- }
+ //event notification
+ await _mediator.EntityInserted(addressAttribute);
+ }
- /// <summary>
- /// Updates the address attribute
- /// </summary>
- /// <param name="addressAttribute">Address attribute</param>
- public virtual async Task UpdateAddressAttribute(AddressAttribute addressAttribute)
- {
- ArgumentNullException.ThrowIfNull(addressAttribute);
+ /// <summary>
+ /// Updates the address attribute
+ /// </summary>
+ /// <param name="addressAttribute">Address attribute</param>
+ public virtual async Task UpdateAddressAttribute(AddressAttribute addressAttribute)
+ {
+ ArgumentNullException.ThrowIfNull(addressAttribute);
- await _addressAttributeRepository.UpdateAsync(addressAttribute);
+ await _addressAttributeRepository.UpdateAsync(addressAttribute);
- await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
- //event notification
- await _mediator.EntityUpdated(addressAttribute);
- }
- /// <summary>
- /// Deletes an address attribute
- /// </summary>
- /// <param name="addressAttribute">Address attribute</param>
- public virtual async Task DeleteAddressAttribute(AddressAttribute addressAttribute)
- {
- ArgumentNullException.ThrowIfNull(addressAttribute);
+ //event notification
+ await _mediator.EntityUpdated(addressAttribute);
+ }
- await _addressAttributeRepository.DeleteAsync(addressAttribute);
+ /// <summary>
+ /// Deletes an address attribute
+ /// </summary>
+ /// <param name="addressAttribute">Address attribute</param>
+ public virtual async Task DeleteAddressAttribute(AddressAttribute addressAttribute)
+ {
+ ArgumentNullException.ThrowIfNull(addressAttribute);
- await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
+ await _addressAttributeRepository.DeleteAsync(addressAttribute);
- //event notification
- await _mediator.EntityDeleted(addressAttribute);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
- /// <summary>
- /// Inserts an address attribute value
- /// </summary>
- /// <param name="addressAttributeValue">Address attribute value</param>
- public virtual async Task InsertAddressAttributeValue(AddressAttributeValue addressAttributeValue)
- {
- ArgumentNullException.ThrowIfNull(addressAttributeValue);
+ //event notification
+ await _mediator.EntityDeleted(addressAttribute);
+ }
- await _addressAttributeRepository.AddToSet(addressAttributeValue.AddressAttributeId, x => x.AddressAttributeValues, addressAttributeValue);
+ /// <summary>
+ /// Inserts an address attribute value
+ /// </summary>
+ /// <param name="addressAttributeValue">Address attribute value</param>
+ public virtual async Task InsertAddressAttributeValue(AddressAttributeValue addressAttributeValue)
+ {
+ ArgumentNullException.ThrowIfNull(addressAttributeValue);
- await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
+ await _addressAttributeRepository.AddToSet(addressAttributeValue.AddressAttributeId,
+ x => x.AddressAttributeValues, addressAttributeValue);
- //event notification
- await _mediator.EntityInserted(addressAttributeValue);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
- /// <summary>
- /// Updates the address attribute value
- /// </summary>
- /// <param name="addressAttributeValue">Address attribute value</param>
- public virtual async Task UpdateAddressAttributeValue(AddressAttributeValue addressAttributeValue)
- {
- ArgumentNullException.ThrowIfNull(addressAttributeValue);
+ //event notification
+ await _mediator.EntityInserted(addressAttributeValue);
+ }
- await _addressAttributeRepository.UpdateToSet(addressAttributeValue.AddressAttributeId,
- x => x.AddressAttributeValues, z => z.Id, addressAttributeValue.Id, addressAttributeValue);
+ /// <summary>
+ /// Updates the address attribute value
+ /// </summary>
+ /// <param name="addressAttributeValue">Address attribute value</param>
+ public virtual async Task UpdateAddressAttributeValue(AddressAttributeValue addressAttributeValue)
+ {
+ ArgumentNullException.ThrowIfNull(addressAttributeValue);
- await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
+ await _addressAttributeRepository.UpdateToSet(addressAttributeValue.AddressAttributeId,
+ x => x.AddressAttributeValues, z => z.Id, addressAttributeValue.Id, addressAttributeValue);
- //event notification
- await _mediator.EntityUpdated(addressAttributeValue);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
- /// <summary>
- /// Deletes an address attribute value
- /// </summary>
- /// <param name="addressAttributeValue">Address attribute value</param>
- public virtual async Task DeleteAddressAttributeValue(AddressAttributeValue addressAttributeValue)
- {
- ArgumentNullException.ThrowIfNull(addressAttributeValue);
+ //event notification
+ await _mediator.EntityUpdated(addressAttributeValue);
+ }
- await _addressAttributeRepository.PullFilter(addressAttributeValue.AddressAttributeId, x => x.AddressAttributeValues, z => z.Id, addressAttributeValue.Id);
+ /// <summary>
+ /// Deletes an address attribute value
+ /// </summary>
+ /// <param name="addressAttributeValue">Address attribute value</param>
+ public virtual async Task DeleteAddressAttributeValue(AddressAttributeValue addressAttributeValue)
+ {
+ ArgumentNullException.ThrowIfNull(addressAttributeValue);
- await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTES_PATTERN_KEY);
- await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
+ await _addressAttributeRepository.PullFilter(addressAttributeValue.AddressAttributeId,
+ x => x.AddressAttributeValues, z => z.Id, addressAttributeValue.Id);
- //event notification
- await _mediator.EntityDeleted(addressAttributeValue);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTES_PATTERN_KEY);
+ await _cacheBase.RemoveByPrefix(CacheKey.ADDRESSATTRIBUTEVALUES_PATTERN_KEY);
- #endregion
+ //event notification
+ await _mediator.EntityDeleted(addressAttributeValue);
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs b/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs
index d28d2b5b3..b5e71981e 100644
--- a/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs
+++ b/src/Business/Grand.Business.Common/Services/Configuration/SettingService.cs
@@ -1,271 +1,268 @@
using Grand.Business.Core.Interfaces.Common.Configuration;
-using Grand.Domain.Configuration;
using Grand.Data;
+using Grand.Domain.Configuration;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using System.Text.Json;
-namespace Grand.Business.Common.Services.Configuration
+namespace Grand.Business.Common.Services.Configuration;
+
+/// <summary>
+/// Setting manager
+/// </summary>
+public class SettingService : ISettingService
{
+ #region Ctor
+
/// <summary>
- /// Setting manager
+ /// Ctor
/// </summary>
- public class SettingService : ISettingService
+ /// <param name="cacheBase">Cache manager</param>
+ /// <param name="settingRepository">Setting repository</param>
+ public SettingService(ICacheBase cacheBase,
+ IRepository<Setting> settingRepository)
{
- #region Fields
+ _cacheBase = cacheBase;
+ _settingRepository = settingRepository;
+ }
- private readonly IRepository<Setting> _settingRepository;
- private readonly ICacheBase _cacheBase;
+ #endregion
- #endregion
+ #region Utilities
- #region Ctor
+ /// <summary>
+ /// Gets a setting by identifier
+ /// </summary>
+ /// <param name="name">Setting name</param>
+ /// <returns>Setting</returns>
+ private IList<Setting> GetSettingsByName(string name)
+ {
+ if (string.IsNullOrEmpty(name))
+ throw new ArgumentNullException(nameof(name));
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="cacheBase">Cache manager</param>
- /// <param name="settingRepository">Setting repository</param>
- public SettingService(ICacheBase cacheBase,
- IRepository<Setting> settingRepository)
- {
- _cacheBase = cacheBase;
- _settingRepository = settingRepository;
- }
+ return _settingRepository.Table.Where(x => x.Name == name.ToLowerInvariant()).ToList();
+ }
- #endregion
+ #endregion
- #region Utilities
+ #region Fields
- /// <summary>
- /// Gets a setting by identifier
- /// </summary>
- /// <param name="name">Setting name</param>
- /// <returns>Setting</returns>
- private IList<Setting> GetSettingsByName(string name)
- {
- if (string.IsNullOrEmpty(name))
- throw new ArgumentNullException(nameof(name));
+ private readonly IRepository<Setting> _settingRepository;
+ private readonly ICacheBase _cacheBase;
- return _settingRepository.Table.Where(x => x.Name == name.ToLowerInvariant()).ToList();
- }
-
- #endregion
+ #endregion
- #region Methods
+ #region Methods
- /// <summary>
- /// Adds a setting
- /// </summary>
- /// <param name="setting">Setting</param>
- /// <param name="clearCache">A value indicating whether to clear cache after setting update</param>
- public virtual async Task InsertSetting(Setting setting, bool clearCache = true)
- {
- ArgumentNullException.ThrowIfNull(setting);
+ /// <summary>
+ /// Adds a setting
+ /// </summary>
+ /// <param name="setting">Setting</param>
+ /// <param name="clearCache">A value indicating whether to clear cache after setting update</param>
+ public virtual async Task InsertSetting(Setting setting, bool clearCache = true)
+ {
+ ArgumentNullException.ThrowIfNull(setting);
- await _settingRepository.InsertAsync(setting);
+ await _settingRepository.InsertAsync(setting);
- //cache
- if (clearCache)
- await _cacheBase.Clear();
+ //cache
+ if (clearCache)
+ await _cacheBase.Clear();
+ }
- }
+ /// <summary>
+ /// Updates a setting
+ /// </summary>
+ /// <param name="setting">Setting</param>
+ /// <param name="clearCache">A value indicating whether to clear cache after setting update</param>
+ public virtual async Task UpdateSetting(Setting setting, bool clearCache = true)
+ {
+ ArgumentNullException.ThrowIfNull(setting);
- /// <summary>
- /// Updates a setting
- /// </summary>
- /// <param name="setting">Setting</param>
- /// <param name="clearCache">A value indicating whether to clear cache after setting update</param>
- public virtual async Task UpdateSetting(Setting setting, bool clearCache = true)
- {
- ArgumentNullException.ThrowIfNull(setting);
+ await _settingRepository.UpdateAsync(setting);
- await _settingRepository.UpdateAsync(setting);
+ //cache
+ if (clearCache)
+ await _cacheBase.Clear();
+ }
- //cache
- if (clearCache)
- await _cacheBase.Clear();
+ /// <summary>
+ /// Deletes a setting
+ /// </summary>
+ /// <param name="setting">Setting</param>
+ public virtual async Task DeleteSetting(Setting setting)
+ {
+ ArgumentNullException.ThrowIfNull(setting);
- }
+ await _settingRepository.DeleteAsync(setting);
- /// <summary>
- /// Deletes a setting
- /// </summary>
- /// <param name="setting">Setting</param>
- public virtual async Task DeleteSetting(Setting setting)
- {
- ArgumentNullException.ThrowIfNull(setting);
+ //cache
+ await _cacheBase.Clear();
+ }
- await _settingRepository.DeleteAsync(setting);
+ /// <summary>
+ /// Gets a setting by identifier
+ /// </summary>
+ /// <param name="settingId">Setting identifier</param>
+ /// <returns>Setting</returns>
+ public virtual Task<Setting> GetSettingById(string settingId)
+ {
+ return _settingRepository.GetByIdAsync(settingId);
+ }
- //cache
- await _cacheBase.Clear();
- }
+ /// <summary>
+ /// Get setting value by key
+ /// </summary>
+ /// <typeparam name="T">Type</typeparam>
+ /// <param name="key">Key</param>
+ /// <param name="defaultValue">Default value</param>
+ /// <param name="storeId">Store identifier</param>
+ /// <returns>Setting value</returns>
+ public virtual T GetSettingByKey<T>(string key, T defaultValue = default, string storeId = "")
+ {
+ if (string.IsNullOrEmpty(key))
+ return defaultValue;
- /// <summary>
- /// Gets a setting by identifier
- /// </summary>
- /// <param name="settingId">Setting identifier</param>
- /// <returns>Setting</returns>
- public virtual Task<Setting> GetSettingById(string settingId)
+ var keyCache = string.Format(CacheKey.SETTINGS_BY_KEY, key, storeId);
+ return _cacheBase.Get(keyCache, () =>
{
- return _settingRepository.GetByIdAsync(settingId);
- }
+ var settings = GetSettingsByName(key);
+ key = key.Trim().ToLowerInvariant();
+ if (!settings.Any()) return defaultValue;
+ var setting = settings.FirstOrDefault(x => x.StoreId == storeId) ??
+ settings.FirstOrDefault(x => string.IsNullOrEmpty(x.StoreId));
+ return setting != null ? JsonSerializer.Deserialize<T>(setting.Metadata) : defaultValue;
+ });
+ }
+
+ /// <summary>
+ /// Set setting value
+ /// </summary>
+ /// <typeparam name="T">Type</typeparam>
+ /// <param name="key">Key</param>
+ /// <param name="value">Value</param>
+ /// <param name="storeId">Store identifier</param>
+ /// <param name="clearCache">A value indicating whether to clear cache after setting update</param>
+ public virtual async Task SetSetting<T>(string key, T value, string storeId = "", bool clearCache = true)
+ {
+ ArgumentNullException.ThrowIfNull(key);
+
+ key = key.Trim().ToLowerInvariant();
- /// <summary>
- /// Get setting value by key
- /// </summary>
- /// <typeparam name="T">Type</typeparam>
- /// <param name="key">Key</param>
- /// <param name="defaultValue">Default value</param>
- /// <param name="storeId">Store identifier</param>
- /// <returns>Setting value</returns>
- public virtual T GetSettingByKey<T>(string key, T defaultValue = default, string storeId = "")
+ var settings = GetSettingsByName(key);
+ var setting = settings.Any() ? settings.FirstOrDefault(x => x.StoreId == storeId) : null;
+ if (setting != null)
{
- if (string.IsNullOrEmpty(key))
- return defaultValue;
-
- var keyCache = string.Format(CacheKey.SETTINGS_BY_KEY, key, storeId);
- return _cacheBase.Get(keyCache, () =>
- {
- var settings = GetSettingsByName(key);
- key = key.Trim().ToLowerInvariant();
- if (!settings.Any()) return defaultValue;
-
- var setting = settings.FirstOrDefault(x => x.StoreId == storeId) ?? settings.FirstOrDefault(x => string.IsNullOrEmpty(x.StoreId));
- return setting != null ? JsonSerializer.Deserialize<T>(setting.Metadata) : defaultValue;
- });
+ //update
+ setting.Metadata = JsonSerializer.Serialize(value);
+ await UpdateSetting(setting, clearCache);
}
-
- /// <summary>
- /// Set setting value
- /// </summary>
- /// <typeparam name="T">Type</typeparam>
- /// <param name="key">Key</param>
- /// <param name="value">Value</param>
- /// <param name="storeId">Store identifier</param>
- /// <param name="clearCache">A value indicating whether to clear cache after setting update</param>
- public virtual async Task SetSetting<T>(string key, T value, string storeId = "", bool clearCache = true)
+ else
{
- ArgumentNullException.ThrowIfNull(key);
+ //insert
+ var metadata = JsonSerializer.Serialize(value);
+ setting = new Setting {
+ Name = key.ToLowerInvariant(),
+ Metadata = metadata,
+ StoreId = storeId
+ };
+ await InsertSetting(setting, clearCache);
+ }
+ }
- key = key.Trim().ToLowerInvariant();
+ /// <summary>
+ /// Gets all settings
+ /// </summary>
+ /// <returns>Settings</returns>
+ public virtual IList<Setting> GetAllSettings()
+ {
+ return _settingRepository.Table.OrderBy(x => x.Name).ToList();
+ }
- var settings = GetSettingsByName(key);
- var setting = settings.Any() ? settings.FirstOrDefault(x => x.StoreId == storeId) : null;
- if (setting != null)
- {
- //update
- setting.Metadata = JsonSerializer.Serialize(value);
- await UpdateSetting(setting, clearCache);
- }
- else
- {
- //insert
- var metadata = JsonSerializer.Serialize(value);
- setting = new Setting {
- Name = key.ToLowerInvariant(),
- Metadata = metadata,
- StoreId = storeId
- };
- await InsertSetting(setting, clearCache);
- }
- }
+ /// <summary>
+ /// Load settings
+ /// </summary>
+ /// <typeparam name="T">Type</typeparam>
+ /// <param name="storeId">Store identifier for which settings should be loaded</param>
+ public virtual T LoadSetting<T>(string storeId = "") where T : ISettings, new()
+ {
+ return (T)LoadSetting(typeof(T), storeId);
+ }
- /// <summary>
- /// Gets all settings
- /// </summary>
- /// <returns>Settings</returns>
- public virtual IList<Setting> GetAllSettings()
+ /// <summary>
+ /// Load settings
+ /// </summary>
+ /// <param name="type">Type</param>
+ /// <param name="storeId">Store identifier for which settings should be loaded</param>
+ public virtual ISettings LoadSetting(Type type, string storeId = "")
+ {
+ var key = string.Format(CacheKey.SETTINGS_BY_KEY, type.Name, storeId);
+ return _cacheBase.Get(key, () =>
{
- return _settingRepository.Table.OrderBy(x => x.Name).ToList();
- }
+ var settings = GetSettingsByName(type.Name);
+ if (!settings.Any()) return Activator.CreateInstance(type) as ISettings;
+ var setting = settings.FirstOrDefault(x => x.StoreId == storeId);
- /// <summary>
- /// Load settings
- /// </summary>
- /// <typeparam name="T">Type</typeparam>
- /// <param name="storeId">Store identifier for which settings should be loaded</param>
- public virtual T LoadSetting<T>(string storeId = "") where T : ISettings, new()
- {
- return (T)LoadSetting(typeof(T), storeId);
- }
+ if (setting == null && !string.IsNullOrEmpty(storeId))
+ setting = settings.FirstOrDefault(x => string.IsNullOrEmpty(x.StoreId));
- /// <summary>
- /// Load settings
- /// </summary>
- /// <param name="type">Type</param>
- /// <param name="storeId">Store identifier for which settings should be loaded</param>
- public virtual ISettings LoadSetting(Type type, string storeId = "")
+ if (setting != null) return JsonSerializer.Deserialize(setting.Metadata, type) as ISettings;
+ return Activator.CreateInstance(type) as ISettings;
+ });
+ }
+
+ /// <summary>
+ /// Save settings object
+ /// </summary>
+ /// <typeparam name="T">Type</typeparam>
+ /// <param name="storeId">Store identifier</param>
+ /// <param name="settings">Setting instance</param>
+ public virtual async Task SaveSetting<T>(T settings, string storeId = "") where T : ISettings, new()
+ {
+ var dbSettings = GetSettingsByName(typeof(T).Name);
+ var setting = dbSettings.Any() ? dbSettings.FirstOrDefault(x => x.StoreId == storeId) : null;
+ if (setting != null)
{
- var key = string.Format(CacheKey.SETTINGS_BY_KEY, type.Name, storeId);
- return _cacheBase.Get(key, () =>
- {
- var settings = GetSettingsByName(type.Name);
- if (!settings.Any()) return Activator.CreateInstance(type) as ISettings;
- var setting = settings.FirstOrDefault(x => x.StoreId == storeId);
-
- if (setting == null && !string.IsNullOrEmpty(storeId))
- setting = settings.FirstOrDefault(x => string.IsNullOrEmpty(x.StoreId));
-
- if (setting != null) return JsonSerializer.Deserialize(setting.Metadata, type) as ISettings;
- return Activator.CreateInstance(type) as ISettings;
- });
+ //update
+ setting.Metadata = JsonSerializer.Serialize(settings);
+ await UpdateSetting(setting);
}
-
- /// <summary>
- /// Save settings object
- /// </summary>
- /// <typeparam name="T">Type</typeparam>
- /// <param name="storeId">Store identifier</param>
- /// <param name="settings">Setting instance</param>
- public virtual async Task SaveSetting<T>(T settings, string storeId = "") where T : ISettings, new()
+ else
{
- var dbSettings = GetSettingsByName(typeof(T).Name);
- var setting = dbSettings.Any() ? dbSettings.FirstOrDefault(x => x.StoreId == storeId) : null;
- if (setting != null)
- {
- //update
- setting.Metadata = JsonSerializer.Serialize(settings);
- await UpdateSetting(setting);
- }
- else
- {
- //insert
- setting = new Setting {
- Name = typeof(T).Name.ToLowerInvariant(),
- Metadata = JsonSerializer.Serialize(settings),
- StoreId = storeId
- };
- await InsertSetting(setting);
- }
-
- //and now clear cache
- await ClearCache();
+ //insert
+ setting = new Setting {
+ Name = typeof(T).Name.ToLowerInvariant(),
+ Metadata = JsonSerializer.Serialize(settings),
+ StoreId = storeId
+ };
+ await InsertSetting(setting);
}
- /// <summary>
- /// Delete all settings
- /// </summary>
- /// <typeparam name="T">Type</typeparam>
- public virtual async Task DeleteSetting<T>() where T : ISettings, new()
- {
- var settingsToDelete = GetSettingsByName(typeof(T).Name);
+ //and now clear cache
+ await ClearCache();
+ }
- foreach (var setting in settingsToDelete)
- await DeleteSetting(setting);
- }
+ /// <summary>
+ /// Delete all settings
+ /// </summary>
+ /// <typeparam name="T">Type</typeparam>
+ public virtual async Task DeleteSetting<T>() where T : ISettings, new()
+ {
+ var settingsToDelete = GetSettingsByName(typeof(T).Name);
- /// <summary>
- /// Clear cache
- /// </summary>
- public virtual async Task ClearCache()
- {
- await _cacheBase.RemoveByPrefix(CacheKey.SETTINGS_PATTERN_KEY);
- }
+ foreach (var setting in settingsToDelete)
+ await DeleteSetting(setting);
+ }
- #endregion
+ /// <summary>
+ /// Clear cache
+ /// </summary>
+ public virtual async Task ClearCache()
+ {
+ await _cacheBase.RemoveByPrefix(CacheKey.SETTINGS_PATTERN_KEY);
}
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs b/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs
index 6bd301201..2ec86a048 100644
--- a/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs
+++ b/src/Business/Grand.Business.Common/Services/Directory/CountryService.cs
@@ -8,308 +8,308 @@ using Grand.Infrastructure.Configuration;
using Grand.Infrastructure.Extensions;
using MediatR;
-namespace Grand.Business.Common.Services.Directory
+namespace Grand.Business.Common.Services.Directory;
+
+/// <summary>
+/// Country service
+/// </summary>
+public class CountryService : ICountryService
{
+ #region Ctor
+
/// <summary>
- /// Country service
+ /// Ctor
/// </summary>
- public class CountryService : ICountryService
+ /// <param name="countryRepository">Country repository</param>
+ /// <param name="mediator">Mediator</param>
+ /// <param name="cacheBase">Cache manager</param>
+ /// <param name="accessControlConfig">Access control</param>
+ public CountryService(
+ IRepository<Country> countryRepository,
+ IMediator mediator,
+ ICacheBase cacheBase,
+ AccessControlConfig accessControlConfig)
{
- #region Fields
-
- private readonly IRepository<Country> _countryRepository;
- private readonly IMediator _mediator;
- private readonly ICacheBase _cacheBase;
- private readonly AccessControlConfig _accessControlConfig;
-
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="countryRepository">Country repository</param>
- /// <param name="mediator">Mediator</param>
- /// <param name="cacheBase">Cache manager</param>
- /// <param name="accessControlConfig">Access control</param>
- public CountryService(
- IRepository<Country> countryRepository,
- IMediator mediator,
- ICacheBase cacheBase,
- AccessControlConfig accessControlConfig)
- {
- _cacheBase = cacheBase;
- _accessControlConfig = accessControlConfig;
- _countryRepository = countryRepository;
- _mediator = mediator;
- }
+ _cacheBase = cacheBase;
+ _accessControlConfig = accessControlConfig;
+ _countryRepository = countryRepository;
+ _mediator = mediator;
+ }
- #endregion
+ #endregion
- #region Methods
+ #region Fields
- /// <summary>
- /// Gets all countries
- /// </summary>
- /// <param name="languageId">Language identifier.</param>
- /// <param name="storeId">Store ident</param>
- /// <param name="showHidden">A value indicating whether to show hidden records</param>
- /// <returns>Countries</returns>
- public virtual async Task<IList<Country>> GetAllCountries(string languageId = "", string storeId = "", bool showHidden = false)
- {
- var key = string.Format(CacheKey.COUNTRIES_ALL_KEY, languageId, storeId, showHidden);
+ private readonly IRepository<Country> _countryRepository;
+ private readonly IMediator _mediator;
+ private readonly ICacheBase _cacheBase;
+ private readonly AccessControlConfig _accessControlConfig;
- return await _cacheBase.GetAsync(key, async () =>
- {
- var query = from p in _countryRepository.Table
- select p;
-
- if (!showHidden)
- query = query.Where(c => c.Published);
-
- if (!showHidden && !_accessControlConfig.IgnoreStoreLimitations && !string.IsNullOrEmpty(storeId))
- {
- //Store acl
- query = from p in query
- where !p.LimitedToStores || p.Stores.Contains(storeId)
- select p;
- }
-
- var countries = await Task.FromResult(query.OrderBy(x => x.DisplayOrder).ThenBy(x => x.Name).ToList());
- if (!string.IsNullOrEmpty(languageId))
- {
- countries = countries
- .OrderBy(c => c.DisplayOrder)
- .ThenBy(c => c.GetTranslation(x => x.Name, languageId))
- .ToList();
- }
- return countries;
- });
- }
+ #endregion
- /// <summary>
- /// Gets all countries that allow billing
- /// </summary>
- /// <param name="languageId">Language identifier.</param>
- /// <param name="storeId">Store ident</param>
- /// <param name="showHidden">A value indicating whether to show hidden records</param>
- /// <returns>Countries</returns>
- public virtual async Task<IList<Country>> GetAllCountriesForBilling(string languageId = "", string storeId = "", bool showHidden = false)
- {
- var countries = await GetAllCountries(languageId, storeId, showHidden);
- return countries.Where(c => c.AllowsBilling).ToList();
- }
+ #region Methods
- /// <summary>
- /// Gets all countries that allow shipping
- /// </summary>
- /// <param name="languageId">Language identifier.</param>
- /// <param name="storeId">Store ident</param>
- /// <param name="showHidden">A value indicating whether to show hidden records</param>
- /// <returns>Countries</returns>
- public virtual async Task<IList<Country>> GetAllCountriesForShipping(string languageId = "", string storeId = "", bool showHidden = false)
- {
- var countries = await GetAllCountries(languageId, storeId, showHidden);
- return countries.Where(c => c.AllowsShipping).ToList();
- }
+ /// <summary>
+ /// Gets all countries
+ /// </summary>
+ /// <param name="languageId">Language identifier.</param>
+ /// <param name="storeId">Store ident</param>
+ /// <param name="showHidden">A value indicating whether to show hidden records</param>
+ /// <returns>Countries</returns>
+ public virtual async Task<IList<Country>> GetAllCountries(string languageId = "", string storeId = "",
+ bool showHidden = false)
+ {
+ var key = string.Format(CacheKey.COUNTRIES_ALL_KEY, languageId, storeId, showHidden);
- /// <summary>
- /// Gets a country
- /// </summary>
- /// <param name="countryId">Country identifier</param>
- /// <returns>Country</returns>
- public virtual async Task<Country> GetCountryById(string countryId)
+ return await _cacheBase.GetAsync(key, async () =>
{
- if (string.IsNullOrEmpty(countryId))
- return null;
+ var query = from p in _countryRepository.Table
+ select p;
+
+ if (!showHidden)
+ query = query.Where(c => c.Published);
+
+ if (!showHidden && !_accessControlConfig.IgnoreStoreLimitations && !string.IsNullOrEmpty(storeId))
+ //Store acl
+ query = from p in query
+ where !p.LimitedToStores || p.Stores.Contains(storeId)
+ select p;
+
+ var countries = await Task.FromResult(query.OrderBy(x => x.DisplayOrder).ThenBy(x => x.Name).ToList());
+ if (!string.IsNullOrEmpty(languageId))
+ countries = countries
+ .OrderBy(c => c.DisplayOrder)
+ .ThenBy(c => c.GetTranslation(x => x.Name, languageId))
+ .ToList();
+ return countries;
+ });
+ }
- var key = string.Format(CacheKey.COUNTRIES_BY_KEY, countryId);
- return await _cacheBase.GetAsync(key, () => _countryRepository.GetByIdAsync(countryId));
- }
+ /// <summary>
+ /// Gets all countries that allow billing
+ /// </summary>
+ /// <param name="languageId">Language identifier.</param>
+ /// <param name="storeId">Store ident</param>
+ /// <param name="showHidden">A value indicating whether to show hidden records</param>
+ /// <returns>Countries</returns>
+ public virtual async Task<IList<Country>> GetAllCountriesForBilling(string languageId = "", string storeId = "",
+ bool showHidden = false)
+ {
+ var countries = await GetAllCountries(languageId, storeId, showHidden);
+ return countries.Where(c => c.AllowsBilling).ToList();
+ }
- /// <summary>
- /// Get countries by identifiers
- /// </summary>
- /// <param name="countryIds">Country identifiers</param>
- /// <returns>Countries</returns>
- public virtual async Task<IList<Country>> GetCountriesByIds(string[] countryIds)
- {
- if (countryIds == null || countryIds.Length == 0)
- return new List<Country>();
-
- var query = from c in _countryRepository.Table
- where countryIds.Contains(c.Id)
- select c;
- var countries = await Task.FromResult(query.ToList());
- //sort by passed identifiers
- return countryIds.Select(id => countries.Find(x => x.Id == id)).Where(country => country != null).ToList();
- }
+ /// <summary>
+ /// Gets all countries that allow shipping
+ /// </summary>
+ /// <param name="languageId">Language identifier.</param>
+ /// <param name="storeId">Store ident</param>
+ /// <param name="showHidden">A value indicating whether to show hidden records</param>
+ /// <returns>Countries</returns>
+ public virtual async Task<IList<Country>> GetAllCountriesForShipping(string languageId = "", string storeId = "",
+ bool showHidden = false)
+ {
+ var countries = await GetAllCountries(languageId, storeId, showHidden);
+ return countries.Where(c => c.AllowsShipping).ToList();
+ }
- /// <summary>
- /// Gets a country by two letter ISO code
- /// </summary>
- /// <param name="twoLetterIsoCode">Country two letter ISO code</param>
- /// <returns>Country</returns>
- public virtual async Task<Country> GetCountryByTwoLetterIsoCode(string twoLetterIsoCode)
- {
- var key = string.Format(CacheKey.COUNTRIES_BY_TWOLETTER, twoLetterIsoCode);
- return await _cacheBase.GetAsync(key, async () =>
- {
- return await _countryRepository.GetOneAsync(x => x.TwoLetterIsoCode == twoLetterIsoCode);
- });
- }
+ /// <summary>
+ /// Gets a country
+ /// </summary>
+ /// <param name="countryId">Country identifier</param>
+ /// <returns>Country</returns>
+ public virtual async Task<Country> GetCountryById(string countryId)
+ {
+ if (string.IsNullOrEmpty(countryId))
+ return null;
+
+ var key = string.Format(CacheKey.COUNTRIES_BY_KEY, countryId);
+ return await _cacheBase.GetAsync(key, () => _countryRepository.GetByIdAsync(countryId));
+ }
+
+ /// <summary>
+ /// Get countries by identifiers
+ /// </summary>
+ /// <param name="countryIds">Country identifiers</param>
+ /// <returns>Countries</returns>
+ public virtual async Task<IList<Country>> GetCountriesByIds(string[] countryIds)
+ {
+ if (countryIds == null || countryIds.Length == 0)
+ return new List<Country>();
+
+ var query = from c in _countryRepository.Table
+ where countryIds.Contains(c.Id)
+ select c;
+ var countries = await Task.FromResult(query.ToList());
+ //sort by passed identifiers
+ return countryIds.Select(id => countries.Find(x => x.Id == id)).Where(country => country != null).ToList();
+ }
- /// <summary>
- /// Gets a country by three letter ISO code
- /// </summary>
- /// <param name="threeLetterIsoCode">Country three letter ISO code</param>
- /// <returns>Country</returns>
- public virtual async Task<Country> GetCountryByThreeLetterIsoCode(string threeLetterIsoCode)
+ /// <summary>
+ /// Gets a country by two letter ISO code
+ /// </summary>
+ /// <param name="twoLetterIsoCode">Country two letter ISO code</param>
+ /// <returns>Country</returns>
+ public virtual async Task<Country> GetCountryByTwoLetterIsoCode(string twoLetterIsoCode)
+ {
+ var key = string.Format(CacheKey.COUNTRIES_BY_TWOLETTER, twoLetterIsoCode);
+ return await _cacheBase.GetAsync(key, async () =>
{
- var key = string.Format(CacheKey.COUNTRIES_BY_THREELETTER, threeLetterIsoCode);
- return await _cacheBase.GetAsync(key, async () =>
- {
- return await _countryRepository.GetOneAsync(x => x.ThreeLetterIsoCode == threeLetterIsoCode);
- });
- }
+ return await _countryRepository.GetOneAsync(x => x.TwoLetterIsoCode == twoLetterIsoCode);
+ });
+ }
- /// <summary>
- /// Inserts a country
- /// </summary>
- /// <param name="country">Country</param>
- public virtual async Task InsertCountry(Country country)
+ /// <summary>
+ /// Gets a country by three letter ISO code
+ /// </summary>
+ /// <param name="threeLetterIsoCode">Country three letter ISO code</param>
+ /// <returns>Country</returns>
+ public virtual async Task<Country> GetCountryByThreeLetterIsoCode(string threeLetterIsoCode)
+ {
+ var key = string.Format(CacheKey.COUNTRIES_BY_THREELETTER, threeLetterIsoCode);
+ return await _cacheBase.GetAsync(key, async () =>
{
- ArgumentNullException.ThrowIfNull(country);
+ return await _countryRepository.GetOneAsync(x => x.ThreeLetterIsoCode == threeLetterIsoCode);
+ });
+ }
- await _countryRepository.InsertAsync(country);
+ /// <summary>
+ /// Inserts a country
+ /// </summary>
+ /// <param name="country">Country</param>
+ public virtual async Task InsertCountry(Country country)
+ {
+ ArgumentNullException.ThrowIfNull(country);
- await _cacheBase.RemoveByPrefix(CacheKey.COUNTRIES_PATTERN_KEY);
+ await _countryRepository.InsertAsync(country);
- //event notification
- await _mediator.EntityInserted(country);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.COUNTRIES_PATTERN_KEY);
- /// <summary>
- /// Updates the country
- /// </summary>
- /// <param name="country">Country</param>
- public virtual async Task UpdateCountry(Country country)
- {
- ArgumentNullException.ThrowIfNull(country);
+ //event notification
+ await _mediator.EntityInserted(country);
+ }
- await _countryRepository.UpdateAsync(country);
+ /// <summary>
+ /// Updates the country
+ /// </summary>
+ /// <param name="country">Country</param>
+ public virtual async Task UpdateCountry(Country country)
+ {
+ ArgumentNullException.ThrowIfNull(country);
- await _cacheBase.RemoveByPrefix(CacheKey.COUNTRIES_PATTERN_KEY);
+ await _countryRepository.UpdateAsync(country);
- //event notification
- await _mediator.EntityUpdated(country);
- }
- /// <summary>
- /// Deletes a country
- /// </summary>
- /// <param name="country">Country</param>
- public virtual async Task DeleteCountry(Country country)
- {
- ArgumentNullException.ThrowIfNull(country);
+ await _cacheBase.RemoveByPrefix(CacheKey.COUNTRIES_PATTERN_KEY);
- await _countryRepository.DeleteAsync(country);
+ //event notification
+ await _mediator.EntityUpdated(country);
+ }
- await _cacheBase.RemoveByPrefix(CacheKey.COUNTRIES_PATTERN_KEY);
+ /// <summary>
+ /// Deletes a country
+ /// </summary>
+ /// <param name="country">Country</param>
+ public virtual async Task DeleteCountry(Country country)
+ {
+ ArgumentNullException.ThrowIfNull(country);
- //event notification
- await _mediator.EntityDeleted(country);
- }
+ await _countryRepository.DeleteAsync(country);
+ await _cacheBase.RemoveByPrefix(CacheKey.COUNTRIES_PATTERN_KEY);
- #region State provinces
+ //event notification
+ await _mediator.EntityDeleted(country);
+ }
- /// <summary>
- /// Gets a state/province collection by country identifier
- /// </summary>
- /// <param name="countryId">Country identifier</param>
- /// <param name="languageId">Language identifier.</param>
- /// <returns>States</returns>
- public virtual async Task<IList<StateProvince>> GetStateProvincesByCountryId(string countryId, string languageId = "")
- {
- if (string.IsNullOrEmpty(countryId))
- return new List<StateProvince>();
- var country = await GetCountryById(countryId);
+ #region State provinces
- return country?.StateProvinces.OrderBy(c => c.DisplayOrder)
- .ThenBy(c => c.GetTranslation(x => x.Name, languageId))
- .ToList();
- }
+ /// <summary>
+ /// Gets a state/province collection by country identifier
+ /// </summary>
+ /// <param name="countryId">Country identifier</param>
+ /// <param name="languageId">Language identifier.</param>
+ /// <returns>States</returns>
+ public virtual async Task<IList<StateProvince>> GetStateProvincesByCountryId(string countryId,
+ string languageId = "")
+ {
+ if (string.IsNullOrEmpty(countryId))
+ return new List<StateProvince>();
- /// <summary>
- /// Inserts a state/province
- /// </summary>
- /// <param name="stateProvince">State/province</param>
- /// <param name="countryId">Country ident</param>
- public virtual async Task InsertStateProvince(StateProvince stateProvince, string countryId)
- {
- ArgumentNullException.ThrowIfNull(stateProvince);
+ var country = await GetCountryById(countryId);
- var country = await GetCountryById(countryId);
- if (country == null)
- throw new ArgumentNullException(nameof(country));
+ return country?.StateProvinces.OrderBy(c => c.DisplayOrder)
+ .ThenBy(c => c.GetTranslation(x => x.Name, languageId))
+ .ToList();
+ }
- country.StateProvinces.Add(stateProvince);
+ /// <summary>
+ /// Inserts a state/province
+ /// </summary>
+ /// <param name="stateProvince">State/province</param>
+ /// <param name="countryId">Country ident</param>
+ public virtual async Task InsertStateProvince(StateProvince stateProvince, string countryId)
+ {
+ ArgumentNullException.ThrowIfNull(stateProvince);
- await UpdateCountry(country);
- }
+ var country = await GetCountryById(countryId);
+ if (country == null)
+ throw new ArgumentNullException(nameof(country));
- /// <summary>
- /// Updates a state/province
- /// </summary>
- /// <param name="stateProvince">State/province</param>
- /// <param name="countryId">Country ident</param>
- public virtual async Task UpdateStateProvince(StateProvince stateProvince, string countryId)
- {
- ArgumentNullException.ThrowIfNull(stateProvince);
+ country.StateProvinces.Add(stateProvince);
+
+ await UpdateCountry(country);
+ }
+
+ /// <summary>
+ /// Updates a state/province
+ /// </summary>
+ /// <param name="stateProvince">State/province</param>
+ /// <param name="countryId">Country ident</param>
+ public virtual async Task UpdateStateProvince(StateProvince stateProvince, string countryId)
+ {
+ ArgumentNullException.ThrowIfNull(stateProvince);
- var country = await GetCountryById(countryId);
- if (country == null)
- throw new ArgumentNullException(nameof(country));
+ var country = await GetCountryById(countryId);
+ if (country == null)
+ throw new ArgumentNullException(nameof(country));
- if (country.StateProvinces.FirstOrDefault(x => x.Id == stateProvince.Id) != null)
+ if (country.StateProvinces.FirstOrDefault(x => x.Id == stateProvince.Id) != null)
+ {
+ var state = country.StateProvinces.FirstOrDefault(x => x.Id == stateProvince.Id);
+ if (state != null)
{
- var state = country.StateProvinces.FirstOrDefault(x => x.Id == stateProvince.Id);
- if (state != null)
- {
- state.Name = stateProvince.Name;
- state.Locales = stateProvince.Locales;
- state.Published = stateProvince.Published;
- state.Abbreviation = stateProvince.Abbreviation;
- state.DisplayOrder = stateProvince.DisplayOrder;
- }
+ state.Name = stateProvince.Name;
+ state.Locales = stateProvince.Locales;
+ state.Published = stateProvince.Published;
+ state.Abbreviation = stateProvince.Abbreviation;
+ state.DisplayOrder = stateProvince.DisplayOrder;
}
- await UpdateCountry(country);
}
- /// <summary>
- /// Deletes a state/province
- /// </summary>
- /// <param name="stateProvince">The state/province</param>
- /// <param name="countryId">Country ident</param>
- public virtual async Task DeleteStateProvince(StateProvince stateProvince, string countryId)
- {
- ArgumentNullException.ThrowIfNull(stateProvince);
- var country = await GetCountryById(countryId);
- if (country == null)
- throw new ArgumentNullException(nameof(country));
+ await UpdateCountry(country);
+ }
- var state = country.StateProvinces.FirstOrDefault(x => x.Id == stateProvince.Id);
- country.StateProvinces.Remove(state);
+ /// <summary>
+ /// Deletes a state/province
+ /// </summary>
+ /// <param name="stateProvince">The state/province</param>
+ /// <param name="countryId">Country ident</param>
+ public virtual async Task DeleteStateProvince(StateProvince stateProvince, string countryId)
+ {
+ ArgumentNullException.ThrowIfNull(stateProvince);
- await UpdateCountry(country);
+ var country = await GetCountryById(countryId);
+ if (country == null)
+ throw new ArgumentNullException(nameof(country));
- }
+ var state = country.StateProvinces.FirstOrDefault(x => x.Id == stateProvince.Id);
+ country.StateProvinces.Remove(state);
+ await UpdateCountry(country);
+ }
- #endregion
+ #endregion
- #endregion
- }
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Directory/CurrencyService.cs b/src/Business/Grand.Business.Common/Services/Directory/CurrencyService.cs
index 36cbdf433..4584fc3b0 100644
--- a/src/Business/Grand.Business.Common/Services/Directory/CurrencyService.cs
+++ b/src/Business/Grand.Business.Common/Services/Directory/CurrencyService.cs
@@ -8,293 +8,290 @@ using Grand.Infrastructure.Extensions;
using Grand.SharedKernel;
using MediatR;
-namespace Grand.Business.Common.Services.Directory
+namespace Grand.Business.Common.Services.Directory;
+
+/// <summary>
+/// Currency service
+/// </summary>
+public class CurrencyService : ICurrencyService
{
+ #region Ctor
+
/// <summary>
- /// Currency service
+ /// Ctor
/// </summary>
- public class CurrencyService : ICurrencyService
+ /// <param name="cacheBase">Cache manager</param>
+ /// <param name="currencyRepository">Currency repository</param>
+ /// <param name="aclService">ACL service</param>
+ /// <param name="currencySettings">Currency settings</param>
+ /// <param name="mediator">Mediator</param>
+ public CurrencyService(ICacheBase cacheBase,
+ IRepository<Currency> currencyRepository,
+ IAclService aclService,
+ CurrencySettings currencySettings,
+ IMediator mediator)
{
- #region Fields
-
- private readonly IRepository<Currency> _currencyRepository;
- private readonly IAclService _aclService;
- private readonly ICacheBase _cacheBase;
- private readonly IMediator _mediator;
- private readonly CurrencySettings _currencySettings;
- private Currency _primaryCurrency;
- private Currency _primaryExchangeRateCurrency;
-
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="cacheBase">Cache manager</param>
- /// <param name="currencyRepository">Currency repository</param>
- /// <param name="aclService">ACL service</param>
- /// <param name="currencySettings">Currency settings</param>
- /// <param name="mediator">Mediator</param>
- public CurrencyService(ICacheBase cacheBase,
- IRepository<Currency> currencyRepository,
- IAclService aclService,
- CurrencySettings currencySettings,
- IMediator mediator)
- {
- _cacheBase = cacheBase;
- _currencyRepository = currencyRepository;
- _aclService = aclService;
- _currencySettings = currencySettings;
- _mediator = mediator;
- }
-
- #endregion
-
- #region Methods
-
- /// <summary>
- /// Gets a currency
- /// </summary>
- /// <param name="currencyId">Currency identifier</param>
- /// <returns>Currency</returns>
- public virtual Task<Currency> GetCurrencyById(string currencyId)
- {
- var key = string.Format(CacheKey.CURRENCIES_BY_ID_KEY, currencyId);
- return _cacheBase.GetAsync(key, () => _currencyRepository.GetByIdAsync(currencyId));
- }
-
- /// <summary>
- /// Gets primary store currency
- /// </summary>
- /// <returns>Currency</returns>
- public async Task<Currency> GetPrimaryStoreCurrency()
- {
- return _primaryCurrency ??= await GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);
- }
-
- /// <summary>
- /// Gets primary exchange currency
- /// </summary>
- /// <returns>Currency</returns>
- public async Task<Currency> GetPrimaryExchangeRateCurrency()
- {
- return _primaryExchangeRateCurrency ??= await GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId);
- }
-
- /// <summary>
- /// Gets a currency by code
- /// </summary>
- /// <param name="currencyCode">Currency code</param>
- /// <returns>Currency</returns>
- public virtual async Task<Currency> GetCurrencyByCode(string currencyCode)
- {
- if (string.IsNullOrEmpty(currencyCode))
- return null;
-
- var key = string.Format(CacheKey.CURRENCIES_BY_CODE, currencyCode);
- return await _cacheBase.GetAsync(key, async () =>
- {
- var query = from q in _currencyRepository.Table
- where q.CurrencyCode.ToLowerInvariant() == currencyCode.ToLowerInvariant()
- select q;
- return await Task.FromResult(query.FirstOrDefault());
- });
- }
-
- /// <summary>
- /// Gets all currencies
- /// </summary>
- /// <param name="showHidden">A value indicating whether to show hidden records</param>
- /// <param name="storeId">Load records allowed only in a specified store; pass "" to load all records</param>
- /// <returns>Currencies</returns>
- public virtual async Task<IList<Currency>> GetAllCurrencies(bool showHidden = false, string storeId = "")
+ _cacheBase = cacheBase;
+ _currencyRepository = currencyRepository;
+ _aclService = aclService;
+ _currencySettings = currencySettings;
+ _mediator = mediator;
+ }
+
+ #endregion
+
+ #region Fields
+
+ private readonly IRepository<Currency> _currencyRepository;
+ private readonly IAclService _aclService;
+ private readonly ICacheBase _cacheBase;
+ private readonly IMediator _mediator;
+ private readonly CurrencySettings _currencySettings;
+ private Currency _primaryCurrency;
+ private Currency _primaryExchangeRateCurrency;
+
+ #endregion
+
+ #region Methods
+
+ /// <summary>
+ /// Gets a currency
+ /// </summary>
+ /// <param name="currencyId">Currency identifier</param>
+ /// <returns>Currency</returns>
+ public virtual Task<Currency> GetCurrencyById(string currencyId)
+ {
+ var key = string.Format(CacheKey.CURRENCIES_BY_ID_KEY, currencyId);
+ return _cacheBase.GetAsync(key, () => _currencyRepository.GetByIdAsync(currencyId));
+ }
+
+ /// <summary>
+ /// Gets primary store currency
+ /// </summary>
+ /// <returns>Currency</returns>
+ public async Task<Currency> GetPrimaryStoreCurrency()
+ {
+ return _primaryCurrency ??= await GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId);
+ }
+
+ /// <summary>
+ /// Gets primary exchange currency
+ /// </summary>
+ /// <returns>Currency</returns>
+ public async Task<Currency> GetPrimaryExchangeRateCurrency()
+ {
+ return _primaryExchangeRateCurrency ??= await GetCurrencyById(_currencySettings.PrimaryExchangeRateCurrencyId);
+ }
+
+ /// <summary>
+ /// Gets a currency by code
+ /// </summary>
+ /// <param name="currencyCode">Currency code</param>
+ /// <returns>Currency</returns>
+ public virtual async Task<Currency> GetCurrencyByCode(string currencyCode)
+ {
+ if (string.IsNullOrEmpty(currencyCode))
+ return null;
+
+ var key = string.Format(CacheKey.CURRENCIES_BY_CODE, currencyCode);
+ return await _cacheBase.GetAsync(key, async () =>
{
- var key = string.Format(CacheKey.CURRENCIES_ALL_KEY, showHidden);
- var currencies = await _cacheBase.GetAsync(key, async () =>
- {
- var query = from p in _currencyRepository.Table
- select p;
-
- if (!showHidden)
- query = query.Where(c => c.Published);
- query = query.OrderBy(c => c.DisplayOrder);
- return await Task.FromResult(query.ToList());
- });
-
- //store acl
- if (!string.IsNullOrEmpty(storeId))
- {
- currencies = currencies.Where(c => _aclService.Authorize(c, storeId)).ToList();
- }
- return currencies;
- }
-
- /// <summary>
- /// Inserts a currency
- /// </summary>
- /// <param name="currency">Currency</param>
- public virtual async Task InsertCurrency(Currency currency)
+ var query = from q in _currencyRepository.Table
+ where q.CurrencyCode.ToLowerInvariant() == currencyCode.ToLowerInvariant()
+ select q;
+ return await Task.FromResult(query.FirstOrDefault());
+ });
+ }
+
+ /// <summary>
+ /// Gets all currencies
+ /// </summary>
+ /// <param name="showHidden">A value indicating whether to show hidden records</param>
+ /// <param name="storeId">Load records allowed only in a specified store; pass "" to load all records</param>
+ /// <returns>Currencies</returns>
+ public virtual async Task<IList<Currency>> GetAllCurrencies(bool showHidden = false, string storeId = "")
+ {
+ var key = string.Format(CacheKey.CURRENCIES_ALL_KEY, showHidden);
+ var currencies = await _cacheBase.GetAsync(key, async () =>
{
- ArgumentNullException.ThrowIfNull(currency);
+ var query = from p in _currencyRepository.Table
+ select p;
+
+ if (!showHidden)
+ query = query.Where(c => c.Published);
+ query = query.OrderBy(c => c.DisplayOrder);
+ return await Task.FromResult(query.ToList());
+ });
+
+ //store acl
+ if (!string.IsNullOrEmpty(storeId))
+ currencies = currencies.Where(c => _aclService.Authorize(c, storeId)).ToList();
+ return currencies;
+ }
- await _currencyRepository.InsertAsync(currency);
+ /// <summary>
+ /// Inserts a currency
+ /// </summary>
+ /// <param name="currency">Currency</param>
+ public virtual async Task InsertCurrency(Currency currency)
+ {
+ ArgumentNullException.ThrowIfNull(currency);
- await _cacheBase.RemoveByPrefix(CacheKey.CURRENCIES_PATTERN_KEY);
+ await _currencyRepository.InsertAsync(currency);
- //event notification
- await _mediator.EntityInserted(currency);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.CURRENCIES_PATTERN_KEY);
- /// <summary>
- /// Updates the currency
- /// </summary>
- /// <param name="currency">Currency</param>
- public virtual async Task UpdateCurrency(Currency currency)
- {
- ArgumentNullException.ThrowIfNull(currency);
+ //event notification
+ await _mediator.EntityInserted(currency);
+ }
- await _currencyRepository.UpdateAsync(currency);
+ /// <summary>
+ /// Updates the currency
+ /// </summary>
+ /// <param name="currency">Currency</param>
+ public virtual async Task UpdateCurrency(Currency currency)
+ {
+ ArgumentNullException.ThrowIfNull(currency);
- await _cacheBase.RemoveByPrefix(CacheKey.CURRENCIES_PATTERN_KEY);
+ await _currencyRepository.UpdateAsync(currency);
- //event notification
- await _mediator.EntityUpdated(currency);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.CURRENCIES_PATTERN_KEY);
- /// <summary>
- /// Deletes currency
- /// </summary>
- /// <param name="currency">Currency</param>
- public virtual async Task DeleteCurrency(Currency currency)
- {
- ArgumentNullException.ThrowIfNull(currency);
+ //event notification
+ await _mediator.EntityUpdated(currency);
+ }
- await _currencyRepository.DeleteAsync(currency);
+ /// <summary>
+ /// Deletes currency
+ /// </summary>
+ /// <param name="currency">Currency</param>
+ public virtual async Task DeleteCurrency(Currency currency)
+ {
+ ArgumentNullException.ThrowIfNull(currency);
- await _cacheBase.RemoveByPrefix(CacheKey.CURRENCIES_PATTERN_KEY);
+ await _currencyRepository.DeleteAsync(currency);
- //event notification
- await _mediator.EntityDeleted(currency);
- }
+ await _cacheBase.RemoveByPrefix(CacheKey.CURRENCIES_PATTERN_KEY);
+ //event notification
+ await _mediator.EntityDeleted(currency);
+ }
- /// <summary>
- /// Converts currency
- /// </summary>
- /// <param name="amount">Amount</param>
- /// <param name="exchangeRate">Currency exchange rate</param>
- /// <returns>Converted value</returns>
- public virtual double ConvertCurrency(double amount, double exchangeRate)
- {
- if (amount != 0 && exchangeRate != 0)
- return Math.Round(amount * exchangeRate, 6);
- return 0;
- }
-
- /// <summary>
- /// Converts currency
- /// </summary>
- /// <param name="amount">Amount</param>
- /// <param name="sourceCurrencyCode">Source currency code</param>
- /// <param name="targetCurrencyCode">Target currency code</param>
- /// <returns>Converted value</returns>
- public virtual async Task<double> ConvertCurrency(double amount, Currency sourceCurrencyCode, Currency targetCurrencyCode)
- {
- ArgumentNullException.ThrowIfNull(sourceCurrencyCode);
- ArgumentNullException.ThrowIfNull(targetCurrencyCode);
- var result = amount;
+ /// <summary>
+ /// Converts currency
+ /// </summary>
+ /// <param name="amount">Amount</param>
+ /// <param name="exchangeRate">Currency exchange rate</param>
+ /// <returns>Converted value</returns>
+ public virtual double ConvertCurrency(double amount, double exchangeRate)
+ {
+ if (amount != 0 && exchangeRate != 0)
+ return Math.Round(amount * exchangeRate, 6);
+ return 0;
+ }
- if (result == 0 || sourceCurrencyCode.Id == targetCurrencyCode.Id)
- return result;
+ /// <summary>
+ /// Converts currency
+ /// </summary>
+ /// <param name="amount">Amount</param>
+ /// <param name="sourceCurrencyCode">Source currency code</param>
+ /// <param name="targetCurrencyCode">Target currency code</param>
+ /// <returns>Converted value</returns>
+ public virtual async Task<double> ConvertCurrency(double amount, Currency sourceCurrencyCode,
+ Currency targetCurrencyCode)
+ {
+ ArgumentNullException.ThrowIfNull(sourceCurrencyCode);
+ ArgumentNullException.ThrowIfNull(targetCurrencyCode);
- result = await ConvertToPrimaryExchangeRateCurrency(result, sourceCurrencyCode);
- result = await ConvertFromPrimaryExchangeRateCurrency(result, targetCurrencyCode);
+ var result = amount;
+ if (result == 0 || sourceCurrencyCode.Id == targetCurrencyCode.Id)
return result;
- }
+ result = await ConvertToPrimaryExchangeRateCurrency(result, sourceCurrencyCode);
+ result = await ConvertFromPrimaryExchangeRateCurrency(result, targetCurrencyCode);
- /// <summary>
- /// Converts to primary exchange rate currency
- /// </summary>
- /// <param name="amount">Amount</param>
- /// <param name="sourceCurrencyCode">Source currency code</param>
- /// <returns>Converted value</returns>
- public virtual async Task<double> ConvertToPrimaryExchangeRateCurrency(double amount, Currency sourceCurrencyCode)
- {
- ArgumentNullException.ThrowIfNull(sourceCurrencyCode);
+ return result;
+ }
+
+ /// <summary>
+ /// Converts to primary exchange rate currency
+ /// </summary>
+ /// <param name="amount">Amount</param>
+ /// <param name="sourceCurrencyCode">Source currency code</param>
+ /// <returns>Converted value</returns>
+ public virtual async Task<double> ConvertToPrimaryExchangeRateCurrency(double amount, Currency sourceCurrencyCode)
+ {
+ ArgumentNullException.ThrowIfNull(sourceCurrencyCode);
+
+ var primaryExchangeRateCurrency = await GetPrimaryExchangeRateCurrency();
+ if (primaryExchangeRateCurrency == null)
+ throw new Exception("Primary exchange rate currency cannot be loaded");
+
+ var result = amount;
+ var exchangeRate = sourceCurrencyCode.Rate;
+ if (exchangeRate == 0)
+ throw new GrandException($"Exchange rate not found for currency [{sourceCurrencyCode.Name}]");
+ result /= exchangeRate;
+ return result;
+ }
- var primaryExchangeRateCurrency = await GetPrimaryExchangeRateCurrency();
- if (primaryExchangeRateCurrency == null)
- throw new Exception("Primary exchange rate currency cannot be loaded");
+ /// <summary>
+ /// Converts from primary exchange rate currency
+ /// </summary>
+ /// <param name="amount">Amount</param>
+ /// <param name="targetCurrencyCode">Target currency code</param>
+ /// <returns>Converted value</returns>
+ public virtual async Task<double> ConvertFromPrimaryExchangeRateCurrency(double amount, Currency targetCurrencyCode)
+ {
+ ArgumentNullException.ThrowIfNull(targetCurrencyCode);
- var result = amount;
- var exchangeRate = sourceCurrencyCode.Rate;
- if (exchangeRate == 0)
- throw new GrandException($"Exchange rate not found for currency [{sourceCurrencyCode.Name}]");
- result /= exchangeRate;
- return result;
- }
-
- /// <summary>
- /// Converts from primary exchange rate currency
- /// </summary>
- /// <param name="amount">Amount</param>
- /// <param name="targetCurrencyCode">Target currency code</param>
- /// <returns>Converted value</returns>
- public virtual async Task<double> ConvertFromPrimaryExchangeRateCurrency(double amount, Currency targetCurrencyCode)
- {
- ArgumentNullException.ThrowIfNull(targetCurrencyCode);
+ var primaryExchangeRateCurrency = await GetPrimaryExchangeRateCurrency();
+ if (primaryExchangeRateCurrency == null)
+ throw new Exception("Primary exchange rate currency cannot be loaded");
- var primaryExchangeRateCurrency = await GetPrimaryExchangeRateCurrency();
- if (primaryExchangeRateCurrency == null)
- throw new Exception("Primary exchange rate currency cannot be loaded");
+ var result = amount;
- var result = amount;
+ var exchangeRate = targetCurrencyCode.Rate;
+ if (exchangeRate == 0)
+ throw new GrandException($"Exchange rate not found for currency [{targetCurrencyCode.Name}]");
- var exchangeRate = targetCurrencyCode.Rate;
- if (exchangeRate == 0)
- throw new GrandException($"Exchange rate not found for currency [{targetCurrencyCode.Name}]");
+ result *= exchangeRate;
- result *= exchangeRate;
+ return result;
+ }
- return result;
- }
-
- /// <summary>
- /// Converts to primary store currency
- /// </summary>
- /// <param name="amount">Amount</param>
- /// <param name="sourceCurrencyCode">Source currency code</param>
- /// <returns>Converted value</returns>
- public virtual async Task<double> ConvertToPrimaryStoreCurrency(double amount, Currency sourceCurrencyCode)
- {
- ArgumentNullException.ThrowIfNull(sourceCurrencyCode);
+ /// <summary>
+ /// Converts to primary store currency
+ /// </summary>
+ /// <param name="amount">Amount</param>
+ /// <param name="sourceCurrencyCode">Source currency code</param>
+ /// <returns>Converted value</returns>
+ public virtual async Task<double> ConvertToPrimaryStoreCurrency(double amount, Currency sourceCurrencyCode)
+ {
+ ArgumentNullException.ThrowIfNull(sourceCurrencyCode);
- var primaryStoreCurrency = await GetPrimaryStoreCurrency();
- var result = await ConvertCurrency(amount, sourceCurrencyCode, primaryStoreCurrency);
+ var primaryStoreCurrency = await GetPrimaryStoreCurrency();
+ var result = await ConvertCurrency(amount, sourceCurrencyCode, primaryStoreCurrency);
- return result;
- }
-
- /// <summary>
- /// Converts from primary store currency
- /// </summary>
- /// <param name="amount">Amount</param>
- /// <param name="targetCurrencyCode">Target currency code</param>
- /// <returns>Converted value</returns>
- public virtual async Task<double> ConvertFromPrimaryStoreCurrency(double amount, Currency targetCurrencyCode)
- {
- if (targetCurrencyCode == null)
- return amount;
+ return result;
+ }
- var result = await ConvertCurrency(amount, await GetPrimaryStoreCurrency(), targetCurrencyCode);
- return result;
- }
+ /// <summary>
+ /// Converts from primary store currency
+ /// </summary>
+ /// <param name="amount">Amount</param>
+ /// <param name="targetCurrencyCode">Target currency code</param>
+ /// <returns>Converted value</returns>
+ public virtual async Task<double> ConvertFromPrimaryStoreCurrency(double amount, Currency targetCurrencyCode)
+ {
+ if (targetCurrencyCode == null)
+ return amount;
- #endregion
+ var result = await ConvertCurrency(amount, await GetPrimaryStoreCurrency(), targetCurrencyCode);
+ return result;
}
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Directory/DateTimeService.cs b/src/Business/Grand.Business.Common/Services/Directory/DateTimeService.cs
index c362f449d..ee24d86fd 100644
--- a/src/Business/Grand.Business.Common/Services/Directory/DateTimeService.cs
+++ b/src/Business/Grand.Business.Common/Services/Directory/DateTimeService.cs
@@ -3,136 +3,143 @@ using Grand.Domain.Directory;
using System.Collections.ObjectModel;
using System.Diagnostics;
-namespace Grand.Business.Common.Services.Directory
+namespace Grand.Business.Common.Services.Directory;
+
+/// <summary>
+/// Represents a datetime service
+/// </summary>
+public class DateTimeService : IDateTimeService
{
+ private readonly DateTimeSettings _dateTimeSettings;
+ private TimeZoneInfo _timeZoneInfo;
+
/// <summary>
- /// Represents a datetime service
+ /// Ctor
/// </summary>
- public class DateTimeService : IDateTimeService
+ /// <param name="dateTimeSettings">Datetime settings</param>
+ public DateTimeService(
+ DateTimeSettings dateTimeSettings)
{
- private readonly DateTimeSettings _dateTimeSettings;
- private TimeZoneInfo _timeZoneInfo;
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="dateTimeSettings">Datetime settings</param>
- public DateTimeService(
- DateTimeSettings dateTimeSettings)
- {
- _dateTimeSettings = dateTimeSettings;
- }
+ _dateTimeSettings = dateTimeSettings;
+ }
- /// <summary>
- /// Retrieves a System.TimeZoneInfo object from the registry based on its identifier.
- /// </summary>
- /// <param name="id">The time zone identifier, which corresponds to the System.TimeZoneInfo.Id property.</param>
- /// <returns>A System.TimeZoneInfo object whose identifier is the value of the id parameter.</returns>
- public virtual TimeZoneInfo FindTimeZoneById(string id)
- {
- return TimeZoneInfo.FindSystemTimeZoneById(id);
- }
+ /// <summary>
+ /// Retrieves a System.TimeZoneInfo object from the registry based on its identifier.
+ /// </summary>
+ /// <param name="id">The time zone identifier, which corresponds to the System.TimeZoneInfo.Id property.</param>
+ /// <returns>A System.TimeZoneInfo object whose identifier is the value of the id parameter.</returns>
+ public virtual TimeZoneInfo FindTimeZoneById(string id)
+ {
+ return TimeZoneInfo.FindSystemTimeZoneById(id);
+ }
- /// <summary>
- /// Returns a sorted collection of all the time zones
- /// </summary>
- /// <returns>A read-only collection of System.TimeZoneInfo objects.</returns>
- public virtual ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones()
- {
- return TimeZoneInfo.GetSystemTimeZones();
- }
+ /// <summary>
+ /// Returns a sorted collection of all the time zones
+ /// </summary>
+ /// <returns>A read-only collection of System.TimeZoneInfo objects.</returns>
+ public virtual ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones()
+ {
+ return TimeZoneInfo.GetSystemTimeZones();
+ }
- /// <summary>
- /// Converts the date and time to current user date and time
- /// </summary>
- /// <param name="dt">The date and time (represents local system time or UTC time) to convert.</param>
- /// <returns>A DateTime value that represents time that corresponds to the dateTime parameter in customer time zone.</returns>
- public virtual DateTime ConvertToUserTime(DateTime dt)
- {
- return ConvertToUserTime(dt, dt.Kind);
- }
+ /// <summary>
+ /// Converts the date and time to current user date and time
+ /// </summary>
+ /// <param name="dt">The date and time (represents local system time or UTC time) to convert.</param>
+ /// <returns>A DateTime value that represents time that corresponds to the dateTime parameter in customer time zone.</returns>
+ public virtual DateTime ConvertToUserTime(DateTime dt)
+ {
+ return ConvertToUserTime(dt, dt.Kind);
+ }
- /// <summary>
- /// Converts the date and time to current user date and time
- /// </summary>
- /// <param name="dt">The date and time (represents local system time or UTC time) to convert.</param>
- /// <param name="sourceDateTimeKind">The source datetime kind</param>
- /// <returns>A DateTime value that represents time that corresponds to the dateTime parameter in customer time zone.</returns>
- public virtual DateTime ConvertToUserTime(DateTime dt, DateTimeKind sourceDateTimeKind)
- {
- dt = DateTime.SpecifyKind(dt, sourceDateTimeKind);
- var currentUserTimeZoneInfo = this.CurrentTimeZone;
- return TimeZoneInfo.ConvertTime(dt, currentUserTimeZoneInfo);
- }
+ /// <summary>
+ /// Converts the date and time to current user date and time
+ /// </summary>
+ /// <param name="dt">The date and time (represents local system time or UTC time) to convert.</param>
+ /// <param name="sourceDateTimeKind">The source datetime kind</param>
+ /// <returns>A DateTime value that represents time that corresponds to the dateTime parameter in customer time zone.</returns>
+ public virtual DateTime ConvertToUserTime(DateTime dt, DateTimeKind sourceDateTimeKind)
+ {
+ dt = DateTime.SpecifyKind(dt, sourceDateTimeKind);
+ var currentUserTimeZoneInfo = CurrentTimeZone;
+ return TimeZoneInfo.ConvertTime(dt, currentUserTimeZoneInfo);
+ }
- /// <summary>
- /// Converts the date and time to current user date and time
- /// </summary>
- /// <param name="dt">The date and time to convert.</param>
- /// <param name="sourceTimeZone">The time zone of dateTime.</param>
- /// <param name="destinationTimeZone">The time zone to convert dateTime to.</param>
- /// <returns>A DateTime value that represents time that corresponds to the dateTime parameter in customer time zone.</returns>
- public virtual DateTime ConvertToUserTime(DateTime dt, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
- {
- return TimeZoneInfo.ConvertTime(dt, sourceTimeZone, destinationTimeZone);
- }
+ /// <summary>
+ /// Converts the date and time to current user date and time
+ /// </summary>
+ /// <param name="dt">The date and time to convert.</param>
+ /// <param name="sourceTimeZone">The time zone of dateTime.</param>
+ /// <param name="destinationTimeZone">The time zone to convert dateTime to.</param>
+ /// <returns>A DateTime value that represents time that corresponds to the dateTime parameter in customer time zone.</returns>
+ public virtual DateTime ConvertToUserTime(DateTime dt, TimeZoneInfo sourceTimeZone,
+ TimeZoneInfo destinationTimeZone)
+ {
+ return TimeZoneInfo.ConvertTime(dt, sourceTimeZone, destinationTimeZone);
+ }
- /// <summary>
- /// Converts the date and time to Coordinated Universal Time (UTC)
- /// </summary>
- /// <param name="dt">The date and time (represents local system time or UTC time) to convert.</param>
- /// <returns>A DateTime value that represents the Coordinated Universal Time (UTC) that corresponds to the dateTime parameter. The DateTime value's Kind property is always set to DateTimeKind.Utc.</returns>
- public virtual DateTime ConvertToUtcTime(DateTime dt)
- {
- return ConvertToUtcTime(dt, dt.Kind);
- }
+ /// <summary>
+ /// Converts the date and time to Coordinated Universal Time (UTC)
+ /// </summary>
+ /// <param name="dt">The date and time (represents local system time or UTC time) to convert.</param>
+ /// <returns>
+ /// A DateTime value that represents the Coordinated Universal Time (UTC) that corresponds to the dateTime
+ /// parameter. The DateTime value's Kind property is always set to DateTimeKind.Utc.
+ /// </returns>
+ public virtual DateTime ConvertToUtcTime(DateTime dt)
+ {
+ return ConvertToUtcTime(dt, dt.Kind);
+ }
- /// <summary>
- /// Converts the date and time to Coordinated Universal Time (UTC)
- /// </summary>
- /// <param name="dt">The date and time (represents local system time or UTC time) to convert.</param>
- /// <param name="sourceDateTimeKind">The source datetime kind</param>
- /// <returns>A DateTime value that represents the Coordinated Universal Time (UTC) that corresponds to the dateTime parameter. The DateTime value's Kind property is always set to DateTimeKind.Utc.</returns>
- public virtual DateTime ConvertToUtcTime(DateTime dt, DateTimeKind sourceDateTimeKind)
- {
- dt = DateTime.SpecifyKind(dt, sourceDateTimeKind);
- return TimeZoneInfo.ConvertTimeToUtc(dt, TimeZoneInfo.Utc);
- }
+ /// <summary>
+ /// Converts the date and time to Coordinated Universal Time (UTC)
+ /// </summary>
+ /// <param name="dt">The date and time (represents local system time or UTC time) to convert.</param>
+ /// <param name="sourceDateTimeKind">The source datetime kind</param>
+ /// <returns>
+ /// A DateTime value that represents the Coordinated Universal Time (UTC) that corresponds to the dateTime
+ /// parameter. The DateTime value's Kind property is always set to DateTimeKind.Utc.
+ /// </returns>
+ public virtual DateTime ConvertToUtcTime(DateTime dt, DateTimeKind sourceDateTimeKind)
+ {
+ dt = DateTime.SpecifyKind(dt, sourceDateTimeKind);
+ return TimeZoneInfo.ConvertTimeToUtc(dt, TimeZoneInfo.Utc);
+ }
- /// <summary>
- /// Converts the date and time to Coordinated Universal Time (UTC)
- /// </summary>
- /// <param name="dt">The date and time to convert.</param>
- /// <param name="sourceTimeZone">The time zone of dateTime.</param>
- /// <returns>A DateTime value that represents the Coordinated Universal Time (UTC) that corresponds to the dateTime parameter. The DateTime value's Kind property is always set to DateTimeKind.Utc.</returns>
- public virtual DateTime ConvertToUtcTime(DateTime dt, TimeZoneInfo sourceTimeZone)
- {
- if (sourceTimeZone.IsInvalidTime(dt))
+ /// <summary>
+ /// Converts the date and time to Coordinated Universal Time (UTC)
+ /// </summary>
+ /// <param name="dt">The date and time to convert.</param>
+ /// <param name="sourceTimeZone">The time zone of dateTime.</param>
+ /// <returns>
+ /// A DateTime value that represents the Coordinated Universal Time (UTC) that corresponds to the dateTime
+ /// parameter. The DateTime value's Kind property is always set to DateTimeKind.Utc.
+ /// </returns>
+ public virtual DateTime ConvertToUtcTime(DateTime dt, TimeZoneInfo sourceTimeZone)
+ {
+ if (sourceTimeZone.IsInvalidTime(dt))
+ //could not convert
+ return dt;
+ return dt.Kind == DateTimeKind.Utc ? dt : TimeZoneInfo.ConvertTimeToUtc(dt, sourceTimeZone);
+ }
+
+ /// <summary>
+ /// Gets the current user time zone
+ /// </summary>
+ public virtual TimeZoneInfo CurrentTimeZone {
+ get {
+ if (_timeZoneInfo != null) return _timeZoneInfo;
+ try
{
- //could not convert
- return dt;
+ if (!string.IsNullOrEmpty(_dateTimeSettings.DefaultStoreTimeZoneId))
+ _timeZoneInfo = FindTimeZoneById(_dateTimeSettings.DefaultStoreTimeZoneId);
}
- return dt.Kind == DateTimeKind.Utc ? dt : TimeZoneInfo.ConvertTimeToUtc(dt, sourceTimeZone);
- }
-
- /// <summary>
- /// Gets the current user time zone
- /// </summary>
- public virtual TimeZoneInfo CurrentTimeZone {
- get {
- if (_timeZoneInfo != null) return _timeZoneInfo;
- try
- {
- if (!string.IsNullOrEmpty(_dateTimeSettings.DefaultStoreTimeZoneId))
- _timeZoneInfo = FindTimeZoneById(_dateTimeSettings.DefaultStoreTimeZoneId);
- }
- catch (Exception exc)
- {
- Debug.Write(exc.ToString());
- }
-
- return _timeZoneInfo ??= TimeZoneInfo.Local;
-
+ catch (Exception exc)
+ {
+ Debug.Write(exc.ToString());
}
+
+ return _timeZoneInfo ??= TimeZoneInfo.Local;
}
}
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Directory/ExchangeRateService.cs b/src/Business/Grand.Business.Common/Services/Directory/ExchangeRateService.cs
index 9e343d5b8..cb4207086 100644
--- a/src/Business/Grand.Business.Common/Services/Directory/ExchangeRateService.cs
+++ b/src/Business/Grand.Business.Common/Services/Directory/ExchangeRateService.cs
@@ -2,65 +2,66 @@
using Grand.Business.Core.Interfaces.Common.Providers;
using Grand.Domain.Directory;
-namespace Grand.Business.Common.Services.Directory
+namespace Grand.Business.Common.Services.Directory;
+
+public class ExchangeRateService : IExchangeRateService
{
- public class ExchangeRateService : IExchangeRateService
- {
- private readonly IEnumerable<IExchangeRateProvider> _exchangeRateProvider;
- private readonly CurrencySettings _currencySettings;
+ private readonly CurrencySettings _currencySettings;
+ private readonly IEnumerable<IExchangeRateProvider> _exchangeRateProvider;
- public ExchangeRateService(IEnumerable<IExchangeRateProvider> exchangeRateProvider, CurrencySettings currencySettings)
- {
- _exchangeRateProvider = exchangeRateProvider;
- _currencySettings = currencySettings;
- }
+ public ExchangeRateService(IEnumerable<IExchangeRateProvider> exchangeRateProvider,
+ CurrencySettings currencySettings)
+ {
+ _exchangeRateProvider = exchangeRateProvider;
+ _currencySettings = currencySettings;
+ }
- /// <summary>
- /// Gets currency live rates
- /// </summary>
- /// <param name="exchangeRateCurrencyCode">Exchange rate currency code</param>
- /// <returns>Exchange rates</returns>
- public virtual Task<IList<ExchangeRate>> GetCurrencyLiveRates(string exchangeRateCurrencyCode)
- {
- var exchangeRateProvider = LoadActiveExchangeRateProvider();
- if (exchangeRateProvider == null)
- throw new Exception("Active exchange rate provider cannot be loaded");
- return exchangeRateProvider.GetCurrencyLiveRates(exchangeRateCurrencyCode);
- }
+ /// <summary>
+ /// Gets currency live rates
+ /// </summary>
+ /// <param name="exchangeRateCurrencyCode">Exchange rate currency code</param>
+ /// <returns>Exchange rates</returns>
+ public virtual Task<IList<ExchangeRate>> GetCurrencyLiveRates(string exchangeRateCurrencyCode)
+ {
+ var exchangeRateProvider = LoadActiveExchangeRateProvider();
+ if (exchangeRateProvider == null)
+ throw new Exception("Active exchange rate provider cannot be loaded");
+ return exchangeRateProvider.GetCurrencyLiveRates(exchangeRateCurrencyCode);
+ }
- /// <summary>
- /// Load active exchange rate provider
- /// </summary>
- /// <returns>Active exchange rate provider</returns>
- public virtual IExchangeRateProvider LoadActiveExchangeRateProvider()
- {
- var exchangeRateProvider = LoadExchangeRateProviderBySystemName(_currencySettings.ActiveExchangeRateProviderSystemName) ??
- LoadAllExchangeRateProviders().FirstOrDefault();
- return exchangeRateProvider;
- }
+ /// <summary>
+ /// Load active exchange rate provider
+ /// </summary>
+ /// <returns>Active exchange rate provider</returns>
+ public virtual IExchangeRateProvider LoadActiveExchangeRateProvider()
+ {
+ var exchangeRateProvider =
+ LoadExchangeRateProviderBySystemName(_currencySettings.ActiveExchangeRateProviderSystemName) ??
+ LoadAllExchangeRateProviders().FirstOrDefault();
+ return exchangeRateProvider;
+ }
- /// <summary>
- /// Load exchange rate provider by system name
- /// </summary>
- /// <param name="systemName">System name</param>
- /// <returns>Found exchange rate provider</returns>
- public virtual IExchangeRateProvider LoadExchangeRateProviderBySystemName(string systemName)
- {
- return _exchangeRateProvider.FirstOrDefault(x => x.SystemName == systemName);
- }
+ /// <summary>
+ /// Load exchange rate provider by system name
+ /// </summary>
+ /// <param name="systemName">System name</param>
+ /// <returns>Found exchange rate provider</returns>
+ public virtual IExchangeRateProvider LoadExchangeRateProviderBySystemName(string systemName)
+ {
+ return _exchangeRateProvider.FirstOrDefault(x => x.SystemName == systemName);
+ }
- /// <summary>
- /// Load all exchange rate providers
- /// </summary>
- /// <returns>Exchange rate providers</returns>
- public virtual IList<IExchangeRateProvider> LoadAllExchangeRateProviders()
- {
- var exchangeRateProviders = _exchangeRateProvider.ToList();
- return exchangeRateProviders
- .OrderBy(tp => tp.Priority)
- .ToList();
- }
+ /// <summary>
+ /// Load all exchange rate providers
+ /// </summary>
+ /// <returns>Exchange rate providers</returns>
+ public virtual IList<IExchangeRateProvider> LoadAllExchangeRateProviders()
+ {
+ var exchangeRateProviders = _exchangeRateProvider.ToList();
+ return exchangeRateProviders
+ .OrderBy(tp => tp.Priority)
+ .ToList();
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs b/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs
index 2691ad43a..dff793280 100644
--- a/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs
+++ b/src/Business/Grand.Business.Common/Services/Directory/GroupService.cs
@@ -1,211 +1,211 @@
using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Customers;
-using Grand.Data;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
using Grand.SharedKernel;
using MediatR;
-namespace Grand.Business.Common.Services.Directory
+namespace Grand.Business.Common.Services.Directory;
+
+public class GroupService : IGroupService
{
- public class GroupService : IGroupService
+ private readonly ICacheBase _cacheBase;
+ private readonly IRepository<CustomerGroup> _customerGroupRepository;
+ private readonly IMediator _mediator;
+
+ public GroupService(IRepository<CustomerGroup> customerGroupRepository,
+ ICacheBase cacheBase,
+ IMediator mediator)
{
- private readonly IRepository<CustomerGroup> _customerGroupRepository;
- private readonly ICacheBase _cacheBase;
- private readonly IMediator _mediator;
+ _customerGroupRepository = customerGroupRepository;
+ _cacheBase = cacheBase;
+ _mediator = mediator;
+ }
- public GroupService(IRepository<CustomerGroup> customerGroupRepository,
- ICacheBase cacheBase,
- IMediator mediator)
- {
- _customerGroupRepository = customerGroupRepository;
- _cacheBase = cacheBase;
- _mediator = mediator;
- }
-
- /// <summary>
- /// Gets a customer group
- /// </summary>
- /// <param name="customerGroupId">Customer group identifier</param>
- /// <returns>Customer group</returns>
- public virtual Task<CustomerGroup> GetCustomerGroupById(string customerGroupId)
- {
- if (string.IsNullOrWhiteSpace(customerGroupId))
- return Task.FromResult<CustomerGroup>(null);
-
- var key = string.Format(CacheKey.CUSTOMERGROUPS_BY_KEY, customerGroupId);
- return _cacheBase.GetAsync(key, () => _customerGroupRepository.GetByIdAsync(customerGroupId));
- }
-
- /// <summary>
- /// Gets a customer group
- /// </summary>
- /// <param name="systemName">Customer group system name</param>
- /// <returns>Customer group</returns>
- public virtual async Task<CustomerGroup> GetCustomerGroupBySystemName(string systemName)
- {
- var key = string.Format(CacheKey.CUSTOMERGROUPS_BY_SYSTEMNAME_KEY, systemName);
- return await _cacheBase.GetAsync(key, async () =>
- {
- return await Task.FromResult(_customerGroupRepository.Table.FirstOrDefault(x => x.SystemName == systemName));
- });
- }
-
- /// <summary>
- /// Gets all customer groups
- /// </summary>
- /// <param name="pageSize"></param>
- /// <param name="showHidden">A value indicating whether to show hidden records</param>
- /// <param name="name"></param>
- /// <param name="pageIndex"></param>
- /// <returns>Customer groups</returns>
- public virtual async Task<IPagedList<CustomerGroup>> GetAllCustomerGroups(string name = "", int pageIndex = 0,
- int pageSize = int.MaxValue, bool showHidden = false)
+ /// <summary>
+ /// Gets a customer group
+ /// </summary>
+ /// <param name="customerGroupId">Customer group identifier</param>
+ /// <returns>Customer group</returns>
+ public virtual Task<CustomerGroup> GetCustomerGroupById(string customerGroupId)
+ {
+ if (string.IsNullOrWhiteSpace(customerGroupId))
+ return Task.FromResult<CustomerGroup>(null);
+
+ var key = string.Format(CacheKey.CUSTOMERGROUPS_BY_KEY, customerGroupId);
+ return _cacheBase.GetAsync(key, () => _customerGroupRepository.GetByIdAsync(customerGroupId));
+ }
+
+ /// <summary>
+ /// Gets a customer group
+ /// </summary>
+ /// <param name="systemName">Customer group system name</param>
+ /// <returns>Customer group</returns>
+ public virtual async Task<CustomerGroup> GetCustomerGroupBySystemName(string systemName)
+ {
+ var key = string.Format(CacheKey.CUSTOMERGROUPS_BY_SYSTEMNAME_KEY, systemName);
+ return await _cacheBase.GetAsync(key, async () =>
{
- var query = from m in _customerGroupRepository.Table
- select m;
+ return await Task.FromResult(
+ _customerGroupRepository.Table.FirstOrDefault(x => x.SystemName == systemName));
+ });
+ }
- if (!showHidden)
- query = query.Where(m => m.Active);
-
- if (!string.IsNullOrEmpty(name))
- query = query.Where(x => x.Name.ToLowerInvariant().Contains(name.ToLowerInvariant()));
+ /// <summary>
+ /// Gets all customer groups
+ /// </summary>
+ /// <param name="pageSize"></param>
+ /// <param name="showHidden">A value indicating whether to show hidden records</param>
+ /// <param name="name"></param>
+ /// <param name="pageIndex"></param>
+ /// <returns>Customer groups</returns>
+ public virtual async Task<IPagedList<CustomerGroup>> GetAllCustomerGroups(string name = "", int pageIndex = 0,
+ int pageSize = int.MaxValue, bool showHidden = false)
+ {
+ var query = from m in _customerGroupRepository.Table
+ select m;
- query = query.OrderBy(m => m.DisplayOrder).ThenBy(m => m.Name);
+ if (!showHidden)
+ query = query.Where(m => m.Active);
- return await PagedList<CustomerGroup>.Create(query, pageIndex, pageSize);
- }
+ if (!string.IsNullOrEmpty(name))
+ query = query.Where(x => x.Name.ToLowerInvariant().Contains(name.ToLowerInvariant()));
- /// <summary>
- /// Inserts a customer group
- /// </summary>
- /// <param name="customerGroup">Customer group</param>
- public virtual async Task InsertCustomerGroup(CustomerGroup customerGroup)
- {
- ArgumentNullException.ThrowIfNull(customerGroup);
+ query = query.OrderBy(m => m.DisplayOrder).ThenBy(m => m.Name);
- await _customerGroupRepository.InsertAsync(customerGroup);
+ return await PagedList<CustomerGroup>.Create(query, pageIndex, pageSize);
+ }
- await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERGROUPS_PATTERN_KEY);
+ /// <summary>
+ /// Inserts a customer group
+ /// </summary>
+ /// <param name="customerGroup">Customer group</param>
+ public virtual async Task InsertCustomerGroup(CustomerGroup customerGroup)
+ {
+ ArgumentNullException.ThrowIfNull(customerGroup);
- //event notification
- await _mediator.EntityInserted(customerGroup);
- }
+ await _customerGroupRepository.InsertAsync(customerGroup);
- /// <summary>
- /// Updates the customer group
- /// </summary>
- /// <param name="customerGroup">Customer group</param>
- public virtual async Task UpdateCustomerGroup(CustomerGroup customerGroup)
- {
- ArgumentNullException.ThrowIfNull(customerGroup);
+ await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERGROUPS_PATTERN_KEY);
- await _customerGroupRepository.UpdateAsync(customerGroup);
+ //event notification
+ await _mediator.EntityInserted(customerGroup);
+ }
- await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERGROUPS_PATTERN_KEY);
+ /// <summary>
+ /// Updates the customer group
+ /// </summary>
+ /// <param name="customerGroup">Customer group</param>
+ public virtual async Task UpdateCustomerGroup(CustomerGroup customerGroup)
+ {
+ ArgumentNullException.ThrowIfNull(customerGroup);
- //event notification
- await _mediator.EntityUpdated(customerGroup);
- }
+ await _customerGroupRepository.UpdateAsync(customerGroup);
- /// <summary>
- /// Delete a customer group
- /// </summary>
- /// <param name="customerGroup">Customer group</param>
- public virtual async Task DeleteCustomerGroup(CustomerGroup customerGroup)
- {
- ArgumentNullException.ThrowIfNull(customerGroup);
-
- if (customerGroup.IsSystem)
- throw new GrandException("System group could not be deleted");
-
- await _customerGroupRepository.DeleteAsync(customerGroup);
-
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERGROUPS_PATTERN_KEY);
-
- //event notification
- await _mediator.EntityDeleted(customerGroup);
- }
-
- /// <summary>
- /// Gets a value indicating whether customer is in a certain customer group
- /// </summary>
- /// <param name="customer">Customer</param>
- /// <param name="customerGroupSystemName">Customer group system name</param>
- /// <param name="onlyActiveCustomerGroups">A value indicating whether we should look only in active customer groups</param>
- /// <param name="isSystem">A value indicating whether we should look only in system groups</param>
- /// <returns>Result</returns>
- public virtual async Task<bool> IsInCustomerGroup(Customer customer,
- string customerGroupSystemName,
- bool onlyActiveCustomerGroups = true,
- bool? isSystem = null)
- {
- ArgumentNullException.ThrowIfNull(customer);
+ await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERGROUPS_PATTERN_KEY);
- if (string.IsNullOrEmpty(customerGroupSystemName))
- throw new ArgumentNullException(nameof(customerGroupSystemName));
+ //event notification
+ await _mediator.EntityUpdated(customerGroup);
+ }
- var customerGroup = await GetCustomerGroupBySystemName(customerGroupSystemName);
- if (customerGroup == null)
- return false;
+ /// <summary>
+ /// Delete a customer group
+ /// </summary>
+ /// <param name="customerGroup">Customer group</param>
+ public virtual async Task DeleteCustomerGroup(CustomerGroup customerGroup)
+ {
+ ArgumentNullException.ThrowIfNull(customerGroup);
- var result =
- customer.Groups.Contains(customerGroup.Id)
- && (!onlyActiveCustomerGroups || customerGroup.Active)
- && customerGroup.SystemName == customerGroupSystemName
- && (!isSystem.HasValue || customerGroup.IsSystem == isSystem);
+ if (customerGroup.IsSystem)
+ throw new GrandException("System group could not be deleted");
- return result;
- }
+ await _customerGroupRepository.DeleteAsync(customerGroup);
- public Task<bool> IsStaff(Customer customer)
- {
- return IsInCustomerGroup(customer, SystemCustomerGroupNames.Staff, true, true);
- }
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.CUSTOMERGROUPS_PATTERN_KEY);
- public Task<bool> IsAdmin(Customer customer)
- {
- return IsInCustomerGroup(customer, SystemCustomerGroupNames.Administrators, true, true);
- }
+ //event notification
+ await _mediator.EntityDeleted(customerGroup);
+ }
- public Task<bool> IsSalesManager(Customer customer)
- {
- return IsInCustomerGroup(customer, SystemCustomerGroupNames.SalesManager, true, true);
- }
+ /// <summary>
+ /// Gets a value indicating whether customer is in a certain customer group
+ /// </summary>
+ /// <param name="customer">Customer</param>
+ /// <param name="customerGroupSystemName">Customer group system name</param>
+ /// <param name="onlyActiveCustomerGroups">A value indicating whether we should look only in active customer groups</param>
+ /// <param name="isSystem">A value indicating whether we should look only in system groups</param>
+ /// <returns>Result</returns>
+ public virtual async Task<bool> IsInCustomerGroup(Customer customer,
+ string customerGroupSystemName,
+ bool onlyActiveCustomerGroups = true,
+ bool? isSystem = null)
+ {
+ ArgumentNullException.ThrowIfNull(customer);
- public Task<bool> IsVendor(Customer customer)
- {
- return IsInCustomerGroup(customer, SystemCustomerGroupNames.Vendors, true, true);
- }
+ if (string.IsNullOrEmpty(customerGroupSystemName))
+ throw new ArgumentNullException(nameof(customerGroupSystemName));
- public async Task<bool> IsOwner(Customer customer)
- {
- return await Task.FromResult(string.IsNullOrEmpty(customer.OwnerId));
- }
+ var customerGroup = await GetCustomerGroupBySystemName(customerGroupSystemName);
+ if (customerGroup == null)
+ return false;
- public Task<bool> IsGuest(Customer customer)
- {
- return IsInCustomerGroup(customer, SystemCustomerGroupNames.Guests, true, true);
- }
+ var result =
+ customer.Groups.Contains(customerGroup.Id)
+ && (!onlyActiveCustomerGroups || customerGroup.Active)
+ && customerGroup.SystemName == customerGroupSystemName
+ && (!isSystem.HasValue || customerGroup.IsSystem == isSystem);
- public Task<bool> IsRegistered(Customer customer)
- {
- return IsInCustomerGroup(customer, SystemCustomerGroupNames.Registered, true, true);
- }
+ return result;
+ }
- public async Task<IList<CustomerGroup>> GetAllByIds(string[] ids)
- {
- var customerGroups = await _cacheBase.GetAsync(CacheKey.CUSTOMERGROUPS_ALL, async () =>
- {
- var query = from cr in _customerGroupRepository.Table
- orderby cr.Name
- select cr;
- return await Task.FromResult(query.ToList());
- });
- return customerGroups.Where(x => ids.Contains(x.Id)).ToList();
- }
- }
-}
+ public Task<bool> IsStaff(Customer customer)
+ {
+ return IsInCustomerGroup(customer, SystemCustomerGroupNames.Staff, true, true);
+ }
+
+ public Task<bool> IsAdmin(Customer customer)
+ {
+ return IsInCustomerGroup(customer, SystemCustomerGroupNames.Administrators, true, true);
+ }
+
+ public Task<bool> IsSalesManager(Customer customer)
+ {
+ return IsInCustomerGroup(customer, SystemCustomerGroupNames.SalesManager, true, true);
+ }
+
+ public Task<bool> IsVendor(Customer customer)
+ {
+ return IsInCustomerGroup(customer, SystemCustomerGroupNames.Vendors, true, true);
+ }
+
+ public async Task<bool> IsOwner(Customer customer)
+ {
+ return await Task.FromResult(string.IsNullOrEmpty(customer.OwnerId));
+ }
+
+ public Task<bool> IsGuest(Customer customer)
+ {
+ return IsInCustomerGroup(customer, SystemCustomerGroupNames.Guests, true, true);
+ }
+
+ public Task<bool> IsRegistered(Customer customer)
+ {
+ return IsInCustomerGroup(customer, SystemCustomerGroupNames.Registered, true, true);
+ }
+
+ public async Task<IList<CustomerGroup>> GetAllByIds(string[] ids)
+ {
+ var customerGroups = await _cacheBase.GetAsync(CacheKey.CUSTOMERGROUPS_ALL, async () =>
+ {
+ var query = from cr in _customerGroupRepository.Table
+ orderby cr.Name
+ select cr;
+ return await Task.FromResult(query.ToList());
+ });
+ return customerGroups.Where(x => ids.Contains(x.Id)).ToList();
+ }
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Directory/HistoryService.cs b/src/Business/Grand.Business.Common/Services/Directory/HistoryService.cs
index ac0f8a849..889269384 100644
--- a/src/Business/Grand.Business.Common/Services/Directory/HistoryService.cs
+++ b/src/Business/Grand.Business.Common/Services/Directory/HistoryService.cs
@@ -1,46 +1,45 @@
using Grand.Business.Core.Interfaces.Common.Directory;
-using Grand.Domain;
using Grand.Data;
+using Grand.Domain;
using Grand.Domain.History;
-namespace Grand.Business.Common.Services.Directory
+namespace Grand.Business.Common.Services.Directory;
+
+/// <summary>
+/// History service interface
+/// </summary>
+public class HistoryService : IHistoryService
{
- /// <summary>
- /// History service interface
- /// </summary>
- public class HistoryService : IHistoryService
+ private readonly IRepository<HistoryObject> _historyRepository;
+
+ public HistoryService(IRepository<HistoryObject> historyRepository)
{
- private readonly IRepository<HistoryObject> _historyRepository;
-
- public HistoryService(IRepository<HistoryObject> historyRepository)
- {
- _historyRepository = historyRepository;
- }
-
- public virtual async Task SaveObject<T>(T entity) where T : BaseEntity
- {
- ArgumentNullException.ThrowIfNull(entity);
- var history = new HistoryObject
- {
- Object = entity
- };
- await _historyRepository.InsertAsync(history);
- }
-
- public virtual async Task<IList<T>> GetHistoryForEntity<T>(BaseEntity entity) where T : BaseEntity
- {
- ArgumentNullException.ThrowIfNull(entity);
-
- var history = await Task.FromResult(_historyRepository.Table.Where(x => x.Object.Id == entity.Id).Select(x => (T)x.Object).ToList());
- return history;
- }
-
- public virtual async Task<IList<HistoryObject>> GetHistoryObjectForEntity(BaseEntity entity)
- {
- ArgumentNullException.ThrowIfNull(entity);
-
- var history = await Task.FromResult(_historyRepository.Table.Where(x => x.Object.Id == entity.Id).ToList());
- return history;
- }
+ _historyRepository = historyRepository;
+ }
+
+ public virtual async Task SaveObject<T>(T entity) where T : BaseEntity
+ {
+ ArgumentNullException.ThrowIfNull(entity);
+ var history = new HistoryObject {
+ Object = entity
+ };
+ await _historyRepository.InsertAsync(history);
+ }
+
+ public virtual async Task<IList<T>> GetHistoryForEntity<T>(BaseEntity entity) where T : BaseEntity
+ {
+ ArgumentNullException.ThrowIfNull(entity);
+
+ var history = await Task.FromResult(_historyRepository.Table.Where(x => x.Object.Id == entity.Id)
+ .Select(x => (T)x.Object).ToList());
+ return history;
+ }
+
+ public virtual async Task<IList<HistoryObject>> GetHistoryObjectForEntity(BaseEntity entity)
+ {
+ ArgumentNullException.ThrowIfNull(entity);
+
+ var history = await Task.FromResult(_historyRepository.Table.Where(x => x.Object.Id == entity.Id).ToList());
+ return history;
}
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Directory/UserFieldService.cs b/src/Business/Grand.Business.Common/Services/Directory/UserFieldService.cs
index a7d9d972f..2fd147475 100644
--- a/src/Business/Grand.Business.Common/Services/Directory/UserFieldService.cs
+++ b/src/Business/Grand.Business.Common/Services/Directory/UserFieldService.cs
@@ -1,122 +1,124 @@
using Grand.Business.Core.Interfaces.Common.Directory;
+using Grand.Data;
using Grand.Domain;
using Grand.Domain.Common;
-using Grand.Data;
using Grand.SharedKernel.Extensions;
-namespace Grand.Business.Common.Services.Directory
+namespace Grand.Business.Common.Services.Directory;
+
+/// <summary>
+/// User field service
+/// </summary>
+public class UserFieldService : IUserFieldService
{
- /// <summary>
- /// User field service
- /// </summary>
- public class UserFieldService : IUserFieldService
- {
+ #region Fields
- #region Fields
+ private readonly IRepository<UserFieldBaseEntity> _userFieldBaseEntityRepository;
- private readonly IRepository<UserFieldBaseEntity> _userFieldBaseEntityRepository;
- #endregion
+ #endregion
- #region Ctor
- public UserFieldService(
- IRepository<UserFieldBaseEntity> userFieldBaseEntityRepository)
- {
- _userFieldBaseEntityRepository = userFieldBaseEntityRepository;
- }
+ #region Ctor
- #endregion
+ public UserFieldService(
+ IRepository<UserFieldBaseEntity> userFieldBaseEntityRepository)
+ {
+ _userFieldBaseEntityRepository = userFieldBaseEntityRepository;
+ }
- #region Methods
+ #endregion
- /// <summary>
- /// Save attribute value
- /// </summary>
- /// <typeparam name="TPropType">Property type</typeparam>
- /// <param name="entity">Entity</param>
- /// <param name="key">Key</param>
- /// <param name="value">Value</param>
- /// <param name="storeId">Store identifier; pass "" if this attribute will be available for all stores</param>
- public virtual async Task SaveField<TPropType>(BaseEntity entity, string key, TPropType value, string storeId = "")
- {
- ArgumentNullException.ThrowIfNull(entity);
- ArgumentNullException.ThrowIfNull(key);
+ #region Methods
- var collectionName = entity.GetType().Name;
+ /// <summary>
+ /// Save attribute value
+ /// </summary>
+ /// <typeparam name="TPropType">Property type</typeparam>
+ /// <param name="entity">Entity</param>
+ /// <param name="key">Key</param>
+ /// <param name="value">Value</param>
+ /// <param name="storeId">Store identifier; pass "" if this attribute will be available for all stores</param>
+ public virtual async Task SaveField<TPropType>(BaseEntity entity, string key, TPropType value, string storeId = "")
+ {
+ ArgumentNullException.ThrowIfNull(entity);
+ ArgumentNullException.ThrowIfNull(key);
+
+ var collectionName = entity.GetType().Name;
- _ = _userFieldBaseEntityRepository.SetCollection(collectionName);
+ _ = _userFieldBaseEntityRepository.SetCollection(collectionName);
- var baseFields = await _userFieldBaseEntityRepository.GetByIdAsync(entity.Id);
+ var baseFields = await _userFieldBaseEntityRepository.GetByIdAsync(entity.Id);
- var props = baseFields.UserFields.Where(x => string.IsNullOrEmpty(storeId) || x.StoreId == storeId);
+ var props = baseFields.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 =>
+ ga.Key.Equals(key, StringComparison.OrdinalIgnoreCase)); //should be culture invariant
- var valueStr = CommonHelper.To<string>(value);
+ var valueStr = CommonHelper.To<string>(value);
- if (prop != null)
+ if (prop != null)
+ {
+ if (string.IsNullOrWhiteSpace(valueStr))
{
- if (string.IsNullOrWhiteSpace(valueStr))
- {
- //delete
- await _userFieldBaseEntityRepository.PullFilter(entity.Id, x => x.UserFields, y => y.Key == prop.Key && y.StoreId == storeId);
-
- var entityProp = entity.UserFields.FirstOrDefault(x => x.Key == prop.Key && x.StoreId == storeId);
- if (entityProp != null)
- entity.UserFields.Remove(entityProp);
- }
- else
- {
- //update
- prop.Value = valueStr;
- await _userFieldBaseEntityRepository.UpdateToSet(entity.Id, x => x.UserFields, y => y.Key == prop.Key && y.StoreId == storeId, prop);
-
- var entityProp = entity.UserFields.FirstOrDefault(x => x.Key == prop.Key && x.StoreId == storeId);
- if (entityProp != null)
- entityProp.Value = valueStr;
-
- }
+ //delete
+ await _userFieldBaseEntityRepository.PullFilter(entity.Id, x => x.UserFields,
+ y => y.Key == prop.Key && y.StoreId == storeId);
+
+ var entityProp = entity.UserFields.FirstOrDefault(x => x.Key == prop.Key && x.StoreId == storeId);
+ if (entityProp != null)
+ entity.UserFields.Remove(entityProp);
}
else
{
- if (!string.IsNullOrWhiteSpace(valueStr))
- {
- prop = new UserField {
- Key = key,
- Value = valueStr,
- StoreId = storeId
- };
- await _userFieldBaseEntityRepository.AddToSet(entity.Id, x => x.UserFields, prop);
-
- entity.UserFields.Add(prop);
- }
+ //update
+ prop.Value = valueStr;
+ await _userFieldBaseEntityRepository.UpdateToSet(entity.Id, x => x.UserFields,
+ y => y.Key == prop.Key && y.StoreId == storeId, prop);
+
+ var entityProp = entity.UserFields.FirstOrDefault(x => x.Key == prop.Key && x.StoreId == storeId);
+ if (entityProp != null)
+ entityProp.Value = valueStr;
}
}
-
- public virtual async Task<TPropType> GetFieldsForEntity<TPropType>(BaseEntity entity, string key, string storeId = "")
+ else
{
- ArgumentNullException.ThrowIfNull(entity);
+ if (!string.IsNullOrWhiteSpace(valueStr))
+ {
+ prop = new UserField {
+ Key = key,
+ Value = valueStr,
+ StoreId = storeId
+ };
+ await _userFieldBaseEntityRepository.AddToSet(entity.Id, x => x.UserFields, prop);
+
+ entity.UserFields.Add(prop);
+ }
+ }
+ }
- var collectionName = entity.GetType().Name;
- _ = _userFieldBaseEntityRepository.SetCollection(collectionName);
+ public virtual async Task<TPropType> GetFieldsForEntity<TPropType>(BaseEntity entity, string key,
+ string storeId = "")
+ {
+ ArgumentNullException.ThrowIfNull(entity);
- var baseFields = await _userFieldBaseEntityRepository.GetByIdAsync(entity.Id);
- var props = baseFields?.UserFields;
- if (props == null)
- return default;
- props = props.Where(x => x.StoreId == storeId).ToList();
- if (!props.Any())
- return default;
+ var collectionName = entity.GetType().Name;
+ _ = _userFieldBaseEntityRepository.SetCollection(collectionName);
- var prop = props.FirstOrDefault(ga =>
- ga.Key.Equals(key, StringComparison.OrdinalIgnoreCase));
+ var baseFields = await _userFieldBaseEntityRepository.GetByIdAsync(entity.Id);
+ var props = baseFields?.UserFields;
+ if (props == null)
+ return default;
+ props = props.Where(x => x.StoreId == storeId).ToList();
+ if (!props.Any())
+ return default;
- if (prop == null || string.IsNullOrEmpty(prop.Value))
- return default;
+ var prop = props.FirstOrDefault(ga =>
+ ga.Key.Equals(key, StringComparison.OrdinalIgnoreCase));
- return CommonHelper.To<TPropType>(prop.Value);
- }
+ if (prop == null || string.IsNullOrEmpty(prop.Value))
+ return default;
- #endregion
+ return CommonHelper.To<TPropType>(prop.Value);
}
+
+ #endregion
}
\ 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 02a3571ee..30db9a938 100644
--- a/src/Business/Grand.Business.Common/Services/ExportImport/CountryImportDataObject.cs
+++ b/src/Business/Grand.Business.Common/Services/ExportImport/CountryImportDataObject.cs
@@ -3,52 +3,47 @@ using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.ExportImport;
using Grand.Domain.Directory;
-namespace Grand.Business.Common.Services.ExportImport
+namespace Grand.Business.Common.Services.ExportImport;
+
+public class CountryImportDataObject : IImportDataObject<CountryStatesDto>
{
- public class CountryImportDataObject : IImportDataObject<CountryStatesDto>
+ private readonly ICountryService _countryService;
+
+ public CountryImportDataObject(ICountryService countryService)
{
- private readonly ICountryService _countryService;
+ _countryService = countryService;
+ }
- public CountryImportDataObject(ICountryService countryService)
- {
- _countryService = countryService;
- }
+ public async Task Execute(IEnumerable<CountryStatesDto> data)
+ {
+ foreach (var item in data) await Import(item);
+ }
- public async Task Execute(IEnumerable<CountryStatesDto> data)
+ private async Task Import(CountryStatesDto countryStatesDtoDto)
+ {
+ var country = await _countryService.GetCountryByTwoLetterIsoCode(countryStatesDtoDto.Country);
+ if (country == null)
+ return;
+
+ var state = country.StateProvinces.FirstOrDefault(x =>
+ x.Abbreviation.Equals(countryStatesDtoDto.Abbreviation, StringComparison.OrdinalIgnoreCase));
+ if (state != null)
{
- foreach (var item in data)
- {
- await Import(item);
- }
+ state.Name = countryStatesDtoDto.StateProvinceName;
+ state.Abbreviation = countryStatesDtoDto.Abbreviation;
+ state.Published = countryStatesDtoDto.Published;
+ state.DisplayOrder = countryStatesDtoDto.DisplayOrder;
+ await _countryService.UpdateStateProvince(state, country.Id);
}
-
- private async Task Import(CountryStatesDto countryStatesDtoDto)
+ else
{
- var country = await _countryService.GetCountryByTwoLetterIsoCode(countryStatesDtoDto.Country);
- if (country == null)
- return;
-
- var state = country.StateProvinces.FirstOrDefault(x => x.Abbreviation.Equals(countryStatesDtoDto.Abbreviation, StringComparison.OrdinalIgnoreCase));
- if (state != null)
- {
- state.Name = countryStatesDtoDto.StateProvinceName;
- state.Abbreviation = countryStatesDtoDto.Abbreviation;
- state.Published = countryStatesDtoDto.Published;
- state.DisplayOrder = countryStatesDtoDto.DisplayOrder;
- await _countryService.UpdateStateProvince(state, country.Id);
- }
- else
- {
- state = new StateProvince {
- Name = countryStatesDtoDto.StateProvinceName,
- Abbreviation = countryStatesDtoDto.Abbreviation,
- Published = countryStatesDtoDto.Published,
- DisplayOrder = countryStatesDtoDto.DisplayOrder
- };
- await _countryService.InsertStateProvince(state, country.Id);
- }
+ state = new StateProvince {
+ Name = countryStatesDtoDto.StateProvinceName,
+ Abbreviation = countryStatesDtoDto.Abbreviation,
+ Published = countryStatesDtoDto.Published,
+ DisplayOrder = countryStatesDtoDto.DisplayOrder
+ };
+ await _countryService.InsertStateProvince(state, country.Id);
}
-
-
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/ExportImport/CountrySchemaProperty.cs b/src/Business/Grand.Business.Common/Services/ExportImport/CountrySchemaProperty.cs
index 967571b79..0989e3fe9 100644
--- a/src/Business/Grand.Business.Common/Services/ExportImport/CountrySchemaProperty.cs
+++ b/src/Business/Grand.Business.Common/Services/ExportImport/CountrySchemaProperty.cs
@@ -2,21 +2,19 @@
using Grand.Business.Core.Interfaces.ExportImport;
using Grand.Business.Core.Utilities.ExportImport;
-namespace Grand.Business.Common.Services.ExportImport
+namespace Grand.Business.Common.Services.ExportImport;
+
+public class CountrySchemaProperty : ISchemaProperty<CountryStatesDto>
{
- public class CountrySchemaProperty : ISchemaProperty<CountryStatesDto>
+ public virtual async Task<PropertyByName<CountryStatesDto>[]> GetProperties()
{
- public virtual async Task<PropertyByName<CountryStatesDto>[]> GetProperties()
- {
- var properties = new[]
- {
- new PropertyByName<CountryStatesDto>("Country", p => p.Country),
- new PropertyByName<CountryStatesDto>("StateProvinceName", p => p.StateProvinceName),
- new PropertyByName<CountryStatesDto>("Abbreviation", p => p.Abbreviation),
- new PropertyByName<CountryStatesDto>("DisplayOrder", p => p.DisplayOrder),
- new PropertyByName<CountryStatesDto>("Published", p => p.Published)
- };
- return await Task.FromResult(properties);
- }
+ var properties = new[] {
+ new PropertyByName<CountryStatesDto>("Country", p => p.Country),
+ new PropertyByName<CountryStatesDto>("StateProvinceName", p => p.StateProvinceName),
+ new PropertyByName<CountryStatesDto>("Abbreviation", p => p.Abbreviation),
+ new PropertyByName<CountryStatesDto>("DisplayOrder", p => p.DisplayOrder),
+ new PropertyByName<CountryStatesDto>("Published", p => p.Published)
+ };
+ return await Task.FromResult(properties);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs b/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs
index da429d537..dfa27b1a5 100644
--- a/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs
+++ b/src/Business/Grand.Business.Common/Services/ExportImport/ExcelExportProvider.cs
@@ -3,90 +3,81 @@ using Grand.Business.Core.Utilities.ExportImport;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
-namespace Grand.Business.Common.Services.ExportImport
+namespace Grand.Business.Common.Services.ExportImport;
+
+public class ExcelExportProvider : IExportProvider
{
- public class ExcelExportProvider : IExportProvider
+ private MemoryStream _stream;
+ private IWorkbook _xlPackage;
+
+ public virtual byte[] ExportToByte<T>(PropertyByName<T>[] properties, IEnumerable<T> itemsToExport)
{
- public virtual byte[] ExportToByte<T>(PropertyByName<T>[] properties, IEnumerable<T> itemsToExport)
- {
- using var stream = new MemoryStream();
- IWorkbook xlPackage = new XSSFWorkbook();
- ISheet worksheet = xlPackage.CreateSheet(typeof(T).Name);
+ using var stream = new MemoryStream();
+ IWorkbook xlPackage = new XSSFWorkbook();
+ var worksheet = xlPackage.CreateSheet(typeof(T).Name);
- _ = new PropertyManager<T>(properties);
+ _ = new PropertyManager<T>(properties);
- WriteCaption(worksheet, properties);
+ WriteCaption(worksheet, properties);
- var row = 1;
+ var row = 1;
- foreach (var items in itemsToExport)
- {
- WriteToXlsx(properties, worksheet, items, row++);
- }
- xlPackage.Write(stream, false);
- return stream.ToArray();
- }
+ foreach (var items in itemsToExport) WriteToXlsx(properties, worksheet, items, row++);
+ xlPackage.Write(stream, false);
+ return stream.ToArray();
+ }
- private MemoryStream _stream;
- private IWorkbook _xlPackage;
- public virtual IExportProvider BuilderExportToByte<T>(PropertyByName<T>[] properties, IEnumerable<T> itemsToExport)
- {
- _stream ??= new MemoryStream();
-
- _xlPackage ??= new XSSFWorkbook();
-
- ISheet worksheet = _xlPackage.CreateSheet(typeof(T).Name);
-
- _ = new PropertyManager<T>(properties);
-
- WriteCaption(worksheet, properties);
- var row = 1;
- foreach (var items in itemsToExport)
- {
- WriteToXlsx(properties, worksheet, items, row++);
- }
-
- return this;
- }
- public virtual byte[] BuilderExportToByte()
- {
- _xlPackage.Write(_stream, false);
- return _stream.ToArray();
- }
+ public virtual IExportProvider BuilderExportToByte<T>(PropertyByName<T>[] properties, IEnumerable<T> itemsToExport)
+ {
+ _stream ??= new MemoryStream();
- /// <summary>
- /// Write caption (first row) to XLSX worksheet
- /// </summary>
- /// <param name="sheet"></param>
- /// <param name="properties"></param>
- private void WriteCaption<T>(ISheet sheet, PropertyByName<T>[] properties)
- {
- IRow row = sheet.CreateRow(0);
- foreach (var caption in properties)
- {
- row.CreateCell(caption.PropertyOrderPosition).SetCellValue(caption.PropertyName);
- }
- }
+ _xlPackage ??= new XSSFWorkbook();
- /// <summary>
- /// Write object data to XLSX worksheet
- /// </summary>
- /// <param name="items"></param>
- /// <param name="idrow">Row index</param>
- /// <param name="properties"></param>
- /// <param name="sheet"></param>
- private void WriteToXlsx<T>(PropertyByName<T>[] properties, ISheet sheet, T items, int idrow)
+ var worksheet = _xlPackage.CreateSheet(typeof(T).Name);
+
+ _ = new PropertyManager<T>(properties);
+
+ WriteCaption(worksheet, properties);
+ var row = 1;
+ foreach (var items in itemsToExport) WriteToXlsx(properties, worksheet, items, row++);
+
+ return this;
+ }
+
+ public virtual byte[] BuilderExportToByte()
+ {
+ _xlPackage.Write(_stream, false);
+ return _stream.ToArray();
+ }
+
+ /// <summary>
+ /// Write caption (first row) to XLSX worksheet
+ /// </summary>
+ /// <param name="sheet"></param>
+ /// <param name="properties"></param>
+ private void WriteCaption<T>(ISheet sheet, PropertyByName<T>[] properties)
+ {
+ var row = sheet.CreateRow(0);
+ foreach (var caption in properties)
+ row.CreateCell(caption.PropertyOrderPosition).SetCellValue(caption.PropertyName);
+ }
+
+ /// <summary>
+ /// Write object data to XLSX worksheet
+ /// </summary>
+ /// <param name="items"></param>
+ /// <param name="idrow">Row index</param>
+ /// <param name="properties"></param>
+ /// <param name="sheet"></param>
+ private void WriteToXlsx<T>(PropertyByName<T>[] properties, ISheet sheet, T items, int idrow)
+ {
+ var row = sheet.CreateRow(idrow);
+ foreach (var prop in properties)
{
- IRow row = sheet.CreateRow(idrow);
- foreach (var prop in properties)
- {
- var cellValue = prop.GetProperty(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);
- }
+ var cellValue = prop.GetProperty(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);
}
}
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/ExportImport/ExcelImportProvider.cs b/src/Business/Grand.Business.Common/Services/ExportImport/ExcelImportProvider.cs
index 76c7d09c1..6a741ebc5 100644
--- a/src/Business/Grand.Business.Common/Services/ExportImport/ExcelImportProvider.cs
+++ b/src/Business/Grand.Business.Common/Services/ExportImport/ExcelImportProvider.cs
@@ -1,17 +1,15 @@
using Grand.Business.Common.Utilities;
using Grand.Business.Core.Interfaces.ExportImport;
-namespace Grand.Business.Common.Services.ExportImport
+namespace Grand.Business.Common.Services.ExportImport;
+
+public class ExcelImportProvider : IImportDataProvider
{
- public class ExcelImportProvider : IImportDataProvider
+ public async Task<IEnumerable<T>> Convert<T>(Stream stream)
{
- public async Task<IEnumerable<T>> Convert<T>(Stream stream)
- {
- var excel = new PowerExcelMapper {
- SkipBlankCells = false
-
- };
- return await excel.FetchAsync<T>(stream);
- }
+ var excel = new PowerExcelMapper {
+ SkipBlankCells = false
+ };
+ return await excel.FetchAsync<T>(stream);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/ExportImport/ExportManager.cs b/src/Business/Grand.Business.Common/Services/ExportImport/ExportManager.cs
index a07d3744e..0e6184414 100644
--- a/src/Business/Grand.Business.Common/Services/ExportImport/ExportManager.cs
+++ b/src/Business/Grand.Business.Common/Services/ExportImport/ExportManager.cs
@@ -1,21 +1,20 @@
using Grand.Business.Core.Interfaces.ExportImport;
-namespace Grand.Business.Common.Services.ExportImport
+namespace Grand.Business.Common.Services.ExportImport;
+
+public class ExportManager<T> : IExportManager<T> where T : class
{
- public class ExportManager<T> : IExportManager<T> where T : class
- {
- private readonly IExportProvider _exportProvider;
- private readonly ISchemaProperty<T> _schemaProperty;
+ private readonly IExportProvider _exportProvider;
+ private readonly ISchemaProperty<T> _schemaProperty;
- public ExportManager(IExportProvider exportProvider, ISchemaProperty<T> schemaProperty)
- {
- _exportProvider = exportProvider;
- _schemaProperty = schemaProperty;
- }
+ public ExportManager(IExportProvider exportProvider, ISchemaProperty<T> schemaProperty)
+ {
+ _exportProvider = exportProvider;
+ _schemaProperty = schemaProperty;
+ }
- public virtual async Task<byte[]> Export(IEnumerable<T> entity)
- {
- return _exportProvider.ExportToByte(await _schemaProperty.GetProperties(), entity);
- }
+ public virtual async Task<byte[]> Export(IEnumerable<T> entity)
+ {
+ return _exportProvider.ExportToByte(await _schemaProperty.GetProperties(), entity);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/ExportImport/ImportManager.cs b/src/Business/Grand.Business.Common/Services/ExportImport/ImportManager.cs
index 7e2290d8e..3c4ac794c 100644
--- a/src/Business/Grand.Business.Common/Services/ExportImport/ImportManager.cs
+++ b/src/Business/Grand.Business.Common/Services/ExportImport/ImportManager.cs
@@ -1,22 +1,21 @@
using Grand.Business.Core.Interfaces.ExportImport;
-namespace Grand.Business.Common.Services.ExportImport
+namespace Grand.Business.Common.Services.ExportImport;
+
+public class ImportManager<T> : IImportManager<T> where T : class
{
- public class ImportManager<T> : IImportManager<T> where T : class
- {
- private readonly IImportDataProvider _importDataProvider;
- private readonly IImportDataObject<T> _importDataObject;
+ private readonly IImportDataObject<T> _importDataObject;
+ private readonly IImportDataProvider _importDataProvider;
- public ImportManager(IImportDataProvider importDataProvider, IImportDataObject<T> importDataObject)
- {
- _importDataProvider = importDataProvider;
- _importDataObject = importDataObject;
- }
+ public ImportManager(IImportDataProvider importDataProvider, IImportDataObject<T> importDataObject)
+ {
+ _importDataProvider = importDataProvider;
+ _importDataObject = importDataObject;
+ }
- public async Task Import(Stream stream)
- {
- var data = await _importDataProvider.Convert<T>(stream);
- await _importDataObject.Execute(data);
- }
+ public async Task Import(Stream stream)
+ {
+ var data = await _importDataProvider.Convert<T>(stream);
+ await _importDataObject.Execute(data);
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs b/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs
index 469a9885c..533189ddc 100644
--- a/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs
+++ b/src/Business/Grand.Business.Common/Services/Localization/LanguageService.cs
@@ -1,161 +1,157 @@
using Grand.Business.Core.Interfaces.Common.Localization;
+using Grand.Data;
+using Grand.Domain.Localization;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
-using Grand.Data;
-using Grand.Domain.Localization;
using MediatR;
-namespace Grand.Business.Common.Services.Localization
+namespace Grand.Business.Common.Services.Localization;
+
+/// <summary>
+/// Language service
+/// </summary>
+public class LanguageService : ILanguageService
{
+ #region Ctor
+
/// <summary>
- /// Language service
+ /// Ctor
/// </summary>
- public class LanguageService : ILanguageService
+ /// <param name="cacheBase">Cache manager</param>
+ /// <param name="languageRepository">Language repository</param>
+ /// <param name="mediator">Mediator</param>
+ public LanguageService(ICacheBase cacheBase,
+ IRepository<Language> languageRepository,
+ IMediator mediator)
{
- #region Fields
+ _cacheBase = cacheBase;
+ _languageRepository = languageRepository;
+ _mediator = mediator;
+ }
- private readonly IRepository<Language> _languageRepository;
- private readonly ICacheBase _cacheBase;
- private readonly IMediator _mediator;
+ #endregion
- #endregion
+ #region Fields
- #region Ctor
+ private readonly IRepository<Language> _languageRepository;
+ private readonly ICacheBase _cacheBase;
+ private readonly IMediator _mediator;
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="cacheBase">Cache manager</param>
- /// <param name="languageRepository">Language repository</param>
- /// <param name="mediator">Mediator</param>
- public LanguageService(ICacheBase cacheBase,
- IRepository<Language> languageRepository,
- IMediator mediator)
- {
- _cacheBase = cacheBase;
- _languageRepository = languageRepository;
- _mediator = mediator;
- }
-
- #endregion
-
- #region Methods
-
-
- /// <summary>
- /// Gets all languages
- /// </summary>
- /// <param name="storeId">Load records allowed only in a specified store; pass "" to load all records</param>
- /// <param name="showHidden">A value indicating whether to show hidden records</param>
- /// <returns>Languages</returns>
- public virtual async Task<IList<Language>> GetAllLanguages(bool showHidden = false, string storeId = "")
- {
- var key = string.Format(CacheKey.LANGUAGES_ALL_KEY, showHidden);
- var languages = await _cacheBase.GetAsync(key, async () =>
- {
- var query = from p in _languageRepository.Table
- select p;
-
- if (!showHidden)
- query = query.Where(l => l.Published);
- query = query.OrderBy(l => l.DisplayOrder);
- return await Task.FromResult(query.ToList());
- });
-
- //store acl
- if (!string.IsNullOrWhiteSpace(storeId))
- {
- languages = languages
- .Where(l => l.Stores.Contains(storeId) || !l.LimitedToStores)
- .ToList();
- }
- return languages;
- }
-
- /// <summary>
- /// Gets a language
- /// </summary>
- /// <param name="languageId">Language identifier</param>
- /// <returns>Language</returns>
- public virtual Task<Language> GetLanguageById(string languageId)
- {
- var key = string.Format(CacheKey.LANGUAGES_BY_ID_KEY, languageId);
- return _cacheBase.GetAsync(key, () => _languageRepository.GetByIdAsync(languageId));
- }
-
- /// <summary>
- /// Gets a language
- /// </summary>
- /// <param name="languageCode">Language code</param>
- /// <returns>Language</returns>
- public virtual async Task<Language> GetLanguageByCode(string languageCode)
+ #endregion
+
+ #region Methods
+
+ /// <summary>
+ /// Gets all languages
+ /// </summary>
+ /// <param name="storeId">Load records allowed only in a specified store; pass "" to load all records</param>
+ /// <param name="showHidden">A value indicating whether to show hidden records</param>
+ /// <returns>Languages</returns>
+ public virtual async Task<IList<Language>> GetAllLanguages(bool showHidden = false, string storeId = "")
+ {
+ var key = string.Format(CacheKey.LANGUAGES_ALL_KEY, showHidden);
+ var languages = await _cacheBase.GetAsync(key, async () =>
{
- if (string.IsNullOrEmpty(languageCode))
- throw new ArgumentNullException(nameof(languageCode));
-
- var key = string.Format(CacheKey.LANGUAGES_BY_CODE, languageCode);
- return await _cacheBase.GetAsync(key, async () =>
- {
- var query = from q in _languageRepository.Table
- where q.UniqueSeoCode.ToLowerInvariant() == languageCode.ToLowerInvariant()
- select q;
- return await Task.FromResult(query.FirstOrDefault());
- });
-
- }
-
- /// <summary>
- /// Inserts a language
- /// </summary>
- /// <param name="language">Language</param>
- public virtual async Task InsertLanguage(Language language)
+ var query = from p in _languageRepository.Table
+ select p;
+
+ if (!showHidden)
+ query = query.Where(l => l.Published);
+ query = query.OrderBy(l => l.DisplayOrder);
+ return await Task.FromResult(query.ToList());
+ });
+
+ //store acl
+ if (!string.IsNullOrWhiteSpace(storeId))
+ languages = languages
+ .Where(l => l.Stores.Contains(storeId) || !l.LimitedToStores)
+ .ToList();
+ return languages;
+ }
+
+ /// <summary>
+ /// Gets a language
+ /// </summary>
+ /// <param name="languageId">Language identifier</param>
+ /// <returns>Language</returns>
+ public virtual Task<Language> GetLanguageById(string languageId)
+ {
+ var key = string.Format(CacheKey.LANGUAGES_BY_ID_KEY, languageId);
+ return _cacheBase.GetAsync(key, () => _languageRepository.GetByIdAsync(languageId));
+ }
+
+ /// <summary>
+ /// Gets a language
+ /// </summary>
+ /// <param name="languageCode">Language code</param>
+ /// <returns>Language</returns>
+ public virtual async Task<Language> GetLanguageByCode(string languageCode)
+ {
+ if (string.IsNullOrEmpty(languageCode))
+ throw new ArgumentNullException(nameof(languageCode));
+
+ var key = string.Format(CacheKey.LANGUAGES_BY_CODE, languageCode);
+ return await _cacheBase.GetAsync(key, async () =>
{
- ArgumentNullException.ThrowIfNull(language);
+ var query = from q in _languageRepository.Table
+ where q.UniqueSeoCode.ToLowerInvariant() == languageCode.ToLowerInvariant()
+ select q;
+ return await Task.FromResult(query.FirstOrDefault());
+ });
+ }
- await _languageRepository.InsertAsync(language);
+ /// <summary>
+ /// Inserts a language
+ /// </summary>
+ /// <param name="language">Language</param>
+ public virtual async Task InsertLanguage(Language language)
+ {
+ ArgumentNullException.ThrowIfNull(language);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.LANGUAGES_PATTERN_KEY);
+ await _languageRepository.InsertAsync(language);
- //event notification
- await _mediator.EntityInserted(language);
- }
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.LANGUAGES_PATTERN_KEY);
- /// <summary>
- /// Updates a language
- /// </summary>
- /// <param name="language">Language</param>
- public virtual async Task UpdateLanguage(Language language)
- {
- ArgumentNullException.ThrowIfNull(language);
-
- //update language
- await _languageRepository.UpdateAsync(language);
-
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.LANGUAGES_PATTERN_KEY);
-
- //event notification
- await _mediator.EntityUpdated(language);
- }
- /// <summary>
- /// Deletes a language
- /// </summary>
- /// <param name="language">Language</param>
- public virtual async Task DeleteLanguage(Language language)
- {
- ArgumentNullException.ThrowIfNull(language);
+ //event notification
+ await _mediator.EntityInserted(language);
+ }
+
+ /// <summary>
+ /// Updates a language
+ /// </summary>
+ /// <param name="language">Language</param>
+ public virtual async Task UpdateLanguage(Language language)
+ {
+ ArgumentNullException.ThrowIfNull(language);
- await _languageRepository.DeleteAsync(language);
+ //update language
+ await _languageRepository.UpdateAsync(language);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.LANGUAGES_PATTERN_KEY);
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.LANGUAGES_PATTERN_KEY);
- //event notification
- await _mediator.EntityDeleted(language);
- }
+ //event notification
+ await _mediator.EntityUpdated(language);
+ }
- #endregion
+ /// <summary>
+ /// Deletes a language
+ /// </summary>
+ /// <param name="language">Language</param>
+ public virtual async Task DeleteLanguage(Language language)
+ {
+ ArgumentNullException.ThrowIfNull(language);
+
+ await _languageRepository.DeleteAsync(language);
+
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.LANGUAGES_PATTERN_KEY);
+
+ //event notification
+ await _mediator.EntityDeleted(language);
}
-}
+
+ #endregion
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs b/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs
index 7ed520f76..92b7c321d 100644
--- a/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs
+++ b/src/Business/Grand.Business.Common/Services/Localization/TranslationService.cs
@@ -9,351 +9,352 @@ using System.Collections.Concurrent;
using System.Xml;
using System.Xml.Schema;
-namespace Grand.Business.Common.Services.Localization
+namespace Grand.Business.Common.Services.Localization;
+
+/// <summary>
+/// Provides information about translations
+/// </summary>
+public class TranslationService : ITranslationService
{
+ #region Ctor
+
/// <summary>
- /// Provides information about translations
+ /// Ctor
/// </summary>
- public class TranslationService : ITranslationService
+ /// <param name="workContext">Work context</param>
+ /// <param name="trRepository">Translate resource repository</param>
+ /// <param name="mediator">Mediator</param>
+ public TranslationService(
+ IWorkContext workContext,
+ IRepository<TranslationResource> trRepository,
+ IMediator mediator)
{
- #region Fields
-
- private static readonly ConcurrentDictionary<string, IDictionary<string, string>> _cachedResources = new();
-
- private readonly IRepository<TranslationResource> _translationRepository;
- private readonly IWorkContext _workContext;
- private readonly IMediator _mediator;
+ _workContext = workContext;
+ _translationRepository = trRepository;
+ _mediator = mediator;
+ }
- #endregion
+ #endregion
- #region Ctor
+ #region Fields
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="workContext">Work context</param>
- /// <param name="trRepository">Translate resource repository</param>
- /// <param name="mediator">Mediator</param>
- public TranslationService(
- IWorkContext workContext,
- IRepository<TranslationResource> trRepository,
- IMediator mediator)
- {
- _workContext = workContext;
- _translationRepository = trRepository;
- _mediator = mediator;
- }
+ private static readonly ConcurrentDictionary<string, IDictionary<string, string>> _cachedResources = new();
- #endregion
+ private readonly IRepository<TranslationResource> _translationRepository;
+ private readonly IWorkContext _workContext;
+ private readonly IMediator _mediator;
- #region Methods
+ #endregion
- /// <summary>
- /// Gets a translate resource
- /// </summary>
- /// <param name="translateResourceId">Translate resource identifier</param>
- /// <returns>Translate resource</returns>
- public virtual Task<TranslationResource> GetTranslateResourceById(string translateResourceId)
- {
- return _translationRepository.GetByIdAsync(translateResourceId);
- }
+ #region Methods
- /// <summary>
- /// Gets a translate resource
- /// </summary>
- /// <param name="name">A string representing a name</param>
- /// <param name="languageId">Language identifier</param>
- /// <returns>Translate resource</returns>
- public virtual async Task<TranslationResource> GetTranslateResourceByName(string name, string languageId)
- {
- var query = from lsr in _translationRepository.Table
- orderby lsr.Name
- where lsr.LanguageId == languageId && lsr.Name == name
- select lsr;
- var translateResource = await Task.FromResult(query.FirstOrDefault());
- return translateResource;
- }
+ /// <summary>
+ /// Gets a translate resource
+ /// </summary>
+ /// <param name="translateResourceId">Translate resource identifier</param>
+ /// <returns>Translate resource</returns>
+ public virtual Task<TranslationResource> GetTranslateResourceById(string translateResourceId)
+ {
+ return _translationRepository.GetByIdAsync(translateResourceId);
+ }
- /// <summary>
- /// Gets all translate resources by language identifier
- /// </summary>
- /// <param name="languageId">Language identifier</param>
- /// <returns>Translate resources</returns>
- public virtual IList<TranslationResource> GetAllResources(string languageId)
- {
- return _translationRepository.Table.Where(x => x.LanguageId == languageId).ToList();
- }
+ /// <summary>
+ /// Gets a translate resource
+ /// </summary>
+ /// <param name="name">A string representing a name</param>
+ /// <param name="languageId">Language identifier</param>
+ /// <returns>Translate resource</returns>
+ public virtual async Task<TranslationResource> GetTranslateResourceByName(string name, string languageId)
+ {
+ var query = from lsr in _translationRepository.Table
+ orderby lsr.Name
+ where lsr.LanguageId == languageId && lsr.Name == name
+ select lsr;
+ var translateResource = await Task.FromResult(query.FirstOrDefault());
+ return translateResource;
+ }
- /// <summary>
- /// Inserts a translate resource
- /// </summary>
- /// <param name="translateResource">Translate resource</param>
- public virtual async Task InsertTranslateResource(TranslationResource translateResource)
- {
- ArgumentNullException.ThrowIfNull(translateResource);
+ /// <summary>
+ /// Gets all translate resources by language identifier
+ /// </summary>
+ /// <param name="languageId">Language identifier</param>
+ /// <returns>Translate resources</returns>
+ public virtual IList<TranslationResource> GetAllResources(string languageId)
+ {
+ return _translationRepository.Table.Where(x => x.LanguageId == languageId).ToList();
+ }
- translateResource.Name = translateResource.Name.ToLowerInvariant();
- await _translationRepository.InsertAsync(translateResource);
+ /// <summary>
+ /// Inserts a translate resource
+ /// </summary>
+ /// <param name="translateResource">Translate resource</param>
+ public virtual async Task InsertTranslateResource(TranslationResource translateResource)
+ {
+ ArgumentNullException.ThrowIfNull(translateResource);
- await RefreshCachedResources(translateResource.LanguageId);
+ translateResource.Name = translateResource.Name.ToLowerInvariant();
+ await _translationRepository.InsertAsync(translateResource);
- //event notification
- await _mediator.EntityInserted(translateResource);
- }
+ await RefreshCachedResources(translateResource.LanguageId);
- /// <summary>
- /// Updates the translate resource
- /// </summary>
- /// <param name="translateResource">Translate resource</param>
- public virtual async Task UpdateTranslateResource(TranslationResource translateResource)
- {
- ArgumentNullException.ThrowIfNull(translateResource);
+ //event notification
+ await _mediator.EntityInserted(translateResource);
+ }
- translateResource.Name = translateResource.Name.ToLowerInvariant();
- await _translationRepository.UpdateAsync(translateResource);
+ /// <summary>
+ /// Updates the translate resource
+ /// </summary>
+ /// <param name="translateResource">Translate resource</param>
+ public virtual async Task UpdateTranslateResource(TranslationResource translateResource)
+ {
+ ArgumentNullException.ThrowIfNull(translateResource);
- //cache
- await RefreshCachedResources(translateResource.LanguageId);
+ translateResource.Name = translateResource.Name.ToLowerInvariant();
+ await _translationRepository.UpdateAsync(translateResource);
- //event notification
- await _mediator.EntityUpdated(translateResource);
- }
+ //cache
+ await RefreshCachedResources(translateResource.LanguageId);
+ //event notification
+ await _mediator.EntityUpdated(translateResource);
+ }
- /// <summary>
- /// Deletes a translate resource
- /// </summary>
- /// <param name="translateResource">Translate resource</param>
- public virtual async Task DeleteTranslateResource(TranslationResource translateResource)
- {
- ArgumentNullException.ThrowIfNull(translateResource);
- await _translationRepository.DeleteAsync(translateResource);
+ /// <summary>
+ /// Deletes a translate resource
+ /// </summary>
+ /// <param name="translateResource">Translate resource</param>
+ public virtual async Task DeleteTranslateResource(TranslationResource translateResource)
+ {
+ ArgumentNullException.ThrowIfNull(translateResource);
- //cache
- await RefreshCachedResources(translateResource.LanguageId);
+ await _translationRepository.DeleteAsync(translateResource);
- //event notification
- await _mediator.EntityDeleted(translateResource);
- }
+ //cache
+ await RefreshCachedResources(translateResource.LanguageId);
- /// <summary>
- /// Gets a resource string based on the specified ResourceKey property.
- /// </summary>
- /// <param name="name">A string representing a name.</param>
- /// <returns>A string representing the requested resource string.</returns>
- public virtual string GetResource(string name)
- {
- return _workContext.WorkingLanguage != null ? GetResource(name, _workContext.WorkingLanguage.Id) : "";
- }
+ //event notification
+ await _mediator.EntityDeleted(translateResource);
+ }
- /// <summary>
- /// Gets a resource string based on the specified ResourceKey property.
- /// </summary>
- /// <param name="name">A string representing a name.</param>
- /// <param name="languageId">Language identifier</param>
- /// <param name="defaultValue">Default value</param>
- /// <param name="returnEmptyIfNotFound">A value indicating whether an empty string will be returned if a resource is not found and default value is set to empty string</param>
- /// <returns>A string representing the requested resource string.</returns>
- public virtual string GetResource(string name, string languageId, string defaultValue = "", bool returnEmptyIfNotFound = false)
- {
- name ??= string.Empty;
- name = name.Trim().ToLowerInvariant();
+ /// <summary>
+ /// Gets a resource string based on the specified ResourceKey property.
+ /// </summary>
+ /// <param name="name">A string representing a name.</param>
+ /// <returns>A string representing the requested resource string.</returns>
+ public virtual string GetResource(string name)
+ {
+ return _workContext.WorkingLanguage != null ? GetResource(name, _workContext.WorkingLanguage.Id) : "";
+ }
- var result = GetOrAddToStaticCache(languageId, name);
+ /// <summary>
+ /// Gets a resource string based on the specified ResourceKey property.
+ /// </summary>
+ /// <param name="name">A string representing a name.</param>
+ /// <param name="languageId">Language identifier</param>
+ /// <param name="defaultValue">Default value</param>
+ /// <param name="returnEmptyIfNotFound">
+ /// A value indicating whether an empty string will be returned if a resource is not
+ /// found and default value is set to empty string
+ /// </param>
+ /// <returns>A string representing the requested resource string.</returns>
+ public virtual string GetResource(string name, string languageId, string defaultValue = "",
+ bool returnEmptyIfNotFound = false)
+ {
+ name ??= string.Empty;
+ name = name.Trim().ToLowerInvariant();
- if (!string.IsNullOrEmpty(result))
- return result;
+ var result = GetOrAddToStaticCache(languageId, name);
- if (!string.IsNullOrEmpty(defaultValue)) result = defaultValue;
- else if (!returnEmptyIfNotFound) result = name;
+ if (!string.IsNullOrEmpty(result))
return result;
- }
- /// <summary>
- /// Export language resources to xml
- /// </summary>
- /// <param name="language">Language</param>
- /// <returns>Result in XML format</returns>
- public virtual async Task<string> ExportResourcesToXml(Language language)
- {
- ArgumentNullException.ThrowIfNull(language);
- var sb = new StringBuilder();
-
- var xwSettings = new XmlWriterSettings {
- ConformanceLevel = ConformanceLevel.Auto,
- Async = true
- };
-
- await using var stringWriter = new StringWriter(sb);
- await using var xmlWriter = XmlWriter.Create(stringWriter, xwSettings);
- await xmlWriter.WriteStartDocumentAsync();
- xmlWriter.WriteStartElement("Language");
- xmlWriter.WriteAttributeString("Name", language.Name);
-
- var resources = GetAllResources(language.Id);
- foreach (var resource in resources)
- {
- xmlWriter.WriteStartElement("Resource");
- xmlWriter.WriteAttributeString("Name", resource.Name);
- xmlWriter.WriteAttributeString("Area", resource.Area.ToString());
- xmlWriter.WriteElementString("Value", null, resource.Value);
- await xmlWriter.WriteEndElementAsync();
- }
+ if (!string.IsNullOrEmpty(defaultValue)) result = defaultValue;
+ else if (!returnEmptyIfNotFound) result = name;
+ return result;
+ }
+ /// <summary>
+ /// Export language resources to xml
+ /// </summary>
+ /// <param name="language">Language</param>
+ /// <returns>Result in XML format</returns>
+ public virtual async Task<string> ExportResourcesToXml(Language language)
+ {
+ ArgumentNullException.ThrowIfNull(language);
+ var sb = new StringBuilder();
+
+ var xwSettings = new XmlWriterSettings {
+ ConformanceLevel = ConformanceLevel.Auto,
+ Async = true
+ };
+
+ await using var stringWriter = new StringWriter(sb);
+ await using var xmlWriter = XmlWriter.Create(stringWriter, xwSettings);
+ await xmlWriter.WriteStartDocumentAsync();
+ xmlWriter.WriteStartElement("Language");
+ xmlWriter.WriteAttributeString("Name", language.Name);
+
+ var resources = GetAllResources(language.Id);
+ foreach (var resource in resources)
+ {
+ xmlWriter.WriteStartElement("Resource");
+ xmlWriter.WriteAttributeString("Name", resource.Name);
+ xmlWriter.WriteAttributeString("Area", resource.Area.ToString());
+ xmlWriter.WriteElementString("Value", null, resource.Value);
await xmlWriter.WriteEndElementAsync();
- await xmlWriter.WriteEndDocumentAsync();
- await xmlWriter.FlushAsync();
- return stringWriter.ToString();
}
- /// <summary>
- /// Import language resources from XML file
- /// </summary>
- /// <param name="language">Language</param>
- /// <param name="xml">XML</param>
- public virtual async Task ImportResourcesFromXml(Language language, string xml)
- {
- ArgumentNullException.ThrowIfNull(language);
+ await xmlWriter.WriteEndElementAsync();
+ await xmlWriter.WriteEndDocumentAsync();
+ await xmlWriter.FlushAsync();
+ return stringWriter.ToString();
+ }
- if (string.IsNullOrEmpty(xml))
- return;
+ /// <summary>
+ /// Import language resources from XML file
+ /// </summary>
+ /// <param name="language">Language</param>
+ /// <param name="xml">XML</param>
+ public virtual async Task ImportResourcesFromXml(Language language, string xml)
+ {
+ ArgumentNullException.ThrowIfNull(language);
+
+ if (string.IsNullOrEmpty(xml))
+ return;
- var xmlDoc = LanguageXmlDocument(xml);
+ var xmlDoc = LanguageXmlDocument(xml);
- var nodes = xmlDoc.SelectNodes("//Language/Resource");
- if (nodes != null)
- foreach (XmlNode node in nodes)
+ var nodes = xmlDoc.SelectNodes("//Language/Resource");
+ if (nodes != null)
+ foreach (XmlNode node in nodes)
+ {
+ var name = node.Attributes?["Name"]?.InnerText.Trim();
+ var area = node.Attributes?["Area"]?.InnerText.Trim();
+ var value = "";
+ var valueNode = node.SelectSingleNode("Value");
+ if (valueNode != null)
+ value = valueNode.InnerText;
+
+ if (string.IsNullOrEmpty(name))
+ continue;
+
+ //bulk insert
+ var resource = (from l in _translationRepository.Table
+ where l.Name == name.ToLowerInvariant() && l.LanguageId == language.Id
+ select l).FirstOrDefault();
+
+ if (resource != null)
{
- var name = node.Attributes?["Name"]?.InnerText.Trim();
- var area = node.Attributes?["Area"]?.InnerText.Trim();
- var value = "";
- var valueNode = node.SelectSingleNode("Value");
- if (valueNode != null)
- value = valueNode.InnerText;
-
- if (string.IsNullOrEmpty(name))
- continue;
-
- //bulk insert
- var resource = (from l in _translationRepository.Table
- where l.Name == name.ToLowerInvariant() && l.LanguageId == language.Id
- select l).FirstOrDefault();
-
- if (resource != null)
- {
- resource.Name = resource.Name.ToLowerInvariant();
- resource.Value = value;
- if (Enum.TryParse<TranslationResourceArea>(area, out var areaEnum))
- resource.Area = areaEnum;
- await _translationRepository.UpdateAsync(resource);
- }
- else
- {
- _ = Enum.TryParse(area, out TranslationResourceArea areaEnum);
- await _translationRepository.InsertAsync(new TranslationResource {
- LanguageId = language.Id,
- Name = name.ToLowerInvariant(),
- Value = value,
- Area = areaEnum,
- CreatedBy = _workContext.CurrentCustomer.Email
- });
- }
+ resource.Name = resource.Name.ToLowerInvariant();
+ resource.Value = value;
+ if (Enum.TryParse<TranslationResourceArea>(area, out var areaEnum))
+ resource.Area = areaEnum;
+ await _translationRepository.UpdateAsync(resource);
}
-
- await RefreshCachedResources(language.Id);
- }
-
- /// <summary>
- /// Import language resources from XML file
- /// </summary>
- /// <param name="language">Language</param>
- /// <param name="xml">XML</param>
- public virtual async Task ImportResourcesFromXmlInstall(Language language, string xml)
- {
- ArgumentNullException.ThrowIfNull(language);
-
- if (string.IsNullOrEmpty(xml))
- return;
-
- var xmlDoc = LanguageXmlDocument(xml);
-
- var translateResources = new List<TranslationResource>();
-
- var nodes = xmlDoc.SelectNodes("//Language/Resource");
- if (nodes != null)
- foreach (XmlNode node in nodes)
+ else
{
- var name = node.Attributes?["Name"]?.InnerText.Trim();
- var area = node.Attributes?["Area"]?.InnerText.Trim();
- var value = "";
- var valueNode = node.SelectSingleNode("Value");
- if (valueNode != null)
- value = valueNode.InnerText;
-
- if (string.IsNullOrEmpty(name))
- continue;
-
_ = Enum.TryParse(area, out TranslationResourceArea areaEnum);
-
await _translationRepository.InsertAsync(new TranslationResource {
LanguageId = language.Id,
Name = name.ToLowerInvariant(),
Value = value,
Area = areaEnum,
- CreatedBy = "System"
+ CreatedBy = _workContext.CurrentCustomer.Email
});
}
+ }
- await RefreshCachedResources(language.Id);
- }
-
- private string GetOrAddToStaticCache(string languageId, string name)
- {
- if (_cachedResources.TryGetValue(languageId, out var languageResources))
- {
- languageResources.TryGetValue(name, out var cachedResult);
- return cachedResult;
- }
- var value = CreateLanguageResourcesDictionary(languageId);
- _cachedResources.TryAdd(languageId, value);
- value.TryGetValue(name, out var result);
- return result;
- }
+ await RefreshCachedResources(language.Id);
+ }
- private Task RefreshCachedResources(string languageId)
- {
- if (_cachedResources.ContainsKey(languageId))
+ /// <summary>
+ /// Import language resources from XML file
+ /// </summary>
+ /// <param name="language">Language</param>
+ /// <param name="xml">XML</param>
+ public virtual async Task ImportResourcesFromXmlInstall(Language language, string xml)
+ {
+ ArgumentNullException.ThrowIfNull(language);
+
+ if (string.IsNullOrEmpty(xml))
+ return;
+
+ var xmlDoc = LanguageXmlDocument(xml);
+
+ var translateResources = new List<TranslationResource>();
+
+ var nodes = xmlDoc.SelectNodes("//Language/Resource");
+ if (nodes != null)
+ foreach (XmlNode node in nodes)
{
- _cachedResources.TryRemove(languageId, out _);
+ var name = node.Attributes?["Name"]?.InnerText.Trim();
+ var area = node.Attributes?["Area"]?.InnerText.Trim();
+ var value = "";
+ var valueNode = node.SelectSingleNode("Value");
+ if (valueNode != null)
+ value = valueNode.InnerText;
+
+ if (string.IsNullOrEmpty(name))
+ continue;
+
+ _ = Enum.TryParse(area, out TranslationResourceArea areaEnum);
+
+ await _translationRepository.InsertAsync(new TranslationResource {
+ LanguageId = language.Id,
+ Name = name.ToLowerInvariant(),
+ Value = value,
+ Area = areaEnum,
+ CreatedBy = "System"
+ });
}
- _cachedResources.TryAdd(languageId, CreateLanguageResourcesDictionary(languageId));
- return Task.CompletedTask;
- }
+ await RefreshCachedResources(language.Id);
+ }
- private Dictionary<string, string> CreateLanguageResourcesDictionary(string languageId)
+ private string GetOrAddToStaticCache(string languageId, string name)
+ {
+ if (_cachedResources.TryGetValue(languageId, out var languageResources))
{
- return GetAllResources(languageId)
- .GroupBy(r => r.Name)
- .ToDictionary(
- keySelector: g => g.Key,
- elementSelector: g => g.First().Value);
+ languageResources.TryGetValue(name, out var cachedResult);
+ return cachedResult;
}
- private static XmlDocument LanguageXmlDocument(string xml)
- {
- var schemas = new XmlSchemaSet();
- schemas.Add("", XmlReader.Create(new StringReader(LanguageSchema.SchemaXsd)));
+ var value = CreateLanguageResourcesDictionary(languageId);
+ _cachedResources.TryAdd(languageId, value);
+ value.TryGetValue(name, out var result);
+ return result;
+ }
- var xmlDoc = new XmlDocument { Schemas = schemas, XmlResolver = null };
- xmlDoc.LoadXml(xml);
+ private Task RefreshCachedResources(string languageId)
+ {
+ if (_cachedResources.ContainsKey(languageId)) _cachedResources.TryRemove(languageId, out _);
+ _cachedResources.TryAdd(languageId, CreateLanguageResourcesDictionary(languageId));
- // Validate XML.
- xmlDoc.Validate((_, e) => throw new XmlException("XML data does not conform to the schema", e.Exception));
- return xmlDoc;
- }
+ return Task.CompletedTask;
+ }
- #endregion
+ private Dictionary<string, string> CreateLanguageResourcesDictionary(string languageId)
+ {
+ return GetAllResources(languageId)
+ .GroupBy(r => r.Name)
+ .ToDictionary(
+ g => g.Key,
+ g => g.First().Value);
}
+
+ private static XmlDocument LanguageXmlDocument(string xml)
+ {
+ var schemas = new XmlSchemaSet();
+ schemas.Add("", XmlReader.Create(new StringReader(LanguageSchema.SchemaXsd)));
+
+ var xmlDoc = new XmlDocument { Schemas = schemas, XmlResolver = null };
+ xmlDoc.LoadXml(xml);
+
+ // Validate XML.
+ xmlDoc.Validate((_, e) => throw new XmlException("XML data does not conform to the schema", e.Exception));
+ return xmlDoc;
+ }
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Pdf/HtmlToPdfService.cs b/src/Business/Grand.Business.Common/Services/Pdf/HtmlToPdfService.cs
index 7dec69f3c..d15ea74c9 100644
--- a/src/Business/Grand.Business.Common/Services/Pdf/HtmlToPdfService.cs
+++ b/src/Business/Grand.Business.Common/Services/Pdf/HtmlToPdfService.cs
@@ -5,104 +5,103 @@ using Grand.Domain.Media;
using Grand.Domain.Orders;
using Grand.Domain.Shipping;
using Grand.SharedKernel.Extensions;
+using Scryber;
+using Scryber.Components;
+using Path = System.IO.Path;
-namespace Grand.Business.Common.Services.Pdf
+namespace Grand.Business.Common.Services.Pdf;
+
+/// <summary>
+/// Generate invoice, shipment as pdf (from html template to pdf)
+/// </summary>
+public class HtmlToPdfService : IPdfService
{
- /// <summary>
- /// Generate invoice, shipment as pdf (from html template to pdf)
- /// </summary>
- public class HtmlToPdfService : IPdfService
+ private const string OrderTemplate = "~/Views/PdfTemplates/OrderPdfTemplate.cshtml";
+ private const string ShipmentsTemplate = "~/Views/PdfTemplates/ShipmentPdfTemplate.cshtml";
+ private readonly IRepository<Download> _downloadRepository;
+ private readonly ILanguageService _languageService;
+ private readonly IStoreFilesContext _storeFilesContext;
+
+ private readonly IViewRenderService _viewRenderService;
+
+ public HtmlToPdfService(IViewRenderService viewRenderService, IRepository<Download> downloadRepository,
+ ILanguageService languageService, IStoreFilesContext storeFilesContext)
+ {
+ _viewRenderService = viewRenderService;
+ _languageService = languageService;
+ _downloadRepository = downloadRepository;
+ _storeFilesContext = storeFilesContext;
+ }
+
+ public async Task PrintOrdersToPdf(Stream stream, IList<Order> orders, string languageId = "",
+ string vendorId = "")
+ {
+ ArgumentNullException.ThrowIfNull(stream);
+ ArgumentNullException.ThrowIfNull(orders);
+
+ var html = await _viewRenderService.RenderToStringAsync(OrderTemplate,
+ new ValueTuple<IList<Order>, string>(orders, vendorId));
+ TextReader sr = new StringReader(html);
+ using var doc = Document.ParseDocument(sr, ParseSourceType.DynamicContent);
+ doc.SaveAsPDF(stream);
+ }
+
+ public async Task<string> PrintOrderToPdf(Order order, string languageId, string vendorId = "")
+ {
+ ArgumentNullException.ThrowIfNull(order);
+
+ var fileName = $"order_{order.OrderGuid}_{CommonHelper.GenerateRandomDigitCode(4)}.pdf";
+
+ var dir = CommonPath.WebMapPath("assets/files/exportimport");
+ if (dir == null)
+ throw new ArgumentNullException(nameof(dir));
+
+ if (!System.IO.Directory.Exists(dir)) System.IO.Directory.CreateDirectory(dir);
+
+ var filePath = Path.Combine(dir, fileName);
+ await using var fileStream = new FileStream(filePath, FileMode.Create);
+ var orders = new List<Order> {
+ order
+ };
+ await PrintOrdersToPdf(fileStream, orders, languageId, vendorId);
+ return filePath;
+ }
+
+ public async Task PrintPackagingSlipsToPdf(Stream stream, IList<Shipment> shipments, string languageId = "")
+ {
+ ArgumentNullException.ThrowIfNull(stream);
+ ArgumentNullException.ThrowIfNull(shipments);
+
+ var lang = await _languageService.GetLanguageById(languageId);
+ if (lang == null)
+ throw new ArgumentException($"Cannot load language. ID={languageId}");
+
+ var html = await _viewRenderService.RenderToStringAsync(ShipmentsTemplate, shipments);
+ TextReader sr = new StringReader(html);
+ using var doc = Document.ParseDocument(sr, ParseSourceType.DynamicContent);
+ doc.SaveAsPDF(stream);
+ }
+
+ public async Task<string> SaveOrderToBinary(Order order, string languageId, string vendorId = "")
{
- private const string OrderTemplate = "~/Views/PdfTemplates/OrderPdfTemplate.cshtml";
- private const string ShipmentsTemplate = "~/Views/PdfTemplates/ShipmentPdfTemplate.cshtml";
-
- private readonly IViewRenderService _viewRenderService;
- private readonly ILanguageService _languageService;
- private readonly IRepository<Download> _downloadRepository;
- private readonly IStoreFilesContext _storeFilesContext;
-
- public HtmlToPdfService(IViewRenderService viewRenderService, IRepository<Download> downloadRepository,
- ILanguageService languageService, IStoreFilesContext storeFilesContext)
- {
- _viewRenderService = viewRenderService;
- _languageService = languageService;
- _downloadRepository = downloadRepository;
- _storeFilesContext = storeFilesContext;
- }
-
- public async Task PrintOrdersToPdf(Stream stream, IList<Order> orders, string languageId = "",
- string vendorId = "")
- {
- ArgumentNullException.ThrowIfNull(stream);
- ArgumentNullException.ThrowIfNull(orders);
-
- var html = await _viewRenderService.RenderToStringAsync<(IList<Order>, string)>(OrderTemplate,
- new(orders, vendorId));
- TextReader sr = new StringReader(html);
- using var doc = Scryber.Components.Document.ParseDocument(sr, Scryber.ParseSourceType.DynamicContent);
- doc.SaveAsPDF(stream);
- }
-
- public async Task<string> PrintOrderToPdf(Order order, string languageId, string vendorId = "")
- {
- ArgumentNullException.ThrowIfNull(order);
-
- var fileName = $"order_{order.OrderGuid}_{CommonHelper.GenerateRandomDigitCode(4)}.pdf";
-
- var dir = CommonPath.WebMapPath("assets/files/exportimport");
- if (dir == null)
- throw new ArgumentNullException(nameof(dir));
-
- if (!System.IO.Directory.Exists(dir))
- {
- System.IO.Directory.CreateDirectory(dir);
- }
-
- var filePath = Path.Combine(dir, fileName);
- await using var fileStream = new FileStream(filePath, FileMode.Create);
- var orders = new List<Order> {
- order
- };
- await PrintOrdersToPdf(fileStream, orders, languageId, vendorId);
- return filePath;
- }
-
- public async Task PrintPackagingSlipsToPdf(Stream stream, IList<Shipment> shipments, string languageId = "")
- {
- ArgumentNullException.ThrowIfNull(stream);
- ArgumentNullException.ThrowIfNull(shipments);
-
- var lang = await _languageService.GetLanguageById(languageId);
- if (lang == null)
- throw new ArgumentException($"Cannot load language. ID={languageId}");
-
- var html = await _viewRenderService.RenderToStringAsync<IList<Shipment>>(ShipmentsTemplate, shipments);
- TextReader sr = new StringReader(html);
- using var doc = Scryber.Components.Document.ParseDocument(sr, Scryber.ParseSourceType.DynamicContent);
- doc.SaveAsPDF(stream);
- }
-
- public async Task<string> SaveOrderToBinary(Order order, string languageId, string vendorId = "")
- {
- ArgumentNullException.ThrowIfNull(order);
-
- var fileName = $"order_{order.OrderGuid}_{CommonHelper.GenerateRandomDigitCode(4)}";
- using MemoryStream ms = new MemoryStream();
- var orders = new List<Order> {
- order
- };
- await PrintOrdersToPdf(ms, orders, languageId, vendorId);
- var download = new Download {
- Filename = fileName,
- Extension = ".pdf",
- ContentType = "application/pdf"
- };
-
- download.DownloadObjectId = await _storeFilesContext.BucketUploadFromBytes(download.Filename, ms.ToArray());
- await _downloadRepository.InsertAsync(download);
-
- //await _mediator.EntityInserted(download);
- return download.Id;
- }
+ ArgumentNullException.ThrowIfNull(order);
+
+ var fileName = $"order_{order.OrderGuid}_{CommonHelper.GenerateRandomDigitCode(4)}";
+ using var ms = new MemoryStream();
+ var orders = new List<Order> {
+ order
+ };
+ await PrintOrdersToPdf(ms, orders, languageId, vendorId);
+ var download = new Download {
+ Filename = fileName,
+ Extension = ".pdf",
+ ContentType = "application/pdf"
+ };
+
+ download.DownloadObjectId = await _storeFilesContext.BucketUploadFromBytes(download.Filename, ms.ToArray());
+ await _downloadRepository.InsertAsync(download);
+
+ //await _mediator.EntityInserted(download);
+ return download.Id;
}
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Security/AclService.cs b/src/Business/Grand.Business.Common/Services/Security/AclService.cs
index 651f2b46a..771622c55 100644
--- a/src/Business/Grand.Business.Common/Services/Security/AclService.cs
+++ b/src/Business/Grand.Business.Common/Services/Security/AclService.cs
@@ -5,77 +5,76 @@ using Grand.Domain.Permissions;
using Grand.Domain.Stores;
using Grand.Infrastructure.Configuration;
-namespace Grand.Business.Common.Services.Security
+namespace Grand.Business.Common.Services.Security;
+
+/// <summary>
+/// ACL service
+/// </summary>
+public class AclService : IAclService
{
+ #region Fields
+
+ private readonly AccessControlConfig _accessControlConfig;
+
+ #endregion
+
+ #region Ctor
+
+ /// <summary>
+ /// Ctor
+ /// </summary>
+ public AclService(AccessControlConfig accessControlConfig)
+ {
+ _accessControlConfig = accessControlConfig;
+ }
+
+ #endregion
+
+ #region Methods
+
/// <summary>
- /// ACL service
+ /// Authorize ACL permission
/// </summary>
- public class AclService : IAclService
+ /// <typeparam name="T">Type</typeparam>
+ /// <param name="entity">Entity</param>
+ /// <param name="customer">Customer</param>
+ /// <returns>true - authorized; otherwise, false</returns>
+ public virtual bool Authorize<T>(T entity, Customer customer) where T : BaseEntity, IGroupLinkEntity
{
- #region Fields
-
- private readonly AccessControlConfig _accessControlConfig;
-
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- public AclService(AccessControlConfig accessControlConfig)
- {
- _accessControlConfig = accessControlConfig;
- }
-
- #endregion
-
- #region Methods
-
-
- /// <summary>
- /// Authorize ACL permission
- /// </summary>
- /// <typeparam name="T">Type</typeparam>
- /// <param name="entity">Entity</param>
- /// <param name="customer">Customer</param>
- /// <returns>true - authorized; otherwise, false</returns>
- public virtual bool Authorize<T>(T entity, Customer customer) where T : BaseEntity, IGroupLinkEntity
- {
- if (entity == null)
- return false;
-
- if (customer == null)
- return false;
-
- if (!entity.LimitedToGroups)
- return true;
-
- return _accessControlConfig.IgnoreAcl || customer.Groups.Any(role1 => entity.CustomerGroups.Any(role2Id => role1 == role2Id));
- }
-
- /// <summary>
- /// Authorize whether entity could be accessed in a store (mapped to this store)
- /// </summary>
- /// <typeparam name="T">Type</typeparam>
- /// <param name="entity">Entity</param>
- /// <param name="storeId">Store identifier</param>
- /// <returns>true - authorized; otherwise, false</returns>
- public virtual bool Authorize<T>(T entity, string storeId) where T : BaseEntity, IStoreLinkEntity
- {
- if (entity == null)
- return false;
-
- if (string.IsNullOrEmpty(storeId))
- //return true if no store specified/found
- return true;
-
- if (_accessControlConfig.IgnoreStoreLimitations)
- return true;
-
- return !entity.LimitedToStores || entity.Stores.Any(storeIdWithAccess => storeId == storeIdWithAccess);
- }
-
- #endregion
+ if (entity == null)
+ return false;
+
+ if (customer == null)
+ return false;
+
+ if (!entity.LimitedToGroups)
+ return true;
+
+ return _accessControlConfig.IgnoreAcl ||
+ customer.Groups.Any(role1 => entity.CustomerGroups.Any(role2Id => role1 == role2Id));
+ }
+
+ /// <summary>
+ /// Authorize whether entity could be accessed in a store (mapped to this store)
+ /// </summary>
+ /// <typeparam name="T">Type</typeparam>
+ /// <param name="entity">Entity</param>
+ /// <param name="storeId">Store identifier</param>
+ /// <returns>true - authorized; otherwise, false</returns>
+ public virtual bool Authorize<T>(T entity, string storeId) where T : BaseEntity, IStoreLinkEntity
+ {
+ if (entity == null)
+ return false;
+
+ if (string.IsNullOrEmpty(storeId))
+ //return true if no store specified/found
+ return true;
+
+ if (_accessControlConfig.IgnoreStoreLimitations)
+ return true;
+
+ return !entity.LimitedToStores || entity.Stores.Any(storeIdWithAccess => storeId == storeIdWithAccess);
}
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Security/EncryptionService.cs b/src/Business/Grand.Business.Common/Services/Security/EncryptionService.cs
index 186ca5f3f..0036aa4d4 100644
--- a/src/Business/Grand.Business.Common/Services/Security/EncryptionService.cs
+++ b/src/Business/Grand.Business.Common/Services/Security/EncryptionService.cs
@@ -2,120 +2,119 @@
using Grand.Domain.Customers;
using System.Security.Cryptography;
-namespace Grand.Business.Common.Services.Security
+namespace Grand.Business.Common.Services.Security;
+
+public class EncryptionService : IEncryptionService
{
- public class EncryptionService : IEncryptionService
+ /// <summary>
+ /// Create salt key
+ /// </summary>
+ /// <param name="size">Key size</param>
+ /// <returns>Salt key</returns>
+ public virtual string CreateSaltKey(int size)
{
- /// <summary>
- /// Create salt key
- /// </summary>
- /// <param name="size">Key size</param>
- /// <returns>Salt key</returns>
- public virtual string CreateSaltKey(int size)
- {
- // Generate a cryptographic random number
- var rng = RandomNumberGenerator.Create();
+ // Generate a cryptographic random number
+ var rng = RandomNumberGenerator.Create();
- var buff = new byte[size];
- rng.GetBytes(buff);
+ var buff = new byte[size];
+ rng.GetBytes(buff);
- // Return a Base64 string representation of the random number
- return Convert.ToBase64String(buff);
- }
+ // Return a Base64 string representation of the random number
+ return Convert.ToBase64String(buff);
+ }
- /// <summary>
- /// Create a password hash
- /// </summary>
- /// <param name="password">password</param>
- /// <param name="saltKey">Salk key</param>
- /// <param name="passwordFormat"></param>
- /// <returns>Password hash</returns>
- public virtual string CreatePasswordHash(string password, string saltKey, HashedPasswordFormat passwordFormat = HashedPasswordFormat.SHA1)
- {
- var saltAndPassword = string.Concat(password, saltKey);
- HashAlgorithm algorithm = passwordFormat switch
- {
- HashedPasswordFormat.SHA1 => SHA1.Create(),
- HashedPasswordFormat.SHA256 => SHA256.Create(),
- HashedPasswordFormat.SHA384 => SHA384.Create(),
- HashedPasswordFormat.SHA512 => SHA512.Create(),
- _ => throw new NotSupportedException("Not supported format")
- };
- if (algorithm == null)
- throw new ArgumentException("Unrecognized hash name");
-
- var hashByteArray = algorithm.ComputeHash(Encoding.UTF8.GetBytes(saltAndPassword));
- return BitConverter.ToString(hashByteArray).Replace("-", "");
- }
+ /// <summary>
+ /// Create a password hash
+ /// </summary>
+ /// <param name="password">password</param>
+ /// <param name="saltKey">Salk key</param>
+ /// <param name="passwordFormat"></param>
+ /// <returns>Password hash</returns>
+ public virtual string CreatePasswordHash(string password, string saltKey,
+ HashedPasswordFormat passwordFormat = HashedPasswordFormat.SHA1)
+ {
+ var saltAndPassword = string.Concat(password, saltKey);
+ HashAlgorithm algorithm = passwordFormat switch {
+ HashedPasswordFormat.SHA1 => SHA1.Create(),
+ HashedPasswordFormat.SHA256 => SHA256.Create(),
+ HashedPasswordFormat.SHA384 => SHA384.Create(),
+ HashedPasswordFormat.SHA512 => SHA512.Create(),
+ _ => throw new NotSupportedException("Not supported format")
+ };
+ if (algorithm == null)
+ throw new ArgumentException("Unrecognized hash name");
+
+ var hashByteArray = algorithm.ComputeHash(Encoding.UTF8.GetBytes(saltAndPassword));
+ return BitConverter.ToString(hashByteArray).Replace("-", "");
+ }
- /// <summary>
- /// Encrypt text
- /// </summary>
- /// <param name="plainText">Text to encrypt</param>
- /// <param name="privateKey">Encryption private key</param>
- /// <returns>Encrypted text</returns>
- public virtual string EncryptText(string plainText, string privateKey)
- {
- if (string.IsNullOrEmpty(plainText))
- return plainText;
+ /// <summary>
+ /// Encrypt text
+ /// </summary>
+ /// <param name="plainText">Text to encrypt</param>
+ /// <param name="privateKey">Encryption private key</param>
+ /// <returns>Encrypted text</returns>
+ public virtual string EncryptText(string plainText, string privateKey)
+ {
+ if (string.IsNullOrEmpty(plainText))
+ return plainText;
- if (string.IsNullOrEmpty(privateKey) || privateKey.Length != 24)
- throw new Exception("Wrong private key");
+ if (string.IsNullOrEmpty(privateKey) || privateKey.Length != 24)
+ throw new Exception("Wrong private key");
- var tDes = TripleDES.Create();
+ var tDes = TripleDES.Create();
- tDes.Key = new ASCIIEncoding().GetBytes(privateKey);
- tDes.IV = new ASCIIEncoding().GetBytes(privateKey[^8..]);
+ tDes.Key = new ASCIIEncoding().GetBytes(privateKey);
+ tDes.IV = new ASCIIEncoding().GetBytes(privateKey[^8..]);
- var encryptedBinary = EncryptTextToMemory(plainText, tDes.Key, tDes.IV);
- return Convert.ToBase64String(encryptedBinary);
- }
+ var encryptedBinary = EncryptTextToMemory(plainText, tDes.Key, tDes.IV);
+ return Convert.ToBase64String(encryptedBinary);
+ }
- /// <summary>
- /// Decrypt text
- /// </summary>
- /// <param name="cipherText">Text to decrypt</param>
- /// <param name="encryptionPrivateKey">Encryption private key</param>
- /// <returns>Decrypted text</returns>
- public virtual string DecryptText(string cipherText, string encryptionPrivateKey)
- {
- if (string.IsNullOrEmpty(cipherText))
- return cipherText;
+ /// <summary>
+ /// Decrypt text
+ /// </summary>
+ /// <param name="cipherText">Text to decrypt</param>
+ /// <param name="encryptionPrivateKey">Encryption private key</param>
+ /// <returns>Decrypted text</returns>
+ public virtual string DecryptText(string cipherText, string encryptionPrivateKey)
+ {
+ if (string.IsNullOrEmpty(cipherText))
+ return cipherText;
- if (string.IsNullOrEmpty(encryptionPrivateKey) || encryptionPrivateKey.Length != 24)
- throw new Exception("Wrong encrypt private key");
+ if (string.IsNullOrEmpty(encryptionPrivateKey) || encryptionPrivateKey.Length != 24)
+ throw new Exception("Wrong encrypt private key");
- var tDes = TripleDES.Create();
- tDes.Key = new ASCIIEncoding().GetBytes(encryptionPrivateKey);
- tDes.IV = new ASCIIEncoding().GetBytes(encryptionPrivateKey[^8..]);
+ var tDes = TripleDES.Create();
+ tDes.Key = new ASCIIEncoding().GetBytes(encryptionPrivateKey);
+ tDes.IV = new ASCIIEncoding().GetBytes(encryptionPrivateKey[^8..]);
- var buffer = Convert.FromBase64String(cipherText);
- return DecryptTextFromMemory(buffer, tDes.Key, tDes.IV);
- }
+ var buffer = Convert.FromBase64String(cipherText);
+ return DecryptTextFromMemory(buffer, tDes.Key, tDes.IV);
+ }
- #region Utilities
+ #region Utilities
- private byte[] EncryptTextToMemory(string data, byte[] key, byte[] iv)
+ private byte[] EncryptTextToMemory(string data, byte[] key, byte[] iv)
+ {
+ using var ms = new MemoryStream();
+ using (var cs = new CryptoStream(ms, TripleDES.Create().CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
- using var ms = new MemoryStream();
- using (var cs = new CryptoStream(ms, TripleDES.Create().CreateEncryptor(key, iv), CryptoStreamMode.Write))
- {
- var toEncrypt = new UnicodeEncoding().GetBytes(data);
- cs.Write(toEncrypt, 0, toEncrypt.Length);
- cs.FlushFinalBlock();
- }
-
- return ms.ToArray();
+ var toEncrypt = new UnicodeEncoding().GetBytes(data);
+ cs.Write(toEncrypt, 0, toEncrypt.Length);
+ cs.FlushFinalBlock();
}
- private 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);
- var sr = new StreamReader(cs, new UnicodeEncoding());
- return sr.ReadLine();
- }
+ return ms.ToArray();
+ }
- #endregion
+ private 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);
+ var sr = new StreamReader(cs, new UnicodeEncoding());
+ return sr.ReadLine();
}
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Security/PermissionProvider.cs b/src/Business/Grand.Business.Common/Services/Security/PermissionProvider.cs
index bed22e751..02fde39cd 100644
--- a/src/Business/Grand.Business.Common/Services/Security/PermissionProvider.cs
+++ b/src/Business/Grand.Business.Common/Services/Security/PermissionProvider.cs
@@ -3,239 +3,224 @@ using Grand.Business.Core.Utilities.Common.Security;
using Grand.Domain.Customers;
using Grand.Domain.Permissions;
-namespace Grand.Business.Common.Services.Security
+namespace Grand.Business.Common.Services.Security;
+
+public class PermissionProvider : IPermissionProvider
{
- public class PermissionProvider : IPermissionProvider
+ public virtual IEnumerable<Permission> GetPermissions()
{
- public virtual IEnumerable<Permission> GetPermissions()
- {
- return new[]
- {
- StandardPermission.ManageAccessAdminPanel,
- StandardPermission.ManageAccessVendorPanel,
- StandardPermission.AllowCustomerImpersonation,
- StandardPermission.ManageProducts,
- StandardPermission.ManageCategories,
- StandardPermission.ManageBrands,
- StandardPermission.ManageCollections,
- StandardPermission.ManageProductReviews,
- StandardPermission.ManageProductTags,
- StandardPermission.ManageProductAttributes,
- StandardPermission.ManageSpecificationAttributes,
- StandardPermission.ManageCheckoutAttribute,
- StandardPermission.ManageContactAttribute,
- StandardPermission.ManageCustomers,
- StandardPermission.ManageCustomerGroups,
- StandardPermission.ManageCustomerTags,
- StandardPermission.ManageSalesEmployees,
- StandardPermission.ManageAddressAttribute,
- StandardPermission.ManageCustomerAttribute,
- StandardPermission.ManageVendors,
- StandardPermission.ManageVendorReviews,
- StandardPermission.ManageCurrentCarts,
- StandardPermission.ManageOrders,
- StandardPermission.ManageShipments,
- StandardPermission.ManageGiftVouchers,
- StandardPermission.ManageMerchandiseReturns,
- StandardPermission.ManagePaymentTransactions,
- StandardPermission.ManageDocuments,
- StandardPermission.ManageReports,
- StandardPermission.ManageAffiliates,
- StandardPermission.ManagePushEvents,
- StandardPermission.ManageCampaigns,
- StandardPermission.ManageDiscounts,
- StandardPermission.ManageNewsletterSubscribers,
- StandardPermission.ManageNewsletterCategories,
- StandardPermission.ManageNews,
- StandardPermission.ManageBlog,
- StandardPermission.ManageWidgets,
- StandardPermission.ManagePages,
- StandardPermission.ManageKnowledgebase,
- StandardPermission.ManageCourses,
- StandardPermission.ManageMessageTemplates,
- StandardPermission.ManageCountries,
- StandardPermission.ManageLanguages,
- StandardPermission.ManageSettings,
- StandardPermission.ManagePaymentMethods,
- StandardPermission.ManageExternalAuthenticationMethods,
- StandardPermission.ManageTaxSettings,
- StandardPermission.ManageShippingSettings,
- StandardPermission.ManageCurrencies,
- StandardPermission.ManageMeasures,
- StandardPermission.ManageAcl,
- StandardPermission.ManageEmailAccounts,
- StandardPermission.ManageStores,
- StandardPermission.ManagePlugins,
- StandardPermission.ManageMessageQueue,
- StandardPermission.ManageMessageContactForm,
- StandardPermission.ManageMaintenance,
- StandardPermission.ManageSystem,
- StandardPermission.ManageFiles,
- StandardPermission.ManagePictures,
- StandardPermission.HtmlEditorManagePictures,
- StandardPermission.ManageScheduleTasks,
- StandardPermission.DisplayPrices,
- StandardPermission.EnableShoppingCart,
- StandardPermission.EnableWishlist,
- StandardPermission.PublicStoreAllowNavigation,
- StandardPermission.AccessClosedStore,
- StandardPermission.ManageOrderTags,
- StandardPermission.ManageOrderStatus,
- StandardPermission.AllowUseApi
- };
- }
+ return new[] {
+ StandardPermission.ManageAccessAdminPanel,
+ StandardPermission.ManageAccessVendorPanel,
+ StandardPermission.AllowCustomerImpersonation,
+ StandardPermission.ManageProducts,
+ StandardPermission.ManageCategories,
+ StandardPermission.ManageBrands,
+ StandardPermission.ManageCollections,
+ StandardPermission.ManageProductReviews,
+ StandardPermission.ManageProductTags,
+ StandardPermission.ManageProductAttributes,
+ StandardPermission.ManageSpecificationAttributes,
+ StandardPermission.ManageCheckoutAttribute,
+ StandardPermission.ManageContactAttribute,
+ StandardPermission.ManageCustomers,
+ StandardPermission.ManageCustomerGroups,
+ StandardPermission.ManageCustomerTags,
+ StandardPermission.ManageSalesEmployees,
+ StandardPermission.ManageAddressAttribute,
+ StandardPermission.ManageCustomerAttribute,
+ StandardPermission.ManageVendors,
+ StandardPermission.ManageVendorReviews,
+ StandardPermission.ManageCurrentCarts,
+ StandardPermission.ManageOrders,
+ StandardPermission.ManageShipments,
+ StandardPermission.ManageGiftVouchers,
+ StandardPermission.ManageMerchandiseReturns,
+ StandardPermission.ManagePaymentTransactions,
+ StandardPermission.ManageDocuments,
+ StandardPermission.ManageReports,
+ StandardPermission.ManageAffiliates,
+ StandardPermission.ManagePushEvents,
+ StandardPermission.ManageCampaigns,
+ StandardPermission.ManageDiscounts,
+ StandardPermission.ManageNewsletterSubscribers,
+ StandardPermission.ManageNewsletterCategories,
+ StandardPermission.ManageNews,
+ StandardPermission.ManageBlog,
+ StandardPermission.ManageWidgets,
+ StandardPermission.ManagePages,
+ StandardPermission.ManageKnowledgebase,
+ StandardPermission.ManageCourses,
+ StandardPermission.ManageMessageTemplates,
+ StandardPermission.ManageCountries,
+ StandardPermission.ManageLanguages,
+ StandardPermission.ManageSettings,
+ StandardPermission.ManagePaymentMethods,
+ StandardPermission.ManageExternalAuthenticationMethods,
+ StandardPermission.ManageTaxSettings,
+ StandardPermission.ManageShippingSettings,
+ StandardPermission.ManageCurrencies,
+ StandardPermission.ManageMeasures,
+ StandardPermission.ManageAcl,
+ StandardPermission.ManageEmailAccounts,
+ StandardPermission.ManageStores,
+ StandardPermission.ManagePlugins,
+ StandardPermission.ManageMessageQueue,
+ StandardPermission.ManageMessageContactForm,
+ StandardPermission.ManageMaintenance,
+ StandardPermission.ManageSystem,
+ StandardPermission.ManageFiles,
+ StandardPermission.ManagePictures,
+ StandardPermission.HtmlEditorManagePictures,
+ StandardPermission.ManageScheduleTasks,
+ StandardPermission.DisplayPrices,
+ StandardPermission.EnableShoppingCart,
+ StandardPermission.EnableWishlist,
+ StandardPermission.PublicStoreAllowNavigation,
+ StandardPermission.AccessClosedStore,
+ StandardPermission.ManageOrderTags,
+ StandardPermission.ManageOrderStatus,
+ StandardPermission.AllowUseApi
+ };
+ }
- public virtual IEnumerable<DefaultPermission> GetDefaultPermissions()
- {
- return new[]
- {
- new DefaultPermission
- {
- CustomerGroupSystemName = SystemCustomerGroupNames.Administrators,
- Permissions = new[]
- {
- StandardPermission.ManageAccessAdminPanel,
- StandardPermission.AllowCustomerImpersonation,
- StandardPermission.ManageProducts,
- StandardPermission.ManageCategories,
- StandardPermission.ManageBrands,
- StandardPermission.ManageCollections,
- StandardPermission.ManageProductReviews,
- StandardPermission.ManageProductTags,
- StandardPermission.ManageOrderStatus,
- StandardPermission.ManageOrderTags,
- StandardPermission.ManageProductAttributes,
- StandardPermission.ManageSpecificationAttributes,
- StandardPermission.ManageCheckoutAttribute,
- StandardPermission.ManageContactAttribute,
- StandardPermission.ManageCustomers,
- StandardPermission.ManageCustomerGroups,
- StandardPermission.ManageCustomerTags,
- StandardPermission.ManageVendors,
- StandardPermission.ManageSalesEmployees,
- StandardPermission.ManageVendorReviews,
- StandardPermission.ManageAddressAttribute,
- StandardPermission.ManageCustomerAttribute,
- StandardPermission.ManageCurrentCarts,
- StandardPermission.ManageOrders,
- StandardPermission.ManageShipments,
- StandardPermission.ManageGiftVouchers,
- StandardPermission.ManagePaymentTransactions,
- StandardPermission.ManageMerchandiseReturns,
- StandardPermission.ManageDocuments,
- StandardPermission.ManageReports,
- StandardPermission.ManageAffiliates,
- StandardPermission.ManagePushEvents,
- StandardPermission.ManageCampaigns,
- StandardPermission.ManageDiscounts,
- StandardPermission.ManageNewsletterSubscribers,
- StandardPermission.ManageNewsletterCategories,
- StandardPermission.ManageNews,
- StandardPermission.ManageBlog,
- StandardPermission.ManageWidgets,
- StandardPermission.ManagePages,
- StandardPermission.ManageKnowledgebase,
- StandardPermission.ManageCourses,
- StandardPermission.ManageMessageTemplates,
- StandardPermission.ManageCountries,
- StandardPermission.ManageLanguages,
- StandardPermission.ManageSettings,
- StandardPermission.ManagePaymentMethods,
- StandardPermission.ManageExternalAuthenticationMethods,
- StandardPermission.ManageTaxSettings,
- StandardPermission.ManageShippingSettings,
- StandardPermission.ManageCurrencies,
- StandardPermission.ManageMeasures,
- StandardPermission.ManageAcl,
- StandardPermission.ManageEmailAccounts,
- StandardPermission.ManageStores,
- StandardPermission.ManagePlugins,
- StandardPermission.ManageMessageQueue,
- StandardPermission.ManageMessageContactForm,
- StandardPermission.ManageMaintenance,
- StandardPermission.ManageSystem,
- StandardPermission.ManageFiles,
- StandardPermission.ManagePictures,
- StandardPermission.HtmlEditorManagePictures,
- StandardPermission.ManageScheduleTasks,
- StandardPermission.DisplayPrices,
- StandardPermission.EnableShoppingCart,
- StandardPermission.EnableWishlist,
- StandardPermission.PublicStoreAllowNavigation,
- StandardPermission.AccessClosedStore,
- StandardPermission.AllowUseApi
- }
- },
- new DefaultPermission
- {
- CustomerGroupSystemName = SystemCustomerGroupNames.Guests,
- Permissions = new[]
- {
- StandardPermission.DisplayPrices,
- StandardPermission.EnableShoppingCart,
- StandardPermission.EnableWishlist,
- StandardPermission.PublicStoreAllowNavigation
- }
- },
- new DefaultPermission
- {
- CustomerGroupSystemName = SystemCustomerGroupNames.Registered,
- Permissions = new[]
- {
- StandardPermission.DisplayPrices,
- StandardPermission.EnableShoppingCart,
- StandardPermission.EnableWishlist,
- StandardPermission.PublicStoreAllowNavigation,
- StandardPermission.AllowUseApi
- }
- },
- new DefaultPermission
- {
- CustomerGroupSystemName = SystemCustomerGroupNames.Vendors,
- Permissions = new[]
- {
- StandardPermission.ManageAccessVendorPanel,
- StandardPermission.ManageProducts,
- StandardPermission.ManageFiles,
- StandardPermission.ManagePictures,
- StandardPermission.ManageOrders,
- StandardPermission.ManageVendorReviews,
- StandardPermission.ManageShipments,
- StandardPermission.ManageMerchandiseReturns,
- StandardPermission.ManageReports
- }
- },
- new DefaultPermission
- {
- CustomerGroupSystemName = SystemCustomerGroupNames.Staff,
- Permissions = new[]
- {
- StandardPermission.ManageAccessAdminPanel,
- StandardPermission.ManageProducts,
- StandardPermission.ManageFiles,
- StandardPermission.ManagePictures,
- StandardPermission.ManageCategories,
- StandardPermission.ManageBrands,
- StandardPermission.ManageCollections,
- StandardPermission.ManageOrders,
- StandardPermission.ManagePaymentTransactions,
- StandardPermission.ManageShipments,
- StandardPermission.ManageMerchandiseReturns,
- StandardPermission.ManageReports
- }
- },
+ public virtual IEnumerable<DefaultPermission> GetDefaultPermissions()
+ {
+ return new[] {
+ new DefaultPermission {
+ CustomerGroupSystemName = SystemCustomerGroupNames.Administrators,
+ Permissions = new[] {
+ StandardPermission.ManageAccessAdminPanel,
+ StandardPermission.AllowCustomerImpersonation,
+ StandardPermission.ManageProducts,
+ StandardPermission.ManageCategories,
+ StandardPermission.ManageBrands,
+ StandardPermission.ManageCollections,
+ StandardPermission.ManageProductReviews,
+ StandardPermission.ManageProductTags,
+ StandardPermission.ManageOrderStatus,
+ StandardPermission.ManageOrderTags,
+ StandardPermission.ManageProductAttributes,
+ StandardPermission.ManageSpecificationAttributes,
+ StandardPermission.ManageCheckoutAttribute,
+ StandardPermission.ManageContactAttribute,
+ StandardPermission.ManageCustomers,
+ StandardPermission.ManageCustomerGroups,
+ StandardPermission.ManageCustomerTags,
+ StandardPermission.ManageVendors,
+ StandardPermission.ManageSalesEmployees,
+ StandardPermission.ManageVendorReviews,
+ StandardPermission.ManageAddressAttribute,
+ StandardPermission.ManageCustomerAttribute,
+ StandardPermission.ManageCurrentCarts,
+ StandardPermission.ManageOrders,
+ StandardPermission.ManageShipments,
+ StandardPermission.ManageGiftVouchers,
+ StandardPermission.ManagePaymentTransactions,
+ StandardPermission.ManageMerchandiseReturns,
+ StandardPermission.ManageDocuments,
+ StandardPermission.ManageReports,
+ StandardPermission.ManageAffiliates,
+ StandardPermission.ManagePushEvents,
+ StandardPermission.ManageCampaigns,
+ StandardPermission.ManageDiscounts,
+ StandardPermission.ManageNewsletterSubscribers,
+ StandardPermission.ManageNewsletterCategories,
+ StandardPermission.ManageNews,
+ StandardPermission.ManageBlog,
+ StandardPermission.ManageWidgets,
+ StandardPermission.ManagePages,
+ StandardPermission.ManageKnowledgebase,
+ StandardPermission.ManageCourses,
+ StandardPermission.ManageMessageTemplates,
+ StandardPermission.ManageCountries,
+ StandardPermission.ManageLanguages,
+ StandardPermission.ManageSettings,
+ StandardPermission.ManagePaymentMethods,
+ StandardPermission.ManageExternalAuthenticationMethods,
+ StandardPermission.ManageTaxSettings,
+ StandardPermission.ManageShippingSettings,
+ StandardPermission.ManageCurrencies,
+ StandardPermission.ManageMeasures,
+ StandardPermission.ManageAcl,
+ StandardPermission.ManageEmailAccounts,
+ StandardPermission.ManageStores,
+ StandardPermission.ManagePlugins,
+ StandardPermission.ManageMessageQueue,
+ StandardPermission.ManageMessageContactForm,
+ StandardPermission.ManageMaintenance,
+ StandardPermission.ManageSystem,
+ StandardPermission.ManageFiles,
+ StandardPermission.ManagePictures,
+ StandardPermission.HtmlEditorManagePictures,
+ StandardPermission.ManageScheduleTasks,
+ StandardPermission.DisplayPrices,
+ StandardPermission.EnableShoppingCart,
+ StandardPermission.EnableWishlist,
+ StandardPermission.PublicStoreAllowNavigation,
+ StandardPermission.AccessClosedStore,
+ StandardPermission.AllowUseApi
+ }
+ },
+ new DefaultPermission {
+ CustomerGroupSystemName = SystemCustomerGroupNames.Guests,
+ Permissions = new[] {
+ StandardPermission.DisplayPrices,
+ StandardPermission.EnableShoppingCart,
+ StandardPermission.EnableWishlist,
+ StandardPermission.PublicStoreAllowNavigation
+ }
+ },
+ new DefaultPermission {
+ CustomerGroupSystemName = SystemCustomerGroupNames.Registered,
+ Permissions = new[] {
+ StandardPermission.DisplayPrices,
+ StandardPermission.EnableShoppingCart,
+ StandardPermission.EnableWishlist,
+ StandardPermission.PublicStoreAllowNavigation,
+ StandardPermission.AllowUseApi
+ }
+ },
+ new DefaultPermission {
+ CustomerGroupSystemName = SystemCustomerGroupNames.Vendors,
+ Permissions = new[] {
+ StandardPermission.ManageAccessVendorPanel,
+ StandardPermission.ManageProducts,
+ StandardPermission.ManageFiles,
+ StandardPermission.ManagePictures,
+ StandardPermission.ManageOrders,
+ StandardPermission.ManageVendorReviews,
+ StandardPermission.ManageShipments,
+ StandardPermission.ManageMerchandiseReturns,
+ StandardPermission.ManageReports
+ }
+ },
+ new DefaultPermission {
+ CustomerGroupSystemName = SystemCustomerGroupNames.Staff,
+ Permissions = new[] {
+ StandardPermission.ManageAccessAdminPanel,
+ StandardPermission.ManageProducts,
+ StandardPermission.ManageFiles,
+ StandardPermission.ManagePictures,
+ StandardPermission.ManageCategories,
+ StandardPermission.ManageBrands,
+ StandardPermission.ManageCollections,
+ StandardPermission.ManageOrders,
+ StandardPermission.ManagePaymentTransactions,
+ StandardPermission.ManageShipments,
+ StandardPermission.ManageMerchandiseReturns,
+ StandardPermission.ManageReports
+ }
+ },
- new DefaultPermission
- {
- CustomerGroupSystemName = SystemCustomerGroupNames.SalesManager,
- Permissions = new[]
- {
- StandardPermission.ManageAccessAdminPanel,
- StandardPermission.ManageOrders,
- StandardPermission.ManageCustomers
- }
+ new DefaultPermission {
+ CustomerGroupSystemName = SystemCustomerGroupNames.SalesManager,
+ Permissions = new[] {
+ StandardPermission.ManageAccessAdminPanel,
+ StandardPermission.ManageOrders,
+ StandardPermission.ManageCustomers
}
- };
- }
+ }
+ };
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs b/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs
index 00c0e12d3..2a742962a 100644
--- a/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs
+++ b/src/Business/Grand.Business.Common/Services/Security/PermissionService.cs
@@ -1,289 +1,293 @@
+using Grand.Business.Core.Interfaces.Common.Directory;
using Grand.Business.Core.Interfaces.Common.Security;
+using Grand.Data;
+using Grand.Domain.Customers;
+using Grand.Domain.Permissions;
using Grand.Infrastructure;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
-using Grand.Domain.Customers;
-using Grand.Data;
-using Grand.Domain.Permissions;
-using Grand.Business.Core.Interfaces.Common.Directory;
-namespace Grand.Business.Common.Services.Security
+namespace Grand.Business.Common.Services.Security;
+
+/// <summary>
+/// Permission service
+/// </summary>
+public class PermissionService : IPermissionService
{
+ #region Ctor
+
/// <summary>
- /// Permission service
+ /// Ctor
/// </summary>
- public class PermissionService : IPermissionService
+ /// <param name="permissionRepository">Permission repository</param>
+ /// <param name="permissionActionRepository">Permission action repository</param>
+ /// <param name="workContext">Work context</param>
+ /// <param name="groupService">Group service</param>
+ /// <param name="cacheBase">Cache manager</param>
+ public PermissionService(
+ IRepository<Permission> permissionRepository,
+ IRepository<PermissionAction> permissionActionRepository,
+ IWorkContext workContext,
+ IGroupService groupService,
+ ICacheBase cacheBase)
{
- #region Fields
-
- private readonly IRepository<Permission> _permissionRepository;
- private readonly IRepository<PermissionAction> _permissionActionRepository;
- private readonly IWorkContext _workContext;
- private readonly IGroupService _groupService;
- private readonly ICacheBase _cacheBase;
-
- #endregion
-
- #region Ctor
-
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="permissionRepository">Permission repository</param>
- /// <param name="permissionActionRepository">Permission action repository</param>
- /// <param name="workContext">Work context</param>
- /// <param name="groupService">Group service</param>
- /// <param name="cacheBase">Cache manager</param>
- public PermissionService(
- IRepository<Permission> permissionRepository,
- IRepository<PermissionAction> permissionActionRepository,
- IWorkContext workContext,
- IGroupService groupService,
- ICacheBase cacheBase)
- {
- _permissionRepository = permissionRepository;
- _permissionActionRepository = permissionActionRepository;
- _workContext = workContext;
- _groupService = groupService;
- _cacheBase = cacheBase;
- }
+ _permissionRepository = permissionRepository;
+ _permissionActionRepository = permissionActionRepository;
+ _workContext = workContext;
+ _groupService = groupService;
+ _cacheBase = cacheBase;
+ }
- #endregion
+ #endregion
- #region Utilities
+ #region Utilities
- /// <summary>
- /// Authorize permission
- /// </summary>
- /// <param name="permissionSystemName">Permission system name</param>
- /// <param name="customerGroup">Customer group</param>
- /// <returns>true - authorized; otherwise, false</returns>
- protected virtual async Task<bool> Authorize(string permissionSystemName, CustomerGroup customerGroup)
+ /// <summary>
+ /// Authorize permission
+ /// </summary>
+ /// <param name="permissionSystemName">Permission system name</param>
+ /// <param name="customerGroup">Customer group</param>
+ /// <returns>true - authorized; otherwise, false</returns>
+ protected virtual async Task<bool> Authorize(string permissionSystemName, CustomerGroup customerGroup)
+ {
+ if (string.IsNullOrEmpty(permissionSystemName))
+ return false;
+
+ var key = string.Format(CacheKey.PERMISSIONS_ALLOWED_KEY, customerGroup.Id, permissionSystemName);
+ return await _cacheBase.GetAsync(key, async () =>
{
- if (string.IsNullOrEmpty(permissionSystemName))
- return false;
+ var permissionRecord =
+ await Task.FromResult(
+ _permissionRepository.Table.FirstOrDefault(x => x.SystemName == permissionSystemName));
+ return permissionRecord?.CustomerGroups.Contains(customerGroup.Id) ?? false;
+ });
+ }
- var key = string.Format(CacheKey.PERMISSIONS_ALLOWED_KEY, customerGroup.Id, permissionSystemName);
- return await _cacheBase.GetAsync(key, async () =>
- {
- var permissionRecord = await Task.FromResult(_permissionRepository.Table.FirstOrDefault(x => x.SystemName == permissionSystemName));
- return permissionRecord?.CustomerGroups.Contains(customerGroup.Id) ?? false;
- });
- }
+ #endregion
- #endregion
+ #region Fields
- #region Methods
+ private readonly IRepository<Permission> _permissionRepository;
+ private readonly IRepository<PermissionAction> _permissionActionRepository;
+ private readonly IWorkContext _workContext;
+ private readonly IGroupService _groupService;
+ private readonly ICacheBase _cacheBase;
- /// <summary>
- /// Delete a permission
- /// </summary>
- /// <param name="permission">Permission</param>
- public virtual async Task DeletePermission(Permission permission)
- {
- ArgumentNullException.ThrowIfNull(permission);
+ #endregion
- await _permissionRepository.DeleteAsync(permission);
+ #region Methods
- await _cacheBase.RemoveByPrefix(CacheKey.PERMISSIONS_PATTERN_KEY);
- }
+ /// <summary>
+ /// Delete a permission
+ /// </summary>
+ /// <param name="permission">Permission</param>
+ public virtual async Task DeletePermission(Permission permission)
+ {
+ ArgumentNullException.ThrowIfNull(permission);
- /// <summary>
- /// Gets a permission
- /// </summary>
- /// <param name="permissionId">Permission identifier</param>
- /// <returns>Permission</returns>
- public virtual Task<Permission> GetPermissionById(string permissionId)
- {
- return _permissionRepository.GetByIdAsync(permissionId);
- }
+ await _permissionRepository.DeleteAsync(permission);
- /// <summary>
- /// Gets a permission
- /// </summary>
- /// <param name="systemName">Permission system name</param>
- /// <returns>Permission</returns>
- public virtual async Task<Permission> GetPermissionBySystemName(string systemName)
- {
- if (string.IsNullOrWhiteSpace(systemName))
- return await Task.FromResult<Permission>(null);
+ await _cacheBase.RemoveByPrefix(CacheKey.PERMISSIONS_PATTERN_KEY);
+ }
- var query = from pr in _permissionRepository.Table
- where pr.SystemName == systemName
- select pr;
+ /// <summary>
+ /// Gets a permission
+ /// </summary>
+ /// <param name="permissionId">Permission identifier</param>
+ /// <returns>Permission</returns>
+ public virtual Task<Permission> GetPermissionById(string permissionId)
+ {
+ return _permissionRepository.GetByIdAsync(permissionId);
+ }
- return await Task.FromResult(query.FirstOrDefault());
- }
+ /// <summary>
+ /// Gets a permission
+ /// </summary>
+ /// <param name="systemName">Permission system name</param>
+ /// <returns>Permission</returns>
+ public virtual async Task<Permission> GetPermissionBySystemName(string systemName)
+ {
+ if (string.IsNullOrWhiteSpace(systemName))
+ return await Task.FromResult<Permission>(null);
- /// <summary>
- /// Gets all permissions
- /// </summary>
- /// <returns>Permissions</returns>
- public virtual async Task<IList<Permission>> GetAllPermissions()
- {
- var query = from pr in _permissionRepository.Table
- orderby pr.Name
- select pr;
- return await Task.FromResult(query.ToList());
- }
+ var query = from pr in _permissionRepository.Table
+ where pr.SystemName == systemName
+ select pr;
- /// <summary>
- /// Inserts a permission
- /// </summary>
- /// <param name="permission">Permission</param>
- public virtual async Task InsertPermission(Permission permission)
- {
- ArgumentNullException.ThrowIfNull(permission);
+ return await Task.FromResult(query.FirstOrDefault());
+ }
- await _permissionRepository.InsertAsync(permission);
+ /// <summary>
+ /// Gets all permissions
+ /// </summary>
+ /// <returns>Permissions</returns>
+ public virtual async Task<IList<Permission>> GetAllPermissions()
+ {
+ var query = from pr in _permissionRepository.Table
+ orderby pr.Name
+ select pr;
+ return await Task.FromResult(query.ToList());
+ }
- await _cacheBase.RemoveByPrefix(CacheKey.PERMISSIONS_PATTERN_KEY);
- }
+ /// <summary>
+ /// Inserts a permission
+ /// </summary>
+ /// <param name="permission">Permission</param>
+ public virtual async Task InsertPermission(Permission permission)
+ {
+ ArgumentNullException.ThrowIfNull(permission);
- /// <summary>
- /// Updates the permission
- /// </summary>
- /// <param name="permission">Permission</param>
- public virtual async Task UpdatePermission(Permission permission)
- {
- ArgumentNullException.ThrowIfNull(permission);
+ await _permissionRepository.InsertAsync(permission);
- await _permissionRepository.UpdateAsync(permission);
+ await _cacheBase.RemoveByPrefix(CacheKey.PERMISSIONS_PATTERN_KEY);
+ }
- await _cacheBase.RemoveByPrefix(CacheKey.PERMISSIONS_PATTERN_KEY);
- }
+ /// <summary>
+ /// Updates the permission
+ /// </summary>
+ /// <param name="permission">Permission</param>
+ public virtual async Task UpdatePermission(Permission permission)
+ {
+ ArgumentNullException.ThrowIfNull(permission);
- /// <summary>
- /// Authorize permission
- /// </summary>
- /// <param name="permission">Permission record</param>
- /// <returns>true - authorized; otherwise, false</returns>
- public virtual async Task<bool> Authorize(Permission permission)
- {
- return await Authorize(permission, _workContext.CurrentCustomer);
- }
+ await _permissionRepository.UpdateAsync(permission);
- /// <summary>
- /// Authorize permission
- /// </summary>
- /// <param name="permission">Permission</param>
- /// <param name="customer">Customer</param>
- /// <returns>true - authorized; otherwise, false</returns>
- public virtual async Task<bool> Authorize(Permission permission, Customer customer)
- {
- if (permission == null)
- return false;
+ await _cacheBase.RemoveByPrefix(CacheKey.PERMISSIONS_PATTERN_KEY);
+ }
- if (customer == null)
- return false;
+ /// <summary>
+ /// Authorize permission
+ /// </summary>
+ /// <param name="permission">Permission record</param>
+ /// <returns>true - authorized; otherwise, false</returns>
+ public virtual async Task<bool> Authorize(Permission permission)
+ {
+ return await Authorize(permission, _workContext.CurrentCustomer);
+ }
- return await Authorize(permission.SystemName, customer);
- }
+ /// <summary>
+ /// Authorize permission
+ /// </summary>
+ /// <param name="permission">Permission</param>
+ /// <param name="customer">Customer</param>
+ /// <returns>true - authorized; otherwise, false</returns>
+ public virtual async Task<bool> Authorize(Permission permission, Customer customer)
+ {
+ if (permission == null)
+ return false;
- /// <summary>
- /// Authorize permission
- /// </summary>
- /// <param name="permissionSystemName">Permission system name</param>
- /// <returns>true - authorized; otherwise, false</returns>
- public virtual async Task<bool> Authorize(string permissionSystemName)
- {
- return await Authorize(permissionSystemName, _workContext.CurrentCustomer);
- }
+ if (customer == null)
+ return false;
- /// <summary>
- /// Authorize permission
- /// </summary>
- /// <param name="permissionSystemName">Permission system name</param>
- /// <param name="customer">Customer</param>
- /// <returns>true - authorized; otherwise, false</returns>
- public virtual async Task<bool> Authorize(string permissionSystemName, Customer customer)
- {
- if (string.IsNullOrEmpty(permissionSystemName))
- return false;
+ return await Authorize(permission.SystemName, customer);
+ }
- var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray());
- foreach (var group in customerGroups)
- if (await Authorize(permissionSystemName, group))
- //yes, we have such permission
- return true;
+ /// <summary>
+ /// Authorize permission
+ /// </summary>
+ /// <param name="permissionSystemName">Permission system name</param>
+ /// <returns>true - authorized; otherwise, false</returns>
+ public virtual async Task<bool> Authorize(string permissionSystemName)
+ {
+ return await Authorize(permissionSystemName, _workContext.CurrentCustomer);
+ }
- //no permission found
+ /// <summary>
+ /// Authorize permission
+ /// </summary>
+ /// <param name="permissionSystemName">Permission system name</param>
+ /// <param name="customer">Customer</param>
+ /// <returns>true - authorized; otherwise, false</returns>
+ public virtual async Task<bool> Authorize(string permissionSystemName, Customer customer)
+ {
+ if (string.IsNullOrEmpty(permissionSystemName))
return false;
- }
- /// <summary>
- /// Gets a permission action
- /// </summary>
- /// <param name="systemName">Permission system name</param>
- /// <param name="customerGroupId">Customer group ident</param>
- /// <returns>Permission action</returns>
- public virtual async Task<IList<PermissionAction>> GetPermissionActions(string systemName, string customerGroupId)
- {
- return await Task.FromResult(_permissionActionRepository.Table
- .Where(x => x.SystemName == systemName && x.CustomerGroupId == customerGroupId).ToList());
- }
+ var customerGroups = await _groupService.GetAllByIds(customer.Groups.ToArray());
+ foreach (var group in customerGroups)
+ if (await Authorize(permissionSystemName, group))
+ //yes, we have such permission
+ return true;
- /// <summary>
- /// Inserts a permission action record
- /// </summary>
- /// <param name="permissionAction">Permission action</param>
- public virtual async Task InsertPermissionAction(PermissionAction permissionAction)
- {
- ArgumentNullException.ThrowIfNull(permissionAction);
+ //no permission found
+ return false;
+ }
- //insert
- await _permissionActionRepository.InsertAsync(permissionAction);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.PERMISSIONS_PATTERN_KEY);
- }
+ /// <summary>
+ /// Gets a permission action
+ /// </summary>
+ /// <param name="systemName">Permission system name</param>
+ /// <param name="customerGroupId">Customer group ident</param>
+ /// <returns>Permission action</returns>
+ public virtual async Task<IList<PermissionAction>> GetPermissionActions(string systemName, string customerGroupId)
+ {
+ return await Task.FromResult(_permissionActionRepository.Table
+ .Where(x => x.SystemName == systemName && x.CustomerGroupId == customerGroupId).ToList());
+ }
- /// <summary>
- /// Inserts a permission action record
- /// </summary>
- /// <param name="permissionAction">Permission action</param>
- public virtual async Task DeletePermissionAction(PermissionAction permissionAction)
- {
- ArgumentNullException.ThrowIfNull(permissionAction);
+ /// <summary>
+ /// Inserts a permission action record
+ /// </summary>
+ /// <param name="permissionAction">Permission action</param>
+ public virtual async Task InsertPermissionAction(PermissionAction permissionAction)
+ {
+ ArgumentNullException.ThrowIfNull(permissionAction);
- //delete
- await _permissionActionRepository.DeleteAsync(permissionAction);
- //clear cache
- await _cacheBase.RemoveByPrefix(CacheKey.PERMISSIONS_PATTERN_KEY);
- }
+ //insert
+ await _permissionActionRepository.InsertAsync(permissionAction);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PERMISSIONS_PATTERN_KEY);
+ }
- /// <summary>
- /// Authorize permission for action
- /// </summary>
- /// <param name="permissionSystemName">Permission system name</param>
- /// <param name="permissionActionName">Permission action name</param>
- /// <returns>true - authorized; otherwise, false</returns>
- public virtual async Task<bool> AuthorizeAction(string permissionSystemName, string permissionActionName)
- {
- if (string.IsNullOrEmpty(permissionSystemName) || string.IsNullOrEmpty(permissionActionName))
- return false;
+ /// <summary>
+ /// Inserts a permission action record
+ /// </summary>
+ /// <param name="permissionAction">Permission action</param>
+ public virtual async Task DeletePermissionAction(PermissionAction permissionAction)
+ {
+ ArgumentNullException.ThrowIfNull(permissionAction);
- if (!await Authorize(permissionSystemName))
- return false;
+ //delete
+ await _permissionActionRepository.DeleteAsync(permissionAction);
+ //clear cache
+ await _cacheBase.RemoveByPrefix(CacheKey.PERMISSIONS_PATTERN_KEY);
+ }
+
+ /// <summary>
+ /// Authorize permission for action
+ /// </summary>
+ /// <param name="permissionSystemName">Permission system name</param>
+ /// <param name="permissionActionName">Permission action name</param>
+ /// <returns>true - authorized; otherwise, false</returns>
+ public virtual async Task<bool> AuthorizeAction(string permissionSystemName, string permissionActionName)
+ {
+ if (string.IsNullOrEmpty(permissionSystemName) || string.IsNullOrEmpty(permissionActionName))
+ return false;
- var customerGroups = await _groupService.GetAllByIds(_workContext.CurrentCustomer.Groups.ToArray());
- foreach (var group in customerGroups)
+ if (!await Authorize(permissionSystemName))
+ return false;
+
+ var customerGroups = await _groupService.GetAllByIds(_workContext.CurrentCustomer.Groups.ToArray());
+ foreach (var group in customerGroups)
+ {
+ if (!await Authorize(permissionSystemName, group))
+ continue;
+
+ var key = string.Format(CacheKey.PERMISSIONS_ALLOWED_ACTION_KEY, group.Id, permissionSystemName,
+ permissionActionName);
+ var permissionAction = await _cacheBase.GetAsync(key, async () =>
{
- if (!await Authorize(permissionSystemName, group))
- continue;
-
- var key = string.Format(CacheKey.PERMISSIONS_ALLOWED_ACTION_KEY, group.Id, permissionSystemName, permissionActionName);
- var permissionAction = await _cacheBase.GetAsync(key, async () =>
- {
- return await Task.FromResult(_permissionActionRepository.Table
- .FirstOrDefault(x => x.SystemName == permissionSystemName && x.CustomerGroupId == group.Id && x.Action == permissionActionName));
- });
- if (permissionAction != null)
- return false;
- }
-
- return true;
+ return await Task.FromResult(_permissionActionRepository.Table
+ .FirstOrDefault(x =>
+ x.SystemName == permissionSystemName && x.CustomerGroupId == group.Id &&
+ x.Action == permissionActionName));
+ });
+ if (permissionAction != null)
+ return false;
}
- #endregion
+ return true;
}
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs b/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs
index 2eab0d216..626fd6223 100644
--- a/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs
+++ b/src/Business/Grand.Business.Common/Services/Seo/SlugService.cs
@@ -1,221 +1,255 @@
using Grand.Business.Core.Interfaces.Common.Seo;
-using Grand.Domain;
using Grand.Data;
+using Grand.Domain;
using Grand.Domain.Seo;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
-namespace Grand.Business.Common.Services.Seo
+namespace Grand.Business.Common.Services.Seo;
+
+/// <summary>
+/// Provides information about Slug URL Entity
+/// </summary>
+public class SlugService : ISlugService
{
+ #region Ctor
+
/// <summary>
- /// Provides information about Slug URL Entity
+ /// Ctor
/// </summary>
- public class SlugService : ISlugService
+ public SlugService(ICacheBase cacheBase,
+ IRepository<EntityUrl> urlEntityRepository)
{
- #region Fields
+ _cacheBase = cacheBase;
+ _urlEntityRepository = urlEntityRepository;
+ }
- private readonly IRepository<EntityUrl> _urlEntityRepository;
- private readonly ICacheBase _cacheBase;
+ #endregion
- #endregion
+ #region Fields
- #region Ctor
+ private readonly IRepository<EntityUrl> _urlEntityRepository;
+ private readonly ICacheBase _cacheBase;
- /// <summary>
- /// Ctor
- /// </summary>
- public SlugService(ICacheBase cacheBase,
- IRepository<EntityUrl> urlEntityRepository)
- {
- _cacheBase = cacheBase;
- _urlEntityRepository = urlEntityRepository;
- }
+ #endregion
- #endregion
-
- #region Methods
+ #region Methods
- /// <summary>
- /// Gets an URL Entity
- /// </summary>
- /// <param name="urlEntityId">URL Entity identifier</param>
- /// <returns>URL Entity</returns>
- public virtual Task<EntityUrl> GetEntityUrlById(string urlEntityId)
- {
- return _urlEntityRepository.GetByIdAsync(urlEntityId);
- }
+ /// <summary>
+ /// Gets an URL Entity
+ /// </summary>
+ /// <param name="urlEntityId">URL Entity identifier</param>
+ /// <returns>URL Entity</returns>
+ public virtual Task<EntityUrl> GetEntityUrlById(string urlEntityId)
+ {
+ return _urlEntityRepository.GetByIdAsync(urlEntityId);
+ }
- /// <summary>
- /// Inserts an URL Entity
- /// </summary>
- /// <param name="urlEntity">URL Entity</param>
- public virtual async Task InsertEntityUrl(EntityUrl urlEntity)
- {
- ArgumentNullException.ThrowIfNull(urlEntity);
+ /// <summary>
+ /// Inserts an URL Entity
+ /// </summary>
+ /// <param name="urlEntity">URL Entity</param>
+ public virtual async Task InsertEntityUrl(EntityUrl urlEntity)
+ {
+ ArgumentNullException.ThrowIfNull(urlEntity);
- await _urlEntityRepository.InsertAsync(urlEntity);
+ await _urlEntityRepository.InsertAsync(urlEntity);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.URLEntity_PATTERN_KEY);
- }
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.URLEntity_PATTERN_KEY);
+ }
- /// <summary>
- /// Updates the URL Entity
- /// </summary>
- /// <param name="urlEntity">URL Entity</param>
- public virtual async Task UpdateEntityUrl(EntityUrl urlEntity)
- {
- ArgumentNullException.ThrowIfNull(urlEntity);
+ /// <summary>
+ /// Updates the URL Entity
+ /// </summary>
+ /// <param name="urlEntity">URL Entity</param>
+ public virtual async Task UpdateEntityUrl(EntityUrl urlEntity)
+ {
+ ArgumentNullException.ThrowIfNull(urlEntity);
- await _urlEntityRepository.UpdateAsync(urlEntity);
+ await _urlEntityRepository.UpdateAsync(urlEntity);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.URLEntity_PATTERN_KEY);
- }
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.URLEntity_PATTERN_KEY);
+ }
- /// <summary>
- /// Deletes an URL Entity
- /// </summary>
- /// <param name="urlEntity">URL Entity</param>
- public virtual async Task DeleteEntityUrl(EntityUrl urlEntity)
- {
- ArgumentNullException.ThrowIfNull(urlEntity);
+ /// <summary>
+ /// Deletes an URL Entity
+ /// </summary>
+ /// <param name="urlEntity">URL Entity</param>
+ public virtual async Task DeleteEntityUrl(EntityUrl urlEntity)
+ {
+ ArgumentNullException.ThrowIfNull(urlEntity);
- await _urlEntityRepository.DeleteAsync(urlEntity);
+ await _urlEntityRepository.DeleteAsync(urlEntity);
- //cache
- await _cacheBase.RemoveByPrefix(CacheKey.URLEntity_PATTERN_KEY);
- }
+ //cache
+ await _cacheBase.RemoveByPrefix(CacheKey.URLEntity_PATTERN_KEY);
+ }
- /// <summary>
- /// Find URL Entity
- /// </summary>
- /// <param name="slug">Slug</param>
- /// <returns>Found URL Entity</returns>
- public virtual async Task<EntityUrl> GetBySlug(string slug)
- {
- if (string.IsNullOrEmpty(slug))
- return null;
+ /// <summary>
+ /// Find URL Entity
+ /// </summary>
+ /// <param name="slug">Slug</param>
+ /// <returns>Found URL Entity</returns>
+ public virtual async Task<EntityUrl> GetBySlug(string slug)
+ {
+ if (string.IsNullOrEmpty(slug))
+ return null;
- slug = slug.ToLowerInvariant();
+ slug = slug.ToLowerInvariant();
- var query = from ur in _urlEntityRepository.Table
- where ur.Slug == slug
- orderby ur.IsActive
- select ur;
- return await Task.FromResult(query.FirstOrDefault());
- }
+ var query = from ur in _urlEntityRepository.Table
+ where ur.Slug == slug
+ orderby ur.IsActive
+ select ur;
+ return await Task.FromResult(query.FirstOrDefault());
+ }
- /// <summary>
- /// Find URL Entity (cached version).
- /// </summary>
- /// <param name="slug">Slug</param>
- /// <returns>Found URL Entity</returns>
- public virtual async Task<EntityUrl> GetBySlugCached(string slug)
+ /// <summary>
+ /// Find URL Entity (cached version).
+ /// </summary>
+ /// <param name="slug">Slug</param>
+ /// <returns>Found URL Entity</returns>
+ public virtual async Task<EntityUrl> GetBySlugCached(string slug)
+ {
+ if (string.IsNullOrEmpty(slug))
+ return null;
+
+ slug = slug.ToLowerInvariant();
+
+ var key = string.Format(CacheKey.URLEntity_BY_SLUG_KEY, slug);
+ return await _cacheBase.GetAsync(key, async () =>
{
- if (string.IsNullOrEmpty(slug))
- return null;
+ var urlEntity = await GetBySlug(slug);
+ return urlEntity;
+ });
+ }
- slug = slug.ToLowerInvariant();
+ /// <summary>
+ /// Gets all URL Entity
+ /// </summary>
+ /// <param name="slug">Slug</param>
+ /// <param name="active">Active</param>
+ /// <param name="pageIndex">Page index</param>
+ /// <param name="pageSize">Page size</param>
+ /// <returns>URL Entity</returns>
+ public virtual async Task<IPagedList<EntityUrl>> GetAllEntityUrl(string slug = "", bool? active = null,
+ int pageIndex = 0, int pageSize = int.MaxValue)
+ {
+ var query = from p in _urlEntityRepository.Table
+ select p;
- var key = string.Format(CacheKey.URLEntity_BY_SLUG_KEY, slug);
- return await _cacheBase.GetAsync(key, async () =>
- {
- var urlEntity = await GetBySlug(slug);
- return urlEntity;
- });
- }
+ if (!string.IsNullOrWhiteSpace(slug))
+ query = query.Where(ur => ur.Slug.Contains(slug.ToLowerInvariant()));
- /// <summary>
- /// Gets all URL Entity
- /// </summary>
- /// <param name="slug">Slug</param>
- /// <param name="active">Active</param>
- /// <param name="pageIndex">Page index</param>
- /// <param name="pageSize">Page size</param>
- /// <returns>URL Entity</returns>
- public virtual async Task<IPagedList<EntityUrl>> GetAllEntityUrl(string slug = "", bool? active = null,
- int pageIndex = 0, int pageSize = int.MaxValue)
+ if (active.HasValue)
+ query = query.Where(ur => ur.IsActive == active.Value);
+
+ query = query.OrderBy(ur => ur.Slug);
+ return await PagedList<EntityUrl>.Create(query, pageIndex, pageSize);
+ }
+
+ /// <summary>
+ /// Find slug
+ /// </summary>
+ /// <param name="entityId">Entity identifier</param>
+ /// <param name="entityName">Entity name</param>
+ /// <param name="languageId">Language identifier</param>
+ /// <returns>Found slug</returns>
+ public virtual async Task<string> 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 () =>
{
- var query = from p in _urlEntityRepository.Table
- select p;
+ var source = _urlEntityRepository.Table;
+ var query = from ur in source
+ where ur.EntityId == entityId &&
+ ur.EntityName == entityName &&
+ ur.LanguageId == languageId &&
+ ur.IsActive
+ select ur.Slug;
+ var slug = await Task.FromResult(query.FirstOrDefault()) ?? "";
+ return slug;
+ });
+ }
- if (!string.IsNullOrWhiteSpace(slug))
- query = query.Where(ur => ur.Slug.Contains(slug.ToLowerInvariant()));
+ /// <summary>
+ /// Save slug
+ /// </summary>
+ /// <typeparam name="T">Type</typeparam>
+ /// <param name="entity">Entity</param>
+ /// <param name="slug">Slug</param>
+ /// <param name="languageId">Language ID</param>
+ public virtual async Task SaveSlug<T>(T entity, string slug, string languageId)
+ where T : BaseEntity, ISlugEntity
+ {
+ ArgumentNullException.ThrowIfNull(entity);
- if (active.HasValue)
- query = query.Where(ur => ur.IsActive == active.Value);
+ var entityId = entity.Id;
+ var entityName = typeof(T).Name;
- query = query.OrderBy(ur => ur.Slug);
- return await PagedList<EntityUrl>.Create(query, pageIndex, pageSize);
- }
+ var query = from ur in _urlEntityRepository.Table
+ where ur.EntityId == entityId &&
+ ur.EntityName == entityName &&
+ ur.LanguageId == languageId
+ select ur;
+
+ var allUrlEntity = query.ToList();
+ var activeUrlEntity = allUrlEntity.FirstOrDefault(x => x.IsActive);
+
+ if (!string.IsNullOrWhiteSpace(slug))
+ slug = slug.ToLowerInvariant();
- /// <summary>
- /// Find slug
- /// </summary>
- /// <param name="entityId">Entity identifier</param>
- /// <param name="entityName">Entity name</param>
- /// <param name="languageId">Language identifier</param>
- /// <returns>Found slug</returns>
- public virtual async Task<string> GetActiveSlug(string entityId, string entityName, string languageId)
+ if (activeUrlEntity == null && !string.IsNullOrWhiteSpace(slug))
{
- var key = string.Format(CacheKey.URLEntity_ACTIVE_BY_ID_NAME_LANGUAGE_KEY, entityId, entityName, languageId);
- return await _cacheBase.GetAsync(key, async () =>
+ //find in non-active records with the specified slug
+ var nonActiveRecordWithSpecifiedSlug = allUrlEntity
+ .FirstOrDefault(x => x.Slug.Equals(slug, StringComparison.OrdinalIgnoreCase) && !x.IsActive);
+ if (nonActiveRecordWithSpecifiedSlug != null)
{
- var source = _urlEntityRepository.Table;
- var query = from ur in source
- where ur.EntityId == entityId &&
- ur.EntityName == entityName &&
- ur.LanguageId == languageId &&
- ur.IsActive
- select ur.Slug;
- var slug = await Task.FromResult(query.FirstOrDefault()) ?? "";
- return slug;
- });
+ //mark non-active record as active
+ nonActiveRecordWithSpecifiedSlug.IsActive = true;
+ await UpdateEntityUrl(nonActiveRecordWithSpecifiedSlug);
+ }
+ else
+ {
+ //new record
+ var entityUrl = new EntityUrl {
+ EntityId = entityId,
+ EntityName = entityName,
+ Slug = slug,
+ LanguageId = languageId,
+ IsActive = true
+ };
+ await InsertEntityUrl(entityUrl);
+ }
}
- /// <summary>
- /// Save slug
- /// </summary>
- /// <typeparam name="T">Type</typeparam>
- /// <param name="entity">Entity</param>
- /// <param name="slug">Slug</param>
- /// <param name="languageId">Language ID</param>
- public virtual async Task SaveSlug<T>(T entity, string slug, string languageId)
- where T : BaseEntity, ISlugEntity
+ if (activeUrlEntity != null && string.IsNullOrWhiteSpace(slug))
{
- ArgumentNullException.ThrowIfNull(entity);
-
- var entityId = entity.Id;
- var entityName = typeof(T).Name;
-
- var query = from ur in _urlEntityRepository.Table
- where ur.EntityId == entityId &&
- ur.EntityName == entityName &&
- ur.LanguageId == languageId
- select ur;
-
- var allUrlEntity = query.ToList();
- var activeUrlEntity = allUrlEntity.FirstOrDefault(x => x.IsActive);
-
- if (!string.IsNullOrWhiteSpace(slug))
- slug = slug.ToLowerInvariant();
+ activeUrlEntity.IsActive = false;
+ await UpdateEntityUrl(activeUrlEntity);
+ }
- if (activeUrlEntity == null && !string.IsNullOrWhiteSpace(slug))
+ if (activeUrlEntity != null && !string.IsNullOrWhiteSpace(slug))
+ if (!activeUrlEntity.Slug.Equals(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);
if (nonActiveRecordWithSpecifiedSlug != null)
{
- //mark non-active record as active
nonActiveRecordWithSpecifiedSlug.IsActive = true;
await UpdateEntityUrl(nonActiveRecordWithSpecifiedSlug);
+
+ activeUrlEntity.IsActive = false;
+ await UpdateEntityUrl(activeUrlEntity);
}
else
{
- //new record
+ //insert new record
var entityUrl = new EntityUrl {
EntityId = entityId,
EntityName = entityName,
@@ -224,49 +258,12 @@ namespace Grand.Business.Common.Services.Seo
IsActive = true
};
await InsertEntityUrl(entityUrl);
- }
- }
-
- if (activeUrlEntity != null && string.IsNullOrWhiteSpace(slug))
- {
- activeUrlEntity.IsActive = false;
- await UpdateEntityUrl(activeUrlEntity);
- }
- if (activeUrlEntity != null && !string.IsNullOrWhiteSpace(slug))
- {
- if (!activeUrlEntity.Slug.Equals(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);
- if (nonActiveRecordWithSpecifiedSlug != null)
- {
- nonActiveRecordWithSpecifiedSlug.IsActive = true;
- await UpdateEntityUrl(nonActiveRecordWithSpecifiedSlug);
-
- activeUrlEntity.IsActive = false;
- await UpdateEntityUrl(activeUrlEntity);
- }
- else
- {
- //insert new record
- var entityUrl = new EntityUrl {
- EntityId = entityId,
- EntityName = entityName,
- Slug = slug,
- LanguageId = languageId,
- IsActive = true
- };
- await InsertEntityUrl(entityUrl);
-
- activeUrlEntity.IsActive = false;
- await UpdateEntityUrl(activeUrlEntity);
- }
+ activeUrlEntity.IsActive = false;
+ await UpdateEntityUrl(activeUrlEntity);
}
}
- }
-
- #endregion
}
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs b/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs
index c65533b68..b92baa29a 100644
--- a/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs
+++ b/src/Business/Grand.Business.Common/Services/Stores/StoreService.cs
@@ -1,139 +1,138 @@
using Grand.Business.Core.Interfaces.Common.Stores;
+using Grand.Data;
+using Grand.Domain.Stores;
using Grand.Infrastructure.Caching;
using Grand.Infrastructure.Caching.Constants;
using Grand.Infrastructure.Extensions;
-using Grand.Data;
-using Grand.Domain.Stores;
using MediatR;
-namespace Grand.Business.Common.Services.Stores
+namespace Grand.Business.Common.Services.Stores;
+
+/// <summary>
+/// Store service
+/// </summary>
+public class StoreService : IStoreService
{
+ #region Ctor
+
/// <summary>
- /// Store service
+ /// Ctor
/// </summary>
- public class StoreService : IStoreService
+ /// <param name="cacheBase">Cache manager</param>
+ /// <param name="storeRepository">Store repository</param>
+ /// <param name="mediator">Mediator</param>
+ public StoreService(ICacheBase cacheBase,
+ IRepository<Store> storeRepository,
+ IMediator mediator)
{
- #region Fields
+ _cacheBase = cacheBase;
+ _storeRepository = storeRepository;
+ _mediator = mediator;
+ }
- private readonly IRepository<Store> _storeRepository;
- private readonly IMediator _mediator;
- private readonly ICacheBase _cacheBase;
+ #endregion
- private List<Store> _allStores;
+ #region Fields
- #endregion
+ private readonly IRepository<Store> _storeRepository;
+ private readonly IMediator _mediator;
+ private readonly ICacheBase _cacheBase;
- #region Ctor
+ private List<Store> _allStores;
- /// <summary>
- /// Ctor
- /// </summary>
- /// <param name="cacheBase">Cache manager</param>
- /// <param name="storeRepository">Store repository</param>
- /// <param name="mediator">Mediator</param>
- public StoreService(ICacheBase cacheBase,
- IRepository<Store> storeRepository,
- IMediator mediator)
- {
- _cacheBase = cacheBase;
- _storeRepository = storeRepository;
- _mediator = mediator;
- }
+ #endregion
- #endregion
+ #region Methods
- #region Methods
-
- /// <summary>
- /// Gets all stores
- /// </summary>
- /// <returns>Stores</returns>
- public virtual async Task<IList<Store>> GetAllStores()
- {
- return _allStores ??= await _cacheBase.GetAsync(CacheKey.STORES_ALL_KEY, async () =>
- {
- return await Task.FromResult(_storeRepository.Table.OrderBy(x => x.DisplayOrder).ToList());
- });
- }
-
- /// <summary>
- /// Gets all stores
- /// </summary>
- /// <returns>Stores</returns>
- public virtual IList<Store> GetAll()
- {
- return _allStores ??= _cacheBase.Get(CacheKey.STORES_ALL_KEY, () =>
- {
- return _storeRepository.Table.OrderBy(x => x.DisplayOrder).ToList();
- });
- }
-
- /// <summary>
- /// Gets a store
- /// </summary>
- /// <param name="storeId">Store identifier</param>
- /// <returns>Store</returns>
- public virtual Task<Store> GetStoreById(string storeId)
+ /// <summary>
+ /// Gets all stores
+ /// </summary>
+ /// <returns>Stores</returns>
+ public virtual async Task<IList<Store>> GetAllStores()
+ {
+ return _allStores ??= await _cacheBase.GetAsync(CacheKey.STORES_ALL_KEY, async () =>
{
- var key = string.Format(CacheKey.STORES_BY_ID_KEY, storeId);
- return _cacheBase.GetAsync(key, () => _storeRepository.GetByIdAsync(storeId));
- }
-
- /// <summary>
- /// Inserts a store
- /// </summary>
- /// <param name="store">Store</param>
- public virtual async Task InsertStore(Store store)
+ return await Task.FromResult(_storeRepository.Table.OrderBy(x => x.DisplayOrder).ToList());
+ });
+ }
+
+ /// <summary>
+ /// Gets all stores
+ /// </summary>
+ /// <returns>Stores</returns>
+ public virtual IList<Store> GetAll()
+ {
+ return _allStores ??= _cacheBase.Get(CacheKey.STORES_ALL_KEY, () =>
{
- ArgumentNullException.ThrowIfNull(store);
+ return _storeRepository.Table.OrderBy(x => x.DisplayOrder).ToList();
+ });
+ }
- await _storeRepository.InsertAsync(store);
+ /// <summary>
+ /// Gets a store
+ /// </summary>
+ /// <param name="storeId">Store identifier</param>
+ /// <returns>Store</returns>
+ public virtual Task<Store> GetStoreById(string storeId)
+ {
+ var key = string.Format(CacheKey.STORES_BY_ID_KEY, storeId);
+ return _cacheBase.GetAsync(key, () => _storeRepository.GetByIdAsync(storeId));
+ }
- //clear cache
- await _cacheBase.Clear();
+ /// <summary>
+ /// Inserts a store
+ /// </summary>
+ /// <param name="store">Store</param>
+ public virtual async Task InsertStore(Store store)
+ {
+ ArgumentNullException.ThrowIfNull(store);
- //event notification
- await _mediator.EntityInserted(store);
- }
+ await _storeRepository.InsertAsync(store);
- /// <summary>
- /// Updates the store
- /// </summary>
- /// <param name="store">Store</param>
- public virtual async Task UpdateStore(Store store)
- {
- ArgumentNullException.ThrowIfNull(store);
+ //clear cache
+ await _cacheBase.Clear();
- await _storeRepository.UpdateAsync(store);
+ //event notification
+ await _mediator.EntityInserted(store);
+ }
- //clear cache
- await _cacheBase.Clear();
+ /// <summary>
+ /// Updates the store
+ /// </summary>
+ /// <param name="store">Store</param>
+ public virtual async Task UpdateStore(Store store)
+ {
+ ArgumentNullException.ThrowIfNull(store);
- //event notification
- await _mediator.EntityUpdated(store);
- }
+ await _storeRepository.UpdateAsync(store);
- /// <summary>
- /// Deletes a store
- /// </summary>
- /// <param name="store">Store</param>
- public virtual async Task DeleteStore(Store store)
- {
- ArgumentNullException.ThrowIfNull(store);
+ //clear cache
+ await _cacheBase.Clear();
- var allStores = await GetAllStores();
- if (allStores.Count == 1)
- throw new Exception("You cannot delete the only configured store");
+ //event notification
+ await _mediator.EntityUpdated(store);
+ }
- await _storeRepository.DeleteAsync(store);
+ /// <summary>
+ /// Deletes a store
+ /// </summary>
+ /// <param name="store">Store</param>
+ public virtual async Task DeleteStore(Store store)
+ {
+ ArgumentNullException.ThrowIfNull(store);
- //clear cache
- await _cacheBase.Clear();
+ var allStores = await GetAllStores();
+ if (allStores.Count == 1)
+ throw new Exception("You cannot delete the only configured store");
- //event notification
- await _mediator.EntityDeleted(store);
- }
+ await _storeRepository.DeleteAsync(store);
- #endregion
+ //clear cache
+ await _cacheBase.Clear();
+
+ //event notification
+ await _mediator.EntityDeleted(store);
}
+
+ #endregion
}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Startup/StartupApplication.cs b/src/Business/Grand.Business.Common/Startup/StartupApplication.cs
index 59aac94ca..9f55bf0eb 100644
--- a/src/Business/Grand.Business.Common/Startup/StartupApplication.cs
+++ b/src/Business/Grand.Business.Common/Startup/StartupApplication.cs
@@ -23,85 +23,88 @@ using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
-namespace Grand.Business.Common.Startup
+namespace Grand.Business.Common.Startup;
+
+public class StartupApplication : IStartupApplication
{
- public class StartupApplication : IStartupApplication
+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
+ {
+ RegisterCommonService(services);
+ RegisterDirectoryService(services);
+ RegisterConfigurationService(services);
+ RegisterLocalizationService(services);
+ RegisterSecurityService(services);
+ RegisterSeoService(services);
+ RegisterStoresService(services);
+ RegisterExportImportService(services);
+ }
+
+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
+ {
+ }
+
+ public int Priority => 100;
+ public bool BeforeConfigure => false;
+
+ private void RegisterCommonService(IServiceCollection serviceCollection)
+ {
+ serviceCollection.AddScoped<IAddressAttributeParser, AddressAttributeParser>();
+ serviceCollection.AddScoped<IAddressAttributeService, AddressAttributeService>();
+ serviceCollection.AddScoped<IUserFieldService, UserFieldService>();
+ serviceCollection.AddScoped<IHistoryService, HistoryService>();
+ serviceCollection.AddScoped<IPdfService, HtmlToPdfService>();
+ }
+
+ private void RegisterDirectoryService(IServiceCollection serviceCollection)
+ {
+ serviceCollection.AddScoped<IDateTimeService, DateTimeService>();
+
+ serviceCollection.AddScoped<ICountryService, CountryService>();
+ serviceCollection.AddScoped<ICurrencyService, CurrencyService>();
+ serviceCollection.AddScoped<IExchangeRateService, ExchangeRateService>();
+ serviceCollection.AddScoped<IGroupService, GroupService>();
+ }
+
+ private void RegisterConfigurationService(IServiceCollection serviceCollection)
+ {
+ serviceCollection.AddScoped<ISettingService, SettingService>();
+ }
+
+ private void RegisterLocalizationService(IServiceCollection serviceCollection)
{
- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
- {
- RegisterCommonService(services);
- RegisterDirectoryService(services);
- RegisterConfigurationService(services);
- RegisterLocalizationService(services);
- RegisterSecurityService(services);
- RegisterSeoService(services);
- RegisterStoresService(services);
- RegisterExportImportService(services);
- }
- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)
- {
-
- }
- public int Priority => 100;
- public bool BeforeConfigure => false;
-
- private void RegisterCommonService(IServiceCollection serviceCollection)
- {
- serviceCollection.AddScoped<IAddressAttributeParser, AddressAttributeParser>();
- serviceCollection.AddScoped<IAddressAttributeService, AddressAttributeService>();
- serviceCollection.AddScoped<IUserFieldService, UserFieldService>();
- serviceCollection.AddScoped<IHistoryService, HistoryService>();
- serviceCollection.AddScoped<IPdfService, HtmlToPdfService>();
-
- }
- private void RegisterDirectoryService(IServiceCollection serviceCollection)
- {
- serviceCollection.AddScoped<IDateTimeService, DateTimeService>();
-
- serviceCollection.AddScoped<ICountryService, CountryService>();
- serviceCollection.AddScoped<ICurrencyService, CurrencyService>();
- serviceCollection.AddScoped<IExchangeRateService, ExchangeRateService>();
- serviceCollection.AddScoped<IGroupService, GroupService>();
- }
- private void RegisterConfigurationService(IServiceCollection serviceCollection)
- {
- serviceCollection.AddScoped<ISettingService, SettingService>();
- }
- private void RegisterLocalizationService(IServiceCollection serviceCollection)
- {
- serviceCollection.AddScoped<ITranslationService, TranslationService>();
- serviceCollection.AddScoped<ILanguageService, LanguageService>();
- }
- private void RegisterSecurityService(IServiceCollection serviceCollection)
- {
- serviceCollection.AddScoped<IPermissionService, PermissionService>();
- serviceCollection.AddScoped<IAclService, AclService>();
- serviceCollection.AddScoped<IEncryptionService, EncryptionService>();
- serviceCollection.AddScoped<IPermissionProvider, PermissionProvider>();
- }
-
- private void RegisterSeoService(IServiceCollection serviceCollection)
- {
- serviceCollection.AddScoped<ISlugService, SlugService>();
- }
-
-
- private void RegisterStoresService(IServiceCollection serviceCollection)
- {
- serviceCollection.AddScoped<IStoreService, StoreService>();
- }
-
- private void RegisterExportImportService(IServiceCollection serviceCollection)
- {
- serviceCollection.AddScoped<ISchemaProperty<CountryStatesDto>, CountrySchemaProperty>();
-
- serviceCollection.AddScoped<IExportProvider, ExcelExportProvider>();
- serviceCollection.AddScoped(typeof(IExportManager<>), typeof(ExportManager<>));
-
- serviceCollection.AddScoped<IImportDataProvider, ExcelImportProvider>();
- serviceCollection.AddScoped(typeof(IImportManager<>), typeof(ImportManager<>));
-
- serviceCollection.AddScoped<IImportDataObject<CountryStatesDto>, CountryImportDataObject>();
- }
+ serviceCollection.AddScoped<ITranslationService, TranslationService>();
+ serviceCollection.AddScoped<ILanguageService, LanguageService>();
+ }
+
+ private void RegisterSecurityService(IServiceCollection serviceCollection)
+ {
+ serviceCollection.AddScoped<IPermissionService, PermissionService>();
+ serviceCollection.AddScoped<IAclService, AclService>();
+ serviceCollection.AddScoped<IEncryptionService, EncryptionService>();
+ serviceCollection.AddScoped<IPermissionProvider, PermissionProvider>();
+ }
+
+ private void RegisterSeoService(IServiceCollection serviceCollection)
+ {
+ serviceCollection.AddScoped<ISlugService, SlugService>();
+ }
+
+
+ private void RegisterStoresService(IServiceCollection serviceCollection)
+ {
+ serviceCollection.AddScoped<IStoreService, StoreService>();
+ }
+
+ private void RegisterExportImportService(IServiceCollection serviceCollection)
+ {
+ serviceCollection.AddScoped<ISchemaProperty<CountryStatesDto>, CountrySchemaProperty>();
+
+ serviceCollection.AddScoped<IExportProvider, ExcelExportProvider>();
+ serviceCollection.AddScoped(typeof(IExportManager<>), typeof(ExportManager<>));
+
+ serviceCollection.AddScoped<IImportDataProvider, ExcelImportProvider>();
+ serviceCollection.AddScoped(typeof(IImportManager<>), typeof(ImportManager<>));
+
+ serviceCollection.AddScoped<IImportDataObject<CountryStatesDto>, CountryImportDataObject>();
}
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Utilities/LanguageSchema.cs b/src/Business/Grand.Business.Common/Utilities/LanguageSchema.cs
index a5a063b18..145067371 100644
--- a/src/Business/Grand.Business.Common/Utilities/LanguageSchema.cs
+++ b/src/Business/Grand.Business.Common/Utilities/LanguageSchema.cs
@@ -2,7 +2,7 @@
public static class LanguageSchema
{
- public const string SchemaXsd = @"
+ public const string SchemaXsd = @"
<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='Language'>
<xs:complexType>
diff --git a/src/Business/Grand.Business.Common/Utilities/PowerExcelExtensions.cs b/src/Business/Grand.Business.Common/Utilities/PowerExcelExtensions.cs
index 5202123ae..60036e3ec 100644
--- a/src/Business/Grand.Business.Common/Utilities/PowerExcelExtensions.cs
+++ b/src/Business/Grand.Business.Common/Utilities/PowerExcelExtensions.cs
@@ -3,76 +3,72 @@ using NPOI.SS.UserModel;
using System.Globalization;
using System.Reflection;
-namespace Grand.Business.Common.Utilities
+namespace Grand.Business.Common.Utilities;
+
+internal static class PowerExcelExtensions
{
- static class PowerExcelExtensions
+ internal static IEnumerable<IRow> Rows(this ISheet sheet)
{
- internal static IEnumerable<IRow> Rows(this ISheet sheet)
- {
- var e = sheet.GetRowEnumerator();
- while (e.MoveNext())
- yield return e.Current as IRow;
- }
+ var e = sheet.GetRowEnumerator();
+ while (e.MoveNext())
+ yield return e.Current as IRow;
+ }
- internal static bool IsIdenticalTo(this MemberInfo memberInfo, MemberInfo other)
- {
- if (memberInfo == null || other == null) return false;
- return memberInfo.Equals(other) || memberInfo.MetadataToken == other.MetadataToken;
- }
+ internal static bool IsIdenticalTo(this MemberInfo memberInfo, MemberInfo other)
+ {
+ if (memberInfo == null || other == null) return false;
+ return memberInfo.Equals(other) || memberInfo.MetadataToken == other.MetadataToken;
+ }
- /// <summary>
- /// convert to Nullable type
- /// </summary>
- /// <param name="type"></param>
- /// <returns></returns>
- internal static Type ConvertToNullableType(this Type type)
- {
- if (type.IsPrimitive || type.IsValueType)
- {
- return typeof(Nullable<>).MakeGenericType(type);
- }
- return type;
- }
+ /// <summary>
+ /// convert to Nullable type
+ /// </summary>
+ /// <param name="type"></param>
+ /// <returns></returns>
+ internal static Type ConvertToNullableType(this Type type)
+ {
+ if (type.IsPrimitive || type.IsValueType) return typeof(Nullable<>).MakeGenericType(type);
+ return type;
+ }
- internal static object GetPropertyValue(ColumnInfo columnInfo, object o, object val, ICell cell)
- {
- object v;
- if (columnInfo.SetProp != null)
- v = columnInfo.SetProp(o, val, cell);
- else if (columnInfo.IsNullable && (val == null || val is string { Length: 0 }) && columnInfo.PropertyType == typeof(string)) //CHANGES FOR GRANDNODE
- v = "";
- else if (columnInfo.IsNullable && (val == null || val is string { Length: 0 }))
- v = null;
- else if (val is string g && columnInfo.PropertyType == typeof(Guid))
- 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
- v = Convert.ChangeType(val, columnInfo.PropertyType, CultureInfo.InvariantCulture);
+ internal static object GetPropertyValue(ColumnInfo columnInfo, object o, object val, ICell cell)
+ {
+ object v;
+ if (columnInfo.SetProp != null)
+ v = columnInfo.SetProp(o, val, cell);
+ else if (columnInfo.IsNullable && (val == null || val is string { Length: 0 }) &&
+ columnInfo.PropertyType == typeof(string)) //CHANGES FOR GRANDNODE
+ v = "";
+ else if (columnInfo.IsNullable && (val == null || val is string { Length: 0 }))
+ v = null;
+ else if (val is string g && columnInfo.PropertyType == typeof(Guid))
+ 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
+ v = Convert.ChangeType(val, columnInfo.PropertyType, CultureInfo.InvariantCulture);
- return v;
- }
+ return v;
+ }
- 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);
- }
+ 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);
+ }
- /// <summary>
- /// Sets the property of the specified object to the specified value.
- /// </summary>
- /// <param name="columnInfo"></param>
- /// <param name="o">The object whose property to set.</param>
- /// <param name="val">The value.</param>
- /// <param name="cell">The cell where the value originates from.</param>
- 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);
- }
+ /// <summary>
+ /// Sets the property of the specified object to the specified value.
+ /// </summary>
+ /// <param name="columnInfo"></param>
+ /// <param name="o">The object whose property to set.</param>
+ /// <param name="val">The value.</param>
+ /// <param name="cell">The cell where the value originates from.</param>
+ 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);
}
-
-}
+}
\ No newline at end of file
diff --git a/src/Business/Grand.Business.Common/Utilities/PowerExcelMapper.cs b/src/Business/Grand.Business.Common/Utilities/PowerExcelMapper.cs
index 4bea34be9..9c6a1f722 100644
--- a/src/Business/Grand.Business.Common/Utilities/PowerExcelMapper.cs
+++ b/src/Business/Grand.Business.Common/Utilities/PowerExcelMapper.cs
@@ -5,313 +5,310 @@ using System.Collections;
using System.Reflection;
using System.Text.Json;
-namespace Grand.Business.Common.Utilities
+namespace Grand.Business.Common.Utilities;
+
+public class PowerExcelMapper : ExcelMapper
{
- public class PowerExcelMapper : ExcelMapper
- {
+ private readonly Dictionary<Type, Func<object>> ObjectFactories = new();
- Dictionary<string, Dictionary<int, object>> Objects { get; set; } = new();
- IWorkbook Workbook { get; set; }
+ private Dictionary<string, Dictionary<int, object>> Objects { get; } = new();
+ private IWorkbook Workbook { get; set; }
- static async Task<Stream> ReadAsync(Stream stream)
- {
- var ms = new MemoryStream();
- await stream.CopyToAsync(ms);
- return ms;
- }
- public new async Task<IEnumerable<T>> FetchAsync<T>(Stream stream, int sheetIndex = 0, Func<string, object, object> valueParser = null)
- {
- using var ms = await ReadAsync(stream);
- return Fetch(ms, typeof(T), sheetIndex, valueParser).OfType<T>();
- }
- public new IEnumerable Fetch(Stream stream, Type type, int sheetIndex, Func<string, object, object> valueParser = null)
- {
- Workbook = WorkbookFactory.Create(stream);
- return Fetch(type, sheetIndex, valueParser);
- }
- public new IEnumerable Fetch(Type type, int sheetIndex = 0, Func<string, object, object> valueParser = null)
- {
- var sheet = Workbook.GetSheetAt(sheetIndex);
- return Fetch(sheet, type, valueParser);
- }
-
- IEnumerable Fetch(ISheet sheet, Type type, Func<string, object, object> valueParser = null)
- {
- var firstRowNumber = HeaderRowNumber;
+ private static async Task<Stream> ReadAsync(Stream stream)
+ {
+ var ms = new MemoryStream();
+ await stream.CopyToAsync(ms);
+ return ms;
+ }
+
+ public new async Task<IEnumerable<T>> FetchAsync<T>(Stream stream, int sheetIndex = 0,
+ Func<string, object, object> valueParser = null)
+ {
+ using var ms = await ReadAsync(stream);
+ return Fetch(ms, typeof(T), sheetIndex, valueParser).OfType<T>();
+ }
- if (!HeaderRow)
- firstRowNumber = sheet.Rows().Where(r => r.RowNum >= MinRowNumber && r.RowNum <= MaxRowNumber)
- .OrderByDescending(r => r.LastCellNum).FirstOrDefault()?.RowNum ?? 0;
+ public new IEnumerable Fetch(Stream stream, Type type, int sheetIndex,
+ Func<string, object, object> valueParser = null)
+ {
+ Workbook = WorkbookFactory.Create(stream);
+ return Fetch(type, sheetIndex, valueParser);
+ }
- var firstRow = sheet.GetRow(firstRowNumber);
+ public new IEnumerable Fetch(Type type, int sheetIndex = 0, Func<string, object, object> valueParser = null)
+ {
+ var sheet = Workbook.GetSheetAt(sheetIndex);
+ return Fetch(sheet, type, valueParser);
+ }
- if (firstRow == null)
- yield break;
+ private IEnumerable Fetch(ISheet sheet, Type type, Func<string, object, object> valueParser = null)
+ {
+ var firstRowNumber = HeaderRowNumber;
- var cells = Enumerable.Range(0, firstRow.LastCellNum).Select(i => firstRow.GetCell(i, MissingCellPolicy.RETURN_BLANK_AS_NULL));
- var firstRowCells = cells
- .Where(c => !HeaderRow || !string.IsNullOrWhiteSpace(c.ToString()));
- var typeMapper = type != null ? TypeMapperFactory.Create(type) : TypeMapper.Create(firstRowCells, HeaderRow);
+ if (!HeaderRow)
+ firstRowNumber = sheet.Rows().Where(r => r.RowNum >= MinRowNumber && r.RowNum <= MaxRowNumber)
+ .OrderByDescending(r => r.LastCellNum).FirstOrDefault()?.RowNum ?? 0;
- if (TrackObjects) Objects[sheet.SheetName] = new Dictionary<int, object>();
+ var firstRow = sheet.GetRow(firstRowNumber);
- var objInstanceIdx = 0;
+ if (firstRow == null)
+ yield break;
- foreach (IRow row in sheet)
- {
- var i = row.RowNum;
+ var cells = Enumerable.Range(0, firstRow.LastCellNum)
+ .Select(i => firstRow.GetCell(i, MissingCellPolicy.RETURN_BLANK_AS_NULL));
+ var firstRowCells = cells
+ .Where(c => !HeaderRow || !string.IsNullOrWhiteSpace(c.ToString()));
+ var typeMapper = type != null ? TypeMapperFactory.Create(type) : TypeMapper.Create(firstRowCells, HeaderRow);
- if (i < MinRowNumber) continue;
- if (i > MaxRowNumber) break;
+ if (TrackObjects) Objects[sheet.SheetName] = new Dictionary<int, object>();
- // optionally skip header row and blank rows
- 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 });
- yield return o;
- }
- }
- }
- private static bool IsCellBlank(ICell cell)
- {
- return cell.CellType switch {
- CellType.String => string.IsNullOrWhiteSpace(cell.StringCellValue),
- CellType.Blank => true,
- _ => false
- };
- }
+ var objInstanceIdx = 0;
- private object MapCells(Type type, Func<string, object, object> valueParser, TypeMapper typeMapper,
- IEnumerable<ICell> cells, ref int objInstanceIdx, IRow row, ISet<Type> callChain)
+ foreach (IRow row in sheet)
{
- var sheet = row.Sheet;
var i = row.RowNum;
- List<(ColumnInfo Col, object CellValue, ICell Cell, int ColumnIndex)> initValues = new();
- var columns = cells
- .Select(c => (Index: c.ColumnIndex,
- Columns: GetColumnInfo(typeMapper, c).Where(c => c.Directions.HasFlag(MappingDirections.ExcelToObject) && !c.IsSubType).ToList()))
- .Where(c => c.Columns.Any())
- .ToList();
-
- foreach (var (columnIndex, columnInfos) in columns)
- {
- var cell = row.GetCell(columnIndex, MissingCellPolicy.CREATE_NULL_AS_BLANK);
- if (cell != null && (!SkipBlankCells || !IsCellBlank(cell)))
- {
- foreach (ColumnInfo ci in columnInfos)
- {
- object cellValue;
+ if (i < MinRowNumber) continue;
+ if (i > MaxRowNumber) break;
- try
- {
- cellValue = GetCellValue(cell, ci);
- }
- catch (Exception e)
- {
- cellValue = GetCellValue(cell);
- TriggerOrThrowParsingError(new ExcelMapperConvertException(cellValue, ci.PropertyType, i, columnIndex, e));
- }
-
- try
- {
- if (valueParser != null)
- cellValue = valueParser(string.IsNullOrWhiteSpace(ci.Name) ? columnIndex.ToString() : ci.Name, cellValue);
-
- initValues.Add((ci, cellValue, cell, columnIndex));
- }
- catch (Exception e)
- {
- TriggerOrThrowParsingError(new ExcelMapperConvertException(cellValue, ci.PropertyType, i, columnIndex, e));
- }
- }
- }
- }
-
- if (!IgnoreNestedTypes)
+ // optionally skip header row and blank rows
+ if ((!HeaderRow || i != HeaderRowNumber) && (!SkipBlankRows || row.Cells.Any(c => !IsCellBlank(c))))
{
- foreach (ColumnInfo ci in typeMapper.ColumnsByName.SelectMany(c => c.Value).Where(c => c.IsSubType))
- {
- if (!callChain.Contains(ci.PropertyType) // check for cycle in type hierarchy
- && !initValues.Any(v => v.Col.Property.IsIdenticalTo(ci.Property))) // map subtypes only if not already mapped
- {
- callChain.Add(ci.PropertyType);
- var subTypeMapper = TypeMapperFactory.Create(ci.PropertyType);
- var subObject = MapCells(ci.PropertyType, valueParser, subTypeMapper, cells, ref objInstanceIdx, row, callChain);
- initValues.Add((ci, subObject, null, -1));
- }
- }
+ var o = MapCells(type, valueParser, typeMapper, firstRowCells, ref objInstanceIdx, row,
+ new HashSet<Type> { type });
+ yield return o;
}
+ }
+ }
- object o;
+ private static bool IsCellBlank(ICell cell)
+ {
+ return cell.CellType switch {
+ CellType.String => string.IsNullOrWhiteSpace(cell.StringCellValue),
+ CellType.Blank => true,
+ _ => false
+ };
+ }
- if (type == null)
- o = typeMapper.CreateExpando();
- else
- {
- if (typeMapper.Constructor != null)
+ private object MapCells(Type type, Func<string, object, object> valueParser, TypeMapper typeMapper,
+ IEnumerable<ICell> cells, ref int objInstanceIdx, IRow row, ISet<Type> callChain)
+ {
+ var sheet = row.Sheet;
+ var i = row.RowNum;
+ List<(ColumnInfo Col, object CellValue, ICell Cell, int ColumnIndex)> initValues = new();
+ var columns = cells
+ .Select(c => (Index: c.ColumnIndex,
+ Columns: GetColumnInfo(typeMapper, c)
+ .Where(c => c.Directions.HasFlag(MappingDirections.ExcelToObject) && !c.IsSubType).ToList()))
+ .Where(c => c.Columns.Any())
+ .ToList();
+
+ foreach (var (columnIndex, columnInfos) in columns)
+ {
+ var cell = row.GetCell(columnIndex, MissingCellPolicy.CREATE_NULL_AS_BLANK);
+
+ if (cell != null && (!SkipBlankCells || !IsCellBlank(cell)))
+ foreach (var ci in columnInfos)
{
- var parms = typeMapper.Constructor.GetParameters();
- var vals = parms.Select(p => GetDefault(p.ParameterType)).ToArray();
+ object cellValue;
- foreach (var initVal in initValues.ToList())
+ try
{
- if (typeMapper.ConstructorParams.TryGetValue(initVal.Col.Property.Name, out var parm))
- {
- try
- {
- object v;
-
- if (initVal.Cell != null)
- v = PowerExcelExtensions.GetPropertyValue(initVal.Col, null, initVal.CellValue, initVal.Cell);
- else
- v = initVal.CellValue;
-
- vals[parm.Position] = v;
-
- initValues.Remove(initVal);
- }
- catch (Exception ex)
- {
- TriggerOrThrowParsingError(new ExcelMapperConvertException(initVal.CellValue, initVal.Col.PropertyType, i, initVal.ColumnIndex, ex));
- }
- }
+ cellValue = GetCellValue(cell, ci);
+ }
+ catch (Exception e)
+ {
+ cellValue = GetCellValue(cell);
+ TriggerOrThrowParsingError(new ExcelMapperConvertException(cellValue, ci.PropertyType, i,
+ columnIndex, e));
}
try
{
- o = typeMapper.Constructor.Invoke(vals);
+ if (valueParser != null)
+ cellValue = valueParser(
+ string.IsNullOrWhiteSpace(ci.Name) ? columnIndex.ToString() : ci.Name, cellValue);
+
+ initValues.Add((ci, cellValue, cell, columnIndex));
}
- catch (Exception ex)
+ catch (Exception e)
{
- throw new ExcelMapperConvertException($"Failed to initialize type {type.FullName}.", ex);
+ TriggerOrThrowParsingError(new ExcelMapperConvertException(cellValue, ci.PropertyType, i,
+ columnIndex, e));
}
}
- else
+ }
+
+ if (!IgnoreNestedTypes)
+ foreach (var ci in typeMapper.ColumnsByName.SelectMany(c => c.Value).Where(c => c.IsSubType))
+ if (!callChain.Contains(ci.PropertyType) // check for cycle in type hierarchy
+ && !initValues.Any(v =>
+ v.Col.Property.IsIdenticalTo(ci.Property))) // map subtypes only if not already mapped
{
- if (ObjectFactories.TryGetValue(type, out var factory))
- {
- o = factory();
- }
- else
- {
+ callChain.Add(ci.PropertyType);
+ var subTypeMapper = TypeMapperFactory.Create(ci.PropertyType);
+ var subObject = MapCells(ci.PropertyType, valueParser, subTypeMapper, cells, ref objInstanceIdx,
+ row, callChain);
+ initValues.Add((ci, subObject, null, -1));
+ }
+
+ object o;
+
+ if (type == null)
+ {
+ o = typeMapper.CreateExpando();
+ }
+ else
+ {
+ if (typeMapper.Constructor != null)
+ {
+ var parms = typeMapper.Constructor.GetParameters();
+ var vals = parms.Select(p => GetDefault(p.ParameterType)).ToArray();
+
+ foreach (var initVal in initValues.ToList())
+ if (typeMapper.ConstructorParams.TryGetValue(initVal.Col.Property.Name, out var parm))
try
{
- o = Activator.CreateInstance(type);
+ object v;
+
+ if (initVal.Cell != null)
+ v = PowerExcelExtensions.GetPropertyValue(initVal.Col, null, initVal.CellValue,
+ initVal.Cell);
+ else
+ v = initVal.CellValue;
+
+ vals[parm.Position] = v;
+
+ initValues.Remove(initVal);
}
- catch (Exception)
+ catch (Exception ex)
{
- o = null;
+ TriggerOrThrowParsingError(new ExcelMapperConvertException(initVal.CellValue,
+ initVal.Col.PropertyType, i, initVal.ColumnIndex, ex));
}
- }
- if (o == null)
- return null;
+ try
+ {
+ o = typeMapper.Constructor.Invoke(vals);
+ }
+ catch (Exception ex)
+ {
+ throw new ExcelMapperConvertException($"Failed to initialize type {type.FullName}.", ex);
}
}
-
- if (initValues.Any())
+ else
{
- foreach (var val in initValues)
- {
+ if (ObjectFactories.TryGetValue(type, out var factory))
+ o = factory();
+ else
try
{
- if (val.Cell != null)
- PowerExcelExtensions.SetProperty(val.Col, o, val.CellValue, val.Cell);
- else
- val.Col.Property.SetValue(o, val.CellValue);
+ o = Activator.CreateInstance(type);
}
- catch (Exception ex)
+ catch (Exception)
{
- TriggerOrThrowParsingError(new ExcelMapperConvertException(val.CellValue, val.Col.PropertyType, i, val.ColumnIndex, ex));
+ o = null;
}
- }
- }
- if (TrackObjects) Objects[sheet.SheetName][i] = o;
- objInstanceIdx++;
- return o;
+ if (o == null)
+ return null;
+ }
}
- static object GetDefault(Type t)
- {
- return t.GetTypeInfo().IsValueType ? Activator.CreateInstance(t) : null;
- }
+ if (initValues.Any())
+ foreach (var val in initValues)
+ try
+ {
+ if (val.Cell != null)
+ PowerExcelExtensions.SetProperty(val.Col, o, val.CellValue, val.Cell);
+ else
+ val.Col.Property.SetValue(o, val.CellValue);
+ }
+ catch (Exception ex)
+ {
+ TriggerOrThrowParsingError(new ExcelMapperConvertException(val.CellValue, val.Col.PropertyType, i,
+ val.ColumnIndex, ex));
+ }
- readonly Dictionary<Type, Func<object>> ObjectFactories = new();
+ if (TrackObjects) Objects[sheet.SheetName][i] = o;
- private void TriggerOrThrowParsingError(ExcelMapperConvertException excelMapperConvertException)
- {
- var parsingError = new ParsingErrorEventArgs(excelMapperConvertException);
- //ErrorParsingCell?.Invoke(this, parsingError);
- if (!parsingError.Cancel)
- throw excelMapperConvertException;
- }
-
- List<ColumnInfo> GetColumnInfo(TypeMapper typeMapper, ICell cell)
- {
- var colByIndex = typeMapper.GetColumnByIndex(cell.ColumnIndex);
+ objInstanceIdx++;
+ return o;
+ }
- if (!HeaderRow || colByIndex != null)
- return colByIndex ?? new();
+ private static object GetDefault(Type t)
+ {
+ return t.GetTypeInfo().IsValueType ? Activator.CreateInstance(t) : null;
+ }
- var name = cell.ToString();
- var colByName = typeMapper.GetColumnByName(name);
+ private void TriggerOrThrowParsingError(ExcelMapperConvertException excelMapperConvertException)
+ {
+ var parsingError = new ParsingErrorEventArgs(excelMapperConvertException);
+ //ErrorParsingCell?.Invoke(this, parsingError);
+ if (!parsingError.Cancel)
+ throw excelMapperConvertException;
+ }
- // map column by name only if it hasn't been mapped to another property by index
- if (colByName != null
- && !typeMapper.ColumnsByIndex.SelectMany(ci => ci.Value).Any(c => c.Property.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
- return colByName;
+ private List<ColumnInfo> GetColumnInfo(TypeMapper typeMapper, ICell cell)
+ {
+ var colByIndex = typeMapper.GetColumnByIndex(cell.ColumnIndex);
- return new();
- }
+ if (!HeaderRow || colByIndex != null)
+ return colByIndex ?? new List<ColumnInfo>();
- object GetCellValue(ICell cell, ColumnInfo targetColumn)
- {
- var formulaResult = cell.CellType == CellType.Formula && (targetColumn.PropertyType != typeof(string) || targetColumn.FormulaResult);
- var cellType = formulaResult ? cell.CachedFormulaResultType : cell.CellType;
- const int maxDate = 2958465; // 31/12/9999
+ var name = cell.ToString();
+ var colByName = typeMapper.GetColumnByName(name);
- switch (cellType)
- {
- case CellType.Numeric:
- if (!formulaResult && targetColumn.PropertyType == typeof(string))
- {
- return DataFormatter.FormatCellValue(cell);
- }
+ // map column by name only if it hasn't been mapped to another property by index
+ if (colByName != null
+ && !typeMapper.ColumnsByIndex.SelectMany(ci => ci.Value)
+ .Any(c => c.Property.Name.Equals(name, StringComparison.OrdinalIgnoreCase)))
+ return colByName;
- if (cell.NumericCellValue < maxDate && DateUtil.IsCellDateFormatted(cell))
- {
- return cell.DateCellValue;
- }
- return cell.NumericCellValue;
- case CellType.Formula:
- return cell.CellFormula;
- case CellType.Boolean:
- return cell.BooleanCellValue;
- case CellType.Error:
- return cell.ErrorCellValue;
- case CellType.Unknown:
- case CellType.Blank:
- case CellType.String:
- default:
- if (targetColumn.Json)
- return JsonSerializer.Deserialize(cell.StringCellValue, targetColumn.PropertyType);
- return cell.StringCellValue;
- }
- }
+ return new List<ColumnInfo>();
+ }
+
+ private object GetCellValue(ICell cell, ColumnInfo targetColumn)
+ {
+ var formulaResult = cell.CellType == CellType.Formula &&
+ (targetColumn.PropertyType != typeof(string) || targetColumn.FormulaResult);
+ var cellType = formulaResult ? cell.CachedFormulaResultType : cell.CellType;
+ const int maxDate = 2958465; // 31/12/9999
- object GetCellValue(ICell cell)
+ switch (cellType)
{
- return cell.CellType switch {
- CellType.Numeric => cell.NumericCellValue,
- CellType.Formula => cell.CellFormula,
- CellType.Boolean => cell.BooleanCellValue,
- CellType.Error => cell.ErrorCellValue,
- CellType.String => cell.StringCellValue,
- CellType.Blank => string.Empty,
- _ => "<unknown>"
- };
+ case CellType.Numeric:
+ if (!formulaResult && targetColumn.PropertyType == typeof(string))
+ return DataFormatter.FormatCellValue(cell);
+
+ if (cell.NumericCellValue < maxDate && DateUtil.IsCellDateFormatted(cell)) return cell.DateCellValue;
+ return cell.NumericCellValue;
+ case CellType.Formula:
+ return cell.CellFormula;
+ case CellType.Boolean:
+ return cell.BooleanCellValue;
+ case CellType.Error:
+ return cell.ErrorCellValue;
+ case CellType.Unknown:
+ case CellType.Blank:
+ case CellType.String:
+ default:
+ if (targetColumn.Json)
+ return JsonSerializer.Deserialize(cell.StringCellValue, targetColumn.PropertyType);
+ return cell.StringCellValue;
}
}
-}
+
+ private object GetCellValue(ICell cell)
+ {
+ return cell.CellType switch {
+ CellType.Numeric => cell.NumericCellValue,
+ CellType.Formula => cell.CellFormula,
+ CellType.Boolean => cell.BooleanCellValue,
+ CellType.Error => cell.ErrorCellValue,
+ CellType.String => cell.StringCellValue,
+ CellType.Blank => string.Empty,
+ _ => "<unknown>"
+ };
+ }
+}
\ No newline at end of file