Open-source eCommerce platform for C# and ASP.NET Core 10 with MongoDB. Build multi-store shops and multi-vendor marketplaces with B2B/B2C, REST API, plugins, Vue 3 and Docker.
C# aspnet-corecsharpdockerdotnetecommerceecommerce-platformmongodbmulti-storemulti-vendornosqlonline-shopshoppingcart
Grand.Infrastructure - Code cleanup (ReSharper)
support1c3183629f7e
diff --git a/src/Core/Grand.Infrastructure/Caching/Constants/AddressCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/AddressCacheKey.csindex 8459748e3..e5b45fce7 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/AddressCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/AddressCacheKey.cs@@ -1,29 +1,27 @@-namespace Grand.Infrastructure.Caching.Constants-{- public static partial class CacheKey- {- /// <summary>- /// Key for caching- /// </summary>- public static string ADDRESSATTRIBUTES_ALL_KEY => "Grand.addressattribute.all";+namespace Grand.Infrastructure.Caching.Constants;- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : address attribute ID- /// </remarks>- public static string ADDRESSATTRIBUTES_BY_ID_KEY => "Grand.addressattribute.id-{0}";+public static partial class CacheKey+{+ /// <summary>+ /// Key for caching+ /// </summary>+ public static string ADDRESSATTRIBUTES_ALL_KEY => "Grand.addressattribute.all";- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string ADDRESSATTRIBUTES_PATTERN_KEY => "Grand.addressattribute.";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : address attribute ID+ /// </remarks>+ public static string ADDRESSATTRIBUTES_BY_ID_KEY => "Grand.addressattribute.id-{0}";- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string ADDRESSATTRIBUTEVALUES_PATTERN_KEY => "Grand.addressattributevalue.";+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string ADDRESSATTRIBUTES_PATTERN_KEY => "Grand.addressattribute.";- }-}+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string ADDRESSATTRIBUTEVALUES_PATTERN_KEY => "Grand.addressattributevalue.";+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/BrandCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/BrandCacheKey.csindex 1716807dd..fdcd28ff0 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/BrandCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/BrandCacheKey.cs@@ -1,20 +1,17 @@-namespace Grand.Infrastructure.Caching.Constants-{- public static partial class CacheKey- {-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string BRANDS_PATTERN_KEY => "Grand.brand.";+namespace Grand.Infrastructure.Caching.Constants;- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : brand ID- /// </remarks>- public static string BRANDS_BY_ID_KEY => "Grand.brand.id-{0}";+public static partial class CacheKey+{+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string BRANDS_PATTERN_KEY => "Grand.brand.";- }-}+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : brand ID+ /// </remarks>+ public static string BRANDS_BY_ID_KEY => "Grand.brand.id-{0}";+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/CategoryCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/CategoryCacheKey.csindex 1506484e4..cd19dfa4d 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/CategoryCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/CategoryCacheKey.cs@@ -1,48 +1,48 @@-namespace Grand.Infrastructure.Caching.Constants+namespace Grand.Infrastructure.Caching.Constants;++public static partial class CacheKey{- public static partial class CacheKey- {- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string CATEGORIES_PATTERN_KEY => "Grand.category.";+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string CATEGORIES_PATTERN_KEY => "Grand.category.";- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : category ID- /// </remarks>- public static string CATEGORIES_BY_ID_KEY => "Grand.category.id-{0}";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : category ID+ /// </remarks>+ public static string CATEGORIES_BY_ID_KEY => "Grand.category.id-{0}";- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : parent category ID- /// {1} : show hidden records?- /// {2} : current customer ID- /// {3} : store ID- /// {4} : include all levels (child)- /// </remarks>- public static string CATEGORIES_BY_PARENT_CATEGORY_ID_KEY => "Grand.category.byparent-{0}-{1}-{2}-{3}-{4}";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : parent category ID+ /// {1} : show hidden records?+ /// {2} : current customer ID+ /// {3} : store ID+ /// {4} : include all levels (child)+ /// </remarks>+ public static string CATEGORIES_BY_PARENT_CATEGORY_ID_KEY => "Grand.category.byparent-{0}-{1}-{2}-{3}-{4}";- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string PRODUCTCATEGORIES_PATTERN_KEY => "Grand.productcategory.";+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string PRODUCTCATEGORIES_PATTERN_KEY => "Grand.productcategory.";- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : show hidden records?- /// {1} : category ID- /// {2} : page index- /// {3} : page size- /// {4} : current customer ID- /// {5} : store ID- /// </remarks>- public static string PRODUCTCATEGORIES_ALLBYCATEGORYID_KEY => "Grand.productcategory.allbycategoryid-{0}-{1}-{2}-{3}-{4}-{5}";- }-}+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : show hidden records?+ /// {1} : category ID+ /// {2} : page index+ /// {3} : page size+ /// {4} : current customer ID+ /// {5} : store ID+ /// </remarks>+ public static string PRODUCTCATEGORIES_ALLBYCATEGORYID_KEY =>+ "Grand.productcategory.allbycategoryid-{0}-{1}-{2}-{3}-{4}-{5}";+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/CollectionCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/CollectionCacheKey.csindex 3642d7cbe..5efae0c93 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/CollectionCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/CollectionCacheKey.cs@@ -1,38 +1,36 @@-namespace Grand.Infrastructure.Caching.Constants-{- public static partial class CacheKey- {-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string COLLECTIONS_PATTERN_KEY => "Grand.collection.";+namespace Grand.Infrastructure.Caching.Constants;- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : collection ID- /// </remarks>- public static string COLLECTIONS_BY_ID_KEY => "Grand.collection.id-{0}";+public static partial class CacheKey+{+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string COLLECTIONS_PATTERN_KEY => "Grand.collection.";- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : show hidden records?- /// {1} : collection ID- /// {2} : page index- /// {3} : page size- /// {4} : current customer ID- /// {5} : store ID- /// </remarks>- public static string PRODUCTCOLLECTIONS_ALLBYCOLLECTIONID_KEY => "Grand.productcollection.allbycollectionid-{0}-{1}-{2}-{3}-{4}-{5}";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : collection ID+ /// </remarks>+ public static string COLLECTIONS_BY_ID_KEY => "Grand.collection.id-{0}";- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string PRODUCTCOLLECTIONS_PATTERN_KEY => "Grand.productcollection.";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : show hidden records?+ /// {1} : collection ID+ /// {2} : page index+ /// {3} : page size+ /// {4} : current customer ID+ /// {5} : store ID+ /// </remarks>+ public static string PRODUCTCOLLECTIONS_ALLBYCOLLECTIONID_KEY =>+ "Grand.productcollection.allbycollectionid-{0}-{1}-{2}-{3}-{4}-{5}";- }-}+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string PRODUCTCOLLECTIONS_PATTERN_KEY => "Grand.productcollection.";+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/CommonCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/CommonCacheKey.csindex b78b7df6f..d0e319fee 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/CommonCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/CommonCacheKey.cs@@ -1,216 +1,216 @@-namespace Grand.Infrastructure.Caching.Constants+namespace Grand.Infrastructure.Caching.Constants;++public static partial class CacheKey{- public static partial class CacheKey- {- #region Settings-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : key - settings name- /// {1} : store ident- /// </remarks>- public static string SETTINGS_BY_KEY => "Grand.setting.{0}.{1}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string SETTINGS_PATTERN_KEY => "Grand.setting.";-- #endregion-- #region Discounts-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : discount ID- /// </remarks>- public static string DISCOUNTS_BY_ID_KEY => "Grand.discount.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : discount type ?- /// {1} : store ident- /// {2} : currency code- /// </remarks>- public static string DISCOUNTS_CONTEXT_KEY => "Grand.discount.context-{0}-{1}-{2}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string DISCOUNTS_PATTERN_KEY => "Grand.discount.";-- #endregion-- #region Languages & localization-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : language ID- /// </remarks>- public static string LANGUAGES_BY_ID_KEY => "Grand.language.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : language code- /// </remarks>- public static string LANGUAGES_BY_CODE => "Grand.language.code-{0}";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : show hidden records?- /// </remarks>- public static string LANGUAGES_ALL_KEY => "Grand.language.all-{0}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string LANGUAGES_PATTERN_KEY => "Grand.language.";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : language ID- /// </remarks>- public static string TRANSLATERESOURCES_ALL_KEY => "Grand.translate.all-{0}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string TRANSLATERESOURCES_PATTERN_KEY => "Grand.translate.";-- #endregion-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : picture ID- /// </remarks>- public static string PICTURE_BY_ID => "Grand.picture-{0}";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : picture ID- /// {1} : target size- /// {2} : showDefaultPicture- /// {3} : storeLocation- /// </remarks>- public static string PICTURE_BY_KEY => "Grand.picture-{0}-{1}-{2}-{3}";-- #region Seo-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : entity ID- /// {1} : entity name- /// {2} : language ID- /// </remarks>- public static string URLEntity_ACTIVE_BY_ID_NAME_LANGUAGE_KEY => "Grand.urlEntity.active.id-name-language-{0}-{1}-{2}";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : slug- /// </remarks>- public static string URLEntity_BY_SLUG_KEY => "Grand.urlEntity.active.slug-{0}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string URLEntity_PATTERN_KEY = "Grand.urlEntity.";-- #endregion-- #region Stores-- /// <summary>- /// Key for caching- /// </summary>- public static string STORES_ALL_KEY => "Grand.stores.all";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : store ID- /// </remarks>- public static string STORES_BY_ID_KEY => "Grand.stores.id-{0}";-- #endregion-- #region Tax-- /// <summary>- /// Key for caching- /// </summary>- public static string TAXCATEGORIES_ALL_KEY => "Grand.taxcategory.all";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : tax category ID- /// </remarks>- public static string TAXCATEGORIES_BY_ID_KEY => "Grand.taxcategory.id-{0}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string TAXCATEGORIES_PATTERN_KEY => "Grand.taxcategory.";-- #endregion-- #region Pages-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : store ID- /// {1} : ignore ACL?- /// </remarks>- public static string PAGES_ALL_KEY => "Grand.pages.all-{0}-{1}";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : page ID- /// </remarks>- public static string PAGES_BY_ID_KEY => "Grand.pages.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : page system name- /// {1} : store id- /// </remarks>- public static string PAGES_BY_SYSTEMNAME => "Grand.pages.systemname-{0}-{1}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string PAGES_PATTERN_KEY => "Grand.pages.";-- #endregion- }-}+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : picture ID+ /// </remarks>+ public static string PICTURE_BY_ID => "Grand.picture-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : picture ID+ /// {1} : target size+ /// {2} : showDefaultPicture+ /// {3} : storeLocation+ /// </remarks>+ public static string PICTURE_BY_KEY => "Grand.picture-{0}-{1}-{2}-{3}";++ #region Settings++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : key - settings name+ /// {1} : store ident+ /// </remarks>+ public static string SETTINGS_BY_KEY => "Grand.setting.{0}.{1}";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string SETTINGS_PATTERN_KEY => "Grand.setting.";++ #endregion++ #region Discounts++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : discount ID+ /// </remarks>+ public static string DISCOUNTS_BY_ID_KEY => "Grand.discount.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : discount type ?+ /// {1} : store ident+ /// {2} : currency code+ /// </remarks>+ public static string DISCOUNTS_CONTEXT_KEY => "Grand.discount.context-{0}-{1}-{2}";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string DISCOUNTS_PATTERN_KEY => "Grand.discount.";++ #endregion++ #region Languages & localization++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : language ID+ /// </remarks>+ public static string LANGUAGES_BY_ID_KEY => "Grand.language.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : language code+ /// </remarks>+ public static string LANGUAGES_BY_CODE => "Grand.language.code-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : show hidden records?+ /// </remarks>+ public static string LANGUAGES_ALL_KEY => "Grand.language.all-{0}";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string LANGUAGES_PATTERN_KEY => "Grand.language.";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : language ID+ /// </remarks>+ public static string TRANSLATERESOURCES_ALL_KEY => "Grand.translate.all-{0}";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string TRANSLATERESOURCES_PATTERN_KEY => "Grand.translate.";++ #endregion++ #region Seo++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : entity ID+ /// {1} : entity name+ /// {2} : language ID+ /// </remarks>+ public static string URLEntity_ACTIVE_BY_ID_NAME_LANGUAGE_KEY =>+ "Grand.urlEntity.active.id-name-language-{0}-{1}-{2}";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : slug+ /// </remarks>+ public static string URLEntity_BY_SLUG_KEY => "Grand.urlEntity.active.slug-{0}";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string URLEntity_PATTERN_KEY = "Grand.urlEntity.";++ #endregion++ #region Stores++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string STORES_ALL_KEY => "Grand.stores.all";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : store ID+ /// </remarks>+ public static string STORES_BY_ID_KEY => "Grand.stores.id-{0}";++ #endregion++ #region Tax++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string TAXCATEGORIES_ALL_KEY => "Grand.taxcategory.all";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : tax category ID+ /// </remarks>+ public static string TAXCATEGORIES_BY_ID_KEY => "Grand.taxcategory.id-{0}";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string TAXCATEGORIES_PATTERN_KEY => "Grand.taxcategory.";++ #endregion++ #region Pages++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : store ID+ /// {1} : ignore ACL?+ /// </remarks>+ public static string PAGES_ALL_KEY => "Grand.pages.all-{0}-{1}";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : page ID+ /// </remarks>+ public static string PAGES_BY_ID_KEY => "Grand.pages.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : page system name+ /// {1} : store id+ /// </remarks>+ public static string PAGES_BY_SYSTEMNAME => "Grand.pages.systemname-{0}-{1}";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string PAGES_PATTERN_KEY => "Grand.pages.";++ #endregion+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/CustomerCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/CustomerCacheKey.csindex a74277a43..49f6c642c 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/CustomerCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/CustomerCacheKey.cs@@ -1,118 +1,117 @@-namespace Grand.Infrastructure.Caching.Constants+namespace Grand.Infrastructure.Caching.Constants;++public static partial class CacheKey{- public static partial class CacheKey- {- public static string CUSTOMER_ACTION_TYPE => "Grand.customer.action.type";-- /// <summary>- /// Key for caching- /// </summary>- public static string CUSTOMERATTRIBUTES_ALL_KEY => "Grand.customerattribute.all";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : customer attribute ID- /// </remarks>- public static string CUSTOMERATTRIBUTES_BY_ID_KEY => "Grand.customerattribute.id-{0}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string CUSTOMERATTRIBUTES_PATTERN_KEY => "Grand.customerattribute.";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string CUSTOMERATTRIBUTEVALUES_PATTERN_KEY => "Grand.customerattributevalue.";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : ident- /// </remarks>- public static string CUSTOMERGROUPS_BY_KEY => "Grand.customergroup.key-{0}";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// </remarks>- public static string CUSTOMERGROUPS_ALL => "Grand.customergroup.all";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : system name- /// </remarks>- public static string CUSTOMERGROUPS_BY_SYSTEMNAME_KEY => "Grand.customergroup.systemname-{0}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string CUSTOMERGROUPS_PATTERN_KEY => "Grand.customergroup.";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : customer group Id?- /// </remarks>- public static string CUSTOMERGROUPSPRODUCTS_ROLE_KEY => "Grand.customergroupproducts.role-{0}";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : ident- /// </remarks>- public static string CUSTOMER_BY_SYSTEMNAME_BY_KEY => "Grand.customer.systemname-{0}";-- #region Customer activity-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : ident- /// </remarks>- public static string ACTIVITYTYPE_BY_KEY => "Grand.activitytype.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- public static string ACTIVITYTYPE_ALL_KEY => "Grand.activitytype.all";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string ACTIVITYTYPE_PATTERN_KEY => "Grand.activitytype.";-- #endregion-- #region Sales person-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : sales-employee ID- /// </remarks>- public static string SALESEMPLOYEE_BY_ID_KEY => "Grand.salesemployee.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- public static string SALESEMPLOYEE_ALL => "Grand.salesemployee.all";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string SALESEMPLOYEE_PATTERN_KEY => "Grand.salesemployee.";-- #endregion- }-}+ public static string CUSTOMER_ACTION_TYPE => "Grand.customer.action.type";++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string CUSTOMERATTRIBUTES_ALL_KEY => "Grand.customerattribute.all";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : customer attribute ID+ /// </remarks>+ public static string CUSTOMERATTRIBUTES_BY_ID_KEY => "Grand.customerattribute.id-{0}";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string CUSTOMERATTRIBUTES_PATTERN_KEY => "Grand.customerattribute.";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string CUSTOMERATTRIBUTEVALUES_PATTERN_KEY => "Grand.customerattributevalue.";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : ident+ /// </remarks>+ public static string CUSTOMERGROUPS_BY_KEY => "Grand.customergroup.key-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// </remarks>+ public static string CUSTOMERGROUPS_ALL => "Grand.customergroup.all";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : system name+ /// </remarks>+ public static string CUSTOMERGROUPS_BY_SYSTEMNAME_KEY => "Grand.customergroup.systemname-{0}";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string CUSTOMERGROUPS_PATTERN_KEY => "Grand.customergroup.";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : customer group Id?+ /// </remarks>+ public static string CUSTOMERGROUPSPRODUCTS_ROLE_KEY => "Grand.customergroupproducts.role-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : ident+ /// </remarks>+ public static string CUSTOMER_BY_SYSTEMNAME_BY_KEY => "Grand.customer.systemname-{0}";++ #region Customer activity++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : ident+ /// </remarks>+ public static string ACTIVITYTYPE_BY_KEY => "Grand.activitytype.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string ACTIVITYTYPE_ALL_KEY => "Grand.activitytype.all";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string ACTIVITYTYPE_PATTERN_KEY => "Grand.activitytype.";++ #endregion++ #region Sales person++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : sales-employee ID+ /// </remarks>+ public static string SALESEMPLOYEE_BY_ID_KEY => "Grand.salesemployee.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string SALESEMPLOYEE_ALL => "Grand.salesemployee.all";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string SALESEMPLOYEE_PATTERN_KEY => "Grand.salesemployee.";++ #endregion+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/DirectoryCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/DirectoryCacheKey.csindex 900839f6d..08b407429 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/DirectoryCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/DirectoryCacheKey.cs@@ -1,157 +1,157 @@-namespace Grand.Infrastructure.Caching.Constants+namespace Grand.Infrastructure.Caching.Constants;++public static partial class CacheKey{- public static partial class CacheKey- {- #region Currency-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : currency ID- /// </remarks>- public static string CURRENCIES_BY_ID_KEY => "Grand.currency.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : currency code- /// </remarks>- public static string CURRENCIES_BY_CODE => "Grand.currency.code-{0}";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : show hidden records?- /// </remarks>- public static string CURRENCIES_ALL_KEY => "Grand.currency.all-{0}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string CURRENCIES_PATTERN_KEY => "Grand.currency.";-- #endregion-- #region Measure-- /// <summary>- /// Key for caching- /// </summary>- public static string MEASUREDIMENSIONS_ALL_KEY => "Grand.measuredimension.all";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : dimension ID- /// </remarks>- public static string MEASUREDIMENSIONS_BY_ID_KEY => "Grand.measuredimension.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- public static string MEASUREWEIGHTS_ALL_KEY => "Grand.measureweight.all";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : weight ID- /// </remarks>- public static string MEASUREWEIGHTS_BY_ID_KEY => "Grand.measureweight.id-{0}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string MEASUREDIMENSIONS_PATTERN_KEY => "Grand.measuredimension.";- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string MEASUREWEIGHTS_PATTERN_KEY => "Grand.measureweight.";-- /// <summary>- /// Key for caching- /// </summary>- public static string MEASUREUNITS_ALL_KEY => "Grand.measureunit.all";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : dimension ID- /// </remarks>- public static string MEASUREUNITS_BY_ID_KEY => "Grand.measureunit.id-{0}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string MEASUREUNITS_PATTERN_KEY => "Grand.measureunit.";-- #endregion-- #region Robots.txt-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// </remarks>- public static string ROBOTS_ALL_KEY => "Grand.robots.";-- /// <summary>- /// Key for caching by store id- /// </summary>- /// <remarks>- /// {0} : store ID- /// </remarks>- public static string ROBOTS_BY_STORE => "Grand.robots.id-{0}";-- #endregion-- #region Country- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : language ID- /// {1} : store ID- /// {2} : show hidden records?- /// </remarks>- public static string COUNTRIES_ALL_KEY => "Grand.country.all-{0}-{1}-{2}";-- /// <summary>- /// key for caching by country id- /// </summary>- /// <remarks>- /// {0} : country ID- /// </remarks>- public static string COUNTRIES_BY_KEY => "Grand.country.id-{0}";-- /// <summary>- /// key for caching by country id- /// </summary>- /// <remarks>- /// {0} : two-letter- /// </remarks>- public static string COUNTRIES_BY_TWOLETTER => "Grand.country.twoletter-{0}";-- /// <summary>- /// key for caching by country id- /// </summary>- /// <remarks>- /// {0} : three-letter- /// </remarks>- public static string COUNTRIES_BY_THREELETTER => "Grand.country.threeletter-{0}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string COUNTRIES_PATTERN_KEY => "Grand.country.";-- #endregion-- }-}+ #region Currency++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : currency ID+ /// </remarks>+ public static string CURRENCIES_BY_ID_KEY => "Grand.currency.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : currency code+ /// </remarks>+ public static string CURRENCIES_BY_CODE => "Grand.currency.code-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : show hidden records?+ /// </remarks>+ public static string CURRENCIES_ALL_KEY => "Grand.currency.all-{0}";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string CURRENCIES_PATTERN_KEY => "Grand.currency.";++ #endregion++ #region Measure++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string MEASUREDIMENSIONS_ALL_KEY => "Grand.measuredimension.all";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : dimension ID+ /// </remarks>+ public static string MEASUREDIMENSIONS_BY_ID_KEY => "Grand.measuredimension.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string MEASUREWEIGHTS_ALL_KEY => "Grand.measureweight.all";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : weight ID+ /// </remarks>+ public static string MEASUREWEIGHTS_BY_ID_KEY => "Grand.measureweight.id-{0}";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string MEASUREDIMENSIONS_PATTERN_KEY => "Grand.measuredimension.";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string MEASUREWEIGHTS_PATTERN_KEY => "Grand.measureweight.";++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string MEASUREUNITS_ALL_KEY => "Grand.measureunit.all";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : dimension ID+ /// </remarks>+ public static string MEASUREUNITS_BY_ID_KEY => "Grand.measureunit.id-{0}";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string MEASUREUNITS_PATTERN_KEY => "Grand.measureunit.";++ #endregion++ #region Robots.txt++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// </remarks>+ public static string ROBOTS_ALL_KEY => "Grand.robots.";++ /// <summary>+ /// Key for caching by store id+ /// </summary>+ /// <remarks>+ /// {0} : store ID+ /// </remarks>+ public static string ROBOTS_BY_STORE => "Grand.robots.id-{0}";++ #endregion++ #region Country++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : language ID+ /// {1} : store ID+ /// {2} : show hidden records?+ /// </remarks>+ public static string COUNTRIES_ALL_KEY => "Grand.country.all-{0}-{1}-{2}";++ /// <summary>+ /// key for caching by country id+ /// </summary>+ /// <remarks>+ /// {0} : country ID+ /// </remarks>+ public static string COUNTRIES_BY_KEY => "Grand.country.id-{0}";++ /// <summary>+ /// key for caching by country id+ /// </summary>+ /// <remarks>+ /// {0} : two-letter+ /// </remarks>+ public static string COUNTRIES_BY_TWOLETTER => "Grand.country.twoletter-{0}";++ /// <summary>+ /// key for caching by country id+ /// </summary>+ /// <remarks>+ /// {0} : three-letter+ /// </remarks>+ public static string COUNTRIES_BY_THREELETTER => "Grand.country.threeletter-{0}";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string COUNTRIES_PATTERN_KEY => "Grand.country.";++ #endregion+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/GrandNodeVersionCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/GrandNodeVersionCacheKey.csindex 57a40ee44..077e108fb 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/GrandNodeVersionCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/GrandNodeVersionCacheKey.cs@@ -1,7 +1,6 @@-namespace Grand.Infrastructure.Caching.Constants+namespace Grand.Infrastructure.Caching.Constants;++public static partial class CacheKey{- public static partial class CacheKey- {- public static string GRAND_NODE_VERSION => "Grand.node.version";- }-}+ public static string GRAND_NODE_VERSION => "Grand.node.version";+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/KnowledgebaseCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/KnowledgebaseCacheKey.csindex 785007edd..40f249305 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/KnowledgebaseCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/KnowledgebaseCacheKey.cs@@ -1,87 +1,85 @@-namespace Grand.Infrastructure.Caching.Constants-{- public static partial class CacheKey- {- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string KNOWLEDGEBASE_CATEGORIES_PATTERN_KEY => "Knowledgebase.category.";+namespace Grand.Infrastructure.Caching.Constants;- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string ARTICLES_PATTERN_KEY => "Knowledgebase.article.";+public static partial class CacheKey+{+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string KNOWLEDGEBASE_CATEGORIES_PATTERN_KEY => "Knowledgebase.category.";- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : category ID- /// {1} : customer groups- /// {2} : store id- /// </remarks>- public static string KNOWLEDGEBASE_CATEGORY_BY_ID => "Knowledgebase.category.id-{0}-{1}-{2}";+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string ARTICLES_PATTERN_KEY => "Knowledgebase.article.";- /// <summary>- /// Key for caching- /// {0} : customer groups- /// {1} : store id- /// </summary>- public static string KNOWLEDGEBASE_CATEGORIES => "Knowledgebase.category.all-{0}-{1}";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : category ID+ /// {1} : customer groups+ /// {2} : store id+ /// </remarks>+ public static string KNOWLEDGEBASE_CATEGORY_BY_ID => "Knowledgebase.category.id-{0}-{1}-{2}";- /// <summary>- /// Key for caching- /// {0} : customer groups- /// {1} : store id- /// </summary>- public static string ARTICLES => "Knowledgebase.article.all-{0}-{1}";+ /// <summary>+ /// Key for caching+ /// {0} : customer groups+ /// {1} : store id+ /// </summary>+ public static string KNOWLEDGEBASE_CATEGORIES => "Knowledgebase.category.all-{0}-{1}";- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : article ID- /// {1} : customer groups- /// {2} : store id- /// </remarks>- public static string ARTICLE_BY_ID => "Knowledgebase.article.id-{0}-{1}-{2}";+ /// <summary>+ /// Key for caching+ /// {0} : customer groups+ /// {1} : store id+ /// </summary>+ public static string ARTICLES => "Knowledgebase.article.all-{0}-{1}";- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : category ID- /// {1} : customer groups- /// {2} : store id- /// </remarks>- public static string ARTICLES_BY_CATEGORY_ID => "Knowledgebase.article.categoryid-{0}-{1}-{2}";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : article ID+ /// {1} : customer groups+ /// {2} : store id+ /// </remarks>+ public static string ARTICLE_BY_ID => "Knowledgebase.article.id-{0}-{1}-{2}";- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : keyword- /// {1} : customer groups- /// {2} : store id- /// </remarks>- public static string ARTICLES_BY_KEYWORD => "Knowledgebase.article.keyword-{0}-{1}-{2}";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : category ID+ /// {1} : customer groups+ /// {2} : store id+ /// </remarks>+ public static string ARTICLES_BY_CATEGORY_ID => "Knowledgebase.article.categoryid-{0}-{1}-{2}";- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : keyword- /// {1} : customer groups- /// {2} : store id- /// </remarks>- public static string KNOWLEDGEBASE_CATEGORIES_BY_KEYWORD => "Knowledgebase.category.keyword-{0}-{1}-{2}";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : keyword+ /// {1} : customer groups+ /// {2} : store id+ /// </remarks>+ public static string ARTICLES_BY_KEYWORD => "Knowledgebase.article.keyword-{0}-{1}-{2}";- /// <summary>- /// Key for caching- /// {0} : customer groups- /// {1} : store id- /// </summary>- public static string HOMEPAGE_ARTICLES => "Knowledgebase.article.homepage-{0}-{1}";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : keyword+ /// {1} : customer groups+ /// {2} : store id+ /// </remarks>+ public static string KNOWLEDGEBASE_CATEGORIES_BY_KEYWORD => "Knowledgebase.category.keyword-{0}-{1}-{2}";- }-}+ /// <summary>+ /// Key for caching+ /// {0} : customer groups+ /// {1} : store id+ /// </summary>+ public static string HOMEPAGE_ARTICLES => "Knowledgebase.article.homepage-{0}-{1}";+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/LayoutCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/LayoutCacheKey.csindex abe866199..4ed841910 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/LayoutCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/LayoutCacheKey.cs@@ -1,115 +1,114 @@-namespace Grand.Infrastructure.Caching.Constants+namespace Grand.Infrastructure.Caching.Constants;++public static partial class CacheKey{- public static partial class CacheKey- {- #region page layout-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : warehouse ID- /// </remarks>- public static string PAGE_LAYOUT_BY_ID_KEY => "Grand.page.layout.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- public static string PAGE_LAYOUT_ALL => "Grand.page.layout.all";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string PAGE_LAYOUT_PATTERN_KEY => "Grand.page.layout.";-- #endregion-- #region product layout-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : layout ID- /// </remarks>- public static string PRODUCT_LAYOUT_BY_ID_KEY => "Grand.product.layout.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- public static string PRODUCT_LAYOUT_ALL => "Grand.product.layout.all";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string PRODUCT_LAYOUT_PATTERN_KEY => "Grand.product.layout.";-- #endregion-- #region category layout- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : layout ID- /// </remarks>- public static string CATEGORY_LAYOUT_BY_ID_KEY => "Grand.category.layout.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- public static string CATEGORY_LAYOUT_ALL => "Grand.category.layout.all";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string CATEGORY_LAYOUT_PATTERN_KEY => "Grand.category.layout.";-- #endregion-- #region brand layout-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : layout ID- /// </remarks>- public static string BRAND_LAYOUT_BY_ID_KEY => "Grand.brand.layout.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- public static string BRAND_LAYOUT_ALL => "Grand.brand.layout.all";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string BRAND_LAYOUT_PATTERN_KEY => "Grand.brand.layout.";-- #endregion-- #region collection layout-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : layout ID- /// </remarks>- public static string COLLECTION_LAYOUT_BY_ID_KEY => "Grand.collection.layout.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- public static string COLLECTION_LAYOUT_ALL => "Grand.collection.layout.all";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string COLLECTION_LAYOUT_PATTERN_KEY => "Grand.collection.layout.";-- #endregion-- }-}+ #region page layout++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : warehouse ID+ /// </remarks>+ public static string PAGE_LAYOUT_BY_ID_KEY => "Grand.page.layout.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string PAGE_LAYOUT_ALL => "Grand.page.layout.all";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string PAGE_LAYOUT_PATTERN_KEY => "Grand.page.layout.";++ #endregion++ #region product layout++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : layout ID+ /// </remarks>+ public static string PRODUCT_LAYOUT_BY_ID_KEY => "Grand.product.layout.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string PRODUCT_LAYOUT_ALL => "Grand.product.layout.all";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string PRODUCT_LAYOUT_PATTERN_KEY => "Grand.product.layout.";++ #endregion++ #region category layout++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : layout ID+ /// </remarks>+ public static string CATEGORY_LAYOUT_BY_ID_KEY => "Grand.category.layout.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string CATEGORY_LAYOUT_ALL => "Grand.category.layout.all";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string CATEGORY_LAYOUT_PATTERN_KEY => "Grand.category.layout.";++ #endregion++ #region brand layout++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : layout ID+ /// </remarks>+ public static string BRAND_LAYOUT_BY_ID_KEY => "Grand.brand.layout.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string BRAND_LAYOUT_ALL => "Grand.brand.layout.all";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string BRAND_LAYOUT_PATTERN_KEY => "Grand.brand.layout.";++ #endregion++ #region collection layout++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : layout ID+ /// </remarks>+ public static string COLLECTION_LAYOUT_BY_ID_KEY => "Grand.collection.layout.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string COLLECTION_LAYOUT_ALL => "Grand.collection.layout.all";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string COLLECTION_LAYOUT_PATTERN_KEY => "Grand.collection.layout.";++ #endregion+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/MerchandiseReturnCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/MerchandiseReturnCacheKey.csindex 27a92bb31..a5d206b8b 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/MerchandiseReturnCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/MerchandiseReturnCacheKey.cs@@ -1,14 +1,14 @@-namespace Grand.Infrastructure.Caching.Constants+namespace Grand.Infrastructure.Caching.Constants;++public static partial class CacheKey{- public static partial class CacheKey- {- /// <summary>- /// Key for all merchandise return reason- /// </summary>- public static string MERCHANDISE_RETURN_REASONS_ALL_KEY => "Grand.merchandisereturn.reasons.all";- /// <summary>- /// Key for all merchandise return actions- /// </summary>- public static string MERCHANDISE_RETURN_ACTIONS_ALL_KEY => "Grand.merchandisereturn.actions.all";- }-}+ /// <summary>+ /// Key for all merchandise return reason+ /// </summary>+ public static string MERCHANDISE_RETURN_REASONS_ALL_KEY => "Grand.merchandisereturn.reasons.all";++ /// <summary>+ /// Key for all merchandise return actions+ /// </summary>+ public static string MERCHANDISE_RETURN_ACTIONS_ALL_KEY => "Grand.merchandisereturn.actions.all";+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/MessagesCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/MessagesCacheKey.csindex 8a912f9cd..6cb16902c 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/MessagesCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/MessagesCacheKey.cs@@ -1,86 +1,85 @@-namespace Grand.Infrastructure.Caching.Constants+namespace Grand.Infrastructure.Caching.Constants;++public static partial class CacheKey{- public static partial class CacheKey- {- #region Contact attributes-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : store ID- /// {1} : ignore ACL?- /// </remarks>- public static string CONTACTATTRIBUTES_ALL_KEY => "Grand.contactattribute.all-{0}-{1}";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : contact attribute ID- /// </remarks>- public static string CONTACTATTRIBUTES_BY_ID_KEY => "Grand.contactattribute.id-{0}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string CONTACTATTRIBUTES_PATTERN_KEY => "Grand.contactattribute.";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string CONTACTATTRIBUTEVALUES_PATTERN_KEY => "Grand.contactattributevalue.";-- #endregion-- #region Email account-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : email account ID- /// </remarks>- public static string EMAILACCOUNT_BY_ID_KEY =>"Grand.emailaccount.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// </remarks>- public static string EMAILACCOUNT_ALL_KEY => "Grand.emailaccount.all";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string EMAILACCOUNT_PATTERN_KEY => "Grand.emailaccount.";-- #endregion-- #region Message template-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : store ID- /// </remarks>- public static string MESSAGETEMPLATES_ALL_KEY => "Grand.messagetemplate.all-{0}";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : template name- /// {1} : store ID- /// </remarks>- public static string MESSAGETEMPLATES_BY_NAME_KEY => "Grand.messagetemplate.name-{0}-{1}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string MESSAGETEMPLATES_PATTERN_KEY => "Grand.messagetemplate.";-- #endregion- }-}+ #region Contact attributes++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : store ID+ /// {1} : ignore ACL?+ /// </remarks>+ public static string CONTACTATTRIBUTES_ALL_KEY => "Grand.contactattribute.all-{0}-{1}";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : contact attribute ID+ /// </remarks>+ public static string CONTACTATTRIBUTES_BY_ID_KEY => "Grand.contactattribute.id-{0}";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string CONTACTATTRIBUTES_PATTERN_KEY => "Grand.contactattribute.";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string CONTACTATTRIBUTEVALUES_PATTERN_KEY => "Grand.contactattributevalue.";++ #endregion++ #region Email account++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : email account ID+ /// </remarks>+ public static string EMAILACCOUNT_BY_ID_KEY => "Grand.emailaccount.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// </remarks>+ public static string EMAILACCOUNT_ALL_KEY => "Grand.emailaccount.all";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string EMAILACCOUNT_PATTERN_KEY => "Grand.emailaccount.";++ #endregion++ #region Message template++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : store ID+ /// </remarks>+ public static string MESSAGETEMPLATES_ALL_KEY => "Grand.messagetemplate.all-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : template name+ /// {1} : store ID+ /// </remarks>+ public static string MESSAGETEMPLATES_BY_NAME_KEY => "Grand.messagetemplate.name-{0}-{1}";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string MESSAGETEMPLATES_PATTERN_KEY => "Grand.messagetemplate.";++ #endregion+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/OrdersCacheKeys.cs b/src/Core/Grand.Infrastructure/Caching/Constants/OrdersCacheKeys.csindex 0258f3b61..d1560a18a 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/OrdersCacheKeys.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/OrdersCacheKeys.cs@@ -1,78 +1,75 @@-namespace Grand.Infrastructure.Caching.Constants-{- public static partial class CacheKey- {+namespace Grand.Infrastructure.Caching.Constants;- #region Order status+public static partial class CacheKey+{+ #region Order status- /// <summary>- /// Key for caching- /// </summary>- public static string ORDER_STATUS_ALL => "Grand.orderstatus.all";+ /// <summary>+ /// Key for caching+ /// </summary>+ public static string ORDER_STATUS_ALL => "Grand.orderstatus.all";- #endregion+ #endregion- #region Checkout attributes+ #region Checkout attributes- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : store ID- /// {1} : >A value indicating whether we should exclude shippable attributes- /// {2} : ignore ACL?- /// </remarks>- public static string CHECKOUTATTRIBUTES_ALL_KEY => "Grand.checkoutattribute.all-{0}-{1}-{2}";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : store ID+ /// {1} : >A value indicating whether we should exclude shippable attributes+ /// {2} : ignore ACL?+ /// </remarks>+ public static string CHECKOUTATTRIBUTES_ALL_KEY => "Grand.checkoutattribute.all-{0}-{1}-{2}";- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : checkout attribute ID- /// </remarks>- public static string CHECKOUTATTRIBUTES_BY_ID_KEY => "Grand.checkoutattribute.id-{0}";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : checkout attribute ID+ /// </remarks>+ public static string CHECKOUTATTRIBUTES_BY_ID_KEY => "Grand.checkoutattribute.id-{0}";- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string CHECKOUTATTRIBUTES_PATTERN_KEY => "Grand.checkoutattribute.";+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string CHECKOUTATTRIBUTES_PATTERN_KEY => "Grand.checkoutattribute.";- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string CHECKOUTATTRIBUTEVALUES_PATTERN_KEY => "Grand.checkoutattributevalue.";+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string CHECKOUTATTRIBUTEVALUES_PATTERN_KEY => "Grand.checkoutattributevalue.";- #endregion+ #endregion- #region Order tags+ #region Order tags- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : store ID- /// </remarks>- public static string ORDERTAG_COUNT_KEY => "Grand.ordertag.count-{0}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string ORDERTAG_PATTERN_KEY => "Grand.ordertag.";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : store ID+ /// </remarks>+ public static string ORDERTAG_COUNT_KEY => "Grand.ordertag.count-{0}";- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : order ID- /// </remarks>- public static string ORDERS_BY_ID_KEY => "Grand.order.id-{0}";+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string ORDERTAG_PATTERN_KEY => "Grand.ordertag.";- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string ORDERS_PATTERN_KEY => "Grand.order.";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : order ID+ /// </remarks>+ public static string ORDERS_BY_ID_KEY => "Grand.order.id-{0}";- #endregion+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string ORDERS_PATTERN_KEY => "Grand.order.";- }-}+ #endregion+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/ProductAttributeCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/ProductAttributeCacheKey.csindex bf8d4e240..ecfba0699 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/ProductAttributeCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/ProductAttributeCacheKey.cs@@ -1,43 +1,41 @@-namespace Grand.Infrastructure.Caching.Constants-{- public static partial class CacheKey- {- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : page index- /// {1} : page size- /// </remarks>- public static string PRODUCTATTRIBUTES_ALL_KEY => "Grand.productattribute.all-{0}-{1}";+namespace Grand.Infrastructure.Caching.Constants;- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : product attribute ID- /// </remarks>- public static string PRODUCTATTRIBUTES_BY_ID_KEY => "Grand.productattribute.id-{0}";+public static partial class CacheKey+{+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : page index+ /// {1} : page size+ /// </remarks>+ public static string PRODUCTATTRIBUTES_ALL_KEY => "Grand.productattribute.all-{0}-{1}";- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string PRODUCTATTRIBUTES_PATTERN_KEY => "Grand.productattribute.";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : product attribute ID+ /// </remarks>+ public static string PRODUCTATTRIBUTES_BY_ID_KEY => "Grand.productattribute.id-{0}";- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY => "Grand.productattributemapping.";+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string PRODUCTATTRIBUTES_PATTERN_KEY => "Grand.productattribute.";- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string PRODUCTATTRIBUTEVALUES_PATTERN_KEY => "Grand.productattributevalue.";+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string PRODUCTATTRIBUTEMAPPINGS_PATTERN_KEY => "Grand.productattributemapping.";- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY => "Grand.productattributecombination.";+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string PRODUCTATTRIBUTEVALUES_PATTERN_KEY => "Grand.productattributevalue.";- }-}+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string PRODUCTATTRIBUTECOMBINATIONS_PATTERN_KEY => "Grand.productattributecombination.";+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/ProductCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/ProductCacheKey.csindex 6ea21811d..2df2f7038 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/ProductCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/ProductCacheKey.cs@@ -1,119 +1,118 @@-namespace Grand.Infrastructure.Caching.Constants+namespace Grand.Infrastructure.Caching.Constants;++public static partial class CacheKey{- public static partial class CacheKey- {- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string PRODUCTS_PATTERN_KEY => "Grand.product.";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : product ID- /// </remarks>- public static string PRODUCTS_BY_ID_KEY => "Grand.product.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : customer group IDs- /// {1} : store ident- /// </remarks>- public static string PRODUCTS_CUSTOMER_GROUP => "Grand.product.cr-{0}-{1}";-- /// <summary>- /// Key for caching- /// </summary>- public static string PRODUCTS_CUSTOMER_GROUP_PATTERN => "Grand.product.cr";-- /// <summary>- /// Key for caching- /// </summary>- public static string PRODUCTS_HOMEPAGE_PATTERN => "Grand.product.homepage";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : customer ID- /// </remarks>- public static string PRODUCTS_CUSTOMER_TAG => "Grand.product.ct-{0}";-- /// <summary>- /// Key for caching- /// </summary>- public static string PRODUCTS_CUSTOMER_TAG_PATTERN => "Grand.product.ct";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : customer tag Id?- /// </remarks>- public static string CUSTOMERTAGPRODUCTS_ROLE_KEY => "Grand.customertagproducts.tag-{0}";-- /// <summary>- /// Key pattern to clear cache- /// {0} customer id- /// </summary>- public static string PRODUCTS_CUSTOMER_PERSONAL_KEY => "Grand.product.personal-{0}";-- /// <summary>- /// Key for caching- /// </summary>- public static string PRODUCTS_CUSTOMER_PERSONAL_PATTERN => "Grand.product.personal";-- /// <summary>- /// Key for cache- /// {0} - customer id- /// {1} - product id- /// </summary>- public static string CUSTOMER_PRODUCT_PRICE_KEY_ID => "Grand.product.price-{0}-{1}";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string PRODUCTS_SHOWONHOMEPAGE => "Grand.product.showonhomepage";-- /// <summary>- /// Compare products cookie name- /// </summary>- public static string PRODUCTS_COMPARE_COOKIE_NAME => "Grand.CompareProduct";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : store ID- /// </remarks>- public static string PRODUCTTAG_COUNT_KEY => "Grand.producttag.count";-- /// <summary>- /// Key for all tags- /// </summary>- public static string PRODUCTTAG_ALL_KEY => "Grand.producttag.all";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string PRODUCTTAG_PATTERN_KEY => "Grand.producttag.";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : customer id- /// {1} : number- /// </remarks>- public static string RECENTLY_VIEW_PRODUCTS_KEY => "Grand.recentlyviewedproducts-{0}-{1}";-- /// <summary>- /// Key pattern to clear cache- /// {0} customer id- /// </summary>- public static string RECENTLY_VIEW_PRODUCTS_PATTERN_KEY => "Grand.recentlyviewedproducts-{0}";- }-}+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string PRODUCTS_PATTERN_KEY => "Grand.product.";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : product ID+ /// </remarks>+ public static string PRODUCTS_BY_ID_KEY => "Grand.product.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : customer group IDs+ /// {1} : store ident+ /// </remarks>+ public static string PRODUCTS_CUSTOMER_GROUP => "Grand.product.cr-{0}-{1}";++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string PRODUCTS_CUSTOMER_GROUP_PATTERN => "Grand.product.cr";++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string PRODUCTS_HOMEPAGE_PATTERN => "Grand.product.homepage";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : customer ID+ /// </remarks>+ public static string PRODUCTS_CUSTOMER_TAG => "Grand.product.ct-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string PRODUCTS_CUSTOMER_TAG_PATTERN => "Grand.product.ct";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : customer tag Id?+ /// </remarks>+ public static string CUSTOMERTAGPRODUCTS_ROLE_KEY => "Grand.customertagproducts.tag-{0}";++ /// <summary>+ /// Key pattern to clear cache+ /// {0} customer id+ /// </summary>+ public static string PRODUCTS_CUSTOMER_PERSONAL_KEY => "Grand.product.personal-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string PRODUCTS_CUSTOMER_PERSONAL_PATTERN => "Grand.product.personal";++ /// <summary>+ /// Key for cache+ /// {0} - customer id+ /// {1} - product id+ /// </summary>+ public static string CUSTOMER_PRODUCT_PRICE_KEY_ID => "Grand.product.price-{0}-{1}";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string PRODUCTS_SHOWONHOMEPAGE => "Grand.product.showonhomepage";++ /// <summary>+ /// Compare products cookie name+ /// </summary>+ public static string PRODUCTS_COMPARE_COOKIE_NAME => "Grand.CompareProduct";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : store ID+ /// </remarks>+ public static string PRODUCTTAG_COUNT_KEY => "Grand.producttag.count";++ /// <summary>+ /// Key for all tags+ /// </summary>+ public static string PRODUCTTAG_ALL_KEY => "Grand.producttag.all";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string PRODUCTTAG_PATTERN_KEY => "Grand.producttag.";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : customer id+ /// {1} : number+ /// </remarks>+ public static string RECENTLY_VIEW_PRODUCTS_KEY => "Grand.recentlyviewedproducts-{0}-{1}";++ /// <summary>+ /// Key pattern to clear cache+ /// {0} customer id+ /// </summary>+ public static string RECENTLY_VIEW_PRODUCTS_PATTERN_KEY => "Grand.recentlyviewedproducts-{0}";+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/SecurityCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/SecurityCacheKey.csindex 89a03ad9a..f23be9766 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/SecurityCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/SecurityCacheKey.cs@@ -1,33 +1,32 @@-namespace Grand.Infrastructure.Caching.Constants+namespace Grand.Infrastructure.Caching.Constants;++public static partial class CacheKey{- public static partial class CacheKey- {- #region Permission+ #region Permission- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : customer group ID- /// {1} : permission system name- /// </remarks>- public static string PERMISSIONS_ALLOWED_KEY => "Grand.permission.allowed-{0}-{1}";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : customer group ID+ /// {1} : permission system name+ /// </remarks>+ public static string PERMISSIONS_ALLOWED_KEY => "Grand.permission.allowed-{0}-{1}";- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : customer group ID- /// {1} : permission system name- /// {2} : permission action name- /// </remarks>- public static string PERMISSIONS_ALLOWED_ACTION_KEY => "Grand.permission.allowed.action-{0}-{1}-{2}";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : customer group ID+ /// {1} : permission system name+ /// {2} : permission action name+ /// </remarks>+ public static string PERMISSIONS_ALLOWED_ACTION_KEY => "Grand.permission.allowed.action-{0}-{1}-{2}";- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string PERMISSIONS_PATTERN_KEY => "Grand.permission.";+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string PERMISSIONS_PATTERN_KEY => "Grand.permission.";- #endregion- }-}+ #endregion+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/ShippingCacheKeys.cs b/src/Core/Grand.Infrastructure/Caching/Constants/ShippingCacheKeys.csindex 5ef7b9719..77f24b910 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/ShippingCacheKeys.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/ShippingCacheKeys.cs@@ -1,97 +1,96 @@-namespace Grand.Infrastructure.Caching.Constants+namespace Grand.Infrastructure.Caching.Constants;++public static partial class CacheKey{- public static partial class CacheKey- {- #region Delivery date-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : delivery date ID- /// </remarks>- public static string DELIVERYDATE_BY_ID_KEY => "Grand.deliverydate.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// </remarks>- public static string DELIVERYDATE_ALL => "Grand.deliverydate.all";-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// </remarks>- public static string DELIVERYDATE_PATTERN_KEY => "Grand.deliverydate.";-- #endregion-- #region Pickup points-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : pickup point point ID- /// </remarks>- public static string PICKUPPOINTS_BY_ID_KEY => "Grand.pickuppoint.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- public static string PICKUPPOINTS_ALL => "Grand.pickuppoint.all";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string PICKUPPOINTS_PATTERN_KEY => "Grand.pickuppoint.";-- #endregion-- #region Shipping method-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : shippingmethod ID- /// </remarks>- public static string SHIPPINGMETHOD_BY_ID_KEY => "Grand.shippingmethod.id-{0}";-- /// <summary>- /// Key to cache- /// </summary>- public static string SHIPPINGMETHOD_ALL => "Grand.shippingmethod.all";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string SHIPPINGMETHOD_PATTERN_KEY => "Grand.shippingmethod.";-- #endregion-- #region Warehouse-- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : warehouse ID- /// </remarks>- public static string WAREHOUSES_BY_ID_KEY => "Grand.warehouse.id-{0}";-- /// <summary>- /// Key for caching- /// </summary>- public static string WAREHOUSES_ALL => "Grand.warehouse.all";-- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string WAREHOUSES_PATTERN_KEY => "Grand.warehouse.";-- #endregion- }-}+ #region Delivery date++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : delivery date ID+ /// </remarks>+ public static string DELIVERYDATE_BY_ID_KEY => "Grand.deliverydate.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// </remarks>+ public static string DELIVERYDATE_ALL => "Grand.deliverydate.all";++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// </remarks>+ public static string DELIVERYDATE_PATTERN_KEY => "Grand.deliverydate.";++ #endregion++ #region Pickup points++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : pickup point point ID+ /// </remarks>+ public static string PICKUPPOINTS_BY_ID_KEY => "Grand.pickuppoint.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string PICKUPPOINTS_ALL => "Grand.pickuppoint.all";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string PICKUPPOINTS_PATTERN_KEY => "Grand.pickuppoint.";++ #endregion++ #region Shipping method++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : shippingmethod ID+ /// </remarks>+ public static string SHIPPINGMETHOD_BY_ID_KEY => "Grand.shippingmethod.id-{0}";++ /// <summary>+ /// Key to cache+ /// </summary>+ public static string SHIPPINGMETHOD_ALL => "Grand.shippingmethod.all";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string SHIPPINGMETHOD_PATTERN_KEY => "Grand.shippingmethod.";++ #endregion++ #region Warehouse++ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : warehouse ID+ /// </remarks>+ public static string WAREHOUSES_BY_ID_KEY => "Grand.warehouse.id-{0}";++ /// <summary>+ /// Key for caching+ /// </summary>+ public static string WAREHOUSES_ALL => "Grand.warehouse.all";++ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string WAREHOUSES_PATTERN_KEY => "Grand.warehouse.";++ #endregion+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/SiteMapCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/SiteMapCacheKey.csindex 9ba1892bf..2d7553a06 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/SiteMapCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/SiteMapCacheKey.cs@@ -1,16 +1,14 @@-namespace Grand.Infrastructure.Caching.Constants-{- public static partial class CacheKey- {- /// <summary>- /// Key for caching- /// </summary>- public static string ADMIN_SITEMAP_KEY => "Grand.admin-sitemap.all";+namespace Grand.Infrastructure.Caching.Constants;- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string ADMIN_SITEMAP_PATTERN_KEY => "Grand.admin-sitemap.";+public static partial class CacheKey+{+ /// <summary>+ /// Key for caching+ /// </summary>+ public static string ADMIN_SITEMAP_KEY => "Grand.admin-sitemap.all";- }-}+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string ADMIN_SITEMAP_PATTERN_KEY => "Grand.admin-sitemap.";+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Constants/SpecificationAttributeCacheKey.cs b/src/Core/Grand.Infrastructure/Caching/Constants/SpecificationAttributeCacheKey.csindex 4e88378b8..0d7d03435 100644--- a/src/Core/Grand.Infrastructure/Caching/Constants/SpecificationAttributeCacheKey.cs+++ b/src/Core/Grand.Infrastructure/Caching/Constants/SpecificationAttributeCacheKey.cs@@ -1,35 +1,33 @@-namespace Grand.Infrastructure.Caching.Constants-{- public static partial class CacheKey- {- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : sename- /// </remarks>- public static string SPECIFICATION_BY_SENAME => "Grand.specification.sename-{0}";+namespace Grand.Infrastructure.Caching.Constants;- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : specification ID- /// </remarks>- public static string SPECIFICATION_BY_ID_KEY => "Grand.specification.id-{0}";+public static partial class CacheKey+{+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : sename+ /// </remarks>+ public static string SPECIFICATION_BY_SENAME => "Grand.specification.sename-{0}";- /// <summary>- /// Key for caching- /// </summary>- /// <remarks>- /// {0} : specification option ID- /// </remarks>- public static string SPECIFICATION_BY_OPTIONID_KEY => "Grand.specification.optionid-{0}";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : specification ID+ /// </remarks>+ public static string SPECIFICATION_BY_ID_KEY => "Grand.specification.id-{0}";- /// <summary>- /// Key pattern to clear cache- /// </summary>- public static string SPECIFICATION_PATTERN_KEY => "Grand.specification.";+ /// <summary>+ /// Key for caching+ /// </summary>+ /// <remarks>+ /// {0} : specification option ID+ /// </remarks>+ public static string SPECIFICATION_BY_OPTIONID_KEY => "Grand.specification.optionid-{0}";- }-}+ /// <summary>+ /// Key pattern to clear cache+ /// </summary>+ public static string SPECIFICATION_PATTERN_KEY => "Grand.specification.";+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/ICacheBase.cs b/src/Core/Grand.Infrastructure/Caching/ICacheBase.csindex af893b2a1..0afcd2d12 100644--- a/src/Core/Grand.Infrastructure/Caching/ICacheBase.cs+++ b/src/Core/Grand.Infrastructure/Caching/ICacheBase.cs@@ -1,18 +1,17 @@-namespace Grand.Infrastructure.Caching+namespace Grand.Infrastructure.Caching;++/// <summary>+/// Cache manager interface+/// </summary>+public interface ICacheBase : IDisposable{- /// <summary>- /// Cache manager interface- /// </summary>- public interface ICacheBase: IDisposable- {- Task<T> GetAsync<T>(string key, Func<Task<T>> acquire);- Task<T> GetAsync<T>(string key, Func<Task<T>> acquire, int cacheTime);- Task<T> SetAsync<T>(string key, Func<Task<T>> acquire);- Task<T> SetAsync<T>(string key, Func<Task<T>> acquire, int cacheTime);- T Get<T>(string key, Func<T> acquire);- T Get<T>(string key, Func<T> acquire, int cacheTime);- Task RemoveAsync(string key, bool publisher = true);- Task RemoveByPrefix(string prefix, bool publisher = true);- Task Clear(bool publisher = true);- }-}+ Task<T> GetAsync<T>(string key, Func<Task<T>> acquire);+ Task<T> GetAsync<T>(string key, Func<Task<T>> acquire, int cacheTime);+ Task<T> SetAsync<T>(string key, Func<Task<T>> acquire);+ Task<T> SetAsync<T>(string key, Func<Task<T>> acquire, int cacheTime);+ T Get<T>(string key, Func<T> acquire);+ T Get<T>(string key, Func<T> acquire, int cacheTime);+ Task RemoveAsync(string key, bool publisher = true);+ Task RemoveByPrefix(string prefix, bool publisher = true);+ Task Clear(bool publisher = true);+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/MemoryCacheBase.cs b/src/Core/Grand.Infrastructure/Caching/MemoryCacheBase.csindex 86cdd2b2e..3b1d12f3b 100644--- a/src/Core/Grand.Infrastructure/Caching/MemoryCacheBase.cs+++ b/src/Core/Grand.Infrastructure/Caching/MemoryCacheBase.cs@@ -5,193 +5,185 @@ using Microsoft.Extensions.Caching.Memory;using Microsoft.Extensions.Primitives;using System.Collections.Concurrent;-namespace Grand.Infrastructure.Caching+namespace Grand.Infrastructure.Caching;++/// <summary>+/// Represents a manager for memory caching+/// </summary>+public class MemoryCacheBase : ICacheBase{- /// <summary>- /// Represents a manager for memory caching- /// </summary>- public class MemoryCacheBase : ICacheBase- {- #region Fields+ #region Ctor- private readonly IMemoryCache _cache;- private readonly IMediator _mediator;- private readonly CacheConfig _cacheConfig;+ public MemoryCacheBase(IMemoryCache cache, IMediator mediator, CacheConfig cacheConfig)+ {+ _cache = cache;+ _mediator = mediator;+ _cacheConfig = cacheConfig;+ }- private bool _disposed;- private static CancellationTokenSource _resetCacheToken = new();+ #endregion- protected readonly ConcurrentDictionary<string, SemaphoreSlim> CacheEntries = new();+ #region Fields- #endregion+ private readonly IMemoryCache _cache;+ private readonly IMediator _mediator;+ private readonly CacheConfig _cacheConfig;- #region Ctor+ private bool _disposed;+ private static CancellationTokenSource _resetCacheToken = new();- public MemoryCacheBase(IMemoryCache cache, IMediator mediator, CacheConfig cacheConfig)- {- _cache = cache;- _mediator = mediator;- _cacheConfig = cacheConfig;- }+ protected readonly ConcurrentDictionary<string, SemaphoreSlim> CacheEntries = new();- #endregion+ #endregion- #region Methods+ #region Methods- public virtual Task<T> GetAsync<T>(string key, Func<Task<T>> acquire)- {- return GetAsync(key, acquire, _cacheConfig.DefaultCacheTimeMinutes);- }+ public virtual Task<T> GetAsync<T>(string key, Func<Task<T>> acquire)+ {+ return GetAsync(key, acquire, _cacheConfig.DefaultCacheTimeMinutes);+ }- public virtual async Task<T> GetAsync<T>(string key, Func<Task<T>> acquire, int cacheTime)+ public virtual async Task<T> GetAsync<T>(string key, Func<Task<T>> acquire, int cacheTime)+ {+ if (_cache.TryGetValue(key, out T cacheEntry)) return cacheEntry;+ var semaphore = CacheEntries.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));+ await semaphore.WaitAsync();+ try{- if (_cache.TryGetValue(key, out T cacheEntry)) return cacheEntry;- SemaphoreSlim semaphore = CacheEntries.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));- await semaphore.WaitAsync();- try- {- if (!_cache.TryGetValue(key, out cacheEntry))- {- cacheEntry = await acquire();- _cache.Set(key, cacheEntry, GetMemoryCacheEntryOptions(cacheTime));- }- }- finally+ if (!_cache.TryGetValue(key, out cacheEntry)){- semaphore.Release();+ cacheEntry = await acquire();+ _cache.Set(key, cacheEntry, GetMemoryCacheEntryOptions(cacheTime));}- return cacheEntry;}-- public virtual Task<T> SetAsync<T>(string key, Func<Task<T>> acquire)+ finally{- return SetAsync(key, acquire, _cacheConfig.DefaultCacheTimeMinutes);+ semaphore.Release();}- public virtual async Task<T> SetAsync<T>(string key, Func<Task<T>> acquire, int cacheTime)+ return cacheEntry;+ }++ public virtual Task<T> SetAsync<T>(string key, Func<Task<T>> acquire)+ {+ return SetAsync(key, acquire, _cacheConfig.DefaultCacheTimeMinutes);+ }++ public virtual async Task<T> SetAsync<T>(string key, Func<Task<T>> acquire, int cacheTime)+ {+ var semaphore = CacheEntries.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));+ await semaphore.WaitAsync();+ try{- SemaphoreSlim semaphore = CacheEntries.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));- await semaphore.WaitAsync();- try- {- var cacheEntry = await acquire();- _cache.Set(key, cacheEntry, GetMemoryCacheEntryOptions(cacheTime));- return cacheEntry;- }- finally- {- semaphore.Release();- }+ var cacheEntry = await acquire();+ _cache.Set(key, cacheEntry, GetMemoryCacheEntryOptions(cacheTime));+ return cacheEntry;}-- public virtual T Get<T>(string key, Func<T> acquire)+ finally{- return Get(key, acquire, _cacheConfig.DefaultCacheTimeMinutes);+ semaphore.Release();}+ }- public virtual T Get<T>(string key, Func<T> acquire, int cacheTime)+ public virtual T Get<T>(string key, Func<T> acquire)+ {+ return Get(key, acquire, _cacheConfig.DefaultCacheTimeMinutes);+ }++ public virtual T Get<T>(string key, Func<T> acquire, int cacheTime)+ {+ if (_cache.TryGetValue(key, out T cacheEntry)) return cacheEntry;+ var semaphore = CacheEntries.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));+ semaphore.Wait();+ try{- if (_cache.TryGetValue(key, out T cacheEntry)) return cacheEntry;- SemaphoreSlim semaphore = CacheEntries.GetOrAdd(key, _ => new SemaphoreSlim(1, 1));- semaphore.Wait();- try+ if (!_cache.TryGetValue(key, out cacheEntry)){- if (!_cache.TryGetValue(key, out cacheEntry))- {- cacheEntry = acquire();- _cache.Set(key, cacheEntry, GetMemoryCacheEntryOptions(cacheTime));- }- }- finally- {- semaphore.Release();+ cacheEntry = acquire();+ _cache.Set(key, cacheEntry, GetMemoryCacheEntryOptions(cacheTime));}- return cacheEntry;}-- public virtual Task RemoveAsync(string key, bool publisher = true)+ finally{- _cache.Remove(key);-- if (publisher)- _mediator.Publish(new EntityCacheEvent(key, CacheEvent.RemoveKey));-- return Task.CompletedTask;+ semaphore.Release();}- public virtual Task RemoveByPrefix(string prefix, bool publisher = true)- {- var entriesToRemove = CacheEntries.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));- foreach (var cacheEntries in entriesToRemove)- {- _cache.Remove(cacheEntries.Key);- }+ return cacheEntry;+ }- if (publisher)- _mediator.Publish(new EntityCacheEvent(prefix, CacheEvent.RemovePrefix));+ public virtual Task RemoveAsync(string key, bool publisher = true)+ {+ _cache.Remove(key);- return Task.CompletedTask;- }+ if (publisher)+ _mediator.Publish(new EntityCacheEvent(key, CacheEvent.RemoveKey));- public virtual Task Clear(bool publisher = true)- {- //clear keys- foreach (var cacheEntry in CacheEntries.Keys.ToList())- _cache.Remove(cacheEntry);+ return Task.CompletedTask;+ }- //cancel- _resetCacheToken.Cancel();- //dispose- _resetCacheToken.Dispose();+ public virtual Task RemoveByPrefix(string prefix, bool publisher = true)+ {+ var entriesToRemove = CacheEntries.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));+ foreach (var cacheEntries in entriesToRemove) _cache.Remove(cacheEntries.Key);- _resetCacheToken = new CancellationTokenSource();+ if (publisher)+ _mediator.Publish(new EntityCacheEvent(prefix, CacheEvent.RemovePrefix));- return Task.CompletedTask;- }+ return Task.CompletedTask;+ }- ~MemoryCacheBase()- {- Dispose(false);- }+ public virtual Task Clear(bool publisher = true)+ {+ //clear keys+ foreach (var cacheEntry in CacheEntries.Keys.ToList())+ _cache.Remove(cacheEntry);- public void Dispose()- {- Dispose(true);- GC.SuppressFinalize(this);- }+ //cancel+ _resetCacheToken.Cancel();+ //dispose+ _resetCacheToken.Dispose();- protected virtual void Dispose(bool disposing)- {- if (_disposed) return;- if (disposing)- {- _cache.Dispose();- }- _disposed = true;- }+ _resetCacheToken = new CancellationTokenSource();- #endregion+ return Task.CompletedTask;+ }- #region Utilities+ ~MemoryCacheBase()+ {+ Dispose(false);+ }- private MemoryCacheEntryOptions GetMemoryCacheEntryOptions(int cacheTime)- {- var options = new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(cacheTime) }- .AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token))- .RegisterPostEvictionCallback(PostEvictionCallback);+ public void Dispose()+ {+ Dispose(true);+ GC.SuppressFinalize(this);+ }- return options;- }+ protected virtual void Dispose(bool disposing)+ {+ if (_disposed) return;+ if (disposing) _cache.Dispose();+ _disposed = true;+ }- private void PostEvictionCallback(object key, object value, EvictionReason reason, object state)- {- if (reason != EvictionReason.Replaced)- CacheEntries.TryRemove(key.ToString(), out var _);+ #endregion- }+ #region Utilities- #endregion+ private MemoryCacheEntryOptions GetMemoryCacheEntryOptions(int cacheTime)+ {+ var options = new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(cacheTime) }+ .AddExpirationToken(new CancellationChangeToken(_resetCacheToken.Token))+ .RegisterPostEvictionCallback(PostEvictionCallback);++ return options;+ }+ private void PostEvictionCallback(object key, object value, EvictionReason reason, object state)+ {+ if (reason != EvictionReason.Replaced)+ CacheEntries.TryRemove(key.ToString(), out var _);}+ #endregion}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Message/CacheMessageEvent.cs b/src/Core/Grand.Infrastructure/Caching/Message/CacheMessageEvent.csindex 10bc43e06..d9df22496 100644--- a/src/Core/Grand.Infrastructure/Caching/Message/CacheMessageEvent.cs+++ b/src/Core/Grand.Infrastructure/Caching/Message/CacheMessageEvent.cs@@ -1,10 +1,8 @@--namespace Grand.Infrastructure.Caching.Message+namespace Grand.Infrastructure.Caching.Message;++public class CacheMessageEvent{- public class CacheMessageEvent- {- public string ClientId { get; set; }- public string Key { get; set; }- public int MessageType { get; set; }- }-}+ public string ClientId { get; set; }+ public string Key { get; set; }+ public int MessageType { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Message/IMessageBus.cs b/src/Core/Grand.Infrastructure/Caching/Message/IMessageBus.csindex f2b34c2de..9e803cd5d 100644--- a/src/Core/Grand.Infrastructure/Caching/Message/IMessageBus.cs+++ b/src/Core/Grand.Infrastructure/Caching/Message/IMessageBus.cs@@ -1,7 +1,6 @@-namespace Grand.Infrastructure.Caching.Message+namespace Grand.Infrastructure.Caching.Message;++public interface IMessageBus : IMessagePublisher, IMessageSubscriber{- public interface IMessageBus : IMessagePublisher, IMessageSubscriber- {- void OnSubscriptionChanged(IMessageEvent message);- }-}+ void OnSubscriptionChanged(IMessageEvent message);+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Message/IMessageEvent.cs b/src/Core/Grand.Infrastructure/Caching/Message/IMessageEvent.csindex c8b42d9ca..ef84139fe 100644--- a/src/Core/Grand.Infrastructure/Caching/Message/IMessageEvent.cs+++ b/src/Core/Grand.Infrastructure/Caching/Message/IMessageEvent.cs@@ -1,9 +1,7 @@--namespace Grand.Infrastructure.Caching.Message+namespace Grand.Infrastructure.Caching.Message;++public interface IMessageEvent{- public interface IMessageEvent- {- string Key { get; set; }- int MessageType { get; set; }- }-}+ string Key { get; set; }+ int MessageType { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Message/IMessageEventClient.cs b/src/Core/Grand.Infrastructure/Caching/Message/IMessageEventClient.csindex 219808d34..afdd7a6e0 100644--- a/src/Core/Grand.Infrastructure/Caching/Message/IMessageEventClient.cs+++ b/src/Core/Grand.Infrastructure/Caching/Message/IMessageEventClient.cs@@ -1,8 +1,6 @@--namespace Grand.Infrastructure.Caching.Message+namespace Grand.Infrastructure.Caching.Message;++public interface IMessageEventClient : IMessageEvent{- public interface IMessageEventClient : IMessageEvent- {- string ClientId { get; set; }- }-}+ string ClientId { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Message/IMessagePublisher.cs b/src/Core/Grand.Infrastructure/Caching/Message/IMessagePublisher.csindex e7ca93e5e..b78dd3b4b 100644--- a/src/Core/Grand.Infrastructure/Caching/Message/IMessagePublisher.cs+++ b/src/Core/Grand.Infrastructure/Caching/Message/IMessagePublisher.cs@@ -1,7 +1,6 @@-namespace Grand.Infrastructure.Caching.Message+namespace Grand.Infrastructure.Caching.Message;++public interface IMessagePublisher{- public interface IMessagePublisher- {- Task PublishAsync<TMessage>(TMessage msg) where TMessage : IMessageEvent;- }-}+ Task PublishAsync<TMessage>(TMessage msg) where TMessage : IMessageEvent;+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Message/IMessageSubscriber.cs b/src/Core/Grand.Infrastructure/Caching/Message/IMessageSubscriber.csindex c5f769f05..8c75aff4e 100644--- a/src/Core/Grand.Infrastructure/Caching/Message/IMessageSubscriber.cs+++ b/src/Core/Grand.Infrastructure/Caching/Message/IMessageSubscriber.cs@@ -1,7 +1,6 @@-namespace Grand.Infrastructure.Caching.Message+namespace Grand.Infrastructure.Caching.Message;++public interface IMessageSubscriber{- public interface IMessageSubscriber- {- Task SubscribeAsync();- }-}+ Task SubscribeAsync();+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Message/MessageEvent.cs b/src/Core/Grand.Infrastructure/Caching/Message/MessageEvent.csindex 607c865cc..3ec90d711 100644--- a/src/Core/Grand.Infrastructure/Caching/Message/MessageEvent.cs+++ b/src/Core/Grand.Infrastructure/Caching/Message/MessageEvent.cs@@ -1,9 +1,7 @@--namespace Grand.Infrastructure.Caching.Message+namespace Grand.Infrastructure.Caching.Message;++public class MessageEvent : IMessageEvent{- public class MessageEvent : IMessageEvent- {- public string Key { get; set; }- public int MessageType { get; set; }- }-}+ public string Key { get; set; }+ public int MessageType { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Message/MessageEventClient.cs b/src/Core/Grand.Infrastructure/Caching/Message/MessageEventClient.csindex 1df03dfc5..6313281ff 100644--- a/src/Core/Grand.Infrastructure/Caching/Message/MessageEventClient.cs+++ b/src/Core/Grand.Infrastructure/Caching/Message/MessageEventClient.cs@@ -1,10 +1,8 @@--namespace Grand.Infrastructure.Caching.Message+namespace Grand.Infrastructure.Caching.Message;++public class MessageEventClient : IMessageEventClient{- public class MessageEventClient : IMessageEventClient- {- public string ClientId { get; set; }- public string Key { get; set; }- public int MessageType { get; set; }- }-}+ public string ClientId { get; set; }+ public string Key { get; set; }+ public int MessageType { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Message/MessageEventType.cs b/src/Core/Grand.Infrastructure/Caching/Message/MessageEventType.csindex 001beb3c3..1ac185ec8 100644--- a/src/Core/Grand.Infrastructure/Caching/Message/MessageEventType.cs+++ b/src/Core/Grand.Infrastructure/Caching/Message/MessageEventType.cs@@ -1,10 +1,8 @@--namespace Grand.Infrastructure.Caching.Message+namespace Grand.Infrastructure.Caching.Message;++public enum MessageEventType{- public enum MessageEventType- {- RemoveKey = 0,- RemoveByPrefix = 1,- ClearCache = 2- }-}+ RemoveKey = 0,+ RemoveByPrefix = 1,+ ClearCache = 2+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/RabbitMq/CacheMessageEventConsumer.cs b/src/Core/Grand.Infrastructure/Caching/RabbitMq/CacheMessageEventConsumer.csindex a1e5cb81a..d51f7aa11 100644--- a/src/Core/Grand.Infrastructure/Caching/RabbitMq/CacheMessageEventConsumer.cs+++ b/src/Core/Grand.Infrastructure/Caching/RabbitMq/CacheMessageEventConsumer.cs@@ -1,33 +1,32 @@using Grand.Infrastructure.Caching.Message;using MassTransit;-namespace Grand.Infrastructure.Caching.RabbitMq+namespace Grand.Infrastructure.Caching.RabbitMq;++public class CacheMessageEventConsumer : IConsumer<CacheMessageEvent>{- public class CacheMessageEventConsumer : IConsumer<CacheMessageEvent>- {- private readonly ICacheBase _cache;+ private readonly ICacheBase _cache;- public CacheMessageEventConsumer(ICacheBase cache)- {- _cache = cache;- }+ public CacheMessageEventConsumer(ICacheBase cache)+ {+ _cache = cache;+ }- public async Task Consume(ConsumeContext<CacheMessageEvent> context)+ public async Task Consume(ConsumeContext<CacheMessageEvent> context)+ {+ var message = context.Message;+ if (RabbitMqMessageCacheManager.ManageClientId.Equals(message.ClientId)) return;+ switch (message.MessageType){- var message = context.Message;- if (RabbitMqMessageCacheManager.ManageClientId.Equals(message.ClientId)) return;- switch (message.MessageType)- {- case (int)MessageEventType.RemoveKey:- await _cache.RemoveAsync(message.Key, false);- break;- case (int)MessageEventType.RemoveByPrefix:- await _cache.RemoveByPrefix(message.Key, false);- break;- case (int)MessageEventType.ClearCache:- await _cache.Clear(false);- break;- }+ case (int)MessageEventType.RemoveKey:+ await _cache.RemoveAsync(message.Key, false);+ break;+ case (int)MessageEventType.RemoveByPrefix:+ await _cache.RemoveByPrefix(message.Key, false);+ break;+ case (int)MessageEventType.ClearCache:+ await _cache.Clear(false);+ break;}}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/RabbitMq/RabbitMqMessageCacheManager.cs b/src/Core/Grand.Infrastructure/Caching/RabbitMq/RabbitMqMessageCacheManager.csindex 7139eff01..a61af9429 100644--- a/src/Core/Grand.Infrastructure/Caching/RabbitMq/RabbitMqMessageCacheManager.cs+++ b/src/Core/Grand.Infrastructure/Caching/RabbitMq/RabbitMqMessageCacheManager.cs@@ -4,60 +4,59 @@ using MassTransit;using MediatR;using Microsoft.Extensions.Caching.Memory;-namespace Grand.Infrastructure.Caching.RabbitMq+namespace Grand.Infrastructure.Caching.RabbitMq;++public class RabbitMqMessageCacheManager : MemoryCacheBase, ICacheBase{- public class RabbitMqMessageCacheManager : MemoryCacheBase, ICacheBase+ public static readonly string ManageClientId = Guid.NewGuid().ToString("N");+ private readonly IBus _bus;+ private readonly IMemoryCache _cache;++ public RabbitMqMessageCacheManager(IMemoryCache cache, IMediator mediator, IBus bus, CacheConfig config)+ : base(cache, mediator, config)+ {+ _cache = cache;+ _bus = bus;+ }++ /// <summary>+ /// Removes the value with the specified key from the cache+ /// </summary>+ /// <param name="key">Key of cached item</param>+ /// <param name="publisher">Publisher</param>+ public override async Task RemoveAsync(string key, bool publisher = true)+ {+ _cache.Remove(key);++ if (publisher)+ await _bus.Publish(new CacheMessageEvent+ { ClientId = ManageClientId, Key = key, MessageType = (int)MessageEventType.RemoveKey });+ }++ /// <summary>+ /// Removes items by key prefix+ /// </summary>+ /// <param name="prefix">String prefix</param>+ /// <param name="publisher">publisher</param>+ public override async Task RemoveByPrefix(string prefix, bool publisher = true)+ {+ var entriesToRemove = CacheEntries.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));+ foreach (var cacheEntries in entriesToRemove) _cache.Remove(cacheEntries.Key);++ if (publisher)+ await _bus.Publish(new CacheMessageEvent+ { ClientId = ManageClientId, Key = prefix, MessageType = (int)MessageEventType.RemoveByPrefix });+ }++ /// <summary>+ /// Clear cache+ /// </summary>+ /// <param name="publisher">publisher</param>+ public override async Task Clear(bool publisher = true){- public static readonly string ManageClientId = Guid.NewGuid().ToString("N");- private readonly IMemoryCache _cache;- private readonly IBus _bus;-- public RabbitMqMessageCacheManager(IMemoryCache cache, IMediator mediator, IBus bus, CacheConfig config)- : base(cache, mediator, config)- {- _cache = cache;- _bus = bus;- }-- /// <summary>- /// Removes the value with the specified key from the cache- /// </summary>- /// <param name="key">Key of cached item</param>- /// <param name="publisher">Publisher</param>- public override async Task RemoveAsync(string key, bool publisher = true)- {- _cache.Remove(key);-- if (publisher)- await _bus.Publish(new CacheMessageEvent { ClientId = ManageClientId, Key = key, MessageType = (int)MessageEventType.RemoveKey });- }-- /// <summary>- /// Removes items by key prefix- /// </summary>- /// <param name="prefix">String prefix</param>- /// <param name="publisher">publisher</param>- public override async Task RemoveByPrefix(string prefix, bool publisher = true)- {- var entriesToRemove = CacheEntries.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));- foreach (var cacheEntries in entriesToRemove)- {- _cache.Remove(cacheEntries.Key);- }-- if (publisher)- await _bus.Publish(new CacheMessageEvent { ClientId = ManageClientId, Key = prefix, MessageType = (int)MessageEventType.RemoveByPrefix });- }-- ///<summary>- /// Clear cache- ///</summary>- /// <param name="publisher">publisher</param>- public override async Task Clear(bool publisher = true)- {- await base.Clear();- if (publisher)- await _bus.Publish(new CacheMessageEvent { ClientId = ManageClientId, Key = "", MessageType = (int)MessageEventType.ClearCache });- }+ await base.Clear();+ if (publisher)+ await _bus.Publish(new CacheMessageEvent+ { ClientId = ManageClientId, Key = "", MessageType = (int)MessageEventType.ClearCache });}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageBus.cs b/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageBus.csindex c7047796e..78970ae22 100644--- a/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageBus.cs+++ b/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageBus.cs@@ -1,80 +1,78 @@-using StackExchange.Redis;-using Microsoft.Extensions.DependencyInjection;-using Grand.Infrastructure.Caching.Message;+using Grand.Infrastructure.Caching.Message;using Grand.Infrastructure.Configuration;+using Microsoft.Extensions.DependencyInjection;+using StackExchange.Redis;using System.Diagnostics;using System.Text.Json;-namespace Grand.Infrastructure.Caching.Redis+namespace Grand.Infrastructure.Caching.Redis;++public sealed class RedisMessageBus : IMessageBus{- public sealed class RedisMessageBus : IMessageBus- {- private readonly ISubscriber _subscriber;- private readonly IServiceProvider _serviceProvider;- private readonly RedisConfig _redisConfig;+ private static readonly string ClientId = Guid.NewGuid().ToString("N");+ private readonly RedisConfig _redisConfig;+ private readonly IServiceProvider _serviceProvider;+ private readonly ISubscriber _subscriber;- private static readonly string ClientId = Guid.NewGuid().ToString("N");+ public RedisMessageBus(ISubscriber subscriber, IServiceProvider serviceProvider, RedisConfig redisConfig)+ {+ _subscriber = subscriber;+ _serviceProvider = serviceProvider;+ _redisConfig = redisConfig;+ SubscribeAsync();+ }- public RedisMessageBus(ISubscriber subscriber, IServiceProvider serviceProvider, RedisConfig redisConfig)+ public async Task PublishAsync<TMessage>(TMessage msg) where TMessage : IMessageEvent+ {+ try{- _subscriber = subscriber;- _serviceProvider = serviceProvider;- _redisConfig = redisConfig;- SubscribeAsync();+ var client = new MessageEventClient {+ ClientId = ClientId,+ Key = msg.Key,+ MessageType = msg.MessageType+ };+ var message = JsonSerializer.Serialize(client);+ await _subscriber.PublishAsync(RedisChannel.Literal(_redisConfig.RedisPubSubChannel), message);}+ catch (Exception ex)+ {+ Debug.WriteLine(ex.Message);+ }+ }- public async Task PublishAsync<TMessage>(TMessage msg) where TMessage : IMessageEvent+ public Task SubscribeAsync()+ {+ _subscriber.SubscribeAsync(RedisChannel.Literal(_redisConfig.RedisPubSubChannel), (_, redisValue) =>{try{- var client = new MessageEventClient {- ClientId = ClientId,- Key = msg.Key,- MessageType = msg.MessageType- };- var message = JsonSerializer.Serialize(client);- await _subscriber.PublishAsync(RedisChannel.Literal(_redisConfig.RedisPubSubChannel), message);+ var message = JsonSerializer.Deserialize<MessageEventClient>(redisValue);+ if (message != null && message.ClientId != ClientId)+ OnSubscriptionChanged(message);}- catch(Exception ex)+ catch (Exception ex){Debug.WriteLine(ex.Message);}- }-- public Task SubscribeAsync()- {- _subscriber.SubscribeAsync(RedisChannel.Literal(_redisConfig.RedisPubSubChannel), (_, redisValue) =>- {- try- {- var message = JsonSerializer.Deserialize<MessageEventClient>(redisValue);- if (message != null && message.ClientId != ClientId)- OnSubscriptionChanged(message);- }- catch (Exception ex)- {- Debug.WriteLine(ex.Message);- }- });- return Task.CompletedTask;- }+ });+ return Task.CompletedTask;+ }- public void OnSubscriptionChanged(IMessageEvent message)+ public void OnSubscriptionChanged(IMessageEvent message)+ {+ using var scope = _serviceProvider.CreateScope();+ var cache = scope.ServiceProvider.GetRequiredService<ICacheBase>();+ switch (message.MessageType){- using var scope = _serviceProvider.CreateScope();- var cache = scope.ServiceProvider.GetRequiredService<ICacheBase>();- switch (message.MessageType)- {- case (int)MessageEventType.RemoveKey:- _ = cache.RemoveAsync(message.Key, false);- break;- case (int)MessageEventType.RemoveByPrefix:- _ = cache.RemoveByPrefix(message.Key, false);- break;- case (int)MessageEventType.ClearCache:- _ = cache.Clear(false);- break;- }+ case (int)MessageEventType.RemoveKey:+ _ = cache.RemoveAsync(message.Key, false);+ break;+ case (int)MessageEventType.RemoveByPrefix:+ _ = cache.RemoveByPrefix(message.Key, false);+ break;+ case (int)MessageEventType.ClearCache:+ _ = cache.Clear(false);+ break;}}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageCacheManager.cs b/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageCacheManager.csindex 1b906370f..a1a21d803 100644--- a/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageCacheManager.cs+++ b/src/Core/Grand.Infrastructure/Caching/Redis/RedisMessageCacheManager.cs@@ -3,65 +3,62 @@ using Grand.Infrastructure.Configuration;using MediatR;using Microsoft.Extensions.Caching.Memory;-namespace Grand.Infrastructure.Caching.Redis+namespace Grand.Infrastructure.Caching.Redis;++public class RedisMessageCacheManager : MemoryCacheBase, ICacheBase{- public class RedisMessageCacheManager : MemoryCacheBase, ICacheBase- {- private readonly IMemoryCache _cache;- private readonly IMessageBus _messageBus;+ private readonly IMemoryCache _cache;+ private readonly IMessageBus _messageBus;- public RedisMessageCacheManager(IMemoryCache cache, IMediator mediator, IMessageBus messageBus, CacheConfig config)- : base(cache, mediator, config)- {- _cache = cache;- _messageBus = messageBus;- }+ public RedisMessageCacheManager(IMemoryCache cache, IMediator mediator, IMessageBus messageBus, CacheConfig config)+ : base(cache, mediator, config)+ {+ _cache = cache;+ _messageBus = messageBus;+ }- /// <summary>- /// Removes the value with the specified key from the cache- /// </summary>- /// <param name="key">Key of cached item</param>- /// <param name="publisher">Publisher</param>- public override Task RemoveAsync(string key, bool publisher = true)- {- _cache.Remove(key);+ /// <summary>+ /// Removes the value with the specified key from the cache+ /// </summary>+ /// <param name="key">Key of cached item</param>+ /// <param name="publisher">Publisher</param>+ public override Task RemoveAsync(string key, bool publisher = true)+ {+ _cache.Remove(key);- if (publisher)- _messageBus.PublishAsync(new MessageEvent { Key = key, MessageType = (int)MessageEventType.RemoveKey });+ if (publisher)+ _messageBus.PublishAsync(new MessageEvent { Key = key, MessageType = (int)MessageEventType.RemoveKey });- return Task.CompletedTask;- }+ return Task.CompletedTask;+ }- /// <summary>- /// Removes items by key prefix- /// </summary>- /// <param name="prefix">String prefix</param>- /// <param name="publisher">publisher</param>- public override Task RemoveByPrefix(string prefix, bool publisher = true)- {- var entriesToRemove = CacheEntries.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));- foreach (var cacheEntries in entriesToRemove)- {- _cache.Remove(cacheEntries.Key);- }+ /// <summary>+ /// Removes items by key prefix+ /// </summary>+ /// <param name="prefix">String prefix</param>+ /// <param name="publisher">publisher</param>+ public override Task RemoveByPrefix(string prefix, bool publisher = true)+ {+ var entriesToRemove = CacheEntries.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));+ foreach (var cacheEntries in entriesToRemove) _cache.Remove(cacheEntries.Key);- if (publisher)- _messageBus.PublishAsync(new MessageEvent { Key = prefix, MessageType = (int)MessageEventType.RemoveByPrefix });+ if (publisher)+ _messageBus.PublishAsync(new MessageEvent+ { Key = prefix, MessageType = (int)MessageEventType.RemoveByPrefix });- return Task.CompletedTask;- }+ return Task.CompletedTask;+ }- ///<summary>- /// Clear cache- ///</summary>- /// <param name="publisher">publisher</param>- public override Task Clear(bool publisher = true)- {- base.Clear();- if (publisher)- _messageBus.PublishAsync(new MessageEvent { Key = "", MessageType = (int)MessageEventType.ClearCache });+ /// <summary>+ /// Clear cache+ /// </summary>+ /// <param name="publisher">publisher</param>+ public override Task Clear(bool publisher = true)+ {+ base.Clear();+ if (publisher)+ _messageBus.PublishAsync(new MessageEvent { Key = "", MessageType = (int)MessageEventType.ClearCache });- return Task.CompletedTask;- }+ return Task.CompletedTask;}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/AccessControlConfig.cs b/src/Core/Grand.Infrastructure/Configuration/AccessControlConfig.csindex 4c2a9c63b..5db74d73d 100644--- a/src/Core/Grand.Infrastructure/Configuration/AccessControlConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/AccessControlConfig.cs@@ -3,13 +3,13 @@public class AccessControlConfig{/// <summary>- /// A value indicating whether to ignore ACL rules (side-wide). It can significantly improve performance when enabled.+ /// A value indicating whether to ignore ACL rules (side-wide). It can significantly improve performance when enabled./// </summary>public bool IgnoreAcl { get; set; }/// <summary>- /// A value indicating whether to ignore "limit per store" rules (side-wide). It can significantly improve performance when enabled.+ /// A value indicating whether to ignore "limit per store" rules (side-wide). It can significantly improve performance+ /// when enabled./// </summary>public bool IgnoreStoreLimitations { get; set; }-}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/AmazonConfig.cs b/src/Core/Grand.Infrastructure/Configuration/AmazonConfig.csindex e78f0671c..4f1846a14 100644--- a/src/Core/Grand.Infrastructure/Configuration/AmazonConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/AmazonConfig.cs@@ -1,31 +1,30 @@-namespace Grand.Infrastructure.Configuration+namespace Grand.Infrastructure.Configuration;++public class AmazonConfig{- public class AmazonConfig- {- /// <summary>- /// Amazon Access Key- /// </summary>- public string AmazonAwsAccessKeyId { get; set; }+ /// <summary>+ /// Amazon Access Key+ /// </summary>+ public string AmazonAwsAccessKeyId { get; set; }- /// <summary>- /// Amazon Secret Access Key- /// </summary>- public string AmazonAwsSecretAccessKey { get; set; }+ /// <summary>+ /// Amazon Secret Access Key+ /// </summary>+ public string AmazonAwsSecretAccessKey { get; set; }- /// <summary>- /// Amazon Bucket Name using for identifying resources- /// </summary>- public string AmazonBucketName { get; set; }+ /// <summary>+ /// Amazon Bucket Name using for identifying resources+ /// </summary>+ public string AmazonBucketName { get; set; }- /// <summary>- /// Amazon Domain name for cloudfront distribution- /// </summary>- public string AmazonDistributionDomainName { get; set; }+ /// <summary>+ /// Amazon Domain name for cloudfront distribution+ /// </summary>+ public string AmazonDistributionDomainName { get; set; }- /// <summary>- /// Amazon Region- /// http://docs.amazonwebservices.com/AmazonS3/latest/BucketConfiguration.html#LocationSelection- /// </summary>- public string AmazonRegion { get; set; }- }-}+ /// <summary>+ /// Amazon Region+ /// http://docs.amazonwebservices.com/AmazonS3/latest/BucketConfiguration.html#LocationSelection+ /// </summary>+ public string AmazonRegion { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs b/src/Core/Grand.Infrastructure/Configuration/AppConfig.csindex 799daa72b..2d570887c 100644--- a/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/AppConfig.cs@@ -1,51 +1,52 @@-namespace Grand.Infrastructure.Configuration+namespace Grand.Infrastructure.Configuration;++/// <summary>+/// Represents a Application Config+/// </summary>+public class AppConfig{/// <summary>- /// Represents a Application Config- /// </summary>- public class AppConfig- {- /// <summary>- /// Indicates whether we should Disable HostedService - BackgroundServiceTask- /// </summary>- public bool DisableHostedService { get; set; }-- /// <summary>- /// A value indicating whether to ignore the migration process- /// </summary>- public bool SkipMigrationProcess { get; set; }-- /// <summary>- /// A value indicating whether SEO friendly URLs with multiple languages are enabled- /// </summary>- public bool SeoFriendlyUrlsForLanguagesEnabled { get; set; }- public string SeoFriendlyUrlsDefaultCode { get; set; } = "en";-- /// <summary>- /// Gets or sets a value of "Cache-Control" header value for static content- /// </summary>- public string StaticFilesCacheControl { get; set; }-- /// <summary>- /// Gets or sets a value indicating whether to display the full error in production environment.- /// It's ignored (always enabled) in development environment- /// </summary>- public bool DisplayFullErrorStack { get; set; }- public bool UseSessionStateTempDataProvider { get; set; }-- /// <summary>- /// Gets or sets a value custom response header encoding may be needed in some cases- /// </summary>- public bool AllowNonAsciiCharInHeaders { get; set; }-- /// <summary>- /// Gets or sets the maximum allowed size of any request body in bytes- /// </summary>- public long? MaxRequestBodySize { get; set; }-- /// <summary>- /// Gets or sets the value to enable a middleware for logging additional information about CurrentCustomer and store- /// </summary>- public bool EnableContextLoggingMiddleware { get; set; }- }-}+ /// Indicates whether we should Disable HostedService - BackgroundServiceTask+ /// </summary>+ public bool DisableHostedService { get; set; }++ /// <summary>+ /// A value indicating whether to ignore the migration process+ /// </summary>+ public bool SkipMigrationProcess { get; set; }++ /// <summary>+ /// A value indicating whether SEO friendly URLs with multiple languages are enabled+ /// </summary>+ public bool SeoFriendlyUrlsForLanguagesEnabled { get; set; }++ public string SeoFriendlyUrlsDefaultCode { get; set; } = "en";++ /// <summary>+ /// Gets or sets a value of "Cache-Control" header value for static content+ /// </summary>+ public string StaticFilesCacheControl { get; set; }++ /// <summary>+ /// Gets or sets a value indicating whether to display the full error in production environment.+ /// It's ignored (always enabled) in development environment+ /// </summary>+ public bool DisplayFullErrorStack { get; set; }++ public bool UseSessionStateTempDataProvider { get; set; }++ /// <summary>+ /// Gets or sets a value custom response header encoding may be needed in some cases+ /// </summary>+ public bool AllowNonAsciiCharInHeaders { get; set; }++ /// <summary>+ /// Gets or sets the maximum allowed size of any request body in bytes+ /// </summary>+ public long? MaxRequestBodySize { get; set; }++ /// <summary>+ /// Gets or sets the value to enable a middleware for logging additional information about CurrentCustomer and store+ /// </summary>+ public bool EnableContextLoggingMiddleware { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/ApplicationInsightsConfig.cs b/src/Core/Grand.Infrastructure/Configuration/ApplicationInsightsConfig.csindex 7580fff64..0331be703 100644--- a/src/Core/Grand.Infrastructure/Configuration/ApplicationInsightsConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/ApplicationInsightsConfig.cs@@ -1,8 +1,7 @@-namespace Grand.Infrastructure.Configuration+namespace Grand.Infrastructure.Configuration;++public class ApplicationInsightsConfig{- public class ApplicationInsightsConfig- {- public string ConnectionString { get; set; }- public bool TrackDependencyMongoDb { get; set; }- }-}+ public string ConnectionString { get; set; }+ public bool TrackDependencyMongoDb { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/AzureConfig.cs b/src/Core/Grand.Infrastructure/Configuration/AzureConfig.csindex 19b7a23a9..6f0e298de 100644--- a/src/Core/Grand.Infrastructure/Configuration/AzureConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/AzureConfig.cs@@ -1,56 +1,55 @@-namespace Grand.Infrastructure.Configuration+namespace Grand.Infrastructure.Configuration;++public class AzureConfig{- public class AzureConfig- {- /// <summary>- /// A value indicating whether the site is run on Windows Azure Web Apps- /// </summary>- public bool RunOnAzureWebApps { get; set; }-- /// <summary>- /// Connection string for Azure BLOB storage- /// </summary>- public string AzureBlobStorageConnectionString { get; set; }-- /// <summary>- /// Container name for Azure BLOB storage- /// </summary>- public string AzureBlobStorageContainerName { get; set; }- /// <summary>- /// End point for Azure BLOB storage- /// </summary>- public string AzureBlobStorageEndPoint { get; set; }---- /// <summary>- /// Connection string for PersistKeys Azure BLOB storage- /// </summary>- public string PersistKeysAzureBlobStorageConnectionString { get; set; }-- /// <summary>- /// Indicates whether we should use Azure Key Vault to store data protection keys- /// </summary>- public bool PersistKeysToAzureKeyVault { get; set; }-- /// <summary>- /// Indicates whether we should use Azure blob storage to store data protection- /// </summary>- public bool PersistKeysToAzureBlobStorage { get; set; }-- /// <summary>- /// Azure blob storage container name- /// </summary>- public string DataProtectionContainerName { get; set; }-- /// <summary>- /// Azure blob storage blob name- /// </summary>- public string DataProtectionBlobName { get; set; }-- /// <summary>- /// The keyIdentifier is the key vault key identifier used for key encryption.- /// </summary>- public string KeyIdentifier { get; set; }- }-}+ /// <summary>+ /// A value indicating whether the site is run on Windows Azure Web Apps+ /// </summary>+ public bool RunOnAzureWebApps { get; set; }++ /// <summary>+ /// Connection string for Azure BLOB storage+ /// </summary>+ public string AzureBlobStorageConnectionString { get; set; }++ /// <summary>+ /// Container name for Azure BLOB storage+ /// </summary>+ public string AzureBlobStorageContainerName { get; set; }++ /// <summary>+ /// End point for Azure BLOB storage+ /// </summary>+ public string AzureBlobStorageEndPoint { get; set; }+++ /// <summary>+ /// Connection string for PersistKeys Azure BLOB storage+ /// </summary>+ public string PersistKeysAzureBlobStorageConnectionString { get; set; }++ /// <summary>+ /// Indicates whether we should use Azure Key Vault to store data protection keys+ /// </summary>+ public bool PersistKeysToAzureKeyVault { get; set; }++ /// <summary>+ /// Indicates whether we should use Azure blob storage to store data protection+ /// </summary>+ public bool PersistKeysToAzureBlobStorage { get; set; }++ /// <summary>+ /// Azure blob storage container name+ /// </summary>+ public string DataProtectionContainerName { get; set; }++ /// <summary>+ /// Azure blob storage blob name+ /// </summary>+ public string DataProtectionBlobName { get; set; }++ /// <summary>+ /// The keyIdentifier is the key vault key identifier used for key encryption.+ /// </summary>+ public string KeyIdentifier { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/BackendAPIConfig.cs b/src/Core/Grand.Infrastructure/Configuration/BackendAPIConfig.csindex fc84c2646..64879fe7d 100644--- a/src/Core/Grand.Infrastructure/Configuration/BackendAPIConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/BackendAPIConfig.cs@@ -1,16 +1,15 @@-namespace Grand.Infrastructure.Configuration+namespace Grand.Infrastructure.Configuration;++public class BackendAPIConfig{- public class BackendAPIConfig- {- public bool Enabled { get; set; }- public string SecretKey { get; set; }- public bool ValidateIssuer { get; set; }- public string ValidIssuer { get; set; }- public bool ValidateAudience { get; set; }- public string ValidAudience { get; set; }- public bool ValidateLifetime { get; set; }- public bool ValidateIssuerSigningKey { get; set; }- public int ExpiryInMinutes { get; set; }- public bool SystemModel { get; set; }- }-}+ public bool Enabled { get; set; }+ public string SecretKey { get; set; }+ public bool ValidateIssuer { get; set; }+ public string ValidIssuer { get; set; }+ public bool ValidateAudience { get; set; }+ public string ValidAudience { get; set; }+ public bool ValidateLifetime { get; set; }+ public bool ValidateIssuerSigningKey { get; set; }+ public int ExpiryInMinutes { get; set; }+ public bool SystemModel { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/CacheConfig.cs b/src/Core/Grand.Infrastructure/Configuration/CacheConfig.csindex 6ab73ee16..1011c5a00 100644--- a/src/Core/Grand.Infrastructure/Configuration/CacheConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/CacheConfig.cs@@ -3,7 +3,7 @@public class CacheConfig{/// <summary>- /// Gets or sets a value indicating for default cache time in minutes+ /// Gets or sets a value indicating for default cache time in minutes/// </summary>public int DefaultCacheTimeMinutes { get; set; }}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/DatabaseConfig.cs b/src/Core/Grand.Infrastructure/Configuration/DatabaseConfig.csindex af9f95d26..c2396e529 100644--- a/src/Core/Grand.Infrastructure/Configuration/DatabaseConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/DatabaseConfig.cs@@ -1,27 +1,26 @@-namespace Grand.Infrastructure.Configuration+namespace Grand.Infrastructure.Configuration;++public class DatabaseConfig{- public class DatabaseConfig- {- /// <summary>- /// Gets or sets a value indicating whether use LiteDB database for your application- /// </summary>- public bool UseLiteDb { get; set; }+ /// <summary>+ /// Gets or sets a value indicating whether use LiteDB database for your application+ /// </summary>+ public bool UseLiteDb { get; set; }++ /// <summary>+ /// Gets or sets a value indicating whether use LiteDB database as a singleton service in the application+ /// </summary>+ public bool Singleton { get; set; }- /// <summary>- /// Gets or sets a value indicating whether use LiteDB database as a singleton service in the application- /// </summary>- public bool Singleton{ get; set; }+ /// <summary>+ /// Gets or sets a value indicating whether use LiteDB database (only for installation process)+ /// </summary>+ public string LiteDbConnectionString { get; set; }- /// <summary>- /// Gets or sets a value indicating whether use LiteDB database (only for installation process)- /// </summary>- public string LiteDbConnectionString { get; set; }-- /// <summary>- /// Gets or sets a value indicating whether use connection string for database (only for installed databases)- /// </summary>- public string ConnectionString { get; set; }- public int DbProvider { get; set; }+ /// <summary>+ /// Gets or sets a value indicating whether use connection string for database (only for installed databases)+ /// </summary>+ public string ConnectionString { get; set; }- }-}+ public int DbProvider { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/ExtensionsConfig.cs b/src/Core/Grand.Infrastructure/Configuration/ExtensionsConfig.csindex f93703a4c..49b4ba903 100644--- a/src/Core/Grand.Infrastructure/Configuration/ExtensionsConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/ExtensionsConfig.cs@@ -1,33 +1,32 @@-namespace Grand.Infrastructure.Configuration+namespace Grand.Infrastructure.Configuration;++/// <summary>+/// Represents a Extensions Config+/// </summary>+public class ExtensionsConfig{/// <summary>- /// Represents a Extensions Config+ /// Indicates whether we disabled upload plugins/themes+ /// </summary>+ public bool DisableUploadExtensions { get; set; }++ /// <summary>+ /// Gets or sets a value indicating whether copy dll plugin files to /Plugins/bin on application startup+ /// </summary>+ public bool PluginShadowCopy { get; set; }++ /// <summary>+ /// A list of plugins to be ignored during start application - pattern+ /// </summary>+ public string PluginSkipLoadingPattern { get; set; }++ /// <summary>+ /// Enable scripting C# applications to execute code./// </summary>- public class ExtensionsConfig- {- /// <summary>- /// Indicates whether we disabled upload plugins/themes- /// </summary>- public bool DisableUploadExtensions { get; set; }-- /// <summary>- /// Gets or sets a value indicating whether copy dll plugin files to /Plugins/bin on application startup- /// </summary>- public bool PluginShadowCopy { get; set; }-- /// <summary>- /// A list of plugins to be ignored during start application - pattern- /// </summary>- public string PluginSkipLoadingPattern { get; set; }+ public bool UseRoslynScripts { get; set; }- /// <summary>- /// Enable scripting C# applications to execute code.- /// </summary>- public bool UseRoslynScripts { get; set; }-- /// <summary>- ///List of installed plugins (comma separated)- /// </summary>- public string InstalledPlugins { get; set; }- }-}+ /// <summary>+ /// List of installed plugins (comma separated)+ /// </summary>+ public string InstalledPlugins { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/FrontendAPIConfig.cs b/src/Core/Grand.Infrastructure/Configuration/FrontendAPIConfig.csindex e542eeedc..dc51d77b5 100644--- a/src/Core/Grand.Infrastructure/Configuration/FrontendAPIConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/FrontendAPIConfig.cs@@ -1,18 +1,17 @@-namespace Grand.Infrastructure.Configuration+namespace Grand.Infrastructure.Configuration;++public class FrontendAPIConfig{- public class FrontendAPIConfig- {- public static string AuthenticationScheme => "FrontAuthentication";- public bool Enabled { get; set; }- public bool JsonContentType { get; set; }- public string SecretKey { get; set; }- public bool ValidateIssuer { get; set; }- public string ValidIssuer { get; set; }- public bool ValidateAudience { get; set; }- public string ValidAudience { get; set; }- public bool ValidateLifetime { get; set; }- public bool ValidateIssuerSigningKey { get; set; }- public int ExpiryInMinutes { get; set; }- public int RefreshTokenExpiryInMinutes { get; set; }- }-}+ public static string AuthenticationScheme => "FrontAuthentication";+ public bool Enabled { get; set; }+ public bool JsonContentType { get; set; }+ public string SecretKey { get; set; }+ public bool ValidateIssuer { get; set; }+ public string ValidIssuer { get; set; }+ public bool ValidateAudience { get; set; }+ public string ValidAudience { get; set; }+ public bool ValidateLifetime { get; set; }+ public bool ValidateIssuerSigningKey { get; set; }+ public int ExpiryInMinutes { get; set; }+ public int RefreshTokenExpiryInMinutes { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/PerformanceConfig.cs b/src/Core/Grand.Infrastructure/Configuration/PerformanceConfig.csindex 846342909..1fa14e21c 100644--- a/src/Core/Grand.Infrastructure/Configuration/PerformanceConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/PerformanceConfig.cs@@ -1,29 +1,27 @@-namespace Grand.Infrastructure.Configuration+namespace Grand.Infrastructure.Configuration;++/// <summary>+/// Represents a Performance Config+/// </summary>+public class PerformanceConfig{/// <summary>- /// Represents a Performance Config+ /// Gets or sets a value indicating whether we compress response/// </summary>- public partial class PerformanceConfig- {- /// <summary>- /// Gets or sets a value indicating whether we compress response- /// </summary>- public bool UseResponseCompression { get; set; }-- /// <summary>- /// Gets or sets a value indicating whether ignore InstallUrlMiddleware- /// </summary>- public bool IgnoreInstallUrlMiddleware { get; set; }+ public bool UseResponseCompression { get; set; }- /// <summary>- /// Gets or sets a value indicating whether ignore DbVersionCheckMiddleware- /// </summary>- public bool IgnoreDbVersionCheckMiddleware { get; set; }+ /// <summary>+ /// Gets or sets a value indicating whether ignore InstallUrlMiddleware+ /// </summary>+ public bool IgnoreInstallUrlMiddleware { get; set; }- /// <summary>- /// Gets or sets a value indicating whether ignore IgnoreUsePoweredByMiddleware- /// </summary>- public bool IgnoreUsePoweredByMiddleware { get; set; }+ /// <summary>+ /// Gets or sets a value indicating whether ignore DbVersionCheckMiddleware+ /// </summary>+ public bool IgnoreDbVersionCheckMiddleware { get; set; }- }-}+ /// <summary>+ /// Gets or sets a value indicating whether ignore IgnoreUsePoweredByMiddleware+ /// </summary>+ public bool IgnoreUsePoweredByMiddleware { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/RabbitConfig.cs b/src/Core/Grand.Infrastructure/Configuration/RabbitConfig.csindex 5c5425c6b..5bd66c220 100644--- a/src/Core/Grand.Infrastructure/Configuration/RabbitConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/RabbitConfig.cs@@ -1,13 +1,12 @@-namespace Grand.Infrastructure.Configuration+namespace Grand.Infrastructure.Configuration;++public class RabbitConfig{- public class RabbitConfig- {- public bool RabbitEnabled { get; set; }- public bool RabbitCachePubSubEnabled { get; set; }- public string RabbitHostName { get; set; }- public string RabbitVirtualHost { get; set; }- public string RabbitUsername { get; set; }- public string RabbitPassword { get; set; }- public string RabbitCacheReceiveEndpoint { get; set; }- }-}+ public bool RabbitEnabled { get; set; }+ public bool RabbitCachePubSubEnabled { get; set; }+ public string RabbitHostName { get; set; }+ public string RabbitVirtualHost { get; set; }+ public string RabbitUsername { get; set; }+ public string RabbitPassword { get; set; }+ public string RabbitCacheReceiveEndpoint { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/RedisConfig.cs b/src/Core/Grand.Infrastructure/Configuration/RedisConfig.csindex 25aabf1fc..9e87ca40d 100644--- a/src/Core/Grand.Infrastructure/Configuration/RedisConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/RedisConfig.cs@@ -1,31 +1,30 @@-namespace Grand.Infrastructure.Configuration-{- public class RedisConfig- {- /// <summary>- /// Enable the Publish/Subscribe messaging with redis to manage memory cache on every server- /// </summary>- public bool RedisPubSubEnabled { get; set; }+namespace Grand.Infrastructure.Configuration;- /// <summary>- /// Redis connection string. Used when Redis Publish/Subscribe is enabled- /// </summary>- public string RedisPubSubConnectionString { get; set; }+public class RedisConfig+{+ /// <summary>+ /// Enable the Publish/Subscribe messaging with redis to manage memory cache on every server+ /// </summary>+ public bool RedisPubSubEnabled { get; set; }- /// <summary>- /// Messages sent by other clients to these channels will be pushed by Redis to all the subscribed clients. It must me the same value on every server- /// </summary>- public string RedisPubSubChannel { get; set; }+ /// <summary>+ /// Redis connection string. Used when Redis Publish/Subscribe is enabled+ /// </summary>+ public string RedisPubSubConnectionString { get; set; }- /// <summary>- /// Indicates whether we should use Redis server for persist keys - required in farm scenario- /// </summary>- public bool PersistKeysToRedis { get; set; }+ /// <summary>+ /// Messages sent by other clients to these channels will be pushed by Redis to all the subscribed clients. It must me+ /// the same value on every server+ /// </summary>+ public string RedisPubSubChannel { get; set; }- /// <summary>- /// Redis connection string. Used when PersistKeysToRedis is enabled- /// </summary>- public string PersistKeysToRedisUrl { get; set; }+ /// <summary>+ /// Indicates whether we should use Redis server for persist keys - required in farm scenario+ /// </summary>+ public bool PersistKeysToRedis { get; set; }- }-}+ /// <summary>+ /// Redis connection string. Used when PersistKeysToRedis is enabled+ /// </summary>+ public string PersistKeysToRedisUrl { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/SecurityConfig.cs b/src/Core/Grand.Infrastructure/Configuration/SecurityConfig.csindex ceea1294d..5174ab745 100644--- a/src/Core/Grand.Infrastructure/Configuration/SecurityConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/SecurityConfig.cs@@ -1,86 +1,86 @@--using Microsoft.AspNetCore.Http;+using Microsoft.AspNetCore.Http;-namespace Grand.Infrastructure.Configuration+namespace Grand.Infrastructure.Configuration;++public class SecurityConfig{- public class SecurityConfig- {- /// <summary>- /// Gets or sets a value indicating whether to use Forwards proxied headers onto current request- /// </summary>- public bool UseForwardedHeaders { get; set; }-- /// <summary>- /// Gets or sets a value indicating whether to force use https- /// </summary>- public bool ForceUseHTTPS { get; set; }-- /// <summary>- /// Gets or sets a value for allowedHosts, is used for host filtering to bind your app to specific hostnames- /// </summary>- public string AllowedHosts { get; set; }-- /// <summary>- /// Gets or sets a value for Key persistence location- /// </summary>- public string KeyPersistenceLocation { get; set; }- /// <summary>- /// Gets or sets a value indicating for cookie expires in hours - default 24 * 365 = 8760- /// </summary>- public int CookieAuthExpires { get; set; }-- /// <summary>- /// Gets or sets a value for Cookie prefix- /// </summary>- public string CookiePrefix { get; set; }-- /// <summary>- /// Gets or sets a value for Cookie SameSite- /// </summary>- public SameSiteMode CookieSameSite { get; set; }-- /// <summary>- /// Gets or sets a value for Cookie SameSite for external authentication- /// </summary>- public SameSiteMode CookieSameSiteExternalAuth { get; set; }-- /// <summary>- /// Gets or sets a value for Cookie claim issuer- /// </summary>- public string CookieClaimsIssuer { get; set; }-- /// <summary>- /// Gets or sets a value of "Cookie SecurePolicy Always"- /// </summary>- public bool CookieSecurePolicyAlways { get; set; }-- /// <summary>- /// Gets or sets a value indicating whether use the default security headers for your application- /// </summary>- public bool UseDefaultSecurityHeaders { get; set; }-- /// <summary>- /// HTTP Strict Transport Security Protocol- /// isn't recommended in development because the HSTS header is highly cacheable by browsers- /// </summary>- public bool UseHsts { get; set; }-- /// <summary>- /// Enforce HTTPS in ASP.NET Core- /// </summary>- public bool UseHttpsRedirection { get; set; }-- public int HttpsRedirectionRedirect { get; set; }- public int? HttpsRedirectionHttpsPort { get; set; }-- /// <summary>- /// When enabled, allowing Razor files to be updated if they're edited.- /// </summary>- public bool EnableRuntimeCompilation { get; set; }-- /// <summary>- /// Gets or sets a value indicating whether to verify access to a specific controller and action in the admin panel using menu configuration.- /// </summary>- public bool AuthorizeAdminMenu { get; set; }- }-}+ /// <summary>+ /// Gets or sets a value indicating whether to use Forwards proxied headers onto current request+ /// </summary>+ public bool UseForwardedHeaders { get; set; }++ /// <summary>+ /// Gets or sets a value indicating whether to force use https+ /// </summary>+ public bool ForceUseHTTPS { get; set; }++ /// <summary>+ /// Gets or sets a value for allowedHosts, is used for host filtering to bind your app to specific hostnames+ /// </summary>+ public string AllowedHosts { get; set; }++ /// <summary>+ /// Gets or sets a value for Key persistence location+ /// </summary>+ public string KeyPersistenceLocation { get; set; }++ /// <summary>+ /// Gets or sets a value indicating for cookie expires in hours - default 24 * 365 = 8760+ /// </summary>+ public int CookieAuthExpires { get; set; }++ /// <summary>+ /// Gets or sets a value for Cookie prefix+ /// </summary>+ public string CookiePrefix { get; set; }++ /// <summary>+ /// Gets or sets a value for Cookie SameSite+ /// </summary>+ public SameSiteMode CookieSameSite { get; set; }++ /// <summary>+ /// Gets or sets a value for Cookie SameSite for external authentication+ /// </summary>+ public SameSiteMode CookieSameSiteExternalAuth { get; set; }++ /// <summary>+ /// Gets or sets a value for Cookie claim issuer+ /// </summary>+ public string CookieClaimsIssuer { get; set; }++ /// <summary>+ /// Gets or sets a value of "Cookie SecurePolicy Always"+ /// </summary>+ public bool CookieSecurePolicyAlways { get; set; }++ /// <summary>+ /// Gets or sets a value indicating whether use the default security headers for your application+ /// </summary>+ public bool UseDefaultSecurityHeaders { get; set; }++ /// <summary>+ /// HTTP Strict Transport Security Protocol+ /// isn't recommended in development because the HSTS header is highly cacheable by browsers+ /// </summary>+ public bool UseHsts { get; set; }++ /// <summary>+ /// Enforce HTTPS in ASP.NET Core+ /// </summary>+ public bool UseHttpsRedirection { get; set; }++ public int HttpsRedirectionRedirect { get; set; }+ public int? HttpsRedirectionHttpsPort { get; set; }++ /// <summary>+ /// When enabled, allowing Razor files to be updated if they're edited.+ /// </summary>+ public bool EnableRuntimeCompilation { get; set; }++ /// <summary>+ /// Gets or sets a value indicating whether to verify access to a specific controller and action in the admin panel+ /// using menu configuration.+ /// </summary>+ public bool AuthorizeAdminMenu { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Configuration/UrlRewriteConfig.cs b/src/Core/Grand.Infrastructure/Configuration/UrlRewriteConfig.csindex c2272a055..4421247d0 100644--- a/src/Core/Grand.Infrastructure/Configuration/UrlRewriteConfig.cs+++ b/src/Core/Grand.Infrastructure/Configuration/UrlRewriteConfig.cs@@ -1,15 +1,14 @@-namespace Grand.Infrastructure.Configuration+namespace Grand.Infrastructure.Configuration;++public class UrlRewriteConfig{- public class UrlRewriteConfig- {- /// <summary>- /// Gets or sets a value indicating whether we use url rewrite- /// </summary>- public bool UseUrlRewrite { get; set; }- public bool UrlRewriteHttpsOptions { get; set; }- public int UrlRewriteHttpsOptionsStatusCode { get; set; }- public int UrlRewriteHttpsOptionsPort { get; set; }- public bool UrlRedirectToHttpsPermanent { get; set; }+ /// <summary>+ /// Gets or sets a value indicating whether we use url rewrite+ /// </summary>+ public bool UseUrlRewrite { get; set; }- }-}+ public bool UrlRewriteHttpsOptions { get; set; }+ public int UrlRewriteHttpsOptionsStatusCode { get; set; }+ public int UrlRewriteHttpsOptionsPort { get; set; }+ public bool UrlRedirectToHttpsPermanent { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Endpoints/IEndpointProvider.cs b/src/Core/Grand.Infrastructure/Endpoints/IEndpointProvider.csindex 8952d06fc..b292680fb 100644--- a/src/Core/Grand.Infrastructure/Endpoints/IEndpointProvider.cs+++ b/src/Core/Grand.Infrastructure/Endpoints/IEndpointProvider.cs@@ -1,21 +1,20 @@using Microsoft.AspNetCore.Routing;-namespace Grand.Infrastructure.Endpoints+namespace Grand.Infrastructure.Endpoints;++/// <summary>+/// Endpoints provider+/// </summary>+public interface IEndpointProvider{/// <summary>- /// Endpoints provider+ /// Gets a priority of endpoint provider/// </summary>- public interface IEndpointProvider- {- /// <summary>- /// Register endpoint- /// </summary>- /// <param name="endpointRouteBuilder">Endpoint Route builder</param>- void RegisterEndpoint(IEndpointRouteBuilder endpointRouteBuilder);+ int Priority { get; }- /// <summary>- /// Gets a priority of endpoint provider- /// </summary>- int Priority { get; }- }-}+ /// <summary>+ /// Register endpoint+ /// </summary>+ /// <param name="endpointRouteBuilder">Endpoint Route builder</param>+ void RegisterEndpoint(IEndpointRouteBuilder endpointRouteBuilder);+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Events/CacheEvent.cs b/src/Core/Grand.Infrastructure/Events/CacheEvent.csindex 907c3f1af..de5af6175 100644--- a/src/Core/Grand.Infrastructure/Events/CacheEvent.cs+++ b/src/Core/Grand.Infrastructure/Events/CacheEvent.cs@@ -1,8 +1,7 @@-namespace Grand.Infrastructure.Events+namespace Grand.Infrastructure.Events;++public enum CacheEvent{- public enum CacheEvent- {- RemoveKey = 0,- RemovePrefix = 2- }-}+ RemoveKey = 0,+ RemovePrefix = 2+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Events/EntityCacheEvent.cs b/src/Core/Grand.Infrastructure/Events/EntityCacheEvent.csindex 2753463c1..733509289 100644--- a/src/Core/Grand.Infrastructure/Events/EntityCacheEvent.cs+++ b/src/Core/Grand.Infrastructure/Events/EntityCacheEvent.cs@@ -1,15 +1,15 @@using MediatR;-namespace Grand.Infrastructure.Events+namespace Grand.Infrastructure.Events;++public class EntityCacheEvent : INotification{- public class EntityCacheEvent : INotification+ public EntityCacheEvent(string entity, CacheEvent @event){- public EntityCacheEvent(string entity, CacheEvent @event)- {- Entity = entity;- Event = @event;- }- public string Entity { get; private set; }- public CacheEvent Event { get; private set; }+ Entity = entity;+ Event = @event;}-}++ public string Entity { get; private set; }+ public CacheEvent Event { get; private set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Events/EntityDeleted.cs b/src/Core/Grand.Infrastructure/Events/EntityDeleted.csindex ef8b36c83..ee5dd1ae2 100644--- a/src/Core/Grand.Infrastructure/Events/EntityDeleted.cs+++ b/src/Core/Grand.Infrastructure/Events/EntityDeleted.cs@@ -1,19 +1,19 @@using Grand.Domain;using MediatR;-namespace Grand.Infrastructure.Events-{- /// <summary>- /// A container for passing entities that have been deleted.- /// </summary>- /// <typeparam name="T"></typeparam>- public class EntityDeleted<T> : INotification where T : ParentEntity+namespace Grand.Infrastructure.Events;++/// <summary>+/// A container for passing entities that have been deleted.+/// </summary>+/// <typeparam name="T"></typeparam>+public class EntityDeleted<T> : INotification where T : ParentEntity+{+ public EntityDeleted(T entity){- public EntityDeleted(T entity)- {- Entity = entity;- }- public T Entity { get; private set; }+ Entity = entity;}-}++ public T Entity { get; private set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Events/EntityInserted.cs b/src/Core/Grand.Infrastructure/Events/EntityInserted.csindex cc2df4030..b0e946957 100644--- a/src/Core/Grand.Infrastructure/Events/EntityInserted.cs+++ b/src/Core/Grand.Infrastructure/Events/EntityInserted.cs@@ -1,20 +1,18 @@using Grand.Domain;using MediatR;-namespace Grand.Infrastructure.Events+namespace Grand.Infrastructure.Events;++/// <summary>+/// A container for entities that have been inserted.+/// </summary>+/// <typeparam name="T"></typeparam>+public class EntityInserted<T> : INotification where T : ParentEntity{- /// <summary>- /// A container for entities that have been inserted.- /// </summary>- /// <typeparam name="T"></typeparam>- public class EntityInserted<T> : INotification where T : ParentEntity+ public EntityInserted(T entity){- public EntityInserted(T entity)- {- Entity = entity;- }-- public T Entity { get; private set; }+ Entity = entity;}-}+ public T Entity { get; private set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Events/EntityUpdated.cs b/src/Core/Grand.Infrastructure/Events/EntityUpdated.csindex bba9c0312..49a4dc7e9 100644--- a/src/Core/Grand.Infrastructure/Events/EntityUpdated.cs+++ b/src/Core/Grand.Infrastructure/Events/EntityUpdated.cs@@ -1,19 +1,18 @@using Grand.Domain;using MediatR;-namespace Grand.Infrastructure.Events+namespace Grand.Infrastructure.Events;++/// <summary>+/// A container for entities that are updated.+/// </summary>+/// <typeparam name="T"></typeparam>+public class EntityUpdated<T> : INotification where T : ParentEntity{- /// <summary>- /// A container for entities that are updated.- /// </summary>- /// <typeparam name="T"></typeparam>- public class EntityUpdated<T> : INotification where T : ParentEntity+ public EntityUpdated(T entity){- public EntityUpdated(T entity)- {- Entity = entity;- }-- public T Entity { get; private set; }+ Entity = entity;}-}++ public T Entity { get; private set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Extensions/CommonExtensions.cs b/src/Core/Grand.Infrastructure/Extensions/CommonExtensions.csindex 5387562d7..40e4f3b81 100644--- a/src/Core/Grand.Infrastructure/Extensions/CommonExtensions.cs+++ b/src/Core/Grand.Infrastructure/Extensions/CommonExtensions.cs@@ -1,56 +1,52 @@using Microsoft.AspNetCore.Http.Extensions;using Microsoft.AspNetCore.WebUtilities;-namespace Grand.Infrastructure.Extensions+namespace Grand.Infrastructure.Extensions;++public static class CommonExtensions{- public static class CommonExtensions+ public static string ModifyQueryString(string url, string key, string value){- public static string ModifyQueryString(string url, string key, string value)- {- if (string.IsNullOrEmpty(url))- return string.Empty;+ if (string.IsNullOrEmpty(url))+ return string.Empty;- if (string.IsNullOrEmpty(key))- return url;+ if (string.IsNullOrEmpty(key))+ return url;- var baseUrl = "";- var queryString = "";+ var baseUrl = "";+ var queryString = "";- if (Uri.IsWellFormedUriString(url, UriKind.Absolute))+ if (Uri.IsWellFormedUriString(url, UriKind.Absolute))+ {+ var uri = new Uri(url);+ baseUrl = uri.AbsolutePath;+ queryString = uri.Query;+ }+ else+ {+ var questionMarkIndex = url.IndexOf('?');+ if (questionMarkIndex != -1){- var uri = new Uri(url);- baseUrl = uri.AbsolutePath;- queryString = uri.Query;+ baseUrl = url.Substring(0, questionMarkIndex);+ queryString = url.Substring(questionMarkIndex);}else{- var questionMarkIndex = url.IndexOf('?');- if (questionMarkIndex != -1)- {- baseUrl = url.Substring(0, questionMarkIndex);- queryString = url.Substring(questionMarkIndex);- }- else- {- baseUrl = url;- }+ baseUrl = url;}+ }- var query = QueryHelpers.ParseQuery(queryString);+ var query = QueryHelpers.ParseQuery(queryString);- var items = query.SelectMany(x => x.Value, (col, val) => new KeyValuePair<string, string>(col.Key, val)).ToList();+ var items = query.SelectMany(x => x.Value, (col, val) => new KeyValuePair<string, string>(col.Key, val))+ .ToList();- items.RemoveAll(x => x.Key == key);+ items.RemoveAll(x => x.Key == key);- if (!string.IsNullOrEmpty(value))- {- items.Add(new KeyValuePair<string, string>(key, value));- }+ if (!string.IsNullOrEmpty(value)) items.Add(new KeyValuePair<string, string>(key, value));- var qb = new QueryBuilder(items);-- return baseUrl + qb.ToQueryString();- }+ var qb = new QueryBuilder(items);+ return baseUrl + qb.ToQueryString();}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Extensions/EventPublisherExtensions.cs b/src/Core/Grand.Infrastructure/Extensions/EventPublisherExtensions.csindex 4d4a1b5bd..2d799658d 100644--- a/src/Core/Grand.Infrastructure/Extensions/EventPublisherExtensions.cs+++ b/src/Core/Grand.Infrastructure/Extensions/EventPublisherExtensions.cs@@ -1,25 +1,23 @@-using Grand.Infrastructure.Events;-using Grand.Domain;+using Grand.Domain;+using Grand.Infrastructure.Events;using MediatR;-namespace Grand.Infrastructure.Extensions+namespace Grand.Infrastructure.Extensions;++public static class EventPublisherExtensions{- public static class EventPublisherExtensions+ public static async Task EntityInserted<T>(this IMediator eventPublisher, T entity) where T : ParentEntity{- public static async Task EntityInserted<T>(this IMediator eventPublisher, T entity) where T : ParentEntity- {- await eventPublisher.Publish(new EntityInserted<T>(entity));- }-- public static async Task EntityUpdated<T>(this IMediator eventPublisher, T entity) where T : ParentEntity- {- await eventPublisher.Publish(new EntityUpdated<T>(entity));- }+ await eventPublisher.Publish(new EntityInserted<T>(entity));+ }- public static async Task EntityDeleted<T>(this IMediator eventPublisher, T entity) where T : ParentEntity- {- await eventPublisher.Publish(new EntityDeleted<T>(entity));- }+ public static async Task EntityUpdated<T>(this IMediator eventPublisher, T entity) where T : ParentEntity+ {+ await eventPublisher.Publish(new EntityUpdated<T>(entity));+ }+ public static async Task EntityDeleted<T>(this IMediator eventPublisher, T entity) where T : ParentEntity+ {+ await eventPublisher.Publish(new EntityDeleted<T>(entity));}}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Extensions/MvcOptionsExtensions.cs b/src/Core/Grand.Infrastructure/Extensions/MvcOptionsExtensions.csindex a42d4b074..29966f4c4 100644--- a/src/Core/Grand.Infrastructure/Extensions/MvcOptionsExtensions.cs+++ b/src/Core/Grand.Infrastructure/Extensions/MvcOptionsExtensions.cs@@ -6,7 +6,8 @@ namespace Grand.Infrastructure.Extensions;public static class MvcOptionsExtensions{- public static void UseJsonBodyModelBinderProviderInsteadOf<T>(this MvcOptions mvcOptions) where T : IModelBinderProvider+ public static void UseJsonBodyModelBinderProviderInsteadOf<T>(this MvcOptions mvcOptions)+ where T : IModelBinderProvider{var replacedModelBinderProvider = mvcOptions.ModelBinderProviders.OfType<T>().FirstOrDefault();if (replacedModelBinderProvider == null) return;diff --git a/src/Core/Grand.Infrastructure/Extensions/ProviderExtensions.cs b/src/Core/Grand.Infrastructure/Extensions/ProviderExtensions.csindex 721e02b40..fb476c738 100644--- a/src/Core/Grand.Infrastructure/Extensions/ProviderExtensions.cs+++ b/src/Core/Grand.Infrastructure/Extensions/ProviderExtensions.cs@@ -4,52 +4,50 @@ using Grand.Infrastructure.Plugins;using Grand.SharedKernel.Extensions;using System.Text.Json;-namespace Grand.Infrastructure.Extensions+namespace Grand.Infrastructure.Extensions;++public static class ProviderExtensions{- public static class ProviderExtensions+ public static bool IsAuthenticateStore(this IProvider method, Store store)+ {+ if (method == null)+ throw new ArgumentNullException(nameof(method));++ return store == null || IsAuthenticateStore(method, store.Id);+ }++ public static bool IsAuthenticateStore(this IProvider method, string storeId)+ {+ if (method == null)+ throw new ArgumentNullException(nameof(method));++ if (string.IsNullOrEmpty(storeId))+ return true;++ if (method.LimitedToStores == null || !method.LimitedToStores.Any())+ return true;++ return method.LimitedToStores.Contains(storeId);+ }++ public static bool IsAuthenticateGroup(this IProvider method, Customer customer)+ {+ if (method == null)+ throw new ArgumentNullException(nameof(method));++ if (customer == null)+ return true;++ if (method.LimitedToGroups == null || !method.LimitedToGroups.Any())+ return true;++ return method.LimitedToGroups.ContainsAny(customer.Groups.Select(x => x));+ }++ public static class JsonSerializerOptionsProvider{- public static bool IsAuthenticateStore(this IProvider method, Store store)- {- if (method == null)- throw new ArgumentNullException(nameof(method));-- return store == null || IsAuthenticateStore(method, store.Id);- }-- public static bool IsAuthenticateStore(this IProvider method, string storeId)- {- if (method == null)- throw new ArgumentNullException(nameof(method));-- if (string.IsNullOrEmpty(storeId))- return true;-- if (method.LimitedToStores == null || !method.LimitedToStores.Any())- return true;-- return method.LimitedToStores.Contains(storeId);- }-- public static bool IsAuthenticateGroup(this IProvider method, Customer customer)- {- if (method == null)- throw new ArgumentNullException(nameof(method));-- if (customer == null)- return true;-- if (method.LimitedToGroups == null || !method.LimitedToGroups.Any())- return true;-- return method.LimitedToGroups.ContainsAny(customer.Groups.Select(x => x));- }-- public static class JsonSerializerOptionsProvider- {- public static JsonSerializerOptions Options { get; } = new JsonSerializerOptions- {- PropertyNameCaseInsensitive = true- };- }+ public static JsonSerializerOptions Options { get; } = new() {+ PropertyNameCaseInsensitive = true+ };}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/GrandVersion.cs b/src/Core/Grand.Infrastructure/GrandVersion.csindex b9275d63b..266c74139 100644--- a/src/Core/Grand.Infrastructure/GrandVersion.cs+++ b/src/Core/Grand.Infrastructure/GrandVersion.cs@@ -1,91 +1,87 @@using System.Reflection;using System.Text.RegularExpressions;-namespace Grand.Infrastructure-{- public static class GrandVersion- {- /// <summary>- /// Gets the major version- /// </summary>- public static readonly string MajorVersion = Assembly.GetExecutingAssembly().GetName().Version?.Major.ToString();+namespace Grand.Infrastructure;- /// <summary>- /// Gets the minor version- /// </summary>- public static readonly string MinorVersion = Assembly.GetExecutingAssembly().GetName().Version?.Minor.ToString();+public static class GrandVersion+{+ /// <summary>+ /// Gets the major version+ /// </summary>+ public static readonly string MajorVersion = Assembly.GetExecutingAssembly().GetName().Version?.Major.ToString();- /// <summary>- /// Gets the patch version- /// </summary>- public static string PatchVersion {- get {-- Assembly assembly = Assembly.GetExecutingAssembly();- if (assembly.GetCustomAttribute(typeof(AssemblyInformationalVersionAttribute)) is not- AssemblyInformationalVersionAttribute infoVersionAttribute) return "0";- var fullVersion = infoVersionAttribute.InformationalVersion;- Match match = Regex.Match(fullVersion, @"(\d+)\.(\d+)\.(\d+)(?:-([^\+]+))?");- if (!match.Success) return "0";- var patch = match.Groups[3].Value;- var suffix = match.Groups[4].Value;- return string.IsNullOrEmpty(suffix) ? patch : $"{patch}-{suffix}";- }- }- /// <summary>- /// Gets the full version- /// </summary>- public static readonly string FullVersion = $"{MajorVersion}.{MinorVersion}.{PatchVersion}";+ /// <summary>+ /// Gets the minor version+ /// </summary>+ public static readonly string MinorVersion = Assembly.GetExecutingAssembly().GetName().Version?.Minor.ToString();- /// <summary>- /// Gets the Supported DB version- /// </summary>- public static readonly string SupportedDBVersion = $"{MajorVersion}.{MinorVersion}";+ /// <summary>+ /// Gets the full version+ /// </summary>+ public static readonly string FullVersion = $"{MajorVersion}.{MinorVersion}.{PatchVersion}";- /// <summary>- /// Gets the Supported plugin version- /// </summary>- public static readonly string SupportedPluginVersion = $"{MajorVersion}.{MinorVersion}";+ /// <summary>+ /// Gets the Supported DB version+ /// </summary>+ public static readonly string SupportedDBVersion = $"{MajorVersion}.{MinorVersion}";- /// <summary>- /// Gets the git branch- /// </summary>- public static string GitBranch = GetGitBranch();+ /// <summary>+ /// Gets the Supported plugin version+ /// </summary>+ public static readonly string SupportedPluginVersion = $"{MajorVersion}.{MinorVersion}";- /// <summary>- /// Gets the git commit- /// </summary>- public static string GitCommit = GetGitHash();+ /// <summary>+ /// Gets the git branch+ /// </summary>+ public static string GitBranch = GetGitBranch();- private static string GetGitHash()- {- if (!string.IsNullOrEmpty(_gitHash)) return _gitHash;+ /// <summary>+ /// Gets the git commit+ /// </summary>+ public static string GitCommit = GetGitHash();- var version = "1.0.0+LOCALBUILD";- var appAssembly = typeof(GrandVersion).Assembly;- var infoVerAttr = (AssemblyInformationalVersionAttribute)appAssembly- .GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute)).FirstOrDefault();- if (infoVerAttr is { InformationalVersion.Length: > 6 })- {- version = infoVerAttr.InformationalVersion;- }- _gitHash = version[(version.IndexOf('+') + 1)..];- return _gitHash;+ /// <summary>+ /// Gets the patch version+ /// </summary>+ public static string PatchVersion {+ get {+ var assembly = Assembly.GetExecutingAssembly();+ if (assembly.GetCustomAttribute(typeof(AssemblyInformationalVersionAttribute)) is not+ AssemblyInformationalVersionAttribute infoVersionAttribute) return "0";+ var fullVersion = infoVersionAttribute.InformationalVersion;+ var match = Regex.Match(fullVersion, @"(\d+)\.(\d+)\.(\d+)(?:-([^\+]+))?");+ if (!match.Success) return "0";+ var patch = match.Groups[3].Value;+ var suffix = match.Groups[4].Value;+ return string.IsNullOrEmpty(suffix) ? patch : $"{patch}-{suffix}";}+ }- private static string _gitHash { get; set; }+ private static string _gitHash { get; set; }- private static string GetGitBranch()- {- if (!string.IsNullOrEmpty(_gitBranch)) return _gitBranch;+ private static string _gitBranch { get; set; }- var appAssembly = typeof(GrandVersion).Assembly;- var infoBranchAttr = appAssembly.GetCustomAttributes(typeof(AssemblyMetadataAttribute))- .FirstOrDefault(x => ((AssemblyMetadataAttribute)x).Key == "GitBranch");- _gitBranch = infoBranchAttr != null ? ((AssemblyMetadataAttribute)infoBranchAttr).Value : "UNKNOWN";- return _gitBranch;- }+ private static string GetGitHash()+ {+ if (!string.IsNullOrEmpty(_gitHash)) return _gitHash;++ var version = "1.0.0+LOCALBUILD";+ var appAssembly = typeof(GrandVersion).Assembly;+ var infoVerAttr = (AssemblyInformationalVersionAttribute)appAssembly+ .GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute)).FirstOrDefault();+ if (infoVerAttr is { InformationalVersion.Length: > 6 }) version = infoVerAttr.InformationalVersion;+ _gitHash = version[(version.IndexOf('+') + 1)..];+ return _gitHash;+ }++ private static string GetGitBranch()+ {+ if (!string.IsNullOrEmpty(_gitBranch)) return _gitBranch;- private static string _gitBranch { get; set; }+ var appAssembly = typeof(GrandVersion).Assembly;+ var infoBranchAttr = appAssembly.GetCustomAttributes(typeof(AssemblyMetadataAttribute))+ .FirstOrDefault(x => ((AssemblyMetadataAttribute)x).Key == "GitBranch");+ _gitBranch = infoBranchAttr != null ? ((AssemblyMetadataAttribute)infoBranchAttr).Value : "UNKNOWN";+ return _gitBranch;}}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/IStartupApplication.cs b/src/Core/Grand.Infrastructure/IStartupApplication.csindex 03190ea61..97ae79f52 100644--- a/src/Core/Grand.Infrastructure/IStartupApplication.cs+++ b/src/Core/Grand.Infrastructure/IStartupApplication.cs@@ -3,32 +3,31 @@ using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Infrastructure+namespace Grand.Infrastructure;++public interface IStartupApplication{- public interface IStartupApplication- {- /// <summary>- /// Add and configure any of the middleware- /// </summary>- /// <param name="services">Collection of service descriptors</param>- /// <param name="configuration">Configuration root of the application</param>- void ConfigureServices(IServiceCollection services, IConfiguration configuration);+ /// <summary>+ /// Gets order of this startup configuration implementation+ /// </summary>+ int Priority { get; }- /// <summary>- /// Configure the using of added middleware- /// </summary>- /// <param name="application">Builder for configuring an application's request pipeline</param>- /// <param name="webHostEnvironment">WebHostEnvironment</param>- void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment);+ /// <summary>+ /// Gets before configure of this startup configuration implementation+ /// </summary>+ bool BeforeConfigure { get; }- /// <summary>- /// Gets order of this startup configuration implementation- /// </summary>- int Priority { get; }+ /// <summary>+ /// Add and configure any of the middleware+ /// </summary>+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="configuration">Configuration root of the application</param>+ void ConfigureServices(IServiceCollection services, IConfiguration configuration);- /// <summary>- /// Gets before configure of this startup configuration implementation- /// </summary>- bool BeforeConfigure { get; }- }-}+ /// <summary>+ /// Configure the using of added middleware+ /// </summary>+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ /// <param name="webHostEnvironment">WebHostEnvironment</param>+ void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment);+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/IStoreHelper.cs b/src/Core/Grand.Infrastructure/IStoreHelper.csindex a8db766d9..adbbb3c1f 100644--- a/src/Core/Grand.Infrastructure/IStoreHelper.cs+++ b/src/Core/Grand.Infrastructure/IStoreHelper.cs@@ -1,13 +1,12 @@using Grand.Domain.Stores;-namespace Grand.Infrastructure+namespace Grand.Infrastructure;++public interface IStoreHelper{- public interface IStoreHelper- {- Store StoreHost { get; }- DomainHost DomainHost { get; }+ Store StoreHost { get; }+ DomainHost DomainHost { get; }- Task SetStoreCookie(string storeId);- Task<Store> SetCurrentStore(string storeId);- }-}+ Task SetStoreCookie(string storeId);+ Task<Store> SetCurrentStore(string storeId);+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/IWorkContext.cs b/src/Core/Grand.Infrastructure/IWorkContext.csindex 5160fec25..a09db321b 100644--- a/src/Core/Grand.Infrastructure/IWorkContext.cs+++ b/src/Core/Grand.Infrastructure/IWorkContext.cs@@ -5,88 +5,85 @@ using Grand.Domain.Stores;using Grand.Domain.Tax;using Grand.Domain.Vendors;-namespace Grand.Infrastructure+namespace Grand.Infrastructure;++/// <summary>+/// Work context - get current information about current customer/store+/// </summary>+public interface IWorkContext{/// <summary>- /// Work context - get current information about current customer/store+ /// Gets the current customer/// </summary>- public interface IWorkContext- {- /// <summary>- /// Gets the current customer- /// </summary>- Customer CurrentCustomer { get; }+ Customer CurrentCustomer { get; }- /// <summary>- /// Gets or sets the original customer (in case the current one is impersonated)- /// </summary>- Customer OriginalCustomerIfImpersonated { get; }+ /// <summary>+ /// Gets or sets the original customer (in case the current one is impersonated)+ /// </summary>+ Customer OriginalCustomerIfImpersonated { get; }++ /// <summary>+ /// Gets the current vendor (logged-in manager)+ /// </summary>+ Vendor CurrentVendor { get; }++ /// <summary>+ /// Gets the current host+ /// </summary>+ DomainHost CurrentHost { get; }- /// <summary>- /// Gets the current vendor (logged-in manager)- /// </summary>- Vendor CurrentVendor { get; }+ /// <summary>+ /// Get or set current user working language+ /// </summary>+ Language WorkingLanguage { get; }++ /// <summary>+ /// Get or set current user working currency+ /// </summary>+ Currency WorkingCurrency { get; }++ /// <summary>+ /// Get current tax display type+ /// </summary>+ TaxDisplayType TaxDisplayType { get; }- /// <summary>- /// Gets the current host- /// </summary>- DomainHost CurrentHost { get; }+ /// <summary>+ /// Gets or sets the current store+ /// </summary>+ Store CurrentStore { get; }+}- /// <summary>- /// Get or set current user working language- /// </summary>- Language WorkingLanguage { get; }+public interface IWorkContextSetter+{+ /// <summary>+ /// Set the current customer by Middleware+ /// </summary>+ /// <returns></returns>+ Task<Customer> SetCurrentCustomer();- /// <summary>- /// Get or set current user working currency- /// </summary>- Currency WorkingCurrency { get; }+ /// <summary>+ /// Set the current customer+ /// </summary>+ /// <returns></returns>+ Task<Customer> SetCurrentCustomer(Customer customer);- /// <summary>- /// Get current tax display type- /// </summary>- TaxDisplayType TaxDisplayType { get; }-- /// <summary>- /// Gets or sets the current store- /// </summary>- Store CurrentStore { get; }-- }+ /// <summary>+ /// Set the current vendor (logged-in manager)+ /// </summary>+ Task<Vendor> SetCurrentVendor(Customer customer);- public interface IWorkContextSetter- {- /// <summary>- /// Set the current customer by Middleware- /// </summary>- /// <returns></returns>- Task<Customer> SetCurrentCustomer();+ /// <summary>+ /// Set current user working language by Middleware+ /// </summary>+ Task<Language> SetWorkingLanguage(Customer customer);- /// <summary>- /// Set the current customer- /// </summary>- /// <returns></returns>- Task<Customer> SetCurrentCustomer(Customer customer);-- /// <summary>- /// Set the current vendor (logged-in manager)- /// </summary>- Task<Vendor> SetCurrentVendor(Customer customer);+ /// <summary>+ /// Set current user working currency by Middleware+ /// </summary>+ Task<Currency> SetWorkingCurrency(Customer customer);- /// <summary>- /// Set current user working language by Middleware- /// </summary>- Task<Language> SetWorkingLanguage(Customer customer);-- /// <summary>- /// Set current user working currency by Middleware- /// </summary>- Task<Currency> SetWorkingCurrency(Customer customer);-- /// <summary>- /// Set current tax display type by Middleware- /// </summary>- Task<TaxDisplayType> SetTaxDisplayType(Customer customer);-- }-}+ /// <summary>+ /// Set current tax display type by Middleware+ /// </summary>+ Task<TaxDisplayType> SetTaxDisplayType(Customer customer);+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Mapper/AutoMapperConfig.cs b/src/Core/Grand.Infrastructure/Mapper/AutoMapperConfig.csindex e4eabce49..9d32a43de 100644--- a/src/Core/Grand.Infrastructure/Mapper/AutoMapperConfig.cs+++ b/src/Core/Grand.Infrastructure/Mapper/AutoMapperConfig.cs@@ -1,21 +1,20 @@using AutoMapper;-namespace Grand.Infrastructure.Mapper+namespace Grand.Infrastructure.Mapper;++public static class AutoMapperConfig{- public static class AutoMapperConfig- {- /// <summary>- /// Mapper- /// </summary>- public static IMapper Mapper { get; private set; }+ /// <summary>+ /// Mapper+ /// </summary>+ public static IMapper Mapper { get; private set; }- /// <summary>- /// Initialize mapper- /// </summary>- /// <param name="config">Mapper configuration</param>- public static void Init(MapperConfiguration config)- {- Mapper = config.CreateMapper();- }+ /// <summary>+ /// Initialize mapper+ /// </summary>+ /// <param name="config">Mapper configuration</param>+ public static void Init(MapperConfiguration config)+ {+ Mapper = config.CreateMapper();}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Mapper/IAutoMapperProfile.cs b/src/Core/Grand.Infrastructure/Mapper/IAutoMapperProfile.csindex 398054a7d..7bf0d78b4 100644--- a/src/Core/Grand.Infrastructure/Mapper/IAutoMapperProfile.cs+++ b/src/Core/Grand.Infrastructure/Mapper/IAutoMapperProfile.cs@@ -1,7 +1,6 @@-namespace Grand.Infrastructure.Mapper+namespace Grand.Infrastructure.Mapper;++public interface IAutoMapperProfile{- public interface IAutoMapperProfile- {- int Order { get; }- }-}+ int Order { get; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Mapper/MappingExtensions.cs b/src/Core/Grand.Infrastructure/Mapper/MappingExtensions.csindex c51a63ef6..9f0fc981a 100644--- a/src/Core/Grand.Infrastructure/Mapper/MappingExtensions.cs+++ b/src/Core/Grand.Infrastructure/Mapper/MappingExtensions.cs@@ -1,15 +1,14 @@-namespace Grand.Infrastructure.Mapper+namespace Grand.Infrastructure.Mapper;++public static class MappingExtensions{- public static class MappingExtensions+ public static TDestination MapTo<TSource, TDestination>(this TSource source){- public static TDestination MapTo<TSource, TDestination>(this TSource source)- {- return AutoMapperConfig.Mapper.Map<TSource, TDestination>(source);- }+ return AutoMapperConfig.Mapper.Map<TSource, TDestination>(source);+ }- public static TDestination MapTo<TSource, TDestination>(this TSource source, TDestination destination)- {- return AutoMapperConfig.Mapper.Map(source, destination);- }+ public static TDestination MapTo<TSource, TDestination>(this TSource source, TDestination destination)+ {+ return AutoMapperConfig.Mapper.Map(source, destination);}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Migrations/DbVersion.cs b/src/Core/Grand.Infrastructure/Migrations/DbVersion.csindex 45a24e01e..bc4ab64e4 100644--- a/src/Core/Grand.Infrastructure/Migrations/DbVersion.cs+++ b/src/Core/Grand.Infrastructure/Migrations/DbVersion.cs@@ -1,53 +1,48 @@-namespace Grand.Infrastructure.Migrations-{- public class DbVersion: IComparable<DbVersion>- {-- public DbVersion(int major, int minor)- {- Major = major;- Minor = minor;- }-- /// <summary>- /// Gets the major version- /// </summary>- public readonly int Major;-- /// <summary>- /// Gets the minor version- /// </summary>- public readonly int Minor;-- /// <summary>- /// Compares the current Version object to a specified Version object and returns an indication of their relative values.- /// </summary>- /// <param name="otherVersion"></param>- /// <returns></returns>- public int CompareTo(DbVersion otherVersion)- {- if (Major != otherVersion.Major)- if (Major > otherVersion.Major)- return 1;- else- return -1;-- if (Minor != otherVersion.Minor)- if (Minor > otherVersion.Minor)- return 1;- else- return -1;+namespace Grand.Infrastructure.Migrations;- return 0;-- }+public class DbVersion : IComparable<DbVersion>+{+ /// <summary>+ /// Gets the major version+ /// </summary>+ public readonly int Major;- public override string ToString()- {- return $"{Major}.{Minor}";- }+ /// <summary>+ /// Gets the minor version+ /// </summary>+ public readonly int Minor;+ public DbVersion(int major, int minor)+ {+ Major = major;+ Minor = minor;+ }+ /// <summary>+ /// Compares the current Version object to a specified Version object and returns an indication of their relative+ /// values.+ /// </summary>+ /// <param name="otherVersion"></param>+ /// <returns></returns>+ public int CompareTo(DbVersion otherVersion)+ {+ if (Major != otherVersion.Major)+ if (Major > otherVersion.Major)+ return 1;+ else+ return -1;++ if (Minor != otherVersion.Minor)+ if (Minor > otherVersion.Minor)+ return 1;+ else+ return -1;++ return 0;+ }+ public override string ToString()+ {+ return $"{Major}.{Minor}";}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Migrations/IBaseMigration.cs b/src/Core/Grand.Infrastructure/Migrations/IBaseMigration.csindex c9b253aed..519d3fdec 100644--- a/src/Core/Grand.Infrastructure/Migrations/IBaseMigration.cs+++ b/src/Core/Grand.Infrastructure/Migrations/IBaseMigration.cs@@ -1,20 +1,19 @@-namespace Grand.Infrastructure.Migrations+namespace Grand.Infrastructure.Migrations;++public interface IBaseMigration{- public interface IBaseMigration- {- /// <summary>- /// Field to which version should be upgraded db- /// </summary>- DbVersion Version { get; }+ /// <summary>+ /// Field to which version should be upgraded db+ /// </summary>+ DbVersion Version { get; }- /// <summary>- /// The unique identity of migration.- /// </summary>- Guid Identity { get; }+ /// <summary>+ /// The unique identity of migration.+ /// </summary>+ Guid Identity { get; }- /// <summary>- /// Name of migration.- /// </summary>- string Name { get; }- }-}+ /// <summary>+ /// Name of migration.+ /// </summary>+ string Name { get; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Migrations/IMigration.cs b/src/Core/Grand.Infrastructure/Migrations/IMigration.csindex 2b5673eea..238133288 100644--- a/src/Core/Grand.Infrastructure/Migrations/IMigration.cs+++ b/src/Core/Grand.Infrastructure/Migrations/IMigration.cs@@ -1,20 +1,19 @@using Grand.Data;-namespace Grand.Infrastructure.Migrations+namespace Grand.Infrastructure.Migrations;++public interface IMigration : IBaseMigration{- public interface IMigration : IBaseMigration- {- /// <summary>- /// Upgrade process- /// </summary>- /// <param name="database"></param>- /// <param name="serviceProvider"></param>- /// <returns></returns>- bool UpgradeProcess(IDatabaseContext database, IServiceProvider serviceProvider);+ /// <summary>+ /// Gets order of this startup migration implementation+ /// </summary>+ int Priority { get; }- /// <summary>- /// Gets order of this startup migration implementation- /// </summary>- int Priority { get; }- }-}+ /// <summary>+ /// Upgrade process+ /// </summary>+ /// <param name="database"></param>+ /// <param name="serviceProvider"></param>+ /// <returns></returns>+ bool UpgradeProcess(IDatabaseContext database, IServiceProvider serviceProvider);+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Migrations/IMigrationProcess.cs b/src/Core/Grand.Infrastructure/Migrations/IMigrationProcess.csindex 110e38c70..afdbcaa75 100644--- a/src/Core/Grand.Infrastructure/Migrations/IMigrationProcess.cs+++ b/src/Core/Grand.Infrastructure/Migrations/IMigrationProcess.cs@@ -1,9 +1,8 @@-namespace Grand.Infrastructure.Migrations+namespace Grand.Infrastructure.Migrations;++public interface IMigrationProcess{- public interface IMigrationProcess- {- void RunMigrationProcess();- void InstallApplication();- MigrationResult RunProcess(IMigration migration);- }-}+ void RunMigrationProcess();+ void InstallApplication();+ MigrationResult RunProcess(IMigration migration);+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Migrations/MigrationManager.cs b/src/Core/Grand.Infrastructure/Migrations/MigrationManager.csindex 68fd4b4de..0e481ac21 100644--- a/src/Core/Grand.Infrastructure/Migrations/MigrationManager.cs+++ b/src/Core/Grand.Infrastructure/Migrations/MigrationManager.cs@@ -1,43 +1,43 @@using Grand.Infrastructure.Plugins;using Grand.Infrastructure.TypeSearch;-namespace Grand.Infrastructure.Migrations+namespace Grand.Infrastructure.Migrations;++public class MigrationManager{- public class MigrationManager+ private readonly IEnumerable<Type> _migrationConfigurations;++ public MigrationManager(){- private readonly IEnumerable<Type> _migrationConfigurations;+ var typeSearcher = new TypeSearcher();+ _migrationConfigurations = typeSearcher.ClassesOfType<IMigration>();+ }- public MigrationManager()- {- var typeSearcher = new TypeSearcher();- _migrationConfigurations = typeSearcher.ClassesOfType<IMigration>();- }-- /// <summary>- /// Get all migrations- /// </summary>- /// <returns></returns>- public IEnumerable<IMigration> GetAllMigrations()- {- return _migrationConfigurations- .Where(PluginExtensions.OnlyInstalledPlugins)- .Select(mg => (IMigration)Activator.CreateInstance(mg))- .OrderBy(mg => mg!.Priority);- }+ /// <summary>+ /// Get all migrations+ /// </summary>+ /// <returns></returns>+ public IEnumerable<IMigration> GetAllMigrations()+ {+ return _migrationConfigurations+ .Where(PluginExtensions.OnlyInstalledPlugins)+ .Select(mg => (IMigration)Activator.CreateInstance(mg))+ .OrderBy(mg => mg!.Priority);+ }- /// <summary>- /// Get current migrations- /// </summary>- /// <returns></returns>- public IEnumerable<IMigration> GetCurrentMigrations()- {- var currentDbVersion = new DbVersion(int.Parse(GrandVersion.MajorVersion), int.Parse(GrandVersion.MinorVersion));+ /// <summary>+ /// Get current migrations+ /// </summary>+ /// <returns></returns>+ public IEnumerable<IMigration> GetCurrentMigrations()+ {+ var currentDbVersion =+ new DbVersion(int.Parse(GrandVersion.MajorVersion), int.Parse(GrandVersion.MinorVersion));- return GetAllMigrations()- .Where(x => currentDbVersion.CompareTo(x.Version) >= 0)- .OrderBy(mg => mg.Version.ToString())- .ThenBy(mg => mg.Priority)- .ToList();- }+ return GetAllMigrations()+ .Where(x => currentDbVersion.CompareTo(x.Version) >= 0)+ .OrderBy(mg => mg.Version.ToString())+ .ThenBy(mg => mg.Priority)+ .ToList();}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Migrations/MigrationResult.cs b/src/Core/Grand.Infrastructure/Migrations/MigrationResult.csindex 0a3d5ccf5..f75122362 100644--- a/src/Core/Grand.Infrastructure/Migrations/MigrationResult.cs+++ b/src/Core/Grand.Infrastructure/Migrations/MigrationResult.cs@@ -1,8 +1,7 @@-namespace Grand.Infrastructure.Migrations+namespace Grand.Infrastructure.Migrations;++public class MigrationResult{- public class MigrationResult- {- public bool Success;- public IBaseMigration Migration;- }-}+ public IBaseMigration Migration;+ public bool Success;+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/ModelBinding/GrandResourceDisplayNameAttribute.cs b/src/Core/Grand.Infrastructure/ModelBinding/GrandResourceDisplayNameAttribute.csindex 3d51ce06d..07cca94d8 100644--- a/src/Core/Grand.Infrastructure/ModelBinding/GrandResourceDisplayNameAttribute.cs+++ b/src/Core/Grand.Infrastructure/ModelBinding/GrandResourceDisplayNameAttribute.cs@@ -1,37 +1,36 @@using System.ComponentModel;-namespace Grand.Infrastructure.ModelBinding+namespace Grand.Infrastructure.ModelBinding;++/// <summary>+/// Represents model attribute that specifies the display name by passed key of the locale resource+/// </summary>+public class GrandResourceDisplayNameAttribute : DisplayNameAttribute, IModelAttribute{+ #region Ctor+/// <summary>- /// Represents model attribute that specifies the display name by passed key of the locale resource+ /// Create instance of the attribute/// </summary>- public class GrandResourceDisplayNameAttribute : DisplayNameAttribute, IModelAttribute+ /// <param name="resourceKey">Key of the locale resource</param>+ public GrandResourceDisplayNameAttribute(string resourceKey) : base(resourceKey){- #region Ctor-- /// <summary>- /// Create instance of the attribute- /// </summary>- /// <param name="resourceKey">Key of the locale resource</param>- public GrandResourceDisplayNameAttribute(string resourceKey) : base(resourceKey)- {- ResourceKey = resourceKey;- }+ ResourceKey = resourceKey;+ }- #endregion+ #endregion- #region Properties+ #region Properties- /// <summary>- /// Gets or sets key of the locale resource- /// </summary>- public string ResourceKey { get; set; }+ /// <summary>+ /// Gets or sets key of the locale resource+ /// </summary>+ public string ResourceKey { get; set; }- /// <summary>- /// Gets name of the attribute- /// </summary>- public string Name => nameof(GrandResourceDisplayNameAttribute);+ /// <summary>+ /// Gets name of the attribute+ /// </summary>+ public string Name => nameof(GrandResourceDisplayNameAttribute);- #endregion- }-}+ #endregion+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/ModelBinding/IModelAttribute.cs b/src/Core/Grand.Infrastructure/ModelBinding/IModelAttribute.csindex 7d96a90f8..3acb94101 100644--- a/src/Core/Grand.Infrastructure/ModelBinding/IModelAttribute.cs+++ b/src/Core/Grand.Infrastructure/ModelBinding/IModelAttribute.cs@@ -1,10 +1,9 @@-namespace Grand.Infrastructure.ModelBinding+namespace Grand.Infrastructure.ModelBinding;++public interface IModelAttribute{- public interface IModelAttribute- {- /// <summary>- /// Gets name of the attribute- /// </summary>- string Name { get; }- }-}+ /// <summary>+ /// Gets name of the attribute+ /// </summary>+ string Name { get; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinder.cs b/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinder.csindex 0359f428e..354bd5d89 100644--- a/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinder.cs+++ b/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinder.cs@@ -25,15 +25,15 @@ public class JsonBodyModelBinder : IModelBinder{jsonPayload = await streamReader.ReadToEndAsync();}- var options = new JsonSerializerOptions- {++ var options = new JsonSerializerOptions {PropertyNameCaseInsensitive = true};options.Converters.Add(new StringConverter());bindingContext.Result =ModelBindingResult.Success(JsonSerializer.Deserialize(jsonPayload, bindingContext.ModelType, options));}- else+ else{await _overriddenModelBinder.BindModelAsync(bindingContext);}diff --git a/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinderProvider.cs b/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinderProvider.csindex ffeeed4b2..ede85b50f 100644--- a/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinderProvider.cs+++ b/src/Core/Grand.Infrastructure/ModelBinding/JsonBodyModelBinderProvider.cs@@ -5,10 +5,12 @@ namespace Grand.Infrastructure.ModelBinding;public class JsonBodyModelBinderProvider : IModelBinderProvider{private readonly IModelBinderProvider _overriddenModelBinderProvider;+public JsonBodyModelBinderProvider(IModelBinderProvider overriddenModelBinderProvider){_overriddenModelBinderProvider = overriddenModelBinderProvider;}+public IModelBinder GetBinder(ModelBinderProviderContext context){var modelBinder = _overriddenModelBinderProvider.GetBinder(context);diff --git a/src/Core/Grand.Infrastructure/Models/BaseEntityModel.cs b/src/Core/Grand.Infrastructure/Models/BaseEntityModel.csindex bfa87dd11..4d0058f97 100644--- a/src/Core/Grand.Infrastructure/Models/BaseEntityModel.cs+++ b/src/Core/Grand.Infrastructure/Models/BaseEntityModel.cs@@ -1,13 +1,12 @@-namespace Grand.Infrastructure.Models+namespace Grand.Infrastructure.Models;++/// <summary>+/// Represents base grandnode entity model+/// </summary>+public class BaseEntityModel : BaseModel{/// <summary>- /// Represents base grandnode entity model+ /// Gets or sets model identifier/// </summary>- public class BaseEntityModel : BaseModel- {- /// <summary>- /// Gets or sets model identifier- /// </summary>- public virtual string Id { get; set; }- }-}+ public virtual string Id { get; set; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Models/BaseModel.cs b/src/Core/Grand.Infrastructure/Models/BaseModel.csindex 611c86eb8..c748ad93e 100644--- a/src/Core/Grand.Infrastructure/Models/BaseModel.cs+++ b/src/Core/Grand.Infrastructure/Models/BaseModel.cs@@ -1,40 +1,38 @@using Grand.Domain.Common;using Microsoft.AspNetCore.Mvc.ModelBinding;-namespace Grand.Infrastructure.Models-{- /// <summary>- /// Represents base model- /// </summary>- public class BaseModel- {- #region Ctor-- public BaseModel()- {- UserFields = new List<UserField>();- PostInitialize();- }+namespace Grand.Infrastructure.Models;- #endregion+/// <summary>+/// Represents base model+/// </summary>+public class BaseModel+{+ #region Ctor- #region Methods+ public BaseModel()+ {+ UserFields = new List<UserField>();+ PostInitialize();+ }- public virtual void BindModel(ModelBindingContext bindingContext)- {- }+ #endregion- protected virtual void PostInitialize()- {- }+ #region Properties- #endregion+ public IList<UserField> UserFields { get; set; }- #region Properties+ #endregion- public IList<UserField> UserFields { get; set; }+ #region Methods- #endregion+ public virtual void BindModel(ModelBindingContext bindingContext)+ {+ }+ protected virtual void PostInitialize()+ {}-}++ #endregion+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Models/ICaptchaValidModel.cs b/src/Core/Grand.Infrastructure/Models/ICaptchaValidModel.csindex ed30e5471..ec7ce9cc8 100644--- a/src/Core/Grand.Infrastructure/Models/ICaptchaValidModel.cs+++ b/src/Core/Grand.Infrastructure/Models/ICaptchaValidModel.cs@@ -10,4 +10,4 @@ public interface ICaptchaValidModelpublic string ReCaptchaResponseField { get; set; }public string ReCaptchaResponseValue { get; set; }public string ReCaptchaResponse { get; set; }-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/OperatingSystem.cs b/src/Core/Grand.Infrastructure/OperatingSystem.csindex d82be46a6..7ff642082 100644--- a/src/Core/Grand.Infrastructure/OperatingSystem.cs+++ b/src/Core/Grand.Infrastructure/OperatingSystem.cs@@ -1,22 +1,21 @@using System.Runtime.InteropServices;-namespace Grand.Infrastructure+namespace Grand.Infrastructure;++public static class OperatingSystem{- public static class OperatingSystem+ public static bool IsWindows(){- public static bool IsWindows()- {- return RuntimeInformation.IsOSPlatform(OSPlatform.Windows);- }+ return RuntimeInformation.IsOSPlatform(OSPlatform.Windows);+ }- public static bool IsMacOs()- {- return RuntimeInformation.IsOSPlatform(OSPlatform.OSX);- }+ public static bool IsMacOs()+ {+ return RuntimeInformation.IsOSPlatform(OSPlatform.OSX);+ }- public static bool IsLinux()- {- return RuntimeInformation.IsOSPlatform(OSPlatform.Linux);- }+ public static bool IsLinux()+ {+ return RuntimeInformation.IsOSPlatform(OSPlatform.Linux);}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Plugins/BasePlugin.cs b/src/Core/Grand.Infrastructure/Plugins/BasePlugin.csindex 3a8314447..17276e550 100644--- a/src/Core/Grand.Infrastructure/Plugins/BasePlugin.cs+++ b/src/Core/Grand.Infrastructure/Plugins/BasePlugin.cs@@ -1,35 +1,34 @@-namespace Grand.Infrastructure.Plugins+namespace Grand.Infrastructure.Plugins;++public abstract class BasePlugin : IPlugin{- public abstract class BasePlugin : IPlugin+ /// <summary>+ /// Gets a configuration page URL+ /// </summary>+ /// <returns></returns>+ public virtual string ConfigurationUrl(){- /// <summary>- /// Gets a configuration page URL- /// </summary>- /// <returns></returns>- public virtual string ConfigurationUrl()- {- return null;- }- /// <summary>- /// Gets or sets the plugin info- /// </summary>- public virtual PluginInfo PluginInfo { get; set; }+ return null;+ }- /// <summary>- /// Install plugin- /// </summary>- public virtual async Task Install()- {- await PluginExtensions.MarkPluginAsInstalled(PluginInfo.SystemName);- }+ /// <summary>+ /// Gets or sets the plugin info+ /// </summary>+ public virtual PluginInfo PluginInfo { get; set; }- /// <summary>- /// Uninstall plugin- /// </summary>- public virtual async Task Uninstall()- {- await PluginExtensions.MarkPluginAsUninstalled(PluginInfo.SystemName);- }+ /// <summary>+ /// Install plugin+ /// </summary>+ public virtual async Task Install()+ {+ await PluginExtensions.MarkPluginAsInstalled(PluginInfo.SystemName);+ }+ /// <summary>+ /// Uninstall plugin+ /// </summary>+ public virtual async Task Uninstall()+ {+ await PluginExtensions.MarkPluginAsUninstalled(PluginInfo.SystemName);}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Plugins/IPlugin.cs b/src/Core/Grand.Infrastructure/Plugins/IPlugin.csindex b8ee08a68..bd1ac5469 100644--- a/src/Core/Grand.Infrastructure/Plugins/IPlugin.cs+++ b/src/Core/Grand.Infrastructure/Plugins/IPlugin.cs@@ -1,29 +1,28 @@-namespace Grand.Infrastructure.Plugins+namespace Grand.Infrastructure.Plugins;++/// <summary>+/// Interface for Plugin+/// the editing interface.+/// </summary>+public interface IPlugin{/// <summary>- /// Interface for Plugin- /// the editing interface.+ /// Gets or sets the plugin info/// </summary>- public interface IPlugin- {- /// <summary>- /// Gets a configuration URL- /// </summary>- string ConfigurationUrl();+ PluginInfo PluginInfo { get; set; }- /// <summary>- /// Gets or sets the plugin info- /// </summary>- PluginInfo PluginInfo { get; set; }+ /// <summary>+ /// Gets a configuration URL+ /// </summary>+ string ConfigurationUrl();- /// <summary>- /// Install plugin- /// </summary>- Task Install();+ /// <summary>+ /// Install plugin+ /// </summary>+ Task Install();- /// <summary>- /// Uninstall plugin- /// </summary>- Task Uninstall();- }-}+ /// <summary>+ /// Uninstall plugin+ /// </summary>+ Task Uninstall();+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Plugins/IProvider.cs b/src/Core/Grand.Infrastructure/Plugins/IProvider.csindex 7edfc74ea..0b5ca5f97 100644--- a/src/Core/Grand.Infrastructure/Plugins/IProvider.cs+++ b/src/Core/Grand.Infrastructure/Plugins/IProvider.cs@@ -1,30 +1,34 @@-namespace Grand.Infrastructure.Plugins+namespace Grand.Infrastructure.Plugins;++public interface IProvider{- public interface IProvider- {- /// <summary>- /// Gets a configuration URL- /// </summary>- string ConfigurationUrl { get; }- /// <summary>- /// Gets a system name for provider- /// </summary>- string SystemName { get; }- /// <summary>- /// Gets a friendly name for provider- /// </summary>- string FriendlyName { get; }- /// <summary>- /// Gets a priority for provider- /// </summary>- int Priority { get; }- /// <summary>- /// Gets a limited to store for provider- /// </summary>- IList<string> LimitedToStores { get; }- /// <summary>- /// Gets a limited to customer group for provider- /// </summary>- IList<string> LimitedToGroups { get; }- }-}+ /// <summary>+ /// Gets a configuration URL+ /// </summary>+ string ConfigurationUrl { get; }++ /// <summary>+ /// Gets a system name for provider+ /// </summary>+ string SystemName { get; }++ /// <summary>+ /// Gets a friendly name for provider+ /// </summary>+ string FriendlyName { get; }++ /// <summary>+ /// Gets a priority for provider+ /// </summary>+ int Priority { get; }++ /// <summary>+ /// Gets a limited to store for provider+ /// </summary>+ IList<string> LimitedToStores { get; }++ /// <summary>+ /// Gets a limited to customer group for provider+ /// </summary>+ IList<string> LimitedToGroups { get; }+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Plugins/LoadPluginsStatus.cs b/src/Core/Grand.Infrastructure/Plugins/LoadPluginsStatus.csindex 3170be874..d5f487c06 100644--- a/src/Core/Grand.Infrastructure/Plugins/LoadPluginsStatus.cs+++ b/src/Core/Grand.Infrastructure/Plugins/LoadPluginsStatus.cs@@ -1,21 +1,22 @@-namespace Grand.Infrastructure.Plugins+namespace Grand.Infrastructure.Plugins;++/// <summary>+/// Represents a status to load plugins+/// </summary>+public enum LoadPluginsStatus{/// <summary>- /// Represents a status to load plugins+ /// All/// </summary>- public enum LoadPluginsStatus- {- /// <summary>- /// All- /// </summary>- All = 0,- /// <summary>- /// Installed only- /// </summary>- InstalledOnly = 1,- /// <summary>- /// Not installed only- /// </summary>- NotInstalledOnly = 2- }+ All = 0,++ /// <summary>+ /// Installed only+ /// </summary>+ InstalledOnly = 1,++ /// <summary>+ /// Not installed only+ /// </summary>+ NotInstalledOnly = 2}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Plugins/PluginExtensions.cs b/src/Core/Grand.Infrastructure/Plugins/PluginExtensions.csindex 9ba22d048..774a4e29f 100644--- a/src/Core/Grand.Infrastructure/Plugins/PluginExtensions.cs+++ b/src/Core/Grand.Infrastructure/Plugins/PluginExtensions.cs@@ -1,82 +1,83 @@using Grand.SharedKernel.Extensions;using System.Text.Json;-namespace Grand.Infrastructure.Plugins+namespace Grand.Infrastructure.Plugins;++public static class PluginExtensions{- public static class PluginExtensions+ public static bool OnlyInstalledPlugins(Type type){- public static bool OnlyInstalledPlugins(Type type)- {- var plugin = PluginManager.FindPlugin(type);- return plugin == null || plugin.Installed;- }-- public static IList<string> ParseInstalledPluginsFile(string filePath)- {- if (!File.Exists(filePath))- return new List<string>();-- var text = File.ReadAllText(filePath);- return string.IsNullOrEmpty(text) ? new List<string>() : JsonSerializer.Deserialize<List<string>>(text);- }+ var plugin = PluginManager.FindPlugin(type);+ return plugin == null || plugin.Installed;+ }- public static async Task SaveInstalledPluginsFile(IList<string> pluginSystemNames, string filePath)- {- //serialize- var result = JsonSerializer.Serialize(pluginSystemNames, new JsonSerializerOptions { WriteIndented = true });- //save- await File.WriteAllTextAsync(filePath, result);- await Task.CompletedTask;- }+ public static IList<string> ParseInstalledPluginsFile(string filePath)+ {+ if (!File.Exists(filePath))+ return new List<string>();- /// <summary>- /// Mark plugin as installed- /// </summary>- /// <param name="systemName">Plugin system name</param>- public static async Task MarkPluginAsInstalled(string systemName)- {- if (string.IsNullOrEmpty(systemName))- throw new ArgumentNullException(nameof(systemName));+ var text = File.ReadAllText(filePath);+ return string.IsNullOrEmpty(text) ? new List<string>() : JsonSerializer.Deserialize<List<string>>(text);+ }- var filePath = CommonPath.InstalledPluginsFilePath;- if (!File.Exists(filePath))- await using (File.Create(filePath))- {- //we use 'using' to close the file after it's created- }+ public static async Task SaveInstalledPluginsFile(IList<string> pluginSystemNames, string filePath)+ {+ //serialize+ var result = JsonSerializer.Serialize(pluginSystemNames, new JsonSerializerOptions { WriteIndented = true });+ //save+ await File.WriteAllTextAsync(filePath, result);+ await Task.CompletedTask;+ }- var installedPluginSystemNames = ParseInstalledPluginsFile(filePath);+ /// <summary>+ /// Mark plugin as installed+ /// </summary>+ /// <param name="systemName">Plugin system name</param>+ public static async Task MarkPluginAsInstalled(string systemName)+ {+ if (string.IsNullOrEmpty(systemName))+ throw new ArgumentNullException(nameof(systemName));- var alreadyMarkedAsInstalled = installedPluginSystemNames.FirstOrDefault(x => x.Equals(systemName, StringComparison.OrdinalIgnoreCase)) != null;- if (!alreadyMarkedAsInstalled)- installedPluginSystemNames.Add(systemName);+ var filePath = CommonPath.InstalledPluginsFilePath;+ if (!File.Exists(filePath))+ await using (File.Create(filePath))+ {+ //we use 'using' to close the file after it's created+ }- await SaveInstalledPluginsFile(installedPluginSystemNames, filePath);- }+ var installedPluginSystemNames = ParseInstalledPluginsFile(filePath);- /// <summary>- /// Mark plugin as uninstalled- /// </summary>- /// <param name="systemName">Plugin system name</param>- public static async Task MarkPluginAsUninstalled(string systemName)- {- if (string.IsNullOrEmpty(systemName))- throw new ArgumentNullException(nameof(systemName));+ var alreadyMarkedAsInstalled =+ installedPluginSystemNames.FirstOrDefault(x => x.Equals(systemName, StringComparison.OrdinalIgnoreCase)) !=+ null;+ if (!alreadyMarkedAsInstalled)+ installedPluginSystemNames.Add(systemName);- var filePath = CommonPath.InstalledPluginsFilePath;- if (!File.Exists(filePath))- await using (File.Create(filePath))- {- }+ await SaveInstalledPluginsFile(installedPluginSystemNames, filePath);+ }- var installedPluginSystemNames = ParseInstalledPluginsFile(filePath);- var alreadyMarkedAsInstalled = installedPluginSystemNames.FirstOrDefault(x => x.Equals(systemName, StringComparison.OrdinalIgnoreCase)) != null;- if (alreadyMarkedAsInstalled)- installedPluginSystemNames.Remove(systemName);+ /// <summary>+ /// Mark plugin as uninstalled+ /// </summary>+ /// <param name="systemName">Plugin system name</param>+ public static async Task MarkPluginAsUninstalled(string systemName)+ {+ if (string.IsNullOrEmpty(systemName))+ throw new ArgumentNullException(nameof(systemName));- await SaveInstalledPluginsFile(installedPluginSystemNames, filePath);- }+ var filePath = CommonPath.InstalledPluginsFilePath;+ if (!File.Exists(filePath))+ await using (File.Create(filePath))+ {+ }+ var installedPluginSystemNames = ParseInstalledPluginsFile(filePath);+ var alreadyMarkedAsInstalled =+ installedPluginSystemNames.FirstOrDefault(x => x.Equals(systemName, StringComparison.OrdinalIgnoreCase)) !=+ null;+ if (alreadyMarkedAsInstalled)+ installedPluginSystemNames.Remove(systemName);+ await SaveInstalledPluginsFile(installedPluginSystemNames, filePath);}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Plugins/PluginInfo.cs b/src/Core/Grand.Infrastructure/Plugins/PluginInfo.csindex 16d1b5f4e..472e19656 100644--- a/src/Core/Grand.Infrastructure/Plugins/PluginInfo.cs+++ b/src/Core/Grand.Infrastructure/Plugins/PluginInfo.cs@@ -2,104 +2,106 @@using Microsoft.Extensions.DependencyInjection;using System.Reflection;-namespace Grand.Infrastructure.Plugins+namespace Grand.Infrastructure.Plugins;++public sealed class PluginInfo{- public sealed class PluginInfo+ public PluginInfo(+ FileInfo originalAssemblyFile,+ Assembly referencedAssembly,+ Type pluginType)+ : this()+ {+ ReferencedAssembly = referencedAssembly;+ OriginalAssemblyFile = originalAssemblyFile;+ PluginType = pluginType;+ }++ public PluginInfo(){- public PluginInfo(- FileInfo originalAssemblyFile,- Assembly referencedAssembly,- Type pluginType)- : this()+ }++ /// <summary>+ /// Plugin type+ /// </summary>+ public string PluginFileName { get; set; }++ /// <summary>+ /// Plugin type+ /// </summary>+ public Type PluginType { get; set; }++ /// <summary>+ /// The assembly that has been shadow copied that is active in the application+ /// </summary>+ public Assembly ReferencedAssembly { get; internal set; }++ /// <summary>+ /// The original assembly file that a shadow copy was made from it+ /// </summary>+ public FileInfo OriginalAssemblyFile { get; internal set; }++ /// <summary>+ /// Gets or sets the plugin group+ /// </summary>+ public string Group { get; set; }++ /// <summary>+ /// Gets or sets the friendly name+ /// </summary>+ public string FriendlyName { get; set; }++ /// <summary>+ /// Gets or sets the system name+ /// </summary>+ public string SystemName { get; set; }++ /// <summary>+ /// Gets or sets the version+ /// </summary>+ public string Version { get; set; }++ /// <summary>+ /// Gets or sets the supported version+ /// </summary>+ public string SupportedVersion { get; set; }++ /// <summary>+ /// Gets or sets the author+ /// </summary>+ public string Author { get; set; }++ /// <summary>+ /// Gets or sets the display order+ /// </summary>+ public int DisplayOrder { get; set; }++ /// <summary>+ /// Gets or sets the value indicating whether plugin is installed+ /// </summary>+ public bool Installed { get; set; }++ public T Instance<T>(IServiceProvider serviceProvider) where T : class, IPlugin+ {+ object instance;+ try{- ReferencedAssembly = referencedAssembly;- OriginalAssemblyFile = originalAssemblyFile;- PluginType = pluginType;+ instance = serviceProvider.GetRequiredService(PluginType);}- public PluginInfo()+ catch{+ throw new GrandException(+ $"Plugin has not been registered getRequiredService - dependency - {PluginType.FullName}");}- /// <summary>- /// Plugin type- /// </summary>- public string PluginFileName { get; set; }-- /// <summary>- /// Plugin type- /// </summary>- public Type PluginType { get; set; }-- /// <summary>- /// The assembly that has been shadow copied that is active in the application- /// </summary>- public Assembly ReferencedAssembly { get; internal set; }-- /// <summary>- /// The original assembly file that a shadow copy was made from it- /// </summary>- public FileInfo OriginalAssemblyFile { get; internal set; }-- /// <summary>- /// Gets or sets the plugin group- /// </summary>- public string Group { get; set; }-- /// <summary>- /// Gets or sets the friendly name- /// </summary>- public string FriendlyName { get; set; }-- /// <summary>- /// Gets or sets the system name- /// </summary>- public string SystemName { get; set; }-- /// <summary>- /// Gets or sets the version- /// </summary>- public string Version { get; set; }-- /// <summary>- /// Gets or sets the supported version- /// </summary>- public string SupportedVersion { get; set; }-- /// <summary>- /// Gets or sets the author- /// </summary>- public string Author { get; set; }-- /// <summary>- /// Gets or sets the display order- /// </summary>- public int DisplayOrder { get; set; }-- /// <summary>- /// Gets or sets the value indicating whether plugin is installed- /// </summary>- public bool Installed { get; set; }-- public T Instance<T>(IServiceProvider serviceProvider) where T : class, IPlugin- {- object instance;- try- {- instance = serviceProvider.GetRequiredService(PluginType);- }- catch- {- throw new GrandException($"Plugin has not been registered getRequiredService - dependency - {PluginType.FullName}");- }- var typedInstance = instance as T;- if (typedInstance != null)- typedInstance.PluginInfo = this;- return typedInstance;- }+ var typedInstance = instance as T;+ if (typedInstance != null)+ typedInstance.PluginInfo = this;+ return typedInstance;+ }- public IPlugin Instance(IServiceProvider serviceProvider)- {- return Instance<IPlugin>(serviceProvider);- }+ public IPlugin Instance(IServiceProvider serviceProvider)+ {+ return Instance<IPlugin>(serviceProvider);}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Plugins/PluginInfoAttribute.cs b/src/Core/Grand.Infrastructure/Plugins/PluginInfoAttribute.csindex c91e97de0..c21c75dd1 100644--- a/src/Core/Grand.Infrastructure/Plugins/PluginInfoAttribute.cs+++ b/src/Core/Grand.Infrastructure/Plugins/PluginInfoAttribute.cs@@ -1,24 +1,23 @@using System.Reflection;-namespace Grand.Infrastructure.Plugins+namespace Grand.Infrastructure.Plugins;++[AttributeUsage(AttributeTargets.Assembly)]+public class PluginInfoAttribute : Attribute{- [AttributeUsage(AttributeTargets.Assembly)]- public class PluginInfoAttribute : Attribute+ public PluginInfoAttribute(){- public PluginInfoAttribute()- {- Assembly assembly = Assembly.GetExecutingAssembly();- Version fullVersion = assembly.GetName().Version;- SupportedVersion = $"{fullVersion?.Minor}.{fullVersion?.Major}";-- }- public string Group { get; set; } = string.Empty;- public string FriendlyName { get; set; } = string.Empty;- public string SystemName { get; set; } = string.Empty;- public string Author { get; set; } = string.Empty;+ var assembly = Assembly.GetExecutingAssembly();+ var fullVersion = assembly.GetName().Version;+ SupportedVersion = $"{fullVersion?.Minor}.{fullVersion?.Major}";+ }- public string SupportedVersion { get; set; }+ public string Group { get; set; } = string.Empty;+ public string FriendlyName { get; set; } = string.Empty;+ public string SystemName { get; set; } = string.Empty;+ public string Author { get; set; } = string.Empty;- public string Version { get; set; }- }+ public string SupportedVersion { get; set; }++ public string Version { get; set; }}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs b/src/Core/Grand.Infrastructure/Plugins/PluginManager.csindex 245e83cd2..7c46c8153 100644--- a/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs+++ b/src/Core/Grand.Infrastructure/Plugins/PluginManager.cs@@ -9,380 +9,382 @@ using System.Runtime.CompilerServices;using System.Runtime.Loader;using System.Text.RegularExpressions;-namespace Grand.Infrastructure.Plugins+namespace Grand.Infrastructure.Plugins;++/// <summary>+/// Plugin manager+/// </summary>+public static class PluginManager{- /// <summary>- /// Plugin manager- /// </summary>- public static class PluginManager- {- #region Const+ #region Const- public const string CopyPath = "Plugins/bin";+ public const string CopyPath = "Plugins/bin";- private static object _synLock = new object();+ private static readonly object _synLock = new();- #endregion+ #endregion- #region Fields+ #region Fields- private static DirectoryInfo _copyFolder;- private static DirectoryInfo _pluginFolder;- private static ExtensionsConfig _config;- private static ILogger _logger;- #endregion+ private static DirectoryInfo _copyFolder;+ private static DirectoryInfo _pluginFolder;+ private static ExtensionsConfig _config;+ private static ILogger _logger;- #region Methods+ #endregion++ #region Methods++ /// <summary>+ /// Returns a collection of all referenced plugin assemblies that have been shadow copied+ /// </summary>+ public static IEnumerable<PluginInfo> ReferencedPlugins { get; set; }- /// <summary>- /// Returns a collection of all referenced plugin assemblies that have been shadow copied- /// </summary>- public static IEnumerable<PluginInfo> ReferencedPlugins { get; set; }+ /// <summary>+ /// Load plugins+ /// </summary>+ [MethodImpl(MethodImplOptions.NoInlining)]+ public static void Load(IMvcCoreBuilder mvcCoreBuilder, IConfiguration configuration)+ {+ _config = new ExtensionsConfig();+ configuration.GetSection("Extensions").Bind(_config);- /// <summary>- /// Load plugins- /// </summary>- [MethodImpl(MethodImplOptions.NoInlining)]- public static void Load(IMvcCoreBuilder mvcCoreBuilder, IConfiguration configuration)+ lock (_synLock){- _config = new ExtensionsConfig();- configuration.GetSection("Extensions").Bind(_config);-- lock (_synLock)+ if (mvcCoreBuilder == null)+ throw new ArgumentNullException(nameof(mvcCoreBuilder));++ _logger = mvcCoreBuilder.Services.BuildServiceProvider().GetService<ILoggerFactory>()+ .CreateLogger("PluginManager");++ _pluginFolder = new DirectoryInfo(CommonPath.PluginsPath);+ _copyFolder = new DirectoryInfo(CommonPath.PluginsCopyPath);++ var referencedPlugins = new List<PluginInfo>();+ try{- if (mvcCoreBuilder == null)- throw new ArgumentNullException(nameof(mvcCoreBuilder));-- _logger = mvcCoreBuilder.Services.BuildServiceProvider().GetService<ILoggerFactory>().CreateLogger("PluginManager");-- _pluginFolder = new DirectoryInfo(CommonPath.PluginsPath);- _copyFolder = new DirectoryInfo(CommonPath.PluginsCopyPath);-- var referencedPlugins = new List<PluginInfo>();- try- {- var installedPluginSystemNames =- !string.IsNullOrEmpty(_config.InstalledPlugins) ? _config.InstalledPlugins.Split(",").Select(x=>x.Trim()) :- PluginExtensions.ParseInstalledPluginsFile(CommonPath.InstalledPluginsFilePath);-- _logger.LogInformation("Creating shadow copy folder and querying for dlls");- Directory.CreateDirectory(_pluginFolder.FullName);- Directory.CreateDirectory(_copyFolder.FullName);- var binFiles = _copyFolder.GetFiles("*", SearchOption.AllDirectories);- if (_config.PluginShadowCopy)+ var installedPluginSystemNames =+ !string.IsNullOrEmpty(_config.InstalledPlugins)+ ? _config.InstalledPlugins.Split(",").Select(x => x.Trim())+ : PluginExtensions.ParseInstalledPluginsFile(CommonPath.InstalledPluginsFilePath);++ _logger.LogInformation("Creating shadow copy folder and querying for dlls");+ Directory.CreateDirectory(_pluginFolder.FullName);+ Directory.CreateDirectory(_copyFolder.FullName);+ var binFiles = _copyFolder.GetFiles("*", SearchOption.AllDirectories);+ if (_config.PluginShadowCopy)+ //clear out shadow plugins+ foreach (var f in binFiles){- //clear out shadow plugins- foreach (var f in binFiles)+ _logger.LogInformation("Deleting {FName}", f.Name);+ try+ {+ var fileName = Path.GetFileName(f.FullName);+ if (fileName.Equals("index.htm", StringComparison.OrdinalIgnoreCase))+ continue;++ File.Delete(f.FullName);+ }+ catch (Exception exc){- _logger.LogInformation("Deleting {FName}", f.Name);- try- {- var fileName = Path.GetFileName(f.FullName);- if (fileName.Equals("index.htm", StringComparison.OrdinalIgnoreCase))- continue;-- File.Delete(f.FullName);- }- catch (Exception exc)- {- _logger.LogError(exc, "PluginManager");- }+ _logger.LogError(exc, "PluginManager");}}- //load description files- foreach (var plugin in GetPluginInfo())+ //load description files+ foreach (var plugin in GetPluginInfo())+ {+ if (plugin.SupportedVersion != GrandVersion.SupportedPluginVersion){- if (plugin.SupportedVersion != GrandVersion.SupportedPluginVersion)- {- _logger.LogInformation("Incompatible plugin {PluginSystemName}", plugin.SystemName);- //set as not installed- referencedPlugins.Add(plugin);- continue;- }+ _logger.LogInformation("Incompatible plugin {PluginSystemName}", plugin.SystemName);+ //set as not installed+ referencedPlugins.Add(plugin);+ continue;+ }- //some validation- if (string.IsNullOrWhiteSpace(plugin.SystemName))- throw new Exception($"The plugin '{plugin.SystemName}' has no system name.");- if (referencedPlugins.Contains(plugin))- throw new Exception($"The plugin with '{plugin.SystemName}' system name is already defined");+ //some validation+ if (string.IsNullOrWhiteSpace(plugin.SystemName))+ throw new Exception($"The plugin '{plugin.SystemName}' has no system name.");+ if (referencedPlugins.Contains(plugin))+ throw new Exception($"The plugin with '{plugin.SystemName}' system name is already defined");- //set 'Installed' property- plugin.Installed = installedPluginSystemNames- .FirstOrDefault(x => x.Equals(plugin.SystemName, StringComparison.OrdinalIgnoreCase)) != null;+ //set 'Installed' property+ plugin.Installed = installedPluginSystemNames+ .FirstOrDefault(x => x.Equals(plugin.SystemName, StringComparison.OrdinalIgnoreCase)) != null;- try+ try+ {+ if (!_config.PluginShadowCopy){- if (!_config.PluginShadowCopy)- {- //remove deps.json files- var depsFiles = plugin.OriginalAssemblyFile.Directory!.GetFiles("*.deps.json", SearchOption.TopDirectoryOnly);- foreach (var f in depsFiles)+ //remove deps.json files+ var depsFiles =+ plugin.OriginalAssemblyFile.Directory!.GetFiles("*.deps.json",+ SearchOption.TopDirectoryOnly);+ foreach (var f in depsFiles)+ try{- try- {- File.Delete(f.FullName);- }- catch (Exception exc)- {- _logger.LogError(exc, "PluginManager");- }+ File.Delete(f.FullName);}- }-- //main plugin file- AddApplicationPart(mvcCoreBuilder, plugin.ReferencedAssembly, plugin.SystemName, plugin.PluginFileName);+ catch (Exception exc)+ {+ _logger.LogError(exc, "PluginManager");+ }+ }- //register interface for IPlugin- RegisterPluginInterface(mvcCoreBuilder, plugin.ReferencedAssembly);+ //main plugin file+ AddApplicationPart(mvcCoreBuilder, plugin.ReferencedAssembly, plugin.SystemName,+ plugin.PluginFileName);- //init plugin type- foreach (var t in plugin.ReferencedAssembly.GetTypes())- if (typeof(IPlugin).IsAssignableFrom(t))- if (!t.GetTypeInfo().IsInterface)- if (t.GetTypeInfo().IsClass && !t.GetTypeInfo().IsAbstract)- {- plugin.PluginType = t;- break;- }+ //register interface for IPlugin+ RegisterPluginInterface(mvcCoreBuilder, plugin.ReferencedAssembly);- referencedPlugins.Add(plugin);- }- catch (ReflectionTypeLoadException ex)- {- var msg = $"Plugin '{plugin.FriendlyName}'. ";- msg = ex.LoaderExceptions.Aggregate(msg, (current, e) => current + e!.Message + Environment.NewLine);+ //init plugin type+ foreach (var t in plugin.ReferencedAssembly.GetTypes())+ if (typeof(IPlugin).IsAssignableFrom(t))+ if (!t.GetTypeInfo().IsInterface)+ if (t.GetTypeInfo().IsClass && !t.GetTypeInfo().IsAbstract)+ {+ plugin.PluginType = t;+ break;+ }- var fail = new Exception(msg, ex);- throw fail;- }- catch (Exception ex)- {- var msg = $"Plugin '{plugin.FriendlyName}'. {ex.Message}";+ referencedPlugins.Add(plugin);+ }+ catch (ReflectionTypeLoadException ex)+ {+ var msg = $"Plugin '{plugin.FriendlyName}'. ";+ msg = ex.LoaderExceptions.Aggregate(msg,+ (current, e) => current + e!.Message + Environment.NewLine);- var fail = new Exception(msg, ex);- throw fail;- }+ var fail = new Exception(msg, ex);+ throw fail;}- }- catch (Exception ex)- {- var msg = string.Empty;- for (var e = ex; e != null; e = e.InnerException)- msg += e.Message + Environment.NewLine;+ catch (Exception ex)+ {+ var msg = $"Plugin '{plugin.FriendlyName}'. {ex.Message}";- var fail = new Exception(msg, ex);- throw fail;+ var fail = new Exception(msg, ex);+ throw fail;+ }}+ }+ catch (Exception ex)+ {+ var msg = string.Empty;+ for (var e = ex; e != null; e = e.InnerException)+ msg += e.Message + Environment.NewLine;- ReferencedPlugins = referencedPlugins;+ var fail = new Exception(msg, ex);+ throw fail;}- }- /// <summary>- /// Find a plugin by some type which is located into the same assembly plugin- /// </summary>- /// <param name="typeAssembly">Type</param>- /// <returns>Plugin descriptor if exists; otherwise null</returns>- public static PluginInfo FindPlugin(Type typeAssembly)- {- if (typeAssembly == null)- throw new ArgumentNullException(nameof(typeAssembly));- return ReferencedPlugins?.FirstOrDefault(plugin => plugin.ReferencedAssembly != null- && plugin.ReferencedAssembly.FullName!.Equals(typeAssembly.GetTypeInfo().Assembly.FullName, StringComparison.OrdinalIgnoreCase));+ ReferencedPlugins = referencedPlugins;}+ }+ /// <summary>+ /// Find a plugin by some type which is located into the same assembly plugin+ /// </summary>+ /// <param name="typeAssembly">Type</param>+ /// <returns>Plugin descriptor if exists; otherwise null</returns>+ public static PluginInfo FindPlugin(Type typeAssembly)+ {+ if (typeAssembly == null)+ throw new ArgumentNullException(nameof(typeAssembly));- /// <summary>- /// Clear plugins- /// </summary>- public static void ClearPlugins()- {- var filePath = CommonPath.InstalledPluginsFilePath;- if (File.Exists(filePath))- File.Delete(filePath);- }+ return ReferencedPlugins?.FirstOrDefault(plugin => plugin.ReferencedAssembly != null+ && plugin.ReferencedAssembly.FullName!.Equals(+ typeAssembly.GetTypeInfo().Assembly.FullName,+ StringComparison.OrdinalIgnoreCase));+ }- #endregion- #region Utilities+ /// <summary>+ /// Clear plugins+ /// </summary>+ public static void ClearPlugins()+ {+ var filePath = CommonPath.InstalledPluginsFilePath;+ if (File.Exists(filePath))+ File.Delete(filePath);+ }- private static IList<PluginInfo> GetPluginInfo()- {- if (_pluginFolder == null)- throw new ArgumentNullException(nameof(_pluginFolder));+ #endregion- var result = new List<PluginInfo>();- foreach (var pluginFile in _pluginFolder.GetFiles("*.dll", SearchOption.AllDirectories))- {- if (!IsPackagePluginFolder(pluginFile.Directory))- continue;+ #region Utilities- if (!string.IsNullOrEmpty(_config.PluginSkipLoadingPattern)- && Matches(pluginFile.Name, _config.PluginSkipLoadingPattern))- continue;+ private static IList<PluginInfo> GetPluginInfo()+ {+ if (_pluginFolder == null)+ throw new ArgumentNullException(nameof(_pluginFolder));- //prepare plugin info- var plugins = PreparePluginInfo(pluginFile);- if (plugins == null)- continue;+ var result = new List<PluginInfo>();+ foreach (var pluginFile in _pluginFolder.GetFiles("*.dll", SearchOption.AllDirectories))+ {+ if (!IsPackagePluginFolder(pluginFile.Directory))+ continue;- result.Add(plugins);- }+ if (!string.IsNullOrEmpty(_config.PluginSkipLoadingPattern)+ && Matches(pluginFile.Name, _config.PluginSkipLoadingPattern))+ continue;- return result;- }+ //prepare plugin info+ var plugins = PreparePluginInfo(pluginFile);+ if (plugins == null)+ continue;- private static PluginInfo PreparePluginInfo(FileInfo pluginFile)- {- var plug = _config.PluginShadowCopy ? ShadowCopyFile(pluginFile, Directory.CreateDirectory(_copyFolder.FullName)) : pluginFile;+ result.Add(plugins);+ }- Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(plug.FullName);+ return result;+ }- var pluginInfo = assembly.GetCustomAttribute<PluginInfoAttribute>();- if (pluginInfo == null)- {- return null;- }+ private static PluginInfo PreparePluginInfo(FileInfo pluginFile)+ {+ var plug = _config.PluginShadowCopy+ ? ShadowCopyFile(pluginFile, Directory.CreateDirectory(_copyFolder.FullName))+ : pluginFile;++ var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(plug.FullName);++ var pluginInfo = assembly.GetCustomAttribute<PluginInfoAttribute>();+ if (pluginInfo == null) return null;++ var plugin = new PluginInfo {+ FriendlyName = pluginInfo.FriendlyName,+ Group = pluginInfo.Group,+ SystemName = pluginInfo.SystemName,+ Version = pluginInfo.Version,+ SupportedVersion = pluginInfo.SupportedVersion,+ Author = pluginInfo.Author,+ PluginFileName = plug.Name,+ OriginalAssemblyFile = pluginFile,+ ReferencedAssembly = assembly+ };++ return plugin;+ }- var plugin = new PluginInfo- {- FriendlyName = pluginInfo.FriendlyName,- Group = pluginInfo.Group,- SystemName = pluginInfo.SystemName,- Version = pluginInfo.Version,- SupportedVersion = pluginInfo.SupportedVersion,- Author = pluginInfo.Author,- PluginFileName = plug.Name,- OriginalAssemblyFile = pluginFile,- ReferencedAssembly = assembly- };-- return plugin;- }+ /// <summary>+ /// Used to initialize plugins when running in Medium Trust+ /// </summary>+ /// <param name="plug"></param>+ /// <param name="shadowCopyPlugFolder"></param>+ /// <returns></returns>+ private static FileInfo ShadowCopyFile(FileInfo plug, DirectoryInfo shadowCopyPlugFolder)+ {+ var shouldCopy = true;+ var shadowCopiedPlug = new FileInfo(Path.Combine(shadowCopyPlugFolder.FullName, plug.Name));- /// <summary>- /// Used to initialize plugins when running in Medium Trust- /// </summary>- /// <param name="plug"></param>- /// <param name="shadowCopyPlugFolder"></param>- /// <returns></returns>- private static FileInfo ShadowCopyFile(FileInfo plug, DirectoryInfo shadowCopyPlugFolder)+ //check if a shadow copied file already exists and if it does, check if it's updated, if not don't copy+ if (shadowCopiedPlug.Exists){- var shouldCopy = true;- var shadowCopiedPlug = new FileInfo(Path.Combine(shadowCopyPlugFolder.FullName, plug.Name));-- //check if a shadow copied file already exists and if it does, check if it's updated, if not don't copy- if (shadowCopiedPlug.Exists)+ //it's better to use LastWriteTimeUTC, but not all file systems have this property+ //maybe it is better to compare file hash?+ var areFilesIdentical = shadowCopiedPlug.CreationTimeUtc.Ticks >= plug.CreationTimeUtc.Ticks;+ if (areFilesIdentical){- //it's better to use LastWriteTimeUTC, but not all file systems have this property- //maybe it is better to compare file hash?- var areFilesIdentical = shadowCopiedPlug.CreationTimeUtc.Ticks >= plug.CreationTimeUtc.Ticks;- if (areFilesIdentical)- {- _logger.LogInformation("Not copying; files appear identical: {Name}", shadowCopiedPlug.Name);- return shadowCopiedPlug;- }-- //delete an existing file- _logger.LogInformation("New plugin found; Deleting the old file: {Name}", shadowCopiedPlug.Name);- try- {- File.Delete(shadowCopiedPlug.FullName);- }- catch (Exception ex)- {- shouldCopy = false;- _logger.LogError(ex, "PluginManager");- }+ _logger.LogInformation("Not copying; files appear identical: {Name}", shadowCopiedPlug.Name);+ return shadowCopiedPlug;}- if (!shouldCopy) return shadowCopiedPlug;+ //delete an existing file+ _logger.LogInformation("New plugin found; Deleting the old file: {Name}", shadowCopiedPlug.Name);try{- File.Copy(plug.FullName, shadowCopiedPlug.FullName, true);+ File.Delete(shadowCopiedPlug.FullName);}- catch (IOException)+ catch (Exception ex){- _logger.LogInformation("{FullName} is locked, attempting to rename", shadowCopiedPlug.FullName);- //this occurs when the files are locked,- //for some reason devenv locks plugin files some times and for another crazy reason you are allowed to rename them- //which releases the lock, so that it what we are doing here, once it's renamed, we can re-shadow copy- try- {- var oldFile = shadowCopiedPlug.FullName + Guid.NewGuid().ToString("N") + ".old";- File.Move(shadowCopiedPlug.FullName, oldFile);- }- catch (IOException exc)- {- throw new IOException(shadowCopiedPlug.FullName + " rename failed, cannot initialize plugin", exc);- }- //ok, we've made it this far, now retry the shadow copy- File.Copy(plug.FullName, shadowCopiedPlug.FullName, true);+ shouldCopy = false;+ _logger.LogError(ex, "PluginManager");}-- return shadowCopiedPlug;}- private static bool Matches(string fullName, string pattern)+ if (!shouldCopy) return shadowCopiedPlug;+ try{- return Regex.IsMatch(fullName, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);+ File.Copy(plug.FullName, shadowCopiedPlug.FullName, true);}-- private static void AddApplicationPart(IMvcCoreBuilder mvcCoreBuilder,- Assembly assembly, string systemName, string filename)+ catch (IOException){+ _logger.LogInformation("{FullName} is locked, attempting to rename", shadowCopiedPlug.FullName);+ //this occurs when the files are locked,+ //for some reason devenv locks plugin files some times and for another crazy reason you are allowed to rename them+ //which releases the lock, so that it what we are doing here, once it's renamed, we can re-shadow copytry{- //we can now register the plugin definition- _logger.LogInformation("Adding to ApplicationParts: '{0}'", systemName);- mvcCoreBuilder.AddApplicationPart(assembly);-- var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, throwOnError: false);- foreach (var relatedAssembly in relatedAssemblies)- {- var applicationPartFactory = ApplicationPartFactory.GetApplicationPartFactory(relatedAssembly);- foreach (var part in applicationPartFactory.GetApplicationParts(relatedAssembly))- {- mvcCoreBuilder.PartManager.ApplicationParts.Add(part);- }- }+ var oldFile = shadowCopiedPlug.FullName + Guid.NewGuid().ToString("N") + ".old";+ File.Move(shadowCopiedPlug.FullName, oldFile);}- catch (Exception ex)+ catch (IOException exc){- _logger.LogError(ex, "PluginManager");- throw new InvalidOperationException($"The plugin directory for the {systemName} file exists in a folder outside of the allowed grandnode folder hierarchy - exception because of {filename} - exception: {ex.Message}");+ throw new IOException(shadowCopiedPlug.FullName + " rename failed, cannot initialize plugin", exc);}++ //ok, we've made it this far, now retry the shadow copy+ File.Copy(plug.FullName, shadowCopiedPlug.FullName, true);}- private static void RegisterPluginInterface(IMvcCoreBuilder mvcCoreBuilder, Assembly assembly)+ return shadowCopiedPlug;+ }++ private static bool Matches(string fullName, string pattern)+ {+ return Regex.IsMatch(fullName, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);+ }++ private static void AddApplicationPart(IMvcCoreBuilder mvcCoreBuilder,+ Assembly assembly, string systemName, string filename)+ {+ try{- try- {- foreach (var t in assembly.GetTypes())- if (typeof(IPlugin).IsAssignableFrom(t))- mvcCoreBuilder.Services.AddScoped(t);- }- catch (Exception ex)+ //we can now register the plugin definition+ _logger.LogInformation("Adding to ApplicationParts: '{0}'", systemName);+ mvcCoreBuilder.AddApplicationPart(assembly);++ var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, false);+ foreach (var relatedAssembly in relatedAssemblies){- _logger.LogError(ex, "RegisterPluginInterface");+ var applicationPartFactory = ApplicationPartFactory.GetApplicationPartFactory(relatedAssembly);+ foreach (var part in applicationPartFactory.GetApplicationParts(relatedAssembly))+ mvcCoreBuilder.PartManager.ApplicationParts.Add(part);}}-- /// <summary>- /// Determines if the folder is a bin plugin folder for a package- /// </summary>- /// <param name="folder"></param>- /// <returns></returns>- private static bool IsPackagePluginFolder(DirectoryInfo folder)+ catch (Exception ex){- if (folder == null) return false;- if (folder.Name.Equals("bin", StringComparison.InvariantCultureIgnoreCase)) return false;- return folder.Parent != null && folder.Parent.Name.Equals("Plugins", StringComparison.OrdinalIgnoreCase);+ _logger.LogError(ex, "PluginManager");+ throw new InvalidOperationException(+ $"The plugin directory for the {systemName} file exists in a folder outside of the allowed grandnode folder hierarchy - exception because of {filename} - exception: {ex.Message}");}+ }+ private static void RegisterPluginInterface(IMvcCoreBuilder mvcCoreBuilder, Assembly assembly)+ {+ try+ {+ foreach (var t in assembly.GetTypes())+ if (typeof(IPlugin).IsAssignableFrom(t))+ mvcCoreBuilder.Services.AddScoped(t);+ }+ catch (Exception ex)+ {+ _logger.LogError(ex, "RegisterPluginInterface");+ }+ }- #endregion+ /// <summary>+ /// Determines if the folder is a bin plugin folder for a package+ /// </summary>+ /// <param name="folder"></param>+ /// <returns></returns>+ private static bool IsPackagePluginFolder(DirectoryInfo folder)+ {+ if (folder == null) return false;+ if (folder.Name.Equals("bin", StringComparison.InvariantCultureIgnoreCase)) return false;+ return folder.Parent != null && folder.Parent.Name.Equals("Plugins", StringComparison.OrdinalIgnoreCase);}-}++ #endregion+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Roslyn/ResultCompiler.cs b/src/Core/Grand.Infrastructure/Roslyn/ResultCompiler.csindex 6a7c03638..1e48db417 100644--- a/src/Core/Grand.Infrastructure/Roslyn/ResultCompiler.cs+++ b/src/Core/Grand.Infrastructure/Roslyn/ResultCompiler.cs@@ -1,13 +1,12 @@using System.Reflection;-namespace Grand.Infrastructure.Roslyn+namespace Grand.Infrastructure.Roslyn;++public class ResultCompiler{- public class ResultCompiler- {- public Assembly ReferencedAssembly { get; internal set; }- public string OriginalFile { get; internal set; }- public virtual string DLLAssemblyFile { get; internal set; }- public bool IsCompiled { get; internal set; }- public IList<string> ErrorInfo { get; internal set; } = new List<string>();- }-}+ public Assembly ReferencedAssembly { get; internal set; }+ public string OriginalFile { get; internal set; }+ public virtual string DLLAssemblyFile { get; internal set; }+ public bool IsCompiled { get; internal set; }+ public IList<string> ErrorInfo { get; internal set; } = new List<string>();+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Roslyn/RoslynCompiler.cs b/src/Core/Grand.Infrastructure/Roslyn/RoslynCompiler.csindex 04914ecca..e8877da2d 100644--- a/src/Core/Grand.Infrastructure/Roslyn/RoslynCompiler.cs+++ b/src/Core/Grand.Infrastructure/Roslyn/RoslynCompiler.cs@@ -7,146 +7,135 @@ using Microsoft.CodeAnalysis.Scripting;using Microsoft.Extensions.Configuration;using System.Collections.Immutable;using System.Diagnostics;-using System.Reflection;using System.Runtime.Loader;-namespace Grand.Infrastructure.Roslyn-{- public static class RoslynCompiler- {- #region Const-- private const string ScriptPath = "Roslyn";- private const string ShadowCopyScriptPath = "Roslyn/bin";+namespace Grand.Infrastructure.Roslyn;- #endregion+public static class RoslynCompiler+{+ #region Fields- #region Fields+ private static DirectoryInfo _shadowCopyScriptPath;- private static DirectoryInfo _shadowCopyScriptPath;+ #endregion- #endregion+ /// <summary>+ /// Returns a collection of all referenced assemblies+ /// </summary>+ public static IEnumerable<ResultCompiler> ReferencedScripts { get; set; }- public static void Load(ApplicationPartManager applicationPartManager, IConfiguration configuration)- {- ArgumentNullException.ThrowIfNull(applicationPartManager);+ public static void Load(ApplicationPartManager applicationPartManager, IConfiguration configuration)+ {+ ArgumentNullException.ThrowIfNull(applicationPartManager);- var config = new ExtensionsConfig();- configuration.GetSection("Extensions").Bind(config);+ var config = new ExtensionsConfig();+ configuration.GetSection("Extensions").Bind(config);- if (!config.UseRoslynScripts)- return;+ if (!config.UseRoslynScripts)+ return;- var referencedScripts = new List<ResultCompiler>();+ var referencedScripts = new List<ResultCompiler>();- var roslynFolder = new DirectoryInfo(CommonPath.MapPath(ScriptPath));+ var roslynFolder = new DirectoryInfo(CommonPath.MapPath(ScriptPath));- _shadowCopyScriptPath = new DirectoryInfo(CommonPath.MapPath(ShadowCopyScriptPath));- Directory.CreateDirectory(_shadowCopyScriptPath.FullName);+ _shadowCopyScriptPath = new DirectoryInfo(CommonPath.MapPath(ShadowCopyScriptPath));+ Directory.CreateDirectory(_shadowCopyScriptPath.FullName);- //clear bin files- var binFiles = _shadowCopyScriptPath.GetFiles("*", SearchOption.AllDirectories);- foreach (var f in binFiles)+ //clear bin files+ var binFiles = _shadowCopyScriptPath.GetFiles("*", SearchOption.AllDirectories);+ foreach (var f in binFiles)+ try{- try- {- //ignore index.htm- var fileName = Path.GetFileName(f.FullName);- if (fileName.Equals("index.htm", StringComparison.OrdinalIgnoreCase))- continue;+ //ignore index.htm+ var fileName = Path.GetFileName(f.FullName);+ if (fileName.Equals("index.htm", StringComparison.OrdinalIgnoreCase))+ continue;- File.Delete(f.FullName);- }- catch (Exception exc)- {- Debug.WriteLine("Error deleting file " + f.Name + ". Exception: " + exc);- }+ File.Delete(f.FullName);+ }+ catch (Exception exc)+ {+ Debug.WriteLine("Error deleting file " + f.Name + ". Exception: " + exc);}- try+ try+ {+ var ctxFiles = roslynFolder.GetFiles("*.csx", SearchOption.TopDirectoryOnly);+ foreach (var file in ctxFiles){- var ctxFiles = roslynFolder.GetFiles("*.csx", SearchOption.TopDirectoryOnly);- foreach (var file in ctxFiles)+ var csxScript = new ResultCompiler {+ OriginalFile = file.FullName+ };++ var ctxCode = File.ReadAllText(file.FullName);+ var sourceFileResolver = new SourceFileResolver(ImmutableArray<string>.Empty, AppContext.BaseDirectory);+ var opts = ScriptOptions.Default.WithSourceResolver(sourceFileResolver);+ var script = CSharpScript.Create(ctxCode, opts);+ var compilation = script.GetCompilation();+ using (var ms = new MemoryStream()){- var csxScript = new ResultCompiler+ var compilationResult = compilation.Emit(ms);++ if (compilationResult.Success){- OriginalFile = file.FullName- };-- var ctxCode = File.ReadAllText(file.FullName);- var sourceFileResolver = new SourceFileResolver(ImmutableArray<string>.Empty, AppContext.BaseDirectory);- var opts = ScriptOptions.Default.WithSourceResolver(sourceFileResolver);- var script = CSharpScript.Create(ctxCode, opts);- var compilation = script.GetCompilation();- using (var ms = new MemoryStream())+ ms.Seek(0, SeekOrigin.Begin);+ var shadowFileName = Path.Combine(_shadowCopyScriptPath.FullName,+ file.Name + "-" + Guid.NewGuid().ToString("D") + ".dll");+ File.WriteAllBytes(shadowFileName, ms.ToArray());+ var shadowCopiedAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(shadowFileName);+ csxScript.DLLAssemblyFile = shadowFileName;+ csxScript.ReferencedAssembly = shadowCopiedAssembly;+ csxScript.IsCompiled = true;+ applicationPartManager.ApplicationParts.Add(new AssemblyPart(shadowCopiedAssembly));+ }+ else{- var compilationResult = compilation.Emit(ms);-- if (compilationResult.Success)- {- ms.Seek(0, SeekOrigin.Begin);- var shadowFileName = Path.Combine(_shadowCopyScriptPath.FullName, file.Name + "-" + Guid.NewGuid().ToString("D") + ".dll");- File.WriteAllBytes(shadowFileName, ms.ToArray());- Assembly shadowCopiedAssembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(shadowFileName);- csxScript.DLLAssemblyFile = shadowFileName;- csxScript.ReferencedAssembly = shadowCopiedAssembly;- csxScript.IsCompiled = true;- applicationPartManager.ApplicationParts.Add(new AssemblyPart(shadowCopiedAssembly));- }- else- {- foreach (var diagnostic in compilationResult.Diagnostics)- {- csxScript.ErrorInfo.Add(diagnostic.ToString());- }- }+ foreach (var diagnostic in compilationResult.Diagnostics)+ csxScript.ErrorInfo.Add(diagnostic.ToString());}- referencedScripts.Add(csxScript);-}- ReferencedScripts = referencedScripts;- }- catch (Exception ex)- {- var msg = $"Roslyn '{ex.Message}'";- var fail = new Exception(msg, ex);- throw fail;+ referencedScripts.Add(csxScript);}- }- /// <summary>- /// Returns a collection of all referenced assemblies- /// </summary>- public static IEnumerable<ResultCompiler> ReferencedScripts { get; set; }-- /// <summary>- /// Method for compiling the code for testing in admin panel- /// </summary>- /// <param name="code"></param>- /// <returns></returns>- public static ResultCompiler ResultCompiledScript(string code)+ ReferencedScripts = referencedScripts;+ }+ catch (Exception ex){- var result = new ResultCompiler();- var sourceFileResolver = new SourceFileResolver(ImmutableArray<string>.Empty, AppContext.BaseDirectory);- var opts = ScriptOptions.Default.WithSourceResolver(sourceFileResolver);- var script = CSharpScript.Create(code, opts);- var compilation = script.GetCompilation();- using var ms = new MemoryStream();- var compilationResult = compilation.Emit(ms);- if (compilationResult.Success)- {- result.IsCompiled = true;- }- else- {- foreach (var diagnostic in compilationResult.Diagnostics)- {- result.ErrorInfo.Add(diagnostic.ToString());- }- }+ var msg = $"Roslyn '{ex.Message}'";- return result;+ var fail = new Exception(msg, ex);+ throw fail;}}-}++ /// <summary>+ /// Method for compiling the code for testing in admin panel+ /// </summary>+ /// <param name="code"></param>+ /// <returns></returns>+ public static ResultCompiler ResultCompiledScript(string code)+ {+ var result = new ResultCompiler();+ var sourceFileResolver = new SourceFileResolver(ImmutableArray<string>.Empty, AppContext.BaseDirectory);+ var opts = ScriptOptions.Default.WithSourceResolver(sourceFileResolver);+ var script = CSharpScript.Create(code, opts);+ var compilation = script.GetCompilation();+ using var ms = new MemoryStream();+ var compilationResult = compilation.Emit(ms);+ if (compilationResult.Success)+ result.IsCompiled = true;+ else+ foreach (var diagnostic in compilationResult.Diagnostics)+ result.ErrorInfo.Add(diagnostic.ToString());++ return result;+ }++ #region Const++ private const string ScriptPath = "Roslyn";+ private const string ShadowCopyScriptPath = "Roslyn/bin";++ #endregion+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Startup/ApplicationInsightsSubscriber.cs b/src/Core/Grand.Infrastructure/Startup/ApplicationInsightsSubscriber.csindex e524a85bb..a74182776 100644--- a/src/Core/Grand.Infrastructure/Startup/ApplicationInsightsSubscriber.cs+++ b/src/Core/Grand.Infrastructure/Startup/ApplicationInsightsSubscriber.cs@@ -5,53 +5,52 @@ using MongoDB.Driver.Core.Events;using System.Collections.Concurrent;using System.Reflection;-namespace Grand.Infrastructure.Startup+namespace Grand.Infrastructure.Startup;++public class ApplicationInsightsSubscriber : IEventSubscriber{- public class ApplicationInsightsSubscriber : IEventSubscriber+ private readonly ConcurrentDictionary<int, Operation> _dictionary = new();+ private readonly IServiceCollection _services;+ private readonly ReflectionEventSubscriber _subscriber;++ private TelemetryClient _telemetryClient;++ public ApplicationInsightsSubscriber(IServiceCollection services)+ {+ _subscriber = new ReflectionEventSubscriber(this,+ bindingFlags: BindingFlags.Instance | BindingFlags.NonPublic);++ _services = services;+ }++ private TelemetryClient TelemetryClient =>+ _telemetryClient ??= _services.BuildServiceProvider().GetRequiredService<TelemetryClient>();++ public bool TryGetEventHandler<TEvent>(out Action<TEvent> handler){- private readonly ReflectionEventSubscriber _subscriber;-- private TelemetryClient _telemetryClient;-- private TelemetryClient TelemetryClient => _telemetryClient ??= _services.BuildServiceProvider().GetRequiredService<TelemetryClient>();- private readonly IServiceCollection _services;-- private readonly ConcurrentDictionary<int, Operation> _dictionary = new ();-- record Operation(string Name, string Command);-- public ApplicationInsightsSubscriber(IServiceCollection services)- {- _subscriber = new ReflectionEventSubscriber(this,- bindingFlags: BindingFlags.Instance | BindingFlags.NonPublic);-- _services = services;- }-- public bool TryGetEventHandler<TEvent>(out Action<TEvent> handler)- {- return _subscriber.TryGetEventHandler(out handler);- }-- private void Handle(CommandStartedEvent cmdStart)- {- _dictionary.TryAdd(cmdStart.RequestId, new Operation(cmdStart.CommandName, cmdStart.Command.ToString()));- }-- private void Handle(CommandSucceededEvent cmdSuccess)- {- if (!_dictionary.TryGetValue(cmdSuccess.RequestId, out var operation)) return;- var telemetry = new DependencyTelemetry {- Data = operation.Command,- Name = operation.Name,- Type = "MongoDB",- Timestamp = DateTime.UtcNow.Subtract(cmdSuccess.Duration),- Duration = cmdSuccess.Duration,- Success = true- };- TelemetryClient?.TrackDependency(telemetry);-- _dictionary.TryRemove(cmdSuccess.RequestId, out _);- }+ return _subscriber.TryGetEventHandler(out handler);}-}++ private void Handle(CommandStartedEvent cmdStart)+ {+ _dictionary.TryAdd(cmdStart.RequestId, new Operation(cmdStart.CommandName, cmdStart.Command.ToString()));+ }++ private void Handle(CommandSucceededEvent cmdSuccess)+ {+ if (!_dictionary.TryGetValue(cmdSuccess.RequestId, out var operation)) return;+ var telemetry = new DependencyTelemetry {+ Data = operation.Command,+ Name = operation.Name,+ Type = "MongoDB",+ Timestamp = DateTime.UtcNow.Subtract(cmdSuccess.Duration),+ Duration = cmdSuccess.Duration,+ Success = true+ };+ TelemetryClient?.TrackDependency(telemetry);++ _dictionary.TryRemove(cmdSuccess.RequestId, out _);+ }++ private record Operation(string Name, string Command);+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Startup/StartupApplication.cs b/src/Core/Grand.Infrastructure/Startup/StartupApplication.csindex d4d238a73..ab877275b 100644--- a/src/Core/Grand.Infrastructure/Startup/StartupApplication.cs+++ b/src/Core/Grand.Infrastructure/Startup/StartupApplication.cs@@ -9,87 +9,88 @@ using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using MongoDB.Driver;-namespace Grand.Infrastructure.Startup-{- public class StartupApplication : IStartupApplication- {- public int Priority => 0;-- public bool BeforeConfigure => false;+namespace Grand.Infrastructure.Startup;+public class StartupApplication : IStartupApplication+{+ public int Priority => 0;- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {+ public bool BeforeConfigure => false;- }- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- RegisterDataLayer(services, configuration);- }+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {+ }- private void RegisterDataLayer(IServiceCollection serviceCollection, IConfiguration configuration)- {- serviceCollection.AddSingleton<IAuditInfoProvider, AuditInfoProvider>();+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration)+ {+ RegisterDataLayer(services, configuration);+ }- var dbConfig = new DatabaseConfig();- configuration.GetSection("Database").Bind(dbConfig);+ private void RegisterDataLayer(IServiceCollection serviceCollection, IConfiguration configuration)+ {+ serviceCollection.AddSingleton<IAuditInfoProvider, AuditInfoProvider>();- var applicationInsights = new ApplicationInsightsConfig();- configuration.GetSection("ApplicationInsights").Bind(applicationInsights);+ var dbConfig = new DatabaseConfig();+ configuration.GetSection("Database").Bind(dbConfig);- var dataProviderSettings = DataSettingsManager.LoadSettings();- if (string.IsNullOrEmpty(dataProviderSettings.ConnectionString))- {- serviceCollection.AddTransient(_ => dataProviderSettings);+ var applicationInsights = new ApplicationInsightsConfig();+ configuration.GetSection("ApplicationInsights").Bind(applicationInsights);- if (dbConfig.UseLiteDb)- serviceCollection.AddSingleton(_ => new LiteDatabase(dbConfig.LiteDbConnectionString));- }- if (dataProviderSettings.IsValid())- {- if (dataProviderSettings.DbProvider != DbProvider.LiteDB)- {- var connectionString = dataProviderSettings.ConnectionString;- var mongoUrl = new MongoUrl(connectionString);- var databaseName = mongoUrl.DatabaseName;- var clientSettings = MongoClientSettings.FromConnectionString(connectionString);-- if (applicationInsights.TrackDependencyMongoDb)- clientSettings.ClusterConfigurator = builder => { builder.Subscribe(new ApplicationInsightsSubscriber(serviceCollection)); };-- serviceCollection.AddScoped(_ => new MongoClient(clientSettings).GetDatabase(databaseName));+ var dataProviderSettings = DataSettingsManager.LoadSettings();+ if (string.IsNullOrEmpty(dataProviderSettings.ConnectionString))+ {+ serviceCollection.AddTransient(_ => dataProviderSettings);- }- else- {- if (dbConfig.Singleton)- serviceCollection.AddSingleton(_ => new LiteDatabase(dataProviderSettings.ConnectionString) { UtcDate = true });- else- serviceCollection.AddScoped(_ => new LiteDatabase(dataProviderSettings.ConnectionString) { UtcDate = true });+ if (dbConfig.UseLiteDb)+ serviceCollection.AddSingleton(_ => new LiteDatabase(dbConfig.LiteDbConnectionString));+ }- }- }- if (!dbConfig.UseLiteDb)+ if (dataProviderSettings.IsValid())+ {+ if (dataProviderSettings.DbProvider != DbProvider.LiteDB){- //database context- serviceCollection.AddScoped<IDatabaseContext, MongoDBContext>();- //store files context - grid fs- serviceCollection.AddScoped<IStoreFilesContext, MongoStoreFilesContext>();- //Mongo Repository- serviceCollection.AddScoped(typeof(IRepository<>), typeof(MongoRepository<>));+ var connectionString = dataProviderSettings.ConnectionString;+ var mongoUrl = new MongoUrl(connectionString);+ var databaseName = mongoUrl.DatabaseName;+ var clientSettings = MongoClientSettings.FromConnectionString(connectionString);++ if (applicationInsights.TrackDependencyMongoDb)+ clientSettings.ClusterConfigurator = builder =>+ {+ builder.Subscribe(new ApplicationInsightsSubscriber(serviceCollection));+ };++ serviceCollection.AddScoped(_ => new MongoClient(clientSettings).GetDatabase(databaseName));}else{- //database context- serviceCollection.AddScoped<IDatabaseContext, LiteDBContext>();- //store files context - grid fs- serviceCollection.AddScoped<IStoreFilesContext, LiteDBStoreFilesContext>();- //Mongo Repository- serviceCollection.AddScoped(typeof(IRepository<>), typeof(LiteDBRepository<>));-+ if (dbConfig.Singleton)+ serviceCollection.AddSingleton(_ => new LiteDatabase(dataProviderSettings.ConnectionString)+ { UtcDate = true });+ else+ serviceCollection.AddScoped(_ => new LiteDatabase(dataProviderSettings.ConnectionString)+ { UtcDate = true });}+ }+ if (!dbConfig.UseLiteDb)+ {+ //database context+ serviceCollection.AddScoped<IDatabaseContext, MongoDBContext>();+ //store files context - grid fs+ serviceCollection.AddScoped<IStoreFilesContext, MongoStoreFilesContext>();+ //Mongo Repository+ serviceCollection.AddScoped(typeof(IRepository<>), typeof(MongoRepository<>));+ }+ else+ {+ //database context+ serviceCollection.AddScoped<IDatabaseContext, LiteDBContext>();+ //store files context - grid fs+ serviceCollection.AddScoped<IStoreFilesContext, LiteDBStoreFilesContext>();+ //Mongo Repository+ serviceCollection.AddScoped(typeof(IRepository<>), typeof(LiteDBRepository<>));}}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/StartupBase.cs b/src/Core/Grand.Infrastructure/StartupBase.csindex e39458765..062cf7ff3 100644--- a/src/Core/Grand.Infrastructure/StartupBase.cs+++ b/src/Core/Grand.Infrastructure/StartupBase.cs@@ -20,350 +20,340 @@ using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Infrastructure+namespace Grand.Infrastructure;++/// <summary>+/// Represents startup+/// </summary>+public static class StartupBase{+ #region Utilities+/// <summary>- /// Represents startup+ /// Init Database/// </summary>- public static class StartupBase+ private static void InitDatabase(IServiceCollection services, IConfiguration configuration){- #region Utilities+ var dbConfig = services.StartupConfig<DatabaseConfig>(configuration.GetSection("Database"));+ if (!string.IsNullOrEmpty(dbConfig.ConnectionString))+ DataSettingsManager.LoadDataSettings(new DataSettings {+ ConnectionString = dbConfig.ConnectionString,+ DbProvider = (DbProvider)dbConfig.DbProvider+ });+ }- /// <summary>- /// Init Database- /// </summary>- private static void InitDatabase(IServiceCollection services, IConfiguration configuration)- {- var dbConfig = services.StartupConfig<DatabaseConfig>(configuration.GetSection("Database"));- if (!string.IsNullOrEmpty(dbConfig.ConnectionString))- {- DataSettingsManager.LoadDataSettings(new DataSettings {- ConnectionString = dbConfig.ConnectionString,- DbProvider = (DbProvider)dbConfig.DbProvider- });- }- }+ /// <summary>+ /// Register and init AutoMapper+ /// </summary>+ /// <param name="typeSearcher">Type finder</param>+ private static void InitAutoMapper(ITypeSearcher typeSearcher)+ {+ //find mapper configurations provided by other assemblies+ var mapperConfigurations = typeSearcher.ClassesOfType<IAutoMapperProfile>();- /// <summary>- /// Register and init AutoMapper- /// </summary>- /// <param name="typeSearcher">Type finder</param>- private static void InitAutoMapper(ITypeSearcher typeSearcher)+ //create and sort instances of mapper configurations+ var instances = mapperConfigurations+ .Where(PluginExtensions.OnlyInstalledPlugins)+ .Select(mapperConfiguration => (IAutoMapperProfile)Activator.CreateInstance(mapperConfiguration))+ .OrderBy(mapperConfiguration => mapperConfiguration!.Order);++ //create AutoMapper configuration+ var config = new MapperConfiguration(cfg =>{- //find mapper configurations provided by other assemblies- var mapperConfigurations = typeSearcher.ClassesOfType<IAutoMapperProfile>();+ foreach (var instance in instances) cfg.AddProfile(instance.GetType());+ });- //create and sort instances of mapper configurations- var instances = mapperConfigurations- .Where(PluginExtensions.OnlyInstalledPlugins)- .Select(mapperConfiguration => (IAutoMapperProfile)Activator.CreateInstance(mapperConfiguration))- .OrderBy(mapperConfiguration => mapperConfiguration!.Order);+ //register automapper+ AutoMapperConfig.Init(config);+ }- //create AutoMapper configuration- var config = new MapperConfiguration(cfg =>- {- foreach (var instance in instances)- {- cfg.AddProfile(instance.GetType());- }- });+ /// <summary>+ /// Register type Converters+ /// </summary>+ /// <param name="typeSearcher"></param>+ private static void RegisterTypeConverter(ITypeSearcher typeSearcher)+ {+ //find converters provided by other assemblies+ var converters = typeSearcher.ClassesOfType<ITypeConverter>();- //register automapper- AutoMapperConfig.Init(config);- }+ //create and sort instances of typeConverter+ var instances = converters+ .Select(converter => (ITypeConverter)Activator.CreateInstance(converter))+ .OrderBy(converter => converter!.Order);- /// <summary>- /// Register type Converters- /// </summary>- /// <param name="typeSearcher"></param>- private static void RegisterTypeConverter(ITypeSearcher typeSearcher)- {- //find converters provided by other assemblies- var converters = typeSearcher.ClassesOfType<ITypeConverter>();-- //create and sort instances of typeConverter- var instances = converters- .Select(converter => (ITypeConverter)Activator.CreateInstance(converter))- .OrderBy(converter => converter!.Order);-- foreach (var item in instances)- item.Register();- }-- /// <summary>- /// Register type ValidatorConsumer- /// </summary>- /// <param name="services">Service collection</param>- /// <param name="typeSearcher">TypeSearcher</param>- private static void RegisterValidatorConsumer(IServiceCollection services, ITypeSearcher typeSearcher)- {- services.Scan(scan => scan.FromAssemblies(typeSearcher.GetAssemblies())- .AddClasses(classes => classes.AssignableTo(typeof(IValidatorConsumer<>)))- .AsImplementedInterfaces().WithScopedLifetime());- }+ foreach (var item in instances)+ item.Register();+ }+ /// <summary>+ /// Register type ValidatorConsumer+ /// </summary>+ /// <param name="services">Service collection</param>+ /// <param name="typeSearcher">TypeSearcher</param>+ private static void RegisterValidatorConsumer(IServiceCollection services, ITypeSearcher typeSearcher)+ {+ services.Scan(scan => scan.FromAssemblies(typeSearcher.GetAssemblies())+ .AddClasses(classes => classes.AssignableTo(typeof(IValidatorConsumer<>)))+ .AsImplementedInterfaces().WithScopedLifetime());+ }- private static T StartupConfig<T>(this IServiceCollection services, IConfiguration configuration)- where T : class, new()- {- ArgumentNullException.ThrowIfNull(services);- ArgumentNullException.ThrowIfNull(configuration);-- var config = new T();- configuration.Bind(config);- services.AddSingleton(config);- return config;- }-- /// <summary>- /// Register HttpContextAccessor- /// </summary>- /// <param name="services">Collection of service descriptors</param>- private static void AddHttpContextAccessor(this IServiceCollection services)- {- services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();- services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();- }-- /// <summary>- /// Register extensions plugins/scripts- /// </summary>- /// <param name="mvcCoreBuilder"></param>- /// <param name="configuration"></param>- private static void RegisterExtensions(IMvcCoreBuilder mvcCoreBuilder, IConfiguration configuration)- {- //Load plugins- PluginManager.Load(mvcCoreBuilder, configuration);-- //Load CTX scripts- RoslynCompiler.Load(mvcCoreBuilder.PartManager, configuration);- }-- /// <summary>- /// Adds services for mediatR- /// </summary>- /// <param name="services">Collection of service descriptors</param>- /// <param name="typeSearcher"></param>- private static void AddMediator(this IServiceCollection services, ITypeSearcher typeSearcher)- {- var assemblies = typeSearcher.GetAssemblies().ToArray();- services.AddMediatR(options =>- {- options.RegisterServicesFromAssemblies(assemblies);- });- }-- /// <summary>- /// Add Mass Transit rabbitmq message broker- /// </summary>- /// <param name="services"></param>- /// <param name="configuration"></param>- /// <param name="typeSearcher"></param>- private static void AddMassTransitRabbitMq(IServiceCollection services, IConfiguration configuration,- ITypeSearcher typeSearcher)++ private static T StartupConfig<T>(this IServiceCollection services, IConfiguration configuration)+ where T : class, new()+ {+ ArgumentNullException.ThrowIfNull(services);+ ArgumentNullException.ThrowIfNull(configuration);++ var config = new T();+ configuration.Bind(config);+ services.AddSingleton(config);+ return config;+ }++ /// <summary>+ /// Register HttpContextAccessor+ /// </summary>+ /// <param name="services">Collection of service descriptors</param>+ private static void AddHttpContextAccessor(this IServiceCollection services)+ {+ services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();+ services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();+ }++ /// <summary>+ /// Register extensions plugins/scripts+ /// </summary>+ /// <param name="mvcCoreBuilder"></param>+ /// <param name="configuration"></param>+ private static void RegisterExtensions(IMvcCoreBuilder mvcCoreBuilder, IConfiguration configuration)+ {+ //Load plugins+ PluginManager.Load(mvcCoreBuilder, configuration);++ //Load CTX scripts+ RoslynCompiler.Load(mvcCoreBuilder.PartManager, configuration);+ }++ /// <summary>+ /// Adds services for mediatR+ /// </summary>+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="typeSearcher"></param>+ private static void AddMediator(this IServiceCollection services, ITypeSearcher typeSearcher)+ {+ var assemblies = typeSearcher.GetAssemblies().ToArray();+ services.AddMediatR(options =>{- var config = new RabbitConfig();- configuration.GetSection("Rabbit").Bind(config);+ options.RegisterServicesFromAssemblies(assemblies);+ });+ }- if (!config.RabbitEnabled) return;- services.AddMassTransit(x =>- {- x.AddConsumers(q => q != typeof(CacheMessageEventConsumer), typeSearcher.GetAssemblies().ToArray());+ /// <summary>+ /// Add Mass Transit rabbitmq message broker+ /// </summary>+ /// <param name="services"></param>+ /// <param name="configuration"></param>+ /// <param name="typeSearcher"></param>+ private static void AddMassTransitRabbitMq(IServiceCollection services, IConfiguration configuration,+ ITypeSearcher typeSearcher)+ {+ var config = new RabbitConfig();+ configuration.GetSection("Rabbit").Bind(config);- if (config.RabbitCachePubSubEnabled)- {- x.AddConsumer<CacheMessageEventConsumer>()- .Endpoint(t => t.Name = config.RabbitCacheReceiveEndpoint);- }+ if (!config.RabbitEnabled) return;+ services.AddMassTransit(x =>+ {+ x.AddConsumers(q => q != typeof(CacheMessageEventConsumer), typeSearcher.GetAssemblies().ToArray());++ if (config.RabbitCachePubSubEnabled)+ x.AddConsumer<CacheMessageEventConsumer>()+ .Endpoint(t => t.Name = config.RabbitCacheReceiveEndpoint);- x.UsingRabbitMq((context, cfg) =>+ x.UsingRabbitMq((context, cfg) =>+ {+ cfg.Host(config.RabbitHostName, config.RabbitVirtualHost, h =>{- cfg.Host(config.RabbitHostName, config.RabbitVirtualHost, h =>- {- h.Password(config.RabbitPassword);- h.Username(config.RabbitUsername);- });- cfg.ConfigureEndpoints(context);+ h.Password(config.RabbitPassword);+ h.Username(config.RabbitUsername);});+ cfg.ConfigureEndpoints(context);});- }-- /// <summary>- /// Register application- /// </summary>- /// <param name="services">Collection of service descriptors</param>- /// <param name="configuration">Configuration</param>- /// <param name="typeSearcher">Type searcher</param>- private static IMvcCoreBuilder RegisterApplication(IServiceCollection services, IConfiguration configuration,- ITypeSearcher typeSearcher)- {- //add accessor to HttpContext- services.AddHttpContextAccessor();+ });+ }- RegisterConfigurations(services, configuration);+ /// <summary>+ /// Register application+ /// </summary>+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="configuration">Configuration</param>+ /// <param name="typeSearcher">Type searcher</param>+ private static IMvcCoreBuilder RegisterApplication(IServiceCollection services, IConfiguration configuration,+ ITypeSearcher typeSearcher)+ {+ //add accessor to HttpContext+ services.AddHttpContextAccessor();++ RegisterConfigurations(services, configuration);- InitDatabase(services, configuration);+ InitDatabase(services, configuration);- //set base application path- var provider = services.BuildServiceProvider();- var hostingEnvironment = provider.GetRequiredService<IWebHostEnvironment>();- var param = configuration["Directory"];- if (!string.IsNullOrEmpty(param))- CommonPath.Param = param;+ //set base application path+ var provider = services.BuildServiceProvider();+ var hostingEnvironment = provider.GetRequiredService<IWebHostEnvironment>();+ var param = configuration["Directory"];+ if (!string.IsNullOrEmpty(param))+ CommonPath.Param = param;- CommonPath.WebHostEnvironment = hostingEnvironment.WebRootPath;- CommonPath.BaseDirectory = hostingEnvironment.ContentRootPath;- services.AddTransient<ValidationFilter>();- var mvcCoreBuilder = services.AddMvcCore(options =>+ CommonPath.WebHostEnvironment = hostingEnvironment.WebRootPath;+ CommonPath.BaseDirectory = hostingEnvironment.ContentRootPath;+ services.AddTransient<ValidationFilter>();+ var mvcCoreBuilder = services.AddMvcCore(options =>+ {+ options.Filters.AddService<ValidationFilter>();+ var frontConfig = new FrontendAPIConfig();+ configuration.GetSection("FrontendAPI").Bind(frontConfig);+ if (frontConfig.JsonContentType){- options.Filters.AddService<ValidationFilter>();- var frontConfig = new FrontendAPIConfig();- configuration.GetSection("FrontendAPI").Bind(frontConfig);- if (frontConfig.JsonContentType)+ options.UseJsonBodyModelBinderProviderInsteadOf<DictionaryModelBinderProvider>();+ options.UseJsonBodyModelBinderProviderInsteadOf<ComplexObjectModelBinderProvider>();+ }+ });++ return mvcCoreBuilder;+ }++ private static void RegisterConfigurations(IServiceCollection services, IConfiguration configuration)+ {+ var appConfiguration = configuration["Azure:AppConfiguration"];+ if (!string.IsNullOrEmpty(appConfiguration))+ ((ConfigurationManager)configuration).AddAzureAppConfiguration(options =>+ {+ options.Connect(appConfiguration);+ var keyPrefix = configuration["Azure:AppKeyPrefix"];+ if (!string.IsNullOrEmpty(keyPrefix)){- options.UseJsonBodyModelBinderProviderInsteadOf<DictionaryModelBinderProvider>();- options.UseJsonBodyModelBinderProviderInsteadOf<ComplexObjectModelBinderProvider>();+ options.Select($"{keyPrefix}:*");+ options.TrimKeyPrefix($"{keyPrefix}:");}});- return mvcCoreBuilder;- }+ services.StartupConfig<AppConfig>(configuration.GetSection("Application"));+ services.StartupConfig<PerformanceConfig>(configuration.GetSection("Performance"));+ services.StartupConfig<SecurityConfig>(configuration.GetSection("Security"));+ services.StartupConfig<ExtensionsConfig>(configuration.GetSection("Extensions"));+ services.StartupConfig<CacheConfig>(configuration.GetSection("Cache"));+ services.StartupConfig<AccessControlConfig>(configuration.GetSection("AccessControl"));+ services.StartupConfig<UrlRewriteConfig>(configuration.GetSection("UrlRewrite"));+ services.StartupConfig<RedisConfig>(configuration.GetSection("Redis"));+ services.StartupConfig<RabbitConfig>(configuration.GetSection("Rabbit"));+ services.StartupConfig<BackendAPIConfig>(configuration.GetSection("BackendAPI"));+ services.StartupConfig<FrontendAPIConfig>(configuration.GetSection("FrontendAPI"));+ services.StartupConfig<DatabaseConfig>(configuration.GetSection("Database"));+ services.StartupConfig<AmazonConfig>(configuration.GetSection("Amazon"));+ services.StartupConfig<AzureConfig>(configuration.GetSection("Azure"));+ services.StartupConfig<ApplicationInsightsConfig>(configuration.GetSection("ApplicationInsights"));+ }- private static void RegisterConfigurations(IServiceCollection services, IConfiguration configuration)- {- var appConfiguration = configuration["Azure:AppConfiguration"];- if (!string.IsNullOrEmpty(appConfiguration))- {- ((ConfigurationManager)configuration).AddAzureAppConfiguration(options =>- {- options.Connect(appConfiguration);- var keyPrefix = configuration["Azure:AppKeyPrefix"];- if (!string.IsNullOrEmpty(keyPrefix))- {- options.Select($"{keyPrefix}:*");- options.TrimKeyPrefix($"{keyPrefix}:");- }- });- }+ #endregion- services.StartupConfig<AppConfig>(configuration.GetSection("Application"));- services.StartupConfig<PerformanceConfig>(configuration.GetSection("Performance"));- services.StartupConfig<SecurityConfig>(configuration.GetSection("Security"));- services.StartupConfig<ExtensionsConfig>(configuration.GetSection("Extensions"));- services.StartupConfig<CacheConfig>(configuration.GetSection("Cache"));- services.StartupConfig<AccessControlConfig>(configuration.GetSection("AccessControl"));- services.StartupConfig<UrlRewriteConfig>(configuration.GetSection("UrlRewrite"));- services.StartupConfig<RedisConfig>(configuration.GetSection("Redis"));- services.StartupConfig<RabbitConfig>(configuration.GetSection("Rabbit"));- services.StartupConfig<BackendAPIConfig>(configuration.GetSection("BackendAPI"));- services.StartupConfig<FrontendAPIConfig>(configuration.GetSection("FrontendAPI"));- services.StartupConfig<DatabaseConfig>(configuration.GetSection("Database"));- services.StartupConfig<AmazonConfig>(configuration.GetSection("Amazon"));- services.StartupConfig<AzureConfig>(configuration.GetSection("Azure"));- services.StartupConfig<ApplicationInsightsConfig>(configuration.GetSection("ApplicationInsights"));- }-- #endregion-- #region Methods-- /// <summary>- /// Add and configure services- /// </summary>- /// <param name="services">Collection of service descriptors</param>- /// <param name="configuration">Configuration root of the application</param>- public static void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- //find startup configurations provided by other assemblies- var typeSearcher = new TypeSearcher();- services.AddSingleton<ITypeSearcher>(typeSearcher);-- //register application- var mvcBuilder = RegisterApplication(services, configuration, typeSearcher);-- //register extensions- RegisterExtensions(mvcBuilder, configuration);-- var startupConfigurations = typeSearcher.ClassesOfType<IStartupApplication>();-- //Register startup- var instancesBefore = startupConfigurations- .Where(PluginExtensions.OnlyInstalledPlugins)- .Select(startup => (IStartupApplication)Activator.CreateInstance(startup))- .Where(startup => startup!.BeforeConfigure)- .OrderBy(startup => startup.Priority);-- //configure services- foreach (var instance in instancesBefore)- instance.ConfigureServices(services, configuration);-- //register mapper configurations- InitAutoMapper(typeSearcher);-- //Register custom type converters- RegisterTypeConverter(typeSearcher);-- //Register type validator consumer- RegisterValidatorConsumer(services, typeSearcher);-- //add mediator- AddMediator(services, typeSearcher);-- //Add MassTransit- AddMassTransitRabbitMq(services, configuration, typeSearcher);-- //Register startup- var instancesAfter = startupConfigurations- .Where(PluginExtensions.OnlyInstalledPlugins)- .Select(startup => (IStartupApplication)Activator.CreateInstance(startup))- .Where(startup => !startup!.BeforeConfigure)- .OrderBy(startup => startup.Priority);-- //configure services- foreach (var instance in instancesAfter)- instance.ConfigureServices(services, configuration);-- //Execute startup interface- ExecuteStartupBase(typeSearcher);- }-- /// <summary>- /// Configure HTTP request pipeline- /// </summary>- /// <param name="application">Builder for configuring an application's request pipeline</param>- /// <param name="webHostEnvironment">WebHostEnvironment</param>- public static void ConfigureRequestPipeline(IApplicationBuilder application,- IWebHostEnvironment webHostEnvironment)- {- //find startup configurations provided by other assemblies- var typeSearcher = new TypeSearcher();- var startupConfigurations = typeSearcher.ClassesOfType<IStartupApplication>();-- //create and sort instances of startup configurations- var instances = startupConfigurations- .Where(PluginExtensions.OnlyInstalledPlugins)- .Select(startup => (IStartupApplication)Activator.CreateInstance(startup))- .OrderBy(startup => startup!.Priority);-- //configure request pipeline- foreach (var instance in instances)- instance.Configure(application, webHostEnvironment);- }-- private static void ExecuteStartupBase(ITypeSearcher typeSearcher)- {- var startupBaseConfigurations = typeSearcher.ClassesOfType<IStartupBase>();+ #region Methods++ /// <summary>+ /// Add and configure services+ /// </summary>+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="configuration">Configuration root of the application</param>+ public static void ConfigureServices(IServiceCollection services, IConfiguration configuration)+ {+ //find startup configurations provided by other assemblies+ var typeSearcher = new TypeSearcher();+ services.AddSingleton<ITypeSearcher>(typeSearcher);++ //register application+ var mvcBuilder = RegisterApplication(services, configuration, typeSearcher);++ //register extensions+ RegisterExtensions(mvcBuilder, configuration);++ var startupConfigurations = typeSearcher.ClassesOfType<IStartupApplication>();++ //Register startup+ var instancesBefore = startupConfigurations+ .Where(PluginExtensions.OnlyInstalledPlugins)+ .Select(startup => (IStartupApplication)Activator.CreateInstance(startup))+ .Where(startup => startup!.BeforeConfigure)+ .OrderBy(startup => startup.Priority);++ //configure services+ foreach (var instance in instancesBefore)+ instance.ConfigureServices(services, configuration);++ //register mapper configurations+ InitAutoMapper(typeSearcher);++ //Register custom type converters+ RegisterTypeConverter(typeSearcher);++ //Register type validator consumer+ RegisterValidatorConsumer(services, typeSearcher);- //create and sort instances of startup configurations- var instances = startupBaseConfigurations- .Select(startup => (IStartupBase)Activator.CreateInstance(startup))- .OrderBy(startup => startup!.Priority);+ //add mediator+ AddMediator(services, typeSearcher);- //execute- foreach (var instance in instances)- instance.Execute();- }+ //Add MassTransit+ AddMassTransitRabbitMq(services, configuration, typeSearcher);- #endregion+ //Register startup+ var instancesAfter = startupConfigurations+ .Where(PluginExtensions.OnlyInstalledPlugins)+ .Select(startup => (IStartupApplication)Activator.CreateInstance(startup))+ .Where(startup => !startup!.BeforeConfigure)+ .OrderBy(startup => startup.Priority);++ //configure services+ foreach (var instance in instancesAfter)+ instance.ConfigureServices(services, configuration);++ //Execute startup interface+ ExecuteStartupBase(typeSearcher);+ }++ /// <summary>+ /// Configure HTTP request pipeline+ /// </summary>+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ /// <param name="webHostEnvironment">WebHostEnvironment</param>+ public static void ConfigureRequestPipeline(IApplicationBuilder application,+ IWebHostEnvironment webHostEnvironment)+ {+ //find startup configurations provided by other assemblies+ var typeSearcher = new TypeSearcher();+ var startupConfigurations = typeSearcher.ClassesOfType<IStartupApplication>();++ //create and sort instances of startup configurations+ var instances = startupConfigurations+ .Where(PluginExtensions.OnlyInstalledPlugins)+ .Select(startup => (IStartupApplication)Activator.CreateInstance(startup))+ .OrderBy(startup => startup!.Priority);++ //configure request pipeline+ foreach (var instance in instances)+ instance.Configure(application, webHostEnvironment);}++ private static void ExecuteStartupBase(ITypeSearcher typeSearcher)+ {+ var startupBaseConfigurations = typeSearcher.ClassesOfType<IStartupBase>();++ //create and sort instances of startup configurations+ var instances = startupBaseConfigurations+ .Select(startup => (IStartupBase)Activator.CreateInstance(startup))+ .OrderBy(startup => startup!.Priority);++ //execute+ foreach (var instance in instances)+ instance.Execute();+ }++ #endregion}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/BoolTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/BoolTypeConverter.csindex 6d4d9d7b4..53ffa1313 100644--- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/BoolTypeConverter.cs+++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/BoolTypeConverter.cs@@ -1,21 +1,20 @@using System.ComponentModel;using System.Globalization;-namespace Grand.Infrastructure.TypeConverters.Converter+namespace Grand.Infrastructure.TypeConverters.Converter;++public class BoolTypeConverter : BooleanConverter{- public class BoolTypeConverter : BooleanConverter+ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value){- public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)+ try+ {+ var result = base.ConvertFrom(context, culture, value);+ return result;+ }+ catch (Exception){- try- {- var result = base.ConvertFrom(context, culture, value);- return result;- }- catch (Exception)- {- return false;- }+ return false;}}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/CustomAttributeListTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/CustomAttributeListTypeConverter.csindex 53078324c..d8d1a91a0 100644--- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/CustomAttributeListTypeConverter.cs+++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/CustomAttributeListTypeConverter.cs@@ -3,40 +3,38 @@ using System.ComponentModel;using System.Globalization;using System.Text.Json;-namespace Grand.Infrastructure.TypeConverters.Converter+namespace Grand.Infrastructure.TypeConverters.Converter;++public class CustomAttributeListTypeConverter : TypeConverter{- public class CustomAttributeListTypeConverter : TypeConverter+ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)+ {+ return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);+ }++ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value){- public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)+ if (value is not string valueStr) return base.ConvertFrom(context, culture, value);+ List<CustomAttribute> customAttributes = null;+ if (string.IsNullOrEmpty(valueStr)) return null;+ try{- return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);+ customAttributes = JsonSerializer.Deserialize<List<CustomAttribute>>(valueStr);}-- public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)+ catch{- if (value is not string valueStr) return base.ConvertFrom(context, culture, value);- List<CustomAttribute> customAttributes = null;- if (string.IsNullOrEmpty(valueStr)) return null;- try- {- customAttributes = JsonSerializer.Deserialize<List<CustomAttribute>>(valueStr);- }- catch- {- // ignored- }-- return customAttributes;+ // ignored}- public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)- {- if (destinationType == typeof(string))- {- return value is List<CustomAttribute> customAttributes ? JsonSerializer.Serialize(customAttributes) : "";- }+ return customAttributes;+ }- return base.ConvertTo(context, culture, value, destinationType);- }+ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,+ Type destinationType)+ {+ if (destinationType == typeof(string))+ return value is List<CustomAttribute> customAttributes ? JsonSerializer.Serialize(customAttributes) : "";++ return base.ConvertTo(context, culture, value, destinationType);}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericDictionaryTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericDictionaryTypeConverter.csindex eeaaea8a0..5a5ecc19e 100644--- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericDictionaryTypeConverter.cs+++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericDictionaryTypeConverter.cs@@ -1,99 +1,103 @@using System.ComponentModel;using System.Globalization;-namespace Grand.Infrastructure.TypeConverters.Converter+namespace Grand.Infrastructure.TypeConverters.Converter;++/// <summary>+/// Generic Dictionary type converted+/// </summary>+/// <typeparam name="K">Key type (simple)</typeparam>+/// <typeparam name="V">Value type (simple)</typeparam>+public class GenericDictionaryTypeConverter<K, V> : TypeConverter{+ private readonly TypeConverter _typeConverterKey;+ private readonly TypeConverter _typeConverterValue;+/// <summary>- /// Generic Dictionary type converted+ /// Ctor/// </summary>- /// <typeparam name="K">Key type (simple)</typeparam>- /// <typeparam name="V">Value type (simple)</typeparam>- public class GenericDictionaryTypeConverter<K, V> : TypeConverter+ public GenericDictionaryTypeConverter(){- private readonly TypeConverter _typeConverterKey;- private readonly TypeConverter _typeConverterValue;+ _typeConverterKey = TypeDescriptor.GetConverter(typeof(K));+ if (_typeConverterKey == null)+ throw new InvalidOperationException("No type converter exists for type " + typeof(K).FullName);+ _typeConverterValue = TypeDescriptor.GetConverter(typeof(V));+ if (_typeConverterValue == null)+ throw new InvalidOperationException("No type converter exists for type " + typeof(V).FullName);+ }- /// <summary>- /// Ctor- /// </summary>- public GenericDictionaryTypeConverter()- {- _typeConverterKey = TypeDescriptor.GetConverter(typeof(K));- if (_typeConverterKey == null)- throw new InvalidOperationException("No type converter exists for type " + typeof(K).FullName);- _typeConverterValue = TypeDescriptor.GetConverter(typeof(V));- if (_typeConverterValue == null)- throw new InvalidOperationException("No type converter exists for type " + typeof(V).FullName);- }+ /// <summary>+ /// Gets a value indicating whether this converter can+ /// convert an object in the given source type to the native type of the converter+ /// using the context.+ /// </summary>+ /// <param name="context">Context</param>+ /// <param name="sourceType">Source type</param>+ /// <returns>Result</returns>+ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)+ {+ return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);+ }- /// <summary>- /// Gets a value indicating whether this converter can- /// convert an object in the given source type to the native type of the converter- /// using the context.- /// </summary>- /// <param name="context">Context</param>- /// <param name="sourceType">Source type</param>- /// <returns>Result</returns>- public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)- {- return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);- }+ /// <summary>+ /// Converts the given object to the converter's native type.+ /// </summary>+ /// <param name="context">Context</param>+ /// <param name="culture">Culture</param>+ /// <param name="value">Value</param>+ /// <returns>Result</returns>+ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)+ {+ if (value is not string input) return base.ConvertFrom(context, culture, value);+ var items = string.IsNullOrEmpty(input)+ ? Array.Empty<string>()+ : input.Split(';').Select(x => x.Trim()).ToArray();- /// <summary>- /// Converts the given object to the converter's native type.- /// </summary>- /// <param name="context">Context</param>- /// <param name="culture">Culture</param>- /// <param name="value">Value</param>- /// <returns>Result</returns>- public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)+ var result = new Dictionary<K, V>();+ foreach (var s in items){- if (value is not string input) return base.ConvertFrom(context, culture, value);- var items = string.IsNullOrEmpty(input) ? Array.Empty<string>() : input.Split(';').Select(x => x.Trim()).ToArray();-- var result = new Dictionary<K, V>();- foreach (var s in items)- {- var keyValueStr = string.IsNullOrEmpty(s) ? Array.Empty<string>() : s.Split(',').Select(x => x.Trim()).ToArray();- if (keyValueStr.Length != 2) continue;- var dictionaryKey = _typeConverterKey.ConvertFromInvariantString(keyValueStr[0]);- var dictionaryValue = _typeConverterKey.ConvertFromInvariantString(keyValueStr[1]);- if (dictionaryKey == null || dictionaryValue == null) continue;- if (result.ContainsKey((K)dictionaryKey)) continue;- var itemValue = Convert.ChangeType(dictionaryValue, typeof(V));- result.Add((K)dictionaryKey, (V)itemValue);- }-- return result;+ var keyValueStr = string.IsNullOrEmpty(s)+ ? Array.Empty<string>()+ : s.Split(',').Select(x => x.Trim()).ToArray();+ if (keyValueStr.Length != 2) continue;+ var dictionaryKey = _typeConverterKey.ConvertFromInvariantString(keyValueStr[0]);+ var dictionaryValue = _typeConverterKey.ConvertFromInvariantString(keyValueStr[1]);+ if (dictionaryKey == null || dictionaryValue == null) continue;+ if (result.ContainsKey((K)dictionaryKey)) continue;+ var itemValue = Convert.ChangeType(dictionaryValue, typeof(V));+ result.Add((K)dictionaryKey, (V)itemValue);}- /// <summary>- /// Converts the given value object to the specified destination type using the specified context and arguments- /// </summary>- /// <param name="context">Context</param>- /// <param name="culture">Culture</param>- /// <param name="value">Value</param>- /// <param name="destinationType">Destination type</param>- /// <returns>Result</returns>- public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)- {- if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType);- var result = string.Empty;- if (value == null) return result;- //we don't use string.Join() because it doesn't support invariant culture- var counter = 0;- var dictionary = (IDictionary<K, V>)value;- foreach (var keyValue in dictionary)- {- result +=- $"{Convert.ToString(keyValue.Key, CultureInfo.InvariantCulture)},{Convert.ToString(keyValue.Value, CultureInfo.InvariantCulture)}";- //don't add ; after the last element- if (counter != dictionary.Count - 1)- result += ";";- counter++;- }- return result;+ return result;+ }+ /// <summary>+ /// Converts the given value object to the specified destination type using the specified context and arguments+ /// </summary>+ /// <param name="context">Context</param>+ /// <param name="culture">Culture</param>+ /// <param name="value">Value</param>+ /// <param name="destinationType">Destination type</param>+ /// <returns>Result</returns>+ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,+ Type destinationType)+ {+ if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType);+ var result = string.Empty;+ if (value == null) return result;+ //we don't use string.Join() because it doesn't support invariant culture+ var counter = 0;+ var dictionary = (IDictionary<K, V>)value;+ foreach (var keyValue in dictionary)+ {+ result +=+ $"{Convert.ToString(keyValue.Key, CultureInfo.InvariantCulture)},{Convert.ToString(keyValue.Value, CultureInfo.InvariantCulture)}";+ //don't add ; after the last element+ if (counter != dictionary.Count - 1)+ result += ";";+ counter++;}++ return result;}}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericListTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericListTypeConverter.csindex 791eed6d8..2b9334fa4 100644--- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericListTypeConverter.cs+++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/GenericListTypeConverter.cs@@ -1,103 +1,99 @@using System.ComponentModel;using System.Globalization;-namespace Grand.Infrastructure.TypeConverters.Converter+namespace Grand.Infrastructure.TypeConverters.Converter;++/// <summary>+/// Generic List type converted+/// </summary>+/// <typeparam name="T">Type</typeparam>+public class GenericListTypeConverter<T> : TypeConverter{/// <summary>- /// Generic List type converted+ /// Type converter+ /// </summary>+ private readonly TypeConverter _typeConverter;++ /// <summary>+ /// Ctor/// </summary>- /// <typeparam name="T">Type</typeparam>- public class GenericListTypeConverter<T> : TypeConverter+ public GenericListTypeConverter(){- /// <summary>- /// Type converter- /// </summary>- private readonly TypeConverter _typeConverter;+ _typeConverter = TypeDescriptor.GetConverter(typeof(T));+ if (_typeConverter == null)+ throw new InvalidOperationException("No type converter exists for type " + typeof(T).FullName);+ }- /// <summary>- /// Ctor- /// </summary>- public GenericListTypeConverter()- {- _typeConverter = TypeDescriptor.GetConverter(typeof(T));- if (_typeConverter == null)- throw new InvalidOperationException("No type converter exists for type " + typeof(T).FullName);- }+ /// <summary>+ /// Get string array from a comma-separate string+ /// </summary>+ /// <param name="input">Input</param>+ /// <returns>Array</returns>+ protected virtual string[] GetStringArray(string input)+ {+ return string.IsNullOrEmpty(input) ? Array.Empty<string>() : input.Split(',').Select(x => x.Trim()).ToArray();+ }- /// <summary>- /// Get string array from a comma-separate string- /// </summary>- /// <param name="input">Input</param>- /// <returns>Array</returns>- protected virtual string[] GetStringArray(string input)- {- return string.IsNullOrEmpty(input) ? Array.Empty<string>() : input.Split(',').Select(x => x.Trim()).ToArray();- }+ /// <summary>+ /// Gets a value indicating whether this converter can+ /// convert an object in the given source type to the native type of the converter+ /// using the context.+ /// </summary>+ /// <param name="context">Context</param>+ /// <param name="sourceType">Source type</param>+ /// <returns>Result</returns>+ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)+ {+ if (sourceType != typeof(string)) return base.CanConvertFrom(context, sourceType);+ var items = GetStringArray(sourceType.ToString());+ return items.Any();+ }- /// <summary>- /// Gets a value indicating whether this converter can- /// convert an object in the given source type to the native type of the converter- /// using the context.- /// </summary>- /// <param name="context">Context</param>- /// <param name="sourceType">Source type</param>- /// <returns>Result</returns>- public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)+ /// <summary>+ /// Converts the given object to the converter's native type.+ /// </summary>+ /// <param name="context">Context</param>+ /// <param name="culture">Culture</param>+ /// <param name="value">Value</param>+ /// <returns>Result</returns>+ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)+ {+ if (value is not string strValue) return base.ConvertFrom(context, culture, value);+ var items = GetStringArray(strValue);+ var result = new List<T>();+ Array.ForEach(items, s =>{- if (sourceType != typeof(string)) return base.CanConvertFrom(context, sourceType);- var items = GetStringArray(sourceType.ToString());- return items.Any();+ var item = _typeConverter.ConvertFromInvariantString(s);+ if (item != null) result.Add((T)item);+ });- }+ return result;+ }- /// <summary>- /// Converts the given object to the converter's native type.- /// </summary>- /// <param name="context">Context</param>- /// <param name="culture">Culture</param>- /// <param name="value">Value</param>- /// <returns>Result</returns>- public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)+ /// <summary>+ /// Converts the given value object to the specified destination type using the specified context and arguments+ /// </summary>+ /// <param name="context">Context</param>+ /// <param name="culture">Culture</param>+ /// <param name="value">Value</param>+ /// <param name="destinationType">Destination type</param>+ /// <returns>Result</returns>+ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,+ Type destinationType)+ {+ if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType);+ var result = string.Empty;+ if (value == null) return result;+ //we don't use string.Join() because it doesn't support invariant culture+ for (var i = 0; i < ((IList<T>)value).Count; i++){- if (value is not string strValue) return base.ConvertFrom(context, culture, value);- var items = GetStringArray(strValue);- var result = new List<T>();- Array.ForEach(items, s =>- {- var item = _typeConverter.ConvertFromInvariantString(s);- if (item != null)- {- result.Add((T)item);- }- });-- return result;+ var str1 = Convert.ToString(((IList<T>)value)[i], CultureInfo.InvariantCulture);+ result += str1;+ //don't add comma after the last element+ if (i != ((IList<T>)value).Count - 1)+ result += ",";}- /// <summary>- /// Converts the given value object to the specified destination type using the specified context and arguments- /// </summary>- /// <param name="context">Context</param>- /// <param name="culture">Culture</param>- /// <param name="value">Value</param>- /// <param name="destinationType">Destination type</param>- /// <returns>Result</returns>- public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)- {- if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType);- var result = string.Empty;- if (value == null) return result;- //we don't use string.Join() because it doesn't support invariant culture- for (var i = 0; i < ((IList<T>)value).Count; i++)- {- var str1 = Convert.ToString(((IList<T>)value)[i], CultureInfo.InvariantCulture);- result += str1;- //don't add comma after the last element- if (i != ((IList<T>)value).Count - 1)- result += ",";- }- return result;-- }+ return result;}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/RefreshTokenTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/RefreshTokenTypeConverter.csindex 1e2cfe604..f3cb301ae 100644--- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/RefreshTokenTypeConverter.cs+++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/RefreshTokenTypeConverter.cs@@ -3,41 +3,38 @@ using System.ComponentModel;using System.Globalization;using System.Text.Json;-namespace Grand.Infrastructure.TypeConverters.Converter+namespace Grand.Infrastructure.TypeConverters.Converter;++public class RefreshTokenTypeConverter : TypeConverter{- public class RefreshTokenTypeConverter : TypeConverter+ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType){- public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)+ return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);+ }++ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)+ {+ if (value is not string valueStr) return base.ConvertFrom(context, culture, value);+ RefreshToken refreshToken = null;+ if (string.IsNullOrEmpty(valueStr)) return null;+ try{- return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);+ refreshToken = JsonSerializer.Deserialize<RefreshToken>(valueStr);}-- public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)+ catch{- if (value is not string valueStr) return base.ConvertFrom(context, culture, value);- RefreshToken refreshToken = null;- if (string.IsNullOrEmpty(valueStr)) return null;- try- {- refreshToken = JsonSerializer.Deserialize<RefreshToken>(valueStr);- }- catch- {- //deserialize error- }- return refreshToken;+ //deserialize error}- public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)- {- if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType);- if (value is RefreshToken refreshToken)- {- return JsonSerializer.Serialize(refreshToken);- }+ return refreshToken;+ }- return "";+ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,+ Type destinationType)+ {+ if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType);+ if (value is RefreshToken refreshToken) return JsonSerializer.Serialize(refreshToken);- }+ return "";}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionListTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionListTypeConverter.csindex f214e0624..c6cc59197 100644--- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionListTypeConverter.cs+++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionListTypeConverter.cs@@ -3,39 +3,38 @@ using System.ComponentModel;using System.Globalization;using System.Text.Json;-namespace Grand.Infrastructure.TypeConverters.Converter+namespace Grand.Infrastructure.TypeConverters.Converter;++public class ShippingOptionListTypeConverter : TypeConverter{- public class ShippingOptionListTypeConverter : TypeConverter+ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType){- public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)+ return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);+ }++ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)+ {+ if (value is not string valueStr) return base.ConvertFrom(context, culture, value);+ List<ShippingOption> shippingOptions = null;+ if (string.IsNullOrEmpty(valueStr)) return null;+ try{- return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);+ shippingOptions = JsonSerializer.Deserialize<List<ShippingOption>>(valueStr);}-- public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)+ catch{- if (value is not string valueStr) return base.ConvertFrom(context, culture, value);- List<ShippingOption> shippingOptions = null;- if (string.IsNullOrEmpty(valueStr)) return null;- try- {- shippingOptions = JsonSerializer.Deserialize<List<ShippingOption>>(valueStr);- }- catch- {- //xml error- }- return shippingOptions;+ //xml error}- public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)- {- if (destinationType == typeof(string))- {- return value is List<ShippingOption> shippingOptions ? JsonSerializer.Serialize(shippingOptions) : "";- }+ return shippingOptions;+ }- return base.ConvertTo(context, culture, value, destinationType);- }+ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,+ Type destinationType)+ {+ if (destinationType == typeof(string))+ return value is List<ShippingOption> shippingOptions ? JsonSerializer.Serialize(shippingOptions) : "";++ return base.ConvertTo(context, culture, value, destinationType);}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionTypeConverter.csindex e662a16fa..0cd0a02fd 100644--- a/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionTypeConverter.cs+++ b/src/Core/Grand.Infrastructure/TypeConverters/Converter/ShippingOptionTypeConverter.cs@@ -3,41 +3,38 @@ using System.ComponentModel;using System.Globalization;using System.Text.Json;-namespace Grand.Infrastructure.TypeConverters.Converter+namespace Grand.Infrastructure.TypeConverters.Converter;++public class ShippingOptionTypeConverter : TypeConverter{- public class ShippingOptionTypeConverter : TypeConverter+ public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType){- public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)+ return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);+ }++ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)+ {+ if (value is not string valueStr) return base.ConvertFrom(context, culture, value);+ ShippingOption shippingOption = null;+ if (string.IsNullOrEmpty(valueStr)) return null;+ try{- return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);+ shippingOption = JsonSerializer.Deserialize<ShippingOption>(valueStr);}-- public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)+ catch{- if (value is not string valueStr) return base.ConvertFrom(context, culture, value);- ShippingOption shippingOption = null;- if (string.IsNullOrEmpty(valueStr)) return null;- try- {- shippingOption = JsonSerializer.Deserialize<ShippingOption>(valueStr);- }- catch- {- //deserialize error- }- return shippingOption;+ //deserialize error}- public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)- {- if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType);- if (value is ShippingOption shippingOption)- {- return JsonSerializer.Serialize(shippingOption);- }+ return shippingOption;+ }- return "";+ public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value,+ Type destinationType)+ {+ if (destinationType != typeof(string)) return base.ConvertTo(context, culture, value, destinationType);+ if (value is ShippingOption shippingOption) return JsonSerializer.Serialize(shippingOption);- }+ return "";}-}+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/TypeConverters/ITypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/ITypeConverter.csindex 132f464fb..0d66edba2 100644--- a/src/Core/Grand.Infrastructure/TypeConverters/ITypeConverter.cs+++ b/src/Core/Grand.Infrastructure/TypeConverters/ITypeConverter.cs@@ -1,15 +1,14 @@-namespace Grand.Infrastructure.TypeConverters+namespace Grand.Infrastructure.TypeConverters;++public interface ITypeConverter{- public interface ITypeConverter- {- /// <summary>- /// Register converter- /// </summary>- void Register();+ /// <summary>+ /// Gets order of this configuration implementation+ /// </summary>+ int Order { get; }- /// <summary>- /// Gets order of this configuration implementation- /// </summary>- int Order { get; }- }-}+ /// <summary>+ /// Register converter+ /// </summary>+ void Register();+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/InterfaceConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/InterfaceConverter.csindex c5c2a35b4..597722266 100644--- a/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/InterfaceConverter.cs+++ b/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/InterfaceConverter.cs@@ -7,14 +7,15 @@ public class InterfaceConverter<TInterface, TConcrete> : JsonConverter<TInterfac{public override TInterface Read(ref Utf8JsonReader reader,- Type typeToConvert,+ Type typeToConvert,JsonSerializerOptions options){return JsonSerializer.Deserialize<TConcrete>(ref reader, options);}+public override void Write(Utf8JsonWriter writer,- TInterface value,+ TInterface value,JsonSerializerOptions options){switch (value)@@ -36,14 +37,14 @@ public class CaptchaConverter : JsonConverter<ICaptchaValidModel>{public override ICaptchaValidModel Read(ref Utf8JsonReader reader,- Type typeToConvert,+ Type typeToConvert,JsonSerializerOptions options){return JsonSerializer.Deserialize<CaptchaModel>(ref reader, options);}public override void Write(Utf8JsonWriter writer,- ICaptchaValidModel value,+ ICaptchaValidModel value,JsonSerializerOptions options){switch (value)diff --git a/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/StringConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/StringConverter.csindex 8b4dfb37a..8b9023b50 100644--- a/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/StringConverter.cs+++ b/src/Core/Grand.Infrastructure/TypeConverters/JsonConverters/StringConverter.cs@@ -1,8 +1,9 @@using System.Text.Json;+using System.Text.Json.Serialization;namespace Grand.Infrastructure.TypeConverters.JsonConverters;-public class StringConverter : System.Text.Json.Serialization.JsonConverter<string>+public class StringConverter : JsonConverter<string>{public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options){@@ -20,13 +21,12 @@ public class StringConverter : System.Text.Json.Serialization.JsonConverter<stricase JsonTokenType.String:return reader.GetString();default:- throw new System.Text.Json.JsonException();+ throw new JsonException();}}-+public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options){writer.WriteStringValue(value);}-}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/TypeConverters/WebTypeConverter.cs b/src/Core/Grand.Infrastructure/TypeConverters/WebTypeConverter.csindex 43c4c4559..e7cdd5305 100644--- a/src/Core/Grand.Infrastructure/TypeConverters/WebTypeConverter.cs+++ b/src/Core/Grand.Infrastructure/TypeConverters/WebTypeConverter.cs@@ -1,35 +1,40 @@-using Grand.Infrastructure.TypeConverters.Converter;-using Grand.Domain.Common;+using Grand.Domain.Common;+using Grand.Domain.Security;using Grand.Domain.Shipping;+using Grand.Infrastructure.TypeConverters.Converter;using System.ComponentModel;-using Grand.Domain.Security;-namespace Grand.Infrastructure.TypeConverters+namespace Grand.Infrastructure.TypeConverters;++public class WebTypeConverter : ITypeConverter{- public class WebTypeConverter : ITypeConverter+ public void Register(){- public void Register()- {- TypeDescriptor.AddAttributes(typeof(bool), new TypeConverterAttribute(typeof(BoolTypeConverter)));-- //dictionaries- TypeDescriptor.AddAttributes(typeof(Dictionary<int, int>), new TypeConverterAttribute(typeof(GenericDictionaryTypeConverter<int, int>)));- TypeDescriptor.AddAttributes(typeof(Dictionary<string, bool>), new TypeConverterAttribute(typeof(GenericDictionaryTypeConverter<string, bool>)));-- //shipping option- TypeDescriptor.AddAttributes(typeof(ShippingOption), new TypeConverterAttribute(typeof(ShippingOptionTypeConverter)));- TypeDescriptor.AddAttributes(typeof(List<ShippingOption>), new TypeConverterAttribute(typeof(ShippingOptionListTypeConverter)));- TypeDescriptor.AddAttributes(typeof(IList<ShippingOption>), new TypeConverterAttribute(typeof(ShippingOptionListTypeConverter)));-- //custom attributes- TypeDescriptor.AddAttributes(typeof(List<CustomAttribute>), new TypeConverterAttribute(typeof(CustomAttributeListTypeConverter)));- TypeDescriptor.AddAttributes(typeof(IList<CustomAttribute>), new TypeConverterAttribute(typeof(CustomAttributeListTypeConverter)));-- TypeDescriptor.AddAttributes(typeof(RefreshToken), new TypeConverterAttribute(typeof(RefreshTokenTypeConverter)));--- }-- public int Order => 0;+ TypeDescriptor.AddAttributes(typeof(bool), new TypeConverterAttribute(typeof(BoolTypeConverter)));++ //dictionaries+ TypeDescriptor.AddAttributes(typeof(Dictionary<int, int>),+ new TypeConverterAttribute(typeof(GenericDictionaryTypeConverter<int, int>)));+ TypeDescriptor.AddAttributes(typeof(Dictionary<string, bool>),+ new TypeConverterAttribute(typeof(GenericDictionaryTypeConverter<string, bool>)));++ //shipping option+ TypeDescriptor.AddAttributes(typeof(ShippingOption),+ new TypeConverterAttribute(typeof(ShippingOptionTypeConverter)));+ TypeDescriptor.AddAttributes(typeof(List<ShippingOption>),+ new TypeConverterAttribute(typeof(ShippingOptionListTypeConverter)));+ TypeDescriptor.AddAttributes(typeof(IList<ShippingOption>),+ new TypeConverterAttribute(typeof(ShippingOptionListTypeConverter)));++ //custom attributes+ TypeDescriptor.AddAttributes(typeof(List<CustomAttribute>),+ new TypeConverterAttribute(typeof(CustomAttributeListTypeConverter)));+ TypeDescriptor.AddAttributes(typeof(IList<CustomAttribute>),+ new TypeConverterAttribute(typeof(CustomAttributeListTypeConverter)));++ TypeDescriptor.AddAttributes(typeof(RefreshToken),+ new TypeConverterAttribute(typeof(RefreshTokenTypeConverter)));}-}++ public int Order => 0;+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/TypeSearch/ITypeSearcher.cs b/src/Core/Grand.Infrastructure/TypeSearch/ITypeSearcher.csindex 5da89d861..7f396558f 100644--- a/src/Core/Grand.Infrastructure/TypeSearch/ITypeSearcher.cs+++ b/src/Core/Grand.Infrastructure/TypeSearch/ITypeSearcher.cs@@ -1,19 +1,18 @@using System.Reflection;-namespace Grand.Infrastructure.TypeSearch-{- /// <summary>- /// Classes implementing this interface provide information about types- /// </summary>- public interface ITypeSearcher- {- IList<Assembly> GetAssemblies();+namespace Grand.Infrastructure.TypeSearch;- IEnumerable<Type> ClassesOfType(Type assignTypeFrom, bool onlyConcreteClasses = true);+/// <summary>+/// Classes implementing this interface provide information about types+/// </summary>+public interface ITypeSearcher+{+ IList<Assembly> GetAssemblies();- IEnumerable<Type> ClassesOfType(Type assignTypeFrom, IEnumerable<Assembly> assemblies, bool onlyConcreteClasses = true);+ IEnumerable<Type> ClassesOfType(Type assignTypeFrom, bool onlyConcreteClasses = true);- IEnumerable<Type> ClassesOfType<T>(bool onlyConcreteClasses = true);+ IEnumerable<Type> ClassesOfType(Type assignTypeFrom, IEnumerable<Assembly> assemblies,+ bool onlyConcreteClasses = true);- }-}+ IEnumerable<Type> ClassesOfType<T>(bool onlyConcreteClasses = true);+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/TypeSearch/TypeSearcher.cs b/src/Core/Grand.Infrastructure/TypeSearch/TypeSearcher.csindex 9b671985d..ef1292018 100644--- a/src/Core/Grand.Infrastructure/TypeSearch/TypeSearcher.cs+++ b/src/Core/Grand.Infrastructure/TypeSearch/TypeSearcher.cs@@ -1,133 +1,131 @@-using System.Diagnostics;+using Grand.Infrastructure.Roslyn;+using System.Diagnostics;using System.Reflection;-namespace Grand.Infrastructure.TypeSearch+namespace Grand.Infrastructure.TypeSearch;++/// <summary>+/// A class that finds types needed by looping assemblies in the+/// currently executing AppDomain.+/// </summary>+public class TypeSearcher : ITypeSearcher{- /// <summary>- /// A class that finds types needed by looping assemblies in the- /// currently executing AppDomain.- /// </summary>- public class TypeSearcher : ITypeSearcher- {- #region Methods+ #region Utilities- public IEnumerable<Type> ClassesOfType<T>(bool onlyConcreteClasses = true)+ private static IList<Assembly> AssembliesInAppDomain()+ {+ var addedAssemblyNames = new List<string>();+ var assemblies = new List<Assembly>();+ var currentAssem = Assembly.GetExecutingAssembly();+ foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()){- return ClassesOfType(typeof(T), onlyConcreteClasses);+ var product = assembly.GetCustomAttribute<AssemblyProductAttribute>();+ var referencedAssemblies = assembly.GetReferencedAssemblies().ToList();+ if (referencedAssemblies.All(x => x.FullName != currentAssem.FullName) &&+ product?.Product != "grandnode") continue;+ if (addedAssemblyNames.Contains(assembly.FullName)) continue;+ assemblies.Add(assembly);+ addedAssemblyNames.Add(assembly.FullName);}- public IEnumerable<Type> ClassesOfType(Type assignTypeFrom, bool onlyConcreteClasses = true)+ //add scripts+ if (RoslynCompiler.ReferencedScripts == null) return assemblies;+ foreach (var scripts in RoslynCompiler.ReferencedScripts){- return ClassesOfType(assignTypeFrom, GetAssemblies(), onlyConcreteClasses);+ if (string.IsNullOrEmpty(scripts.ReferencedAssembly.FullName)) continue;+ if (addedAssemblyNames.Contains(scripts.ReferencedAssembly.FullName)) continue;+ assemblies.Add(scripts.ReferencedAssembly);+ addedAssemblyNames.Add(scripts.ReferencedAssembly.FullName);}- public IEnumerable<Type> ClassesOfType(Type assignTypeFrom, IEnumerable<Assembly> assemblies,- bool onlyConcreteClasses = true)+ return assemblies;+ }++ #endregion++ #region Methods++ public IEnumerable<Type> ClassesOfType<T>(bool onlyConcreteClasses = true)+ {+ return ClassesOfType(typeof(T), onlyConcreteClasses);+ }++ public IEnumerable<Type> ClassesOfType(Type assignTypeFrom, bool onlyConcreteClasses = true)+ {+ return ClassesOfType(assignTypeFrom, GetAssemblies(), onlyConcreteClasses);+ }++ public IEnumerable<Type> ClassesOfType(Type assignTypeFrom, IEnumerable<Assembly> assemblies,+ bool onlyConcreteClasses = true)+ {+ var result = new List<Type>();+ try{- var result = new List<Type>();- try+ foreach (var a in assemblies){- foreach (var a in assemblies)+ var types = a.GetTypes();+ foreach (var t in types){- Type[] types = a.GetTypes();- foreach (var t in types)+ if (!assignTypeFrom.IsAssignableFrom(t) && (!assignTypeFrom.IsGenericTypeDefinition ||+ !DoesTypeImplementOpenGeneric(t, assignTypeFrom)))+ continue;++ if (t.IsInterface)+ continue;++ if (onlyConcreteClasses){- if (!assignTypeFrom.IsAssignableFrom(t) && (!assignTypeFrom.IsGenericTypeDefinition ||- !DoesTypeImplementOpenGeneric(t, assignTypeFrom)))- continue;-- if (t.IsInterface)- continue;-- if (onlyConcreteClasses)- {- if (t.IsClass && !t.IsAbstract)- {- result.Add(t);- }- }- else- {- result.Add(t);- }+ if (t.IsClass && !t.IsAbstract) result.Add(t);+ }+ else+ {+ result.Add(t);}}}- catch (ReflectionTypeLoadException ex)- {- var msg = ex.LoaderExceptions.Aggregate(string.Empty,- (current, e) => current + e!.Message + Environment.NewLine);-- var fail = new Exception(msg, ex);- Debug.WriteLine(fail.Message, fail);-- throw fail;- }-- return result;}- /// <summary>- /// Does type implement generic?- /// </summary>- /// <param name="type"></param>- /// <param name="openGeneric"></param>- /// <returns></returns>- private static bool DoesTypeImplementOpenGeneric(Type type, Type openGeneric)+ catch (ReflectionTypeLoadException ex){- try- {- var genericTypeDefinition = openGeneric.GetGenericTypeDefinition();- return (from implementedInterface in type.FindInterfaces((_, _) => true, null)- where implementedInterface.IsGenericType- select genericTypeDefinition.IsAssignableFrom(implementedInterface.GetGenericTypeDefinition()))- .FirstOrDefault();- }- catch- {- return false;- }- }+ var msg = ex.LoaderExceptions.Aggregate(string.Empty,+ (current, e) => current + e!.Message + Environment.NewLine);- /// <summary>Gets the assemblies related to the current implementation.</summary>- /// <returns>A list of assemblies that should be loaded by the Grand factory.</returns>- public virtual IList<Assembly> GetAssemblies()- {- return AssembliesInAppDomain();- }+ var fail = new Exception(msg, ex);+ Debug.WriteLine(fail.Message, fail);- #endregion+ throw fail;+ }- #region Utilities+ return result;+ }- private static IList<Assembly> AssembliesInAppDomain()+ /// <summary>+ /// Does type implement generic?+ /// </summary>+ /// <param name="type"></param>+ /// <param name="openGeneric"></param>+ /// <returns></returns>+ private static bool DoesTypeImplementOpenGeneric(Type type, Type openGeneric)+ {+ try{- var addedAssemblyNames = new List<string>();- var assemblies = new List<Assembly>();- var currentAssem = Assembly.GetExecutingAssembly();- foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())- {- var product = assembly.GetCustomAttribute<AssemblyProductAttribute>();- var referencedAssemblies = assembly.GetReferencedAssemblies().ToList();- if (referencedAssemblies.All(x => x.FullName != currentAssem.FullName) &&- product?.Product != "grandnode") continue;- if (addedAssemblyNames.Contains(assembly.FullName)) continue;- assemblies.Add(assembly);- addedAssemblyNames.Add(assembly.FullName);- }-- //add scripts- if (Roslyn.RoslynCompiler.ReferencedScripts == null) return assemblies;- foreach (var scripts in Roslyn.RoslynCompiler.ReferencedScripts)- {- if (string.IsNullOrEmpty(scripts.ReferencedAssembly.FullName)) continue;- if (addedAssemblyNames.Contains(scripts.ReferencedAssembly.FullName)) continue;- assemblies.Add(scripts.ReferencedAssembly);- addedAssemblyNames.Add(scripts.ReferencedAssembly.FullName);- }-- return assemblies;+ var genericTypeDefinition = openGeneric.GetGenericTypeDefinition();+ return (from implementedInterface in type.FindInterfaces((_, _) => true, null)+ where implementedInterface.IsGenericType+ select genericTypeDefinition.IsAssignableFrom(implementedInterface.GetGenericTypeDefinition()))+ .FirstOrDefault();+ }+ catch+ {+ return false;}+ }- #endregion+ /// <summary>Gets the assemblies related to the current implementation.</summary>+ /// <returns>A list of assemblies that should be loaded by the Grand factory.</returns>+ public virtual IList<Assembly> GetAssemblies()+ {+ return AssembliesInAppDomain();}++ #endregion}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Validators/BaseGrandValidator.cs b/src/Core/Grand.Infrastructure/Validators/BaseGrandValidator.csindex 53d241fb7..8f662d7a6 100644--- a/src/Core/Grand.Infrastructure/Validators/BaseGrandValidator.cs+++ b/src/Core/Grand.Infrastructure/Validators/BaseGrandValidator.cs@@ -1,25 +1,16 @@using FluentValidation;-namespace Grand.Infrastructure.Validators+namespace Grand.Infrastructure.Validators;++public abstract class BaseGrandValidator<T> : AbstractValidator<T> where T : class{- public abstract class BaseGrandValidator<T> : AbstractValidator<T> where T : class+ protected BaseGrandValidator(IEnumerable<IValidatorConsumer<T>> validators){-- protected BaseGrandValidator(IEnumerable<IValidatorConsumer<T>> validators)- {- PostInitialize(validators);- }-- private void PostInitialize(IEnumerable<IValidatorConsumer<T>> validators)- {- foreach (var item in validators)- {- item.AddRules(this);- }-- }-+ PostInitialize(validators);}-+ private void PostInitialize(IEnumerable<IValidatorConsumer<T>> validators)+ {+ foreach (var item in validators) item.AddRules(this);+ }}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Validators/IValidatorConsumer.cs b/src/Core/Grand.Infrastructure/Validators/IValidatorConsumer.csindex 4f69bbb1a..feb893fd0 100644--- a/src/Core/Grand.Infrastructure/Validators/IValidatorConsumer.cs+++ b/src/Core/Grand.Infrastructure/Validators/IValidatorConsumer.cs@@ -1,7 +1,6 @@-namespace Grand.Infrastructure.Validators+namespace Grand.Infrastructure.Validators;++public interface IValidatorConsumer<T> where T : class{- public interface IValidatorConsumer<T> where T : class- {- void AddRules(BaseGrandValidator<T> validator);- }-}+ void AddRules(BaseGrandValidator<T> validator);+}\ No newline at end of filediff --git a/src/Core/Grand.Infrastructure/Validators/ValidationFilter.cs b/src/Core/Grand.Infrastructure/Validators/ValidationFilter.csindex 0b0681c30..0f23e2a6b 100644--- a/src/Core/Grand.Infrastructure/Validators/ValidationFilter.cs+++ b/src/Core/Grand.Infrastructure/Validators/ValidationFilter.cs@@ -4,74 +4,68 @@ using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;-namespace Grand.Infrastructure.Validators+namespace Grand.Infrastructure.Validators;++public class ValidationFilter : IAsyncActionFilter{- public class ValidationFilter : IAsyncActionFilter- {- #region Fields+ #region Fields- private readonly IServiceProvider _serviceProvider;+ private readonly IServiceProvider _serviceProvider;- #endregion+ #endregion- #region Ctor+ #region Ctor- public ValidationFilter(IServiceProvider serviceProvider)- {- _serviceProvider = serviceProvider;- }+ public ValidationFilter(IServiceProvider serviceProvider)+ {+ _serviceProvider = serviceProvider;+ }- #endregion+ #endregion- #region Methods+ #region Methods- /// <summary>- /// Called before the action executes, after model binding is complete- /// </summary>- /// <param name="context">A context for action filters</param>- /// <param name="next"></param>- public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)+ /// <summary>+ /// Called before the action executes, after model binding is complete+ /// </summary>+ /// <param name="context">A context for action filters</param>+ /// <param name="next"></param>+ public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)+ {+ //only in POST requests+ if (!HttpMethods.IsPost(context.HttpContext.Request.Method)){- //only in POST requests- if (!HttpMethods.IsPost(context.HttpContext.Request.Method))- {- await next();- return;- }+ await next();+ return;+ }- foreach (var argument in context.ActionArguments.Where(x => !CommonHelper.IsSimpleType(x.Value?.GetType())))+ foreach (var argument in context.ActionArguments.Where(x => !CommonHelper.IsSimpleType(x.Value?.GetType())))+ {+ var targetType = argument.Value!.GetType();+ var implementedInterfaces = new[] { targetType }.Concat(targetType.GetInterfaces()).ToArray();+ foreach (var interfaceType in implementedInterfaces){- Type targetType = argument.Value!.GetType();- Type[] implementedInterfaces = new[] { targetType }.Concat(targetType.GetInterfaces()).ToArray();- foreach (Type interfaceType in implementedInterfaces)- {- Type genericType = typeof(IValidator<>).MakeGenericType(interfaceType);- var validator = (IValidator)_serviceProvider.GetService(genericType);- if (validator is null)- {- continue;- }+ var genericType = typeof(IValidator<>).MakeGenericType(interfaceType);+ var validator = (IValidator)_serviceProvider.GetService(genericType);+ if (validator is null) continue;- var contextValidator = new ValidationContext<object>(argument.Value);- var result = await validator.ValidateAsync(contextValidator);- if (result.IsValid) continue;- foreach (var error in result.Errors)- {- context.ModelState.AddModelError(error.PropertyName, error.ErrorMessage);- }- }- }-- var hasJsonData = context.HttpContext.Request.ContentType?.Contains("application/json") ?? false;- if (hasJsonData && !context.ModelState.IsValid)- {- context.Result = new BadRequestObjectResult(context.ModelState);- return;+ var contextValidator = new ValidationContext<object>(argument.Value);+ var result = await validator.ValidateAsync(contextValidator);+ if (result.IsValid) continue;+ foreach (var error in result.Errors)+ context.ModelState.AddModelError(error.PropertyName, error.ErrorMessage);}+ }- await next();+ var hasJsonData = context.HttpContext.Request.ContentType?.Contains("application/json") ?? false;+ if (hasJsonData && !context.ModelState.IsValid)+ {+ context.Result = new BadRequestObjectResult(context.ModelState);+ return;}- #endregion+ await next();}++ #endregion}\ No newline at end of file