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.Web.Common - Code cleanup
supportdea7443e24bf
diff --git a/src/Web/Grand.Web.Common/Binders/CustomAttributesBinder.cs b/src/Web/Grand.Web.Common/Binders/CustomAttributesBinder.csindex 1ee0e6cff..2e71b51d3 100644--- a/src/Web/Grand.Web.Common/Binders/CustomAttributesBinder.cs+++ b/src/Web/Grand.Web.Common/Binders/CustomAttributesBinder.cs@@ -8,23 +8,19 @@ public class CustomAttributesBinder : IModelBinder{public Task BindModelAsync(ModelBindingContext bindingContext){- if (bindingContext == null)- {- throw new ArgumentNullException(nameof(bindingContext));- }+ if (bindingContext == null) throw new ArgumentNullException(nameof(bindingContext));if (bindingContext.HttpContext.Request.HasFormContentType){var model = new List<CustomAttributeModel>();var formCollection = bindingContext.HttpContext.Request.Form;foreach (var form in formCollection)- {if (form.Key.StartsWith("attributes"))model.Add(new CustomAttributeModel { Key = GetKey(form.Key), Value = form.Value });- }bindingContext.Result = ModelBindingResult.Success(model);}+return Task.CompletedTask;}@@ -32,11 +28,8 @@ public class CustomAttributesBinder : IModelBinder{var regex = new Regex("\\[(?<Value>\\w+)\\]");string value = null;- Match match = regex.Match(key);- if (match.Success)- {- value = match.Groups["Value"].Value;- }+ var match = regex.Match(key);+ if (match.Success) value = match.Groups["Value"].Value;return value;}diff --git a/src/Web/Grand.Web.Common/Binders/CustomAttributesBinderProvider.cs b/src/Web/Grand.Web.Common/Binders/CustomAttributesBinderProvider.csindex 203d8ffe3..8de9ba1c8 100644--- a/src/Web/Grand.Web.Common/Binders/CustomAttributesBinderProvider.cs+++ b/src/Web/Grand.Web.Common/Binders/CustomAttributesBinderProvider.cs@@ -9,6 +9,8 @@ public class CustomAttributesBinderProvider : IModelBinderProviderpublic IModelBinder GetBinder(ModelBinderProviderContext context){ArgumentNullException.ThrowIfNull(context);- return context.Metadata.ModelType == typeof(IList<CustomAttributeModel>) ? new BinderTypeModelBinder(typeof(CustomAttributesBinder)) : null;+ return context.Metadata.ModelType == typeof(IList<CustomAttributeModel>)+ ? new BinderTypeModelBinder(typeof(CustomAttributesBinder))+ : null;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Components/BaseAdminViewComponent.cs b/src/Web/Grand.Web.Common/Components/BaseAdminViewComponent.csindex f4a3a08fe..998bb2581 100644--- a/src/Web/Grand.Web.Common/Components/BaseAdminViewComponent.cs+++ b/src/Web/Grand.Web.Common/Components/BaseAdminViewComponent.cs@@ -1,23 +1,22 @@using Microsoft.AspNetCore.Mvc;-namespace Grand.Web.Common.Components+namespace Grand.Web.Common.Components;++[Area("Admin")]+public abstract class BaseAdminViewComponent : ViewComponent{- [Area("Admin")]- public abstract class BaseAdminViewComponent : ViewComponent+ public new IViewComponentResult View<TModel>(string viewName, TModel model){- public new IViewComponentResult View<TModel>(string viewName, TModel model)- {- return base.View<TModel>(viewName, model);- }+ return base.View(viewName, model);+ }- public new IViewComponentResult View<TModel>(TModel model)- {- return base.View<TModel>(model);- }+ public new IViewComponentResult View<TModel>(TModel model)+ {+ return base.View(model);+ }- public new IViewComponentResult View(string viewName)- {- return base.View(viewName);- }+ public new IViewComponentResult View(string viewName)+ {+ return base.View(viewName);}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Components/BaseVendorViewComponent.cs b/src/Web/Grand.Web.Common/Components/BaseVendorViewComponent.csindex 2397a49b3..eff2a9431 100644--- a/src/Web/Grand.Web.Common/Components/BaseVendorViewComponent.cs+++ b/src/Web/Grand.Web.Common/Components/BaseVendorViewComponent.cs@@ -1,23 +1,22 @@using Microsoft.AspNetCore.Mvc;-namespace Grand.Web.Common.Components+namespace Grand.Web.Common.Components;++[Area("Vendor")]+public abstract class BaseVendorViewComponent : ViewComponent{- [Area("Vendor")]- public abstract class BaseVendorViewComponent : ViewComponent+ public new IViewComponentResult View<TModel>(string viewName, TModel model){- public new IViewComponentResult View<TModel>(string viewName, TModel model)- {- return base.View<TModel>(viewName, model);- }+ return base.View(viewName, model);+ }- public new IViewComponentResult View<TModel>(TModel model)- {- return base.View<TModel>(model);- }+ public new IViewComponentResult View<TModel>(TModel model)+ {+ return base.View(model);+ }- public new IViewComponentResult View(string viewName)- {- return base.View(viewName);- }+ public new IViewComponentResult View(string viewName)+ {+ return base.View(viewName);}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Components/BaseViewComponent.cs b/src/Web/Grand.Web.Common/Components/BaseViewComponent.csindex 1a036485e..e062b662b 100644--- a/src/Web/Grand.Web.Common/Components/BaseViewComponent.cs+++ b/src/Web/Grand.Web.Common/Components/BaseViewComponent.cs@@ -1,27 +1,24 @@using Microsoft.AspNetCore.Mvc;using System.Text.Json;-namespace Grand.Web.Common.Components+namespace Grand.Web.Common.Components;++public abstract class BaseViewComponent : ViewComponent{- public abstract class BaseViewComponent : ViewComponent+ public new IViewComponentResult View<TModel>(string viewName, TModel model){- public new IViewComponentResult View<TModel>(string viewName, TModel model)- {- return base.View<TModel>(viewName, model);- }+ return base.View(viewName, model);+ }- public new IViewComponentResult View<TModel>(TModel model)- {- if(Request?.ContentType == "application/json")- {- return new JsonContentViewComponentResult(JsonSerializer.Serialize(model));- }- return base.View<TModel>(model);- }+ public new IViewComponentResult View<TModel>(TModel model)+ {+ if (Request?.ContentType == "application/json")+ return new JsonContentViewComponentResult(JsonSerializer.Serialize(model));+ return base.View(model);+ }- public new IViewComponentResult View(string viewName)- {- return base.View(viewName);- }+ public new IViewComponentResult View(string viewName)+ {+ return base.View(viewName);}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Components/JsonContentViewComponentResult.cs b/src/Web/Grand.Web.Common/Components/JsonContentViewComponentResult.csindex 2b75bf704..1e776e76b 100644--- a/src/Web/Grand.Web.Common/Components/JsonContentViewComponentResult.cs+++ b/src/Web/Grand.Web.Common/Components/JsonContentViewComponentResult.cs@@ -5,54 +5,53 @@ using Microsoft.AspNetCore.Html;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.ViewComponents;-namespace Grand.Web.Common.Components+namespace Grand.Web.Common.Components;++/// <summary>+/// An <see cref="IViewComponentResult" /> which writes an <see cref="IHtmlContent" /> when executed.+/// </summary>+/// <remarks>+/// The provided content will be HTML-encoded as specified when the content was created. To encoded and write+/// text, use a <see cref="ContentViewComponentResult" />.+/// </remarks>+public class JsonContentViewComponentResult : IViewComponentResult{/// <summary>- /// An <see cref="IViewComponentResult"/> which writes an <see cref="IHtmlContent"/> when executed.+ /// Initializes a new <see cref="HtmlContentViewComponentResult" />./// </summary>- /// <remarks>- /// The provided content will be HTML-encoded as specified when the content was created. To encoded and write- /// text, use a <see cref="ContentViewComponentResult"/>.- /// </remarks>- public class JsonContentViewComponentResult : IViewComponentResult+ public JsonContentViewComponentResult(string content){- /// <summary>- /// Initializes a new <see cref="HtmlContentViewComponentResult"/>.- /// </summary>- public JsonContentViewComponentResult(string content)- {- EncodedContent = content ?? throw new ArgumentNullException(nameof(content));- }+ EncodedContent = content ?? throw new ArgumentNullException(nameof(content));+ }- /// <summary>- /// Gets the encoded content.- /// </summary>- public string EncodedContent { get; }+ /// <summary>+ /// Gets the encoded content.+ /// </summary>+ public string EncodedContent { get; }- /// <summary>- /// Set content type for response- /// </summary>- /// <param name="context"></param>- private static void ContentType(ViewComponentContext context)- {- context.ViewContext.HttpContext.Response.ContentType = "application/json";- }+ public void Execute(ViewComponentContext context)+ {+ ContentType(context);+ context.Writer.Write(EncodedContent);+ }- public void Execute(ViewComponentContext context)- {- ContentType(context);- context.Writer.Write(EncodedContent);- }+ /// <summary>+ /// Writes the <see cref="EncodedContent" />.+ /// </summary>+ /// <param name="context">The <see cref="ViewComponentContext" />.</param>+ /// <returns>A completed <see cref="Task" />.</returns>+ public async Task ExecuteAsync(ViewComponentContext context)+ {+ ContentType(context);+ await context.Writer.WriteAsync(EncodedContent);+ }- /// <summary>- /// Writes the <see cref="EncodedContent"/>.- /// </summary>- /// <param name="context">The <see cref="ViewComponentContext"/>.</param>- /// <returns>A completed <see cref="Task"/>.</returns>- public async Task ExecuteAsync(ViewComponentContext context)- {- ContentType(context);- await context.Writer.WriteAsync(EncodedContent);- }+ /// <summary>+ /// Set content type for response+ /// </summary>+ /// <param name="context"></param>+ private static void ContentType(ViewComponentContext context)+ {+ context.ViewContext.HttpContext.Response.ContentType = "application/json";}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Controllers/BaseAdminPluginController.cs b/src/Web/Grand.Web.Common/Controllers/BaseAdminPluginController.csindex 533affdfa..2a32183d0 100644--- a/src/Web/Grand.Web.Common/Controllers/BaseAdminPluginController.cs+++ b/src/Web/Grand.Web.Common/Controllers/BaseAdminPluginController.cs@@ -1,15 +1,14 @@using Grand.Web.Common.Filters;using Microsoft.AspNetCore.Mvc;-namespace Grand.Web.Common.Controllers+namespace Grand.Web.Common.Controllers;++/// <summary>+/// Base controller for plugins+/// </summary>+[AuthorizeAdmin]+[Area("Admin")]+[AuthorizeMenu]+public abstract class BaseAdminPluginController : BaseController{- /// <summary>- /// Base controller for plugins- /// </summary>- [AuthorizeAdmin]- [Area("Admin")]- [AuthorizeMenu]- public abstract class BaseAdminPluginController : BaseController- {- }}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Controllers/BaseController.cs b/src/Web/Grand.Web.Common/Controllers/BaseController.csindex bb3e0fc27..075f3b01b 100644--- a/src/Web/Grand.Web.Common/Controllers/BaseController.cs+++ b/src/Web/Grand.Web.Common/Controllers/BaseController.cs@@ -13,223 +13,220 @@ using Microsoft.AspNetCore.Mvc.ModelBinding;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;-namespace Grand.Web.Common.Controllers+namespace Grand.Web.Common.Controllers;++/// <summary>+/// Base controller+/// </summary>+[PasswordExpired]+[CustomerActivity]+public abstract class BaseController : Controller{- /// <summary>- /// Base controller- /// </summary>- [PasswordExpired]- [CustomerActivity]- public abstract class BaseController : Controller+ public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next){+ // event notification before execute+ var mediator = context.HttpContext.RequestServices.GetService<IMediator>();+ await mediator.Publish(new ActionExecutingContextNotification(context, true));- #region Notifications+ await next();- /// <summary>- /// Display success notification- /// </summary>- /// <param name="message">Message</param>- /// <param name="persistNextRequest">A value indicating whether a message should be persisted for the next request</param>- protected void Success(string message, bool persistNextRequest = true)- {- Notification(NotifyType.Success, message, persistNextRequest);- }+ //event notification after execute+ await mediator.Publish(new ActionExecutingContextNotification(context, false));+ }- /// <summary>- /// Display warning notification- /// </summary>- /// <param name="message">Message</param>- /// <param name="persistNextRequest">A value indicating whether a message should be persisted for the next request</param>- protected void Warning(string message, bool persistNextRequest = true)- {- Notification(NotifyType.Warning, message, persistNextRequest);- }+ #region Notifications- /// <summary>- /// Display error notification- /// </summary>- /// <param name="message">Message</param>- /// <param name="persistNextRequest">A value indicating whether a message should be persisted for the next request</param>- protected void Error(string message, bool persistNextRequest = true)- {- Notification(NotifyType.Error, message, persistNextRequest);- }+ /// <summary>+ /// Display success notification+ /// </summary>+ /// <param name="message">Message</param>+ /// <param name="persistNextRequest">A value indicating whether a message should be persisted for the next request</param>+ protected void Success(string message, bool persistNextRequest = true)+ {+ Notification(NotifyType.Success, message, persistNextRequest);+ }- /// <summary>- /// Display error notification- /// </summary>- /// <param name="modelState">Model state</param>- /// <param name="persistNextRequest">A value indicating whether a message should be persisted for the next request</param>- protected void Error(ModelStateDictionary modelState, bool persistNextRequest = true)- {- var modelErrors = new List<string>();- foreach (var value in modelState.Values)- {- modelErrors.AddRange(value.Errors.Select(modelError => modelError.ErrorMessage));- }- Notification(NotifyType.Error, string.Join(',', modelErrors), persistNextRequest);- }+ /// <summary>+ /// Display warning notification+ /// </summary>+ /// <param name="message">Message</param>+ /// <param name="persistNextRequest">A value indicating whether a message should be persisted for the next request</param>+ protected void Warning(string message, bool persistNextRequest = true)+ {+ Notification(NotifyType.Warning, message, persistNextRequest);+ }- /// <summary>- /// Display error notification- /// </summary>- /// <param name="exception">Exception</param>- /// <param name="persistNextRequest">A value indicating whether a message should be persisted for the next request</param>- /// <param name="logException">A value indicating whether exception should be logged</param>- protected void Error(Exception exception, bool persistNextRequest = true, bool logException = true)- {- if (logException)- LogException(exception);+ /// <summary>+ /// Display error notification+ /// </summary>+ /// <param name="message">Message</param>+ /// <param name="persistNextRequest">A value indicating whether a message should be persisted for the next request</param>+ protected void Error(string message, bool persistNextRequest = true)+ {+ Notification(NotifyType.Error, message, persistNextRequest);+ }- Notification(NotifyType.Error, exception.Message, persistNextRequest);- }+ /// <summary>+ /// Display error notification+ /// </summary>+ /// <param name="modelState">Model state</param>+ /// <param name="persistNextRequest">A value indicating whether a message should be persisted for the next request</param>+ protected void Error(ModelStateDictionary modelState, bool persistNextRequest = true)+ {+ var modelErrors = new List<string>();+ foreach (var value in modelState.Values)+ modelErrors.AddRange(value.Errors.Select(modelError => modelError.ErrorMessage));+ Notification(NotifyType.Error, string.Join(',', modelErrors), persistNextRequest);+ }- /// <summary>- /// Log exception- /// </summary>- /// <param name="exception">Exception</param>- private void LogException(Exception exception)- {- var logger = HttpContext.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("BaseController");- logger.LogError(exception, exception.Message);- }+ /// <summary>+ /// Display error notification+ /// </summary>+ /// <param name="exception">Exception</param>+ /// <param name="persistNextRequest">A value indicating whether a message should be persisted for the next request</param>+ /// <param name="logException">A value indicating whether exception should be logged</param>+ protected void Error(Exception exception, bool persistNextRequest = true, bool logException = true)+ {+ if (logException)+ LogException(exception);- /// <summary>- /// Display notification- /// </summary>- /// <param name="type">Notification type</param>- /// <param name="message">Message</param>- /// <param name="persistNextRequest">A value indicating whether a message should be persisted for the next request</param>- protected void Notification(NotifyType type, string message, bool persistNextRequest)- {- var dataKey = $"grand.notifications.{type}";-- if (persistNextRequest)- {- if (TempData[dataKey] == null || TempData[dataKey] is not List<string>)- TempData[dataKey] = new List<string>();- ((List<string>)TempData[dataKey]).Add(message);- }- else- {- //1. Compare with null (first usage)- //2. For some unknown reasons sometimes List<string> is converted to string[]. And it throws exceptions. That's why we reset it- if (ViewData[dataKey] == null || ViewData[dataKey] is not List<string>)- ViewData[dataKey] = new List<string>();- ((List<string>)ViewData[dataKey]).Add(message);- }- }+ Notification(NotifyType.Error, exception.Message, persistNextRequest);+ }- /// <summary>- /// Error's json data for kendo grid- /// </summary>- /// <param name="errorMessage">Error message</param>- /// <returns>Error's json data</returns>- protected JsonResult ErrorForKendoGridJson(string errorMessage)- {- var gridModel = new DataSourceResult {- Errors = errorMessage- };+ /// <summary>+ /// Log exception+ /// </summary>+ /// <param name="exception">Exception</param>+ private void LogException(Exception exception)+ {+ var logger = HttpContext.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("BaseController");+ logger.LogError(exception, exception.Message);+ }- return Json(gridModel);- }- /// <summary>- /// Error's json data for kendo grid- /// </summary>- /// <param name="modelState">Model state</param>- /// <returns>Error's json data</returns>- protected JsonResult ErrorForKendoGridJson(ModelStateDictionary modelState)+ /// <summary>+ /// Display notification+ /// </summary>+ /// <param name="type">Notification type</param>+ /// <param name="message">Message</param>+ /// <param name="persistNextRequest">A value indicating whether a message should be persisted for the next request</param>+ protected void Notification(NotifyType type, string message, bool persistNextRequest)+ {+ var dataKey = $"grand.notifications.{type}";++ if (persistNextRequest){- var gridModel = new DataSourceResult {- Errors = modelState.SerializeErrors()- };- return Json(gridModel);+ if (TempData[dataKey] == null || TempData[dataKey] is not List<string>)+ TempData[dataKey] = new List<string>();+ ((List<string>)TempData[dataKey]).Add(message);}- /// <summary>- /// Display "Edit" (manage) link (in public store)- /// </summary>- /// <param name="editPageUrl">Edit page URL</param>- protected virtual void DisplayEditLink(string editPageUrl)+ else{- HttpContext.RequestServices.GetRequiredService<IPageHeadBuilder>().EditPageUrl = editPageUrl;+ //1. Compare with null (first usage)+ //2. For some unknown reasons sometimes List<string> is converted to string[]. And it throws exceptions. That's why we reset it+ if (ViewData[dataKey] == null || ViewData[dataKey] is not List<string>)+ ViewData[dataKey] = new List<string>();+ ((List<string>)ViewData[dataKey]).Add(message);}+ }+ /// <summary>+ /// Error's json data for kendo grid+ /// </summary>+ /// <param name="errorMessage">Error message</param>+ /// <returns>Error's json data</returns>+ protected JsonResult ErrorForKendoGridJson(string errorMessage)+ {+ var gridModel = new DataSourceResult {+ Errors = errorMessage+ };- #endregion-- #region Localization-- /// <summary>- /// Add locales for localizable entities- /// </summary>- /// <typeparam name="TLocalizedModelLocal">Localizable model</typeparam>- /// <param name="languageService">Language service</param>- /// <param name="locales">Locales</param>- protected virtual async Task AddLocales<TLocalizedModelLocal>(ILanguageService languageService,- IList<TLocalizedModelLocal> locales) where TLocalizedModelLocal : ILocalizedModelLocal- {- await AddLocales(languageService, locales, null);- }-- /// <summary>- /// Add locales for localizable entities- /// </summary>- /// <typeparam name="TLocalizedModelLocal">Localizable model</typeparam>- /// <param name="languageService">Language service</param>- /// <param name="locales">Locales</param>- /// <param name="configure">Configure action</param>- /// https://github.com/smartstore/Smartstore/blob/98494cd31f5a376bf67010264e10c37a657f6ee9/src/Smartstore.Web.Common/Controllers/ManageController.cs- protected virtual async Task AddLocales<TLocalizedModelLocal>(ILanguageService languageService,- IList<TLocalizedModelLocal> locales, Action<TLocalizedModelLocal, string> configure) where TLocalizedModelLocal : ILocalizedModelLocal- {- foreach (var language in await languageService.GetAllLanguages(true))- {- var locale = Activator.CreateInstance<TLocalizedModelLocal>();- locale.LanguageId = language.Id;+ return Json(gridModel);+ }- if (configure != null)- configure.Invoke(locale, locale.LanguageId);+ /// <summary>+ /// Error's json data for kendo grid+ /// </summary>+ /// <param name="modelState">Model state</param>+ /// <returns>Error's json data</returns>+ protected JsonResult ErrorForKendoGridJson(ModelStateDictionary modelState)+ {+ var gridModel = new DataSourceResult {+ Errors = modelState.SerializeErrors()+ };+ return Json(gridModel);+ }- locales.Add(locale);- }- }+ /// <summary>+ /// Display "Edit" (manage) link (in public store)+ /// </summary>+ /// <param name="editPageUrl">Edit page URL</param>+ protected virtual void DisplayEditLink(string editPageUrl)+ {+ HttpContext.RequestServices.GetRequiredService<IPageHeadBuilder>().EditPageUrl = editPageUrl;+ }+ #endregion- #endregion+ #region Localization- #region Security+ /// <summary>+ /// Add locales for localizable entities+ /// </summary>+ /// <typeparam name="TLocalizedModelLocal">Localizable model</typeparam>+ /// <param name="languageService">Language service</param>+ /// <param name="locales">Locales</param>+ protected virtual async Task AddLocales<TLocalizedModelLocal>(ILanguageService languageService,+ IList<TLocalizedModelLocal> locales) where TLocalizedModelLocal : ILocalizedModelLocal+ {+ await AddLocales(languageService, locales, null);+ }- /// <summary>- /// Access denied view- /// </summary>- /// <returns>Access denied view</returns>- protected IActionResult AccessDeniedView()+ /// <summary>+ /// Add locales for localizable entities+ /// </summary>+ /// <typeparam name="TLocalizedModelLocal">Localizable model</typeparam>+ /// <param name="languageService">Language service</param>+ /// <param name="locales">Locales</param>+ /// <param name="configure">Configure action</param>+ /// https://github.com/smartstore/Smartstore/blob/98494cd31f5a376bf67010264e10c37a657f6ee9/src/Smartstore.Web.Common/Controllers/ManageController.cs+ protected virtual async Task AddLocales<TLocalizedModelLocal>(ILanguageService languageService,+ IList<TLocalizedModelLocal> locales, Action<TLocalizedModelLocal, string> configure)+ where TLocalizedModelLocal : ILocalizedModelLocal+ {+ foreach (var language in await languageService.GetAllLanguages(true)){- return RedirectToAction("AccessDenied", "Home", new { pageUrl = HttpContext.Request.GetEncodedPathAndQuery() });- }+ var locale = Activator.CreateInstance<TLocalizedModelLocal>();+ locale.LanguageId = language.Id;- /// <summary>- /// Access denied json data for kendo grid- /// </summary>- /// <returns>Access denied json data</returns>- protected JsonResult AccessDeniedKendoGridJson()- {- var translationService = HttpContext.RequestServices.GetRequiredService<ITranslationService>();- return ErrorForKendoGridJson(translationService.GetResource("Admin.AccessDenied.Description"));+ if (configure != null)+ configure.Invoke(locale, locale.LanguageId);++ locales.Add(locale);}+ }- #endregion+ #endregion- public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)- {- // event notification before execute- var mediator = context.HttpContext.RequestServices.GetService<IMediator>();- await mediator.Publish(new ActionExecutingContextNotification(context, true));+ #region Security- await next();+ /// <summary>+ /// Access denied view+ /// </summary>+ /// <returns>Access denied view</returns>+ protected IActionResult AccessDeniedView()+ {+ return RedirectToAction("AccessDenied", "Home", new { pageUrl = HttpContext.Request.GetEncodedPathAndQuery() });+ }- //event notification after execute- await mediator.Publish(new ActionExecutingContextNotification(context, false));- }+ /// <summary>+ /// Access denied json data for kendo grid+ /// </summary>+ /// <returns>Access denied json data</returns>+ protected JsonResult AccessDeniedKendoGridJson()+ {+ var translationService = HttpContext.RequestServices.GetRequiredService<ITranslationService>();+ return ErrorForKendoGridJson(translationService.GetResource("Admin.AccessDenied.Description"));}++ #endregion}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Controllers/BasePaymentController.cs b/src/Web/Grand.Web.Common/Controllers/BasePaymentController.csindex a08c4a2a2..b918589aa 100644--- a/src/Web/Grand.Web.Common/Controllers/BasePaymentController.cs+++ b/src/Web/Grand.Web.Common/Controllers/BasePaymentController.cs@@ -1,9 +1,8 @@-namespace Grand.Web.Common.Controllers+namespace Grand.Web.Common.Controllers;++/// <summary>+/// Base controller for payment plugins+/// </summary>+public abstract class BasePaymentController : BasePluginController{- /// <summary>- /// Base controller for payment plugins- /// </summary>- public abstract class BasePaymentController : BasePluginController- {- }-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Controllers/BasePluginController.cs b/src/Web/Grand.Web.Common/Controllers/BasePluginController.csindex d338dfb39..84fa5c7e3 100644--- a/src/Web/Grand.Web.Common/Controllers/BasePluginController.cs+++ b/src/Web/Grand.Web.Common/Controllers/BasePluginController.cs@@ -1,9 +1,8 @@-namespace Grand.Web.Common.Controllers+namespace Grand.Web.Common.Controllers;++/// <summary>+/// Base controller for plugins+/// </summary>+public abstract class BasePluginController : BaseController{- /// <summary>- /// Base controller for plugins- /// </summary>- public abstract class BasePluginController : BaseController- {- }-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Controllers/BasePublicController.cs b/src/Web/Grand.Web.Common/Controllers/BasePublicController.csindex 054e1fff5..83175299f 100644--- a/src/Web/Grand.Web.Common/Controllers/BasePublicController.cs+++ b/src/Web/Grand.Web.Common/Controllers/BasePublicController.cs@@ -2,54 +2,54 @@using Grand.Web.Common.Filters;using Microsoft.AspNetCore.Mvc;-namespace Grand.Web.Common.Controllers+namespace Grand.Web.Common.Controllers;++[PublicStore]+[ClosedStore]+[Language]+[Affiliate]+[SharedKernel.Attributes.ApiController]+public abstract class BasePublicController : BaseController{- [PublicStore]- [ClosedStore]- [Language]- [Affiliate]- [SharedKernel.Attributes.ApiController]- public abstract class BasePublicController : BaseController+ protected IActionResult InvokeHttp404()+ {+ Response.StatusCode = 404;+ return new EmptyResult();+ }++ private bool IsJsonResponseView()+ {+ if (Request.Method.Equals("GET", StringComparison.InvariantCultureIgnoreCase))+ return Request.Headers.Accept.ToString()+ .Contains("application/json", StringComparison.InvariantCultureIgnoreCase) ||+ Request.Headers.Accept.ToString().Equals("*/*", StringComparison.InvariantCultureIgnoreCase);++ if (Request.Method.Equals("POST", StringComparison.InvariantCultureIgnoreCase))+ return Request.ContentType?.Contains("application/json") ?? false;++ return false;+ }++ [IgnoreApi]+ public new IActionResult View(object model)+ {+ if (IsJsonResponseView())+ return Ok(model);++ return base.View(model);+ }++ [IgnoreApi]+ public new IActionResult View(string viewName, object model)+ {+ if (IsJsonResponseView())+ return Json(model);++ return base.View(viewName, model);+ }++ public override RedirectToRouteResult RedirectToRoute(string routeName){- protected IActionResult InvokeHttp404()- {- Response.StatusCode = 404;- return new EmptyResult();- }-- private bool IsJsonResponseView()- {- if (Request.Method.Equals("GET", StringComparison.InvariantCultureIgnoreCase))- return Request.Headers.Accept.ToString().Contains("application/json", StringComparison.InvariantCultureIgnoreCase) ||- Request.Headers.Accept.ToString().Equals("*/*", StringComparison.InvariantCultureIgnoreCase);-- if (Request.Method.Equals("POST", StringComparison.InvariantCultureIgnoreCase))- return Request.ContentType?.Contains("application/json") ?? false;-- return false;- }-- [IgnoreApi]- public new IActionResult View(object model)- {- if (IsJsonResponseView())- return Ok(model);-- return base.View(model);- }-- [IgnoreApi]- public new IActionResult View(string viewName, object model)- {- if (IsJsonResponseView())- return Json(model);-- return base.View(viewName, model);- }-- public override RedirectToRouteResult RedirectToRoute(string routeName)- {- return IsJsonResponseView() ? RedirectToRoute("Route", new { routeName }) : base.RedirectToRoute(routeName);- }+ return IsJsonResponseView() ? RedirectToRoute("Route", new { routeName }) : base.RedirectToRoute(routeName);}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Controllers/BaseShippingController.cs b/src/Web/Grand.Web.Common/Controllers/BaseShippingController.csindex 9656eae2c..f16503ea3 100644--- a/src/Web/Grand.Web.Common/Controllers/BaseShippingController.cs+++ b/src/Web/Grand.Web.Common/Controllers/BaseShippingController.cs@@ -1,7 +1,5 @@-namespace Grand.Web.Common.Controllers+namespace Grand.Web.Common.Controllers;++public abstract class BaseShippingController : BasePluginController{- public abstract class BaseShippingController : BasePluginController- {-- }-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Controllers/ControllerExtensions.cs b/src/Web/Grand.Web.Common/Controllers/ControllerExtensions.csindex dc004cdc7..2d7fc693d 100644--- a/src/Web/Grand.Web.Common/Controllers/ControllerExtensions.cs+++ b/src/Web/Grand.Web.Common/Controllers/ControllerExtensions.cs@@ -3,41 +3,36 @@ using Microsoft.AspNetCore.Mvc.Rendering;using Microsoft.AspNetCore.Mvc.ViewEngines;using Microsoft.AspNetCore.Mvc.ViewFeatures;-namespace Grand.Web.Common.Controllers+namespace Grand.Web.Common.Controllers;++public static class ControllerExtensions{- public static class ControllerExtensions+ public static async Task<string> RenderPartialViewToString<TModel>(this Controller controller, string viewName,+ TModel model, bool partial = false){- public static async Task<string> RenderPartialViewToString<TModel>(this Controller controller, string viewName, TModel model, bool partial = false)- {- if (string.IsNullOrEmpty(viewName))- {- viewName = controller.ControllerContext.ActionDescriptor.ActionName;- }-- controller.ViewData.Model = model;-- await using var writer = new StringWriter();- IViewEngine viewEngine = controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;- if (viewEngine == null) return writer.GetStringBuilder().ToString();- ViewEngineResult viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);-- if (viewResult.Success == false)- {- return $"A view with the name {viewName} could not be found";- }-- ViewContext viewContext = new(- controller.ControllerContext,- viewResult.View,- controller.ViewData,- controller.TempData,- writer,- new HtmlHelperOptions()- );-- await viewResult.View.RenderAsync(viewContext);-- return writer.GetStringBuilder().ToString();- }+ if (string.IsNullOrEmpty(viewName)) viewName = controller.ControllerContext.ActionDescriptor.ActionName;++ controller.ViewData.Model = model;++ await using var writer = new StringWriter();+ IViewEngine viewEngine =+ controller.HttpContext.RequestServices.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;+ if (viewEngine == null) return writer.GetStringBuilder().ToString();+ var viewResult = viewEngine.FindView(controller.ControllerContext, viewName, !partial);++ if (viewResult.Success == false) return $"A view with the name {viewName} could not be found";++ ViewContext viewContext = new(+ controller.ControllerContext,+ viewResult.View,+ controller.ViewData,+ controller.TempData,+ writer,+ new HtmlHelperOptions()+ );++ await viewResult.View.RenderAsync(viewContext);++ return writer.GetStringBuilder().ToString();}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/DataSource/DataSourceRequest.cs b/src/Web/Grand.Web.Common/DataSource/DataSourceRequest.csindex d1b340619..65e52917c 100644--- a/src/Web/Grand.Web.Common/DataSource/DataSourceRequest.cs+++ b/src/Web/Grand.Web.Common/DataSource/DataSourceRequest.cs@@ -1,9 +1,8 @@-namespace Grand.Web.Common.DataSource+namespace Grand.Web.Common.DataSource;++public class DataSourceRequest{- public class DataSourceRequest- {- public int Page { get; set; } = 1;+ public int Page { get; set; } = 1;- public int PageSize { get; set; } = 10;- }-}+ public int PageSize { get; set; } = 10;+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/DataSource/DataSourceResult.cs b/src/Web/Grand.Web.Common/DataSource/DataSourceResult.csindex ceb38fee6..15e809e27 100644--- a/src/Web/Grand.Web.Common/DataSource/DataSourceResult.cs+++ b/src/Web/Grand.Web.Common/DataSource/DataSourceResult.cs@@ -1,15 +1,14 @@using System.Collections;-namespace Grand.Web.Common.DataSource+namespace Grand.Web.Common.DataSource;++public class DataSourceResult{- public class DataSourceResult- {- public object ExtraData { get; set; }+ public object ExtraData { get; set; }- public IEnumerable Data { get; set; }+ public IEnumerable Data { get; set; }- public object Errors { get; set; }+ public object Errors { get; set; }- public int Total { get; set; }- }-}+ public int Total { get; set; }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Events/ActionExecutingContextNotification.cs b/src/Web/Grand.Web.Common/Events/ActionExecutingContextNotification.csindex 8dcb5e802..2053a42a9 100644--- a/src/Web/Grand.Web.Common/Events/ActionExecutingContextNotification.cs+++ b/src/Web/Grand.Web.Common/Events/ActionExecutingContextNotification.cs@@ -1,18 +1,17 @@using MediatR;using Microsoft.AspNetCore.Mvc.Filters;-namespace Grand.Web.Common.Events+namespace Grand.Web.Common.Events;++public class ActionExecutingContextNotification : INotification{- public class ActionExecutingContextNotification : INotification+ public ActionExecutingContextNotification(ActionExecutingContext context, bool before){- public ActionExecutingContext Context { get; private set; }+ Context = context;+ Before = before;+ }- public bool Before { get; private set; }+ public ActionExecutingContext Context { get; private set; }- public ActionExecutingContextNotification(ActionExecutingContext context, bool before)- {- Context = context;- Before = before;- }- }-}+ public bool Before { get; private set; }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Events/AdminTabStripCreated.cs b/src/Web/Grand.Web.Common/Events/AdminTabStripCreated.csindex 27990ab8e..bbffd53e0 100644--- a/src/Web/Grand.Web.Common/Events/AdminTabStripCreated.cs+++ b/src/Web/Grand.Web.Common/Events/AdminTabStripCreated.cs@@ -1,20 +1,19 @@using MediatR;using Microsoft.AspNetCore.Html;-namespace Grand.Web.Common.Events+namespace Grand.Web.Common.Events;++/// <summary>+/// Admin tabstrip created event+/// </summary>+public class AdminTabStripCreated : INotification{- /// <summary>- /// Admin tabstrip created event- /// </summary>- public class AdminTabStripCreated : INotification+ public AdminTabStripCreated(string tabStripName){- public AdminTabStripCreated(string tabStripName)- {- this.TabStripName = tabStripName;- this.BlocksToRender = new List<(string tabname, IHtmlContent content)>();- }-- public string TabStripName { get; private set; }- public IList<(string tabname, IHtmlContent content)> BlocksToRender { get; set; }+ TabStripName = tabStripName;+ BlocksToRender = new List<(string tabname, IHtmlContent content)>();}-}++ public string TabStripName { get; private set; }+ public IList<(string tabname, IHtmlContent content)> BlocksToRender { get; set; }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Extensions/CommonExtensions.cs b/src/Web/Grand.Web.Common/Extensions/CommonExtensions.csindex b94b4b3dd..2bbd2db5b 100644--- a/src/Web/Grand.Web.Common/Extensions/CommonExtensions.cs+++ b/src/Web/Grand.Web.Common/Extensions/CommonExtensions.cs@@ -7,49 +7,53 @@ using Microsoft.AspNetCore.Mvc.Rendering;using Microsoft.Extensions.DependencyInjection;using System.Reflection;-namespace Grand.Web.Common.Extensions+namespace Grand.Web.Common.Extensions;++/// <summary>+/// Extensions+/// </summary>+public static class CommonExtensions{- /// <summary>- /// Extensions- /// </summary>- public static class CommonExtensions+ public static IEnumerable<T> PagedForCommand<T>(this IEnumerable<T> current, DataSourceRequest command)+ {+ return current.Skip((command.Page - 1) * command.PageSize).Take(command.PageSize);+ }++ public static IEnumerable<T> PagedForCommand<T>(this IEnumerable<T> current, int pageIndex, int pageSize)+ {+ return current.Skip((pageIndex - 1) * pageSize).Take(pageSize);+ }++ public static SelectList ToSelectList<TEnum>(this TEnum enumObj, HttpContext httpContext,+ bool markCurrentAsSelected = true, int[] valuesToExclude = null) where TEnum : struct{- public static IEnumerable<T> PagedForCommand<T>(this IEnumerable<T> current, DataSourceRequest command)- {- return current.Skip((command.Page - 1) * command.PageSize).Take(command.PageSize);- }- public static IEnumerable<T> PagedForCommand<T>(this IEnumerable<T> current, int pageIndex, int pageSize)- {- return current.Skip((pageIndex - 1) * pageSize).Take(pageSize);- }-- public static SelectList ToSelectList<TEnum>(this TEnum enumObj, HttpContext httpContext, bool markCurrentAsSelected = true, int[] valuesToExclude = null) where TEnum : struct- {- if (!typeof(TEnum).GetTypeInfo().IsEnum)- throw new ArgumentException("Enumeration type is required.");-- var translationService = httpContext.RequestServices.GetRequiredService<ITranslationService>();- var workContext = httpContext.RequestServices.GetRequiredService<IWorkContext>();-- return ToSelectList(enumObj, translationService, workContext, markCurrentAsSelected, valuesToExclude);- }-- public static SelectList ToSelectList<TEnum>(this TEnum enumObj, ITranslationService translationService = null, IWorkContext workContext = null, bool markCurrentAsSelected = true, int[] valuesToExclude = null) where TEnum : struct- {- if (!typeof(TEnum).GetTypeInfo().IsEnum)- throw new ArgumentException("Enumeration type is required.");-- var values = from TEnum enumValue in Enum.GetValues(typeof(TEnum))- where valuesToExclude == null || !valuesToExclude.Contains(Convert.ToInt32(enumValue))- select new- {- ID = Convert.ToInt32(enumValue),- Name = translationService != null && workContext != null ? enumValue.GetTranslationEnum(translationService, workContext) : enumValue.ToString()- };- object selectedValue = null;- if (markCurrentAsSelected)- selectedValue = Convert.ToInt32(enumObj);- return new SelectList(values, "ID", "Name", selectedValue);- }+ if (!typeof(TEnum).GetTypeInfo().IsEnum)+ throw new ArgumentException("Enumeration type is required.");++ var translationService = httpContext.RequestServices.GetRequiredService<ITranslationService>();+ var workContext = httpContext.RequestServices.GetRequiredService<IWorkContext>();++ return ToSelectList(enumObj, translationService, workContext, markCurrentAsSelected, valuesToExclude);+ }++ public static SelectList ToSelectList<TEnum>(this TEnum enumObj, ITranslationService translationService = null,+ IWorkContext workContext = null, bool markCurrentAsSelected = true, int[] valuesToExclude = null)+ where TEnum : struct+ {+ if (!typeof(TEnum).GetTypeInfo().IsEnum)+ throw new ArgumentException("Enumeration type is required.");++ var values = from TEnum enumValue in Enum.GetValues(typeof(TEnum))+ where valuesToExclude == null || !valuesToExclude.Contains(Convert.ToInt32(enumValue))+ select new {+ ID = Convert.ToInt32(enumValue),+ Name = translationService != null && workContext != null+ ? enumValue.GetTranslationEnum(translationService, workContext)+ : enumValue.ToString()+ };+ object selectedValue = null;+ if (markCurrentAsSelected)+ selectedValue = Convert.ToInt32(enumObj);+ return new SelectList(values, "ID", "Name", selectedValue);}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Extensions/ConfigurationExtensions.cs b/src/Web/Grand.Web.Common/Extensions/ConfigurationExtensions.csindex a1056db33..6e9857231 100644--- a/src/Web/Grand.Web.Common/Extensions/ConfigurationExtensions.cs+++ b/src/Web/Grand.Web.Common/Extensions/ConfigurationExtensions.cs@@ -5,50 +5,44 @@ using Microsoft.AspNetCore.Http.Features;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Web.Common.Extensions+namespace Grand.Web.Common.Extensions;++public static class ConfigurationExtensions{- public static class ConfigurationExtensions+ public static void AddAppSettingsJsonFile(this IConfigurationManager configuration, string[] args){-- public static void AddAppSettingsJsonFile(this IConfigurationManager configuration, string[] args)+ configuration.AddJsonFile("App_Data/appsettings.json");+ configuration.AddEnvironmentVariables();+ if (args.Any()){- configuration.AddJsonFile("App_Data/appsettings.json");- configuration.AddEnvironmentVariables();- if (args.Any())- {- configuration.AddCommandLine(args);- var appSettings = configuration["appsettings"];- if (!string.IsNullOrEmpty(appSettings))- {- configuration.AddJsonFile($"App_Data/{appSettings}/appsettings.json");- }- }+ configuration.AddCommandLine(args);+ var appSettings = configuration["appsettings"];+ if (!string.IsNullOrEmpty(appSettings))+ configuration.AddJsonFile($"App_Data/{appSettings}/appsettings.json");}- public static void ConfigureApplicationSettings(this WebApplicationBuilder builder)- {- //Allow non ASCII chars in headers- var config = new AppConfig();- builder.Configuration.GetSection("Application").Bind(config);- if (config.AllowNonAsciiCharInHeaders)+ }++ public static void ConfigureApplicationSettings(this WebApplicationBuilder builder)+ {+ //Allow non ASCII chars in headers+ var config = new AppConfig();+ builder.Configuration.GetSection("Application").Bind(config);+ if (config.AllowNonAsciiCharInHeaders)+ builder.WebHost.ConfigureKestrel(options =>{- builder.WebHost.ConfigureKestrel(options =>- {- options.ResponseHeaderEncodingSelector = _ => Encoding.UTF8;- });- }- if (config.MaxRequestBodySize.HasValue)+ options.ResponseHeaderEncodingSelector = _ => Encoding.UTF8;+ });+ if (config.MaxRequestBodySize.HasValue)+ {+ builder.WebHost.ConfigureKestrel(host =>{- builder.WebHost.ConfigureKestrel(host =>- {- host.Limits.MaxRequestBodySize = config.MaxRequestBodySize.Value;- });+ host.Limits.MaxRequestBodySize = config.MaxRequestBodySize.Value;+ });- builder.Services.Configure<FormOptions>(opt =>- {- opt.MultipartBodyLengthLimit = config.MaxRequestBodySize.Value;- });-- }+ builder.Services.Configure<FormOptions>(opt =>+ {+ opt.MultipartBodyLengthLimit = config.MaxRequestBodySize.Value;+ });}}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Extensions/DateTimeMappingExtensions.cs b/src/Web/Grand.Web.Common/Extensions/DateTimeMappingExtensions.csindex f2d53c206..a2b658b27 100644--- a/src/Web/Grand.Web.Common/Extensions/DateTimeMappingExtensions.cs+++ b/src/Web/Grand.Web.Common/Extensions/DateTimeMappingExtensions.cs@@ -1,41 +1,38 @@using Grand.Business.Core.Interfaces.Common.Directory;-namespace Grand.Web.Common.Extensions+namespace Grand.Web.Common.Extensions;++public static class DateTimeMappingExtensions{- public static class DateTimeMappingExtensions+ public static DateTime? ConvertToUserTime(this DateTime? datetime, IDateTimeService dateTimeService){- public static DateTime? ConvertToUserTime(this DateTime? datetime, IDateTimeService dateTimeService)- {- if (datetime is { Kind: DateTimeKind.Utc }) datetime = dateTimeService.ConvertToUserTime(datetime.Value, TimeZoneInfo.Utc, dateTimeService.CurrentTimeZone);- return datetime;- }-- public static DateTime? ConvertToUtcTime(this DateTime? datetime, IDateTimeService dateTimeService)- {- if (datetime.HasValue)- {- if (datetime.Value.Kind != DateTimeKind.Utc)- datetime = dateTimeService.ConvertToUtcTime(datetime.Value, dateTimeService.CurrentTimeZone);- }- return datetime;- }-- public static DateTime ConvertToUserTime(this DateTime datetime, IDateTimeService dateTimeService)- {- if (datetime.Kind == DateTimeKind.Utc)- return dateTimeService.ConvertToUserTime(datetime, TimeZoneInfo.Utc, dateTimeService.CurrentTimeZone);+ if (datetime is { Kind: DateTimeKind.Utc })+ datetime = dateTimeService.ConvertToUserTime(datetime.Value, TimeZoneInfo.Utc,+ dateTimeService.CurrentTimeZone);+ return datetime;+ }- return datetime;- }+ public static DateTime? ConvertToUtcTime(this DateTime? datetime, IDateTimeService dateTimeService)+ {+ if (datetime.HasValue)+ if (datetime.Value.Kind != DateTimeKind.Utc)+ datetime = dateTimeService.ConvertToUtcTime(datetime.Value, dateTimeService.CurrentTimeZone);+ return datetime;+ }- public static DateTime ConvertToUtcTime(this DateTime datetime, IDateTimeService dateTimeService)- {- if (datetime.Kind == DateTimeKind.Local)- return dateTimeService.ConvertToUtcTime(datetime, dateTimeService.CurrentTimeZone);+ public static DateTime ConvertToUserTime(this DateTime datetime, IDateTimeService dateTimeService)+ {+ if (datetime.Kind == DateTimeKind.Utc)+ return dateTimeService.ConvertToUserTime(datetime, TimeZoneInfo.Utc, dateTimeService.CurrentTimeZone);- return datetime;- }+ return datetime;}+ public static DateTime ConvertToUtcTime(this DateTime datetime, IDateTimeService dateTimeService)+ {+ if (datetime.Kind == DateTimeKind.Local)+ return dateTimeService.ConvertToUtcTime(datetime, dateTimeService.CurrentTimeZone);-}+ return datetime;+ }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Extensions/HtmlExtensions.cs b/src/Web/Grand.Web.Common/Extensions/HtmlExtensions.csindex 0bf22a601..6e67bccaf 100644--- a/src/Web/Grand.Web.Common/Extensions/HtmlExtensions.cs+++ b/src/Web/Grand.Web.Common/Extensions/HtmlExtensions.cs@@ -1,31 +1,30 @@using Microsoft.AspNetCore.Html;using System.Text.Encodings.Web;-namespace Grand.Web.Common.Extensions+namespace Grand.Web.Common.Extensions;++public static class HtmlExtensions{- public static class HtmlExtensions- {- #region Admin area extensions+ #region Admin area extensions- public static string RenderHtmlContent(this IHtmlContent htmlContent)- {- using var writer = new StringWriter();- htmlContent.WriteTo(writer, HtmlEncoder.Default);- var htmlOutput = writer.ToString();- return htmlOutput;- }- #endregion+ public static string RenderHtmlContent(this IHtmlContent htmlContent)+ {+ using var writer = new StringWriter();+ htmlContent.WriteTo(writer, HtmlEncoder.Default);+ var htmlOutput = writer.ToString();+ return htmlOutput;+ }- #region Common extensions+ #endregion- public static string ToHtmlString(this IHtmlContent tag)- {- using var writer = new StringWriter();- tag.WriteTo(writer, HtmlEncoder.Default);- return writer.ToString();- }+ #region Common extensions- #endregion+ public static string ToHtmlString(this IHtmlContent tag)+ {+ using var writer = new StringWriter();+ tag.WriteTo(writer, HtmlEncoder.Default);+ return writer.ToString();}-}+ #endregion+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Extensions/ModelStateExtensions.cs b/src/Web/Grand.Web.Common/Extensions/ModelStateExtensions.csindex 20a4cbc90..7ba43244f 100644--- a/src/Web/Grand.Web.Common/Extensions/ModelStateExtensions.cs+++ b/src/Web/Grand.Web.Common/Extensions/ModelStateExtensions.cs@@ -1,26 +1,26 @@using Microsoft.AspNetCore.Mvc.ModelBinding;-namespace Grand.Web.Common.Extensions+namespace Grand.Web.Common.Extensions;++public static class ModelStateExtensions{- public static class ModelStateExtensions+ public static object SerializeErrors(this ModelStateDictionary modelStateDictionary){- public static object SerializeErrors(this ModelStateDictionary modelStateDictionary)- {- return modelStateDictionary.Where(entry => entry.Value != null && entry.Value.Errors.Any())- .ToDictionary(entry => entry.Key, entry => SerializeModelState(entry.Value));- }+ return modelStateDictionary.Where(entry => entry.Value != null && entry.Value.Errors.Any())+ .ToDictionary(entry => entry.Key, entry => SerializeModelState(entry.Value));+ }- private static Dictionary<string, object> SerializeModelState(ModelStateEntry modelState)- {- var dictionary = new Dictionary<string, object> {- ["errors"] = modelState.Errors.Select(modelError => modelError.ErrorMessage).Where(errorText => !string.IsNullOrEmpty(errorText)).ToArray()- };- return dictionary;- }+ private static Dictionary<string, object> SerializeModelState(ModelStateEntry modelState)+ {+ var dictionary = new Dictionary<string, object> {+ ["errors"] = modelState.Errors.Select(modelError => modelError.ErrorMessage)+ .Where(errorText => !string.IsNullOrEmpty(errorText)).ToArray()+ };+ return dictionary;+ }- public static object ToDataSourceResult(this ModelStateDictionary modelState)- {- return !modelState.IsValid ? modelState.SerializeErrors() : null;- }+ public static object ToDataSourceResult(this ModelStateDictionary modelState)+ {+ return !modelState.IsValid ? modelState.SerializeErrors() : null;}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Extensions/ProductList.cs b/src/Web/Grand.Web.Common/Extensions/ProductList.csindex 3b8e85f05..89fa15250 100644--- a/src/Web/Grand.Web.Common/Extensions/ProductList.cs+++ b/src/Web/Grand.Web.Common/Extensions/ProductList.cs@@ -2,32 +2,32 @@using Grand.Domain;using Grand.Domain.Catalog;-namespace Grand.Web.Common.Extensions+namespace Grand.Web.Common.Extensions;++public static class ProductList{- public static class ProductList+ public static async Task<IPagedList<Product>> PrepareProductList(this IProductService productService,+ string searchCategoryId,+ string searchBrandId, string searchCollectionId, string searchStoreId, string searchVendorId, int productTypeId,+ string searchProductName, int pageIndex, int pageSize){- public static async Task<IPagedList<Product>> PrepareProductList(this IProductService productService, string searchCategoryId,- string searchBrandId, string searchCollectionId, string searchStoreId, string searchVendorId, int productTypeId,- string searchProductName, int pageIndex, int pageSize)- {- var searchCategoryIds = new List<string>();- if (!string.IsNullOrEmpty(searchCategoryId))- searchCategoryIds.Add(searchCategoryId);+ var searchCategoryIds = new List<string>();+ if (!string.IsNullOrEmpty(searchCategoryId))+ searchCategoryIds.Add(searchCategoryId);- var products = (await productService.SearchProducts(- categoryIds: searchCategoryIds,- brandId: searchBrandId,- collectionId: searchCollectionId,- storeId: searchStoreId,- vendorId: searchVendorId,- productType: productTypeId > 0 ? (ProductType?)productTypeId : null,- keywords: searchProductName,- pageIndex: pageIndex - 1,- pageSize: pageSize,- showHidden: true- )).products;+ var products = (await productService.SearchProducts(+ categoryIds: searchCategoryIds,+ brandId: searchBrandId,+ collectionId: searchCollectionId,+ storeId: searchStoreId,+ vendorId: searchVendorId,+ productType: productTypeId > 0 ? (ProductType?)productTypeId : null,+ keywords: searchProductName,+ pageIndex: pageIndex - 1,+ pageSize: pageSize,+ showHidden: true+ )).products;- return products;- }+ return products;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs b/src/Web/Grand.Web.Common/Extensions/SessionExtensions.csindex cc3f13635..bf20dbfba 100644--- a/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs+++ b/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs@@ -1,36 +1,35 @@using Microsoft.AspNetCore.Http;using System.Text.Json;-namespace Grand.Web.Common.Extensions+namespace Grand.Web.Common.Extensions;++/// <summary>+/// Represents extensions of ISession+/// </summary>+public static class SessionExtensions{/// <summary>- /// Represents extensions of ISession+ /// Set value to Session/// </summary>- public static class SessionExtensions+ /// <typeparam name="T">Type of value</typeparam>+ /// <param name="session">Session</param>+ /// <param name="key">Key</param>+ /// <param name="value">Value</param>+ public static void Set<T>(this ISession session, string key, T value){- /// <summary>- /// Set value to Session- /// </summary>- /// <typeparam name="T">Type of value</typeparam>- /// <param name="session">Session</param>- /// <param name="key">Key</param>- /// <param name="value">Value</param>- public static void Set<T>(this ISession session, string key, T value)- {- session.SetString(key, JsonSerializer.Serialize(value));- }+ session.SetString(key, JsonSerializer.Serialize(value));+ }- /// <summary>- /// Get value from session- /// </summary>- /// <typeparam name="T">Type of value</typeparam>- /// <param name="session">Session</param>- /// <param name="key">Key</param>- /// <returns>Value</returns>- public static T Get<T>(this ISession session, string key)- {- var value = session.GetString(key);- return value == null ? default : JsonSerializer.Deserialize<T>(value);- }+ /// <summary>+ /// Get value from session+ /// </summary>+ /// <typeparam name="T">Type of value</typeparam>+ /// <param name="session">Session</param>+ /// <param name="key">Key</param>+ /// <returns>Value</returns>+ public static T Get<T>(this ISession session, string key)+ {+ var value = session.GetString(key);+ return value == null ? default : JsonSerializer.Deserialize<T>(value);}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Extensions/StorageExtensions.cs b/src/Web/Grand.Web.Common/Extensions/StorageExtensions.csindex c211f8f73..a38723285 100644--- a/src/Web/Grand.Web.Common/Extensions/StorageExtensions.cs+++ b/src/Web/Grand.Web.Common/Extensions/StorageExtensions.cs@@ -1,36 +1,33 @@using Microsoft.AspNetCore.Http;-namespace Grand.Web.Common.Extensions+namespace Grand.Web.Common.Extensions;++/// <summary>+/// Storage extensions+/// </summary>+public static class Extensions{/// <summary>- /// Storage extensions+ /// Gets the download binary array/// </summary>- public static class Extensions+ /// <param name="file">Posted file</param>+ /// <returns>Download binary array</returns>+ public static byte[] GetDownloadBits(this IFormFile file){- /// <summary>- /// Gets the download binary array- /// </summary>- /// <param name="file">Posted file</param>- /// <returns>Download binary array</returns>- public static byte[] GetDownloadBits(this IFormFile file)- {- using var fileStream = file.OpenReadStream();- using var ms = new MemoryStream();- fileStream.CopyTo(ms);- var fileBytes = ms.ToArray();- return fileBytes;- }-- /// <summary>- /// Gets the picture binary array- /// </summary>- /// <param name="file">File</param>- /// <returns>Picture binary array</returns>- public static byte[] GetPictureBits(this IFormFile file)- {- return GetDownloadBits(file);- }-+ using var fileStream = file.OpenReadStream();+ using var ms = new MemoryStream();+ fileStream.CopyTo(ms);+ var fileBytes = ms.ToArray();+ return fileBytes;+ }+ /// <summary>+ /// Gets the picture binary array+ /// </summary>+ /// <param name="file">File</param>+ /// <returns>Picture binary array</returns>+ public static byte[] GetPictureBits(this IFormFile file)+ {+ return GetDownloadBits(file);}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Extensions/TranslationExtension.cs b/src/Web/Grand.Web.Common/Extensions/TranslationExtension.csindex e4d1921a3..5093b5769 100644--- a/src/Web/Grand.Web.Common/Extensions/TranslationExtension.cs+++ b/src/Web/Grand.Web.Common/Extensions/TranslationExtension.cs@@ -1,114 +1,118 @@using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Business.Core.Interfaces.Common.Seo;-using Grand.Web.Common.Models;using Grand.Domain;using Grand.Domain.Localization;using Grand.Domain.Seo;+using Grand.Web.Common.Models;using System.Linq.Expressions;using System.Reflection;-namespace Grand.Web.Common.Extensions+namespace Grand.Web.Common.Extensions;++public static class TranslationExtension{- public static class TranslationExtension+ public static List<TranslationEntity> ToTranslationProperty<T>(this IList<T> list) where T : ILocalizedModelLocal{- public static List<TranslationEntity> ToTranslationProperty<T>(this IList<T> list) where T : ILocalizedModelLocal+ var local = new List<TranslationEntity>();+ foreach (var item in list){- var local = new List<TranslationEntity>();- foreach (var item in list)+ var interfaces = item.GetType().GetInterfaces();+ var props = item.GetType()+ .GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);+ foreach (var prop in props){- Type[] interfaces = item.GetType().GetInterfaces();- PropertyInfo[] props = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);- foreach (var prop in props)- {- var insert = true;+ var insert = true;- foreach (var i in interfaces)- {- if (i.HasProperty(prop.Name))- {- insert = false;- }- }+ foreach (var i in interfaces)+ if (i.HasProperty(prop.Name))+ insert = false;- if (insert && prop.GetValue(item) != null)- local.Add(new TranslationEntity {- LanguageId = item.LanguageId,- LocaleKey = prop.Name,- LocaleValue = prop.GetValue(item)?.ToString()- });- }+ if (insert && prop.GetValue(item) != null)+ local.Add(new TranslationEntity {+ LanguageId = item.LanguageId,+ LocaleKey = prop.Name,+ LocaleValue = prop.GetValue(item)?.ToString()+ });}- return local;}- public static async Task<List<TranslationEntity>> ToTranslationProperty<T, E>(this IList<T> list, E entity, Expression<Func<T, string>> keySelector,- SeoSettings seoSettings, ISlugService slugService, ILanguageService languageService) where T : ILocalizedModelLocal where E : BaseEntity, ISlugEntity+ return local;+ }++ public static async Task<List<TranslationEntity>> ToTranslationProperty<T, E>(this IList<T> list, E entity,+ Expression<Func<T, string>> keySelector,+ SeoSettings seoSettings, ISlugService slugService, ILanguageService languageService)+ where T : ILocalizedModelLocal where E : BaseEntity, ISlugEntity+ {+ var local = new List<TranslationEntity>();+ foreach (var item in list){- var local = new List<TranslationEntity>();- foreach (var item in list)+ var interfaces = item.GetType().GetInterfaces();+ var props = item.GetType()+ .GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);+ foreach (var prop in props){- Type[] interfaces = item.GetType().GetInterfaces();- PropertyInfo[] props = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);- foreach (var prop in props)- {- var insert = true;+ var insert = true;- foreach (var i in interfaces)+ foreach (var i in interfaces)+ {+ if (i.HasProperty(prop.Name) && typeof(ILocalizedModelLocal).IsAssignableFrom(i)) insert = false;+ if (i.HasProperty(prop.Name) && typeof(ISlugModelLocal).IsAssignableFrom(i)){- if (i.HasProperty(prop.Name) && typeof(ILocalizedModelLocal).IsAssignableFrom(i))+ var member = keySelector.Body as MemberExpression;+ if (member == null)+ throw new ArgumentException(+ $"Expression '{keySelector}' refers to a method, not a property.");++ var propInfo = member.Member as PropertyInfo;+ if (propInfo == null)+ throw new ArgumentException(+ $"Expression '{keySelector}' refers to a field, not a property.");++ var value = item.GetType().GetProperty(propInfo.Name)?.GetValue(item, null);+ if (value != null){- insert = false;+ var name = value.ToString();+ var itemvalue = prop.GetValue(item) ?? "";+ var seName = await entity.ValidateSeName(itemvalue.ToString(), name, false, seoSettings,+ slugService, languageService);+ prop.SetValue(item, seName);+ await slugService.SaveSlug(entity, seName, item.LanguageId);}- if (i.HasProperty(prop.Name) && typeof(ISlugModelLocal).IsAssignableFrom(i))+ else{- var member = keySelector.Body as MemberExpression;- if (member == null)- throw new ArgumentException($"Expression '{keySelector}' refers to a method, not a property.");-- var propInfo = member.Member as PropertyInfo;- if (propInfo == null)- throw new ArgumentException($"Expression '{keySelector}' refers to a field, not a property.");-- var value = item.GetType().GetProperty(propInfo.Name)?.GetValue(item, null);- if (value != null)+ var itemvalue = prop.GetValue(item) ?? "";+ if (!string.IsNullOrEmpty(itemvalue.ToString())){- var name = value.ToString();- var itemvalue = prop.GetValue(item) ?? "";- var seName = await entity.ValidateSeName(itemvalue.ToString(), name, false, seoSettings, slugService, languageService);+ var seName = await entity.ValidateSeName(itemvalue.ToString(), "", false, seoSettings,+ slugService, languageService);prop.SetValue(item, seName);await slugService.SaveSlug(entity, seName, item.LanguageId);}else{- var itemvalue = prop.GetValue(item) ?? "";- if (!string.IsNullOrEmpty(itemvalue.ToString()))- {- var seName = await entity.ValidateSeName(itemvalue.ToString(), "", false, seoSettings, slugService, languageService);- prop.SetValue(item, seName);- await slugService.SaveSlug(entity, seName, item.LanguageId);- }- else- insert = false;+ insert = false;}}}-- if (insert && prop.GetValue(item) != null)- local.Add(new TranslationEntity {- LanguageId = item.LanguageId,- LocaleKey = prop.Name,- LocaleValue = prop.GetValue(item)?.ToString()- });}++ if (insert && prop.GetValue(item) != null)+ local.Add(new TranslationEntity {+ LanguageId = item.LanguageId,+ LocaleKey = prop.Name,+ LocaleValue = prop.GetValue(item)?.ToString()+ });}- return local;}+ return local;+ }- private static bool HasProperty(this Type obj, string propertyName)- {- return obj.GetProperty(propertyName) != null;- }++ private static bool HasProperty(this Type obj, string propertyName)+ {+ return obj.GetProperty(propertyName) != null;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs b/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.csindex 5a4fda32a..3e915e9e0 100644--- a/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs@@ -1,123 +1,123 @@using Grand.Business.Core.Interfaces.Customers;-using Grand.Domain.Affiliates;using Grand.Data;+using Grand.Domain.Affiliates;using Grand.Infrastructure;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;-namespace Grand.Web.Common.Filters+namespace Grand.Web.Common.Filters;++/// <summary>+/// Represents filter attribute that checks and updates affiliate of customer+/// </summary>+public class AffiliateAttribute : TypeFilterAttribute{/// <summary>- /// Represents filter attribute that checks and updates affiliate of customer+ /// Create instance of the filter attribute/// </summary>- public class AffiliateAttribute : TypeFilterAttribute+ public AffiliateAttribute() : base(typeof(AffiliateFilter)){- /// <summary>- /// Create instance of the filter attribute- /// </summary>- public AffiliateAttribute() : base(typeof(AffiliateFilter))+ }++ #region Filter++ /// <summary>+ /// Represents a filter that checks and updates affiliate of customer+ /// </summary>+ private class AffiliateFilter : IAsyncActionFilter+ {+ #region Ctor++ public AffiliateFilter(IAffiliateService affiliateService,+ ICustomerService customerService,+ IWorkContext workContext){+ _affiliateService = affiliateService;+ _customerService = customerService;+ _workContext = workContext;}- #region Filter+ #endregion++ #region Methods/// <summary>- /// Represents a filter that checks and updates affiliate of customer+ /// Called before the action executes, after model binding is complete/// </summary>- private class AffiliateFilter : IAsyncActionFilter+ /// <param name="context">A context for action filters</param>+ /// <param name="next">Action execution delegate</param>+ public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next){- #region Constants-- private const string IdQueryParameterName = "affiliateid";- private const string FriendlyUrlNameQueryParameterName = "affiliate";+ await next();- #endregion+ if (!DataSettingsManager.DatabaseIsInstalled())+ return;- #region Fields+ //check request query parameters+ var request = context.HttpContext.Request;+ if (!request.Query.Any())+ return;- private readonly IAffiliateService _affiliateService;- private readonly ICustomerService _customerService;- private readonly IWorkContext _workContext;- #endregion-- #region Ctor+ //try to find by ID+ var affiliateIds = request.Query[IdQueryParameterName];+ if (affiliateIds.Any())+ {+ var affiliateId = affiliateIds.FirstOrDefault();+ if (!string.IsNullOrEmpty(affiliateId))+ await SetCustomerAffiliateId(await _affiliateService.GetAffiliateById(affiliateId));+ return;+ }- public AffiliateFilter(IAffiliateService affiliateService,- ICustomerService customerService,- IWorkContext workContext)+ //try to find by friendly name+ var affiliateNames = request.Query[FriendlyUrlNameQueryParameterName];+ if (affiliateNames.Any()){- _affiliateService = affiliateService;- _customerService = customerService;- _workContext = workContext;+ var affiliateName = affiliateNames.FirstOrDefault();+ if (!string.IsNullOrEmpty(affiliateName))+ await SetCustomerAffiliateId(await _affiliateService.GetAffiliateByFriendlyUrlName(affiliateName));}+ }- #endregion+ #endregion- #region Utilities+ #region Utilities- /// <summary>- /// Set the affiliate identifier of current customer- /// </summary>- /// <param name="affiliate">Affiliate</param>- private async Task SetCustomerAffiliateId(Affiliate affiliate)- {- if (affiliate is not { Active: true })- return;+ /// <summary>+ /// Set the affiliate identifier of current customer+ /// </summary>+ /// <param name="affiliate">Affiliate</param>+ private async Task SetCustomerAffiliateId(Affiliate affiliate)+ {+ if (affiliate is not { Active: true })+ return;- if (affiliate.Id == _workContext.CurrentCustomer.AffiliateId)- return;+ if (affiliate.Id == _workContext.CurrentCustomer.AffiliateId)+ return;- //update affiliate identifier- _workContext.CurrentCustomer.AffiliateId = affiliate.Id;- await _customerService.UpdateCustomerField(_workContext.CurrentCustomer.Id, x => x.AffiliateId, _workContext.CurrentCustomer.AffiliateId);- }+ //update affiliate identifier+ _workContext.CurrentCustomer.AffiliateId = affiliate.Id;+ await _customerService.UpdateCustomerField(_workContext.CurrentCustomer.Id, x => x.AffiliateId,+ _workContext.CurrentCustomer.AffiliateId);+ }- #endregion+ #endregion- #region Methods+ #region Constants- /// <summary>- /// Called before the action executes, after model binding is complete- /// </summary>- /// <param name="context">A context for action filters</param>- /// <param name="next">Action execution delegate</param>- public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)- {- await next();-- if (!DataSettingsManager.DatabaseIsInstalled())- return;-- //check request query parameters- var request = context.HttpContext.Request;- if (!request.Query.Any())- return;--- //try to find by ID- var affiliateIds = request.Query[IdQueryParameterName];- if (affiliateIds.Any())- {- var affiliateId = affiliateIds.FirstOrDefault();- if (!string.IsNullOrEmpty(affiliateId))- await SetCustomerAffiliateId(await _affiliateService.GetAffiliateById(affiliateId));- return;- }-- //try to find by friendly name- var affiliateNames = request.Query[FriendlyUrlNameQueryParameterName];- if (affiliateNames.Any())- {- var affiliateName = affiliateNames.FirstOrDefault();- if (!string.IsNullOrEmpty(affiliateName))- await SetCustomerAffiliateId(await _affiliateService.GetAffiliateByFriendlyUrlName(affiliateName));- }- }+ private const string IdQueryParameterName = "affiliateid";+ private const string FriendlyUrlNameQueryParameterName = "affiliate";- #endregion- }+ #endregion++ #region Fields++ private readonly IAffiliateService _affiliateService;+ private readonly ICustomerService _customerService;+ private readonly IWorkContext _workContext;#endregion}++ #endregion}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Filters/ArgumentNameFilterAttribute.cs b/src/Web/Grand.Web.Common/Filters/ArgumentNameFilterAttribute.csindex a4477397d..4080bd93c 100644--- a/src/Web/Grand.Web.Common/Filters/ArgumentNameFilterAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/ArgumentNameFilterAttribute.cs@@ -1,15 +1,14 @@using Microsoft.AspNetCore.Mvc.Filters;-namespace Grand.Web.Common.Filters+namespace Grand.Web.Common.Filters;++public class ArgumentNameFilterAttribute : ActionFilterAttribute{- public class ArgumentNameFilterAttribute : ActionFilterAttribute- {- public string KeyName { get; set; }- public string Argument { get; set; }+ public string KeyName { get; set; }+ public string Argument { get; set; }- public override void OnActionExecuting(ActionExecutingContext context)- {- context.ActionArguments[Argument] = context.HttpContext.Request.Form.Keys.Any(key => key.Equals(KeyName));- }+ public override void OnActionExecuting(ActionExecutingContext context)+ {+ context.ActionArguments[Argument] = context.HttpContext.Request.Form.Keys.Any(key => key.Equals(KeyName));}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Filters/AuthorizeAdminAttribute.cs b/src/Web/Grand.Web.Common/Filters/AuthorizeAdminAttribute.csindex 6e9c65c6f..5d16b3513 100644--- a/src/Web/Grand.Web.Common/Filters/AuthorizeAdminAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/AuthorizeAdminAttribute.cs@@ -8,109 +8,107 @@ using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.Routing;-namespace Grand.Web.Common.Filters+namespace Grand.Web.Common.Filters;++/// <summary>+/// Represents a filter attribute that confirms access to the admin panel+/// </summary>+public class AuthorizeAdminAttribute : TypeFilterAttribute{/// <summary>- /// Represents a filter attribute that confirms access to the admin panel+ /// Create instance of the filter attribute/// </summary>- public class AuthorizeAdminAttribute : TypeFilterAttribute+ /// <param name="ignore">Whether to ignore the execution of filter actions</param>+ public AuthorizeAdminAttribute(bool ignore = false) : base(typeof(AuthorizeAdminFilter)){- private readonly bool _ignoreFilter;+ IgnoreFilter = ignore;+ Arguments = [ignore];+ }- /// <summary>- /// Create instance of the filter attribute- /// </summary>- /// <param name="ignore">Whether to ignore the execution of filter actions</param>- public AuthorizeAdminAttribute(bool ignore = false) : base(typeof(AuthorizeAdminFilter))+ public bool IgnoreFilter { get; }++ #region Filter++ /// <summary>+ /// Represents a filter that confirms access to the admin panel+ /// </summary>+ private class AuthorizeAdminFilter : IAsyncAuthorizationFilter+ {+ #region Ctor++ public AuthorizeAdminFilter(bool ignoreFilter, IPermissionService permissionService,+ SecuritySettings securitySettings, IWorkContext workContext, IGroupService groupService){- _ignoreFilter = ignore;- Arguments = [ignore];+ _ignoreFilter = ignoreFilter;+ _permissionService = permissionService;+ _securitySettings = securitySettings;+ _workContext = workContext;+ _groupService = groupService;}- public bool IgnoreFilter => _ignoreFilter;+ #endregion- #region Filter+ #region Methods/// <summary>- /// Represents a filter that confirms access to the admin panel+ /// Called early in the filter pipeline to confirm request is authorized/// </summary>- private class AuthorizeAdminFilter : IAsyncAuthorizationFilter+ /// <param name="filterContext">Authorization filter context</param>+ public async Task OnAuthorizationAsync(AuthorizationFilterContext filterContext){- #region Fields-- private readonly bool _ignoreFilter;- private readonly IPermissionService _permissionService;- private readonly IWorkContext _workContext;- private readonly IGroupService _groupService;+ ArgumentNullException.ThrowIfNull(filterContext);- private readonly SecuritySettings _securitySettings;+ //check whether this filter has been overridden for the action+ var actionFilter = filterContext.ActionDescriptor.FilterDescriptors+ .Where(f => f.Scope == FilterScope.Action)+ .Select(f => f.Filter).OfType<AuthorizeAdminAttribute>().FirstOrDefault();- #endregion+ //ignore filter (the action is available even if a customer hasn't access to the admin area)+ if (actionFilter?.IgnoreFilter ?? _ignoreFilter)+ return;- #region Ctor+ if (!DataSettingsManager.DatabaseIsInstalled())+ return;- public AuthorizeAdminFilter(bool ignoreFilter, IPermissionService permissionService, SecuritySettings securitySettings, IWorkContext workContext, IGroupService groupService)+ //there is AdminAuthorizeFilter, so check access+ if (filterContext.Filters.Any(filter => filter is AuthorizeAdminFilter)){- _ignoreFilter = ignoreFilter;- _permissionService = permissionService;- _securitySettings = securitySettings;- _workContext = workContext;- _groupService = groupService;- }+ //authorize permission of access to the admin area+ if (!await _permissionService.Authorize(StandardPermission.ManageAccessAdminPanel))+ filterContext.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());- #endregion+ //whether current customer is vendor+ if (await _groupService.IsVendor(_workContext.CurrentCustomer) ||+ _workContext.CurrentVendor is not null)+ filterContext.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());- #region Methods+ //get allowed IP addresses+ var ipAddresses = _securitySettings.AdminAreaAllowedIpAddresses;- /// <summary>- /// Called early in the filter pipeline to confirm request is authorized- /// </summary>- /// <param name="filterContext">Authorization filter context</param>- public async Task OnAuthorizationAsync(AuthorizationFilterContext filterContext)- {- ArgumentNullException.ThrowIfNull(filterContext);+ //there are no restrictions+ if (ipAddresses == null || !ipAddresses.Any())+ return;- //check whether this filter has been overridden for the action- var actionFilter = filterContext.ActionDescriptor.FilterDescriptors- .Where(f => f.Scope == FilterScope.Action)- .Select(f => f.Filter).OfType<AuthorizeAdminAttribute>().FirstOrDefault();+ //whether current IP is allowed+ var currentIp = filterContext.HttpContext.Connection.RemoteIpAddress?.ToString();+ if (!ipAddresses.Any(ip => ip.Equals(currentIp, StringComparison.OrdinalIgnoreCase)))+ filterContext.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());+ }+ }- //ignore filter (the action is available even if a customer hasn't access to the admin area)- if (actionFilter?.IgnoreFilter ?? _ignoreFilter)- return;+ #endregion- if (!DataSettingsManager.DatabaseIsInstalled())- return;+ #region Fields- //there is AdminAuthorizeFilter, so check access- if (filterContext.Filters.Any(filter => filter is AuthorizeAdminFilter))- {- //authorize permission of access to the admin area- if (!await _permissionService.Authorize(StandardPermission.ManageAccessAdminPanel))- filterContext.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());-- //whether current customer is vendor- if (await _groupService.IsVendor(_workContext.CurrentCustomer) || _workContext.CurrentVendor is not null)- filterContext.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());-- //get allowed IP addresses- var ipAddresses = _securitySettings.AdminAreaAllowedIpAddresses;-- //there are no restrictions- if (ipAddresses == null || !ipAddresses.Any())- return;-- //whether current IP is allowed- var currentIp = filterContext.HttpContext.Connection.RemoteIpAddress?.ToString();- if (!ipAddresses.Any(ip => ip.Equals(currentIp, StringComparison.OrdinalIgnoreCase)))- filterContext.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());-- }- }+ private readonly bool _ignoreFilter;+ private readonly IPermissionService _permissionService;+ private readonly IWorkContext _workContext;+ private readonly IGroupService _groupService;- #endregion- }+ private readonly SecuritySettings _securitySettings;#endregion}++ #endregion}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs b/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.csindex c6a9750dc..eb706be43 100644--- a/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/AuthorizeMenuAttribute.cs@@ -1,144 +1,142 @@using Grand.Business.Core.Interfaces.Common.Security;using Grand.Business.Core.Interfaces.System.Admin;-using Grand.Domain.Admin;using Grand.Data;+using Grand.Domain.Admin;using Grand.Infrastructure;using Grand.Infrastructure.Configuration;using Grand.SharedKernel.Extensions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;-namespace Grand.Web.Common.Filters+namespace Grand.Web.Common.Filters;++/// <summary>+/// Represents a filter attribute that confirms access by admin menu to the controllers/actions in the admin+/// </summary>+public class AuthorizeMenuAttribute : TypeFilterAttribute{/// <summary>- /// Represents a filter attribute that confirms access by admin menu to the controllers/actions in the admin+ /// Create instance of the filter attribute/// </summary>- public class AuthorizeMenuAttribute : TypeFilterAttribute+ /// <param name="ignore">Whether to ignore the execution of filter actions</param>+ public AuthorizeMenuAttribute(bool ignore = false) : base(typeof(AuthorizeMenuFilter)){- private readonly bool _ignoreFilter;-- /// <summary>- /// Create instance of the filter attribute- /// </summary>- /// <param name="ignore">Whether to ignore the execution of filter actions</param>- public AuthorizeMenuAttribute(bool ignore = false) : base(typeof(AuthorizeMenuFilter))- {- _ignoreFilter = ignore;- Arguments = [ignore];- }+ IgnoreFilter = ignore;+ Arguments = [ignore];+ }- public bool IgnoreFilter => _ignoreFilter;+ public bool IgnoreFilter { get; }- #region Filter+ #region Filter- /// <summary>- /// Represents a filter that confirms access to the admin panel- /// </summary>- public class AuthorizeMenuFilter : IAsyncAuthorizationFilter+ /// <summary>+ /// Represents a filter that confirms access to the admin panel+ /// </summary>+ public class AuthorizeMenuFilter : IAsyncAuthorizationFilter+ {+ #region Ctor++ public AuthorizeMenuFilter(+ bool ignoreFilter,+ IPermissionService permissionService,+ IAdminSiteMapService adminSiteMapService,+ IWorkContext workContext,+ SecurityConfig securityConfig){- #region Fields-- private readonly bool _ignoreFilter;- private readonly IPermissionService _permissionService;- private readonly IAdminSiteMapService _adminSiteMapService;- private readonly IWorkContext _workContext;- private readonly SecurityConfig _securityConfig;+ _ignoreFilter = ignoreFilter;+ _permissionService = permissionService;+ _adminSiteMapService = adminSiteMapService;+ _workContext = workContext;+ _securityConfig = securityConfig;+ }- #endregion+ #endregion- #region Ctor+ #region Fields- public AuthorizeMenuFilter(- bool ignoreFilter,- IPermissionService permissionService,- IAdminSiteMapService adminSiteMapService,- IWorkContext workContext,- SecurityConfig securityConfig)- {- _ignoreFilter = ignoreFilter;- _permissionService = permissionService;- _adminSiteMapService = adminSiteMapService;- _workContext = workContext;- _securityConfig = securityConfig;- }+ private readonly bool _ignoreFilter;+ private readonly IPermissionService _permissionService;+ private readonly IAdminSiteMapService _adminSiteMapService;+ private readonly IWorkContext _workContext;+ private readonly SecurityConfig _securityConfig;- #endregion+ #endregion- #region Methods+ #region Methods- /// <summary>- /// Called early in the filter pipeline to confirm request is authorized- /// </summary>- /// <param name="filterContext">Authorization filter context</param>- public async Task OnAuthorizationAsync(AuthorizationFilterContext filterContext)- {- ArgumentNullException.ThrowIfNull(filterContext);+ /// <summary>+ /// Called early in the filter pipeline to confirm request is authorized+ /// </summary>+ /// <param name="filterContext">Authorization filter context</param>+ public async Task OnAuthorizationAsync(AuthorizationFilterContext filterContext)+ {+ ArgumentNullException.ThrowIfNull(filterContext);- //check whether this filter has been overridden for the action- var actionFilter = filterContext.ActionDescriptor.FilterDescriptors- .Where(f => f.Scope == FilterScope.Action)- .Select(f => f.Filter).OfType<AuthorizeMenuAttribute>().FirstOrDefault();+ //check whether this filter has been overridden for the action+ var actionFilter = filterContext.ActionDescriptor.FilterDescriptors+ .Where(f => f.Scope == FilterScope.Action)+ .Select(f => f.Filter).OfType<AuthorizeMenuAttribute>().FirstOrDefault();- //ignore filter (the action is available even if a customer hasn't access to the admin area)- if (actionFilter?.IgnoreFilter ?? _ignoreFilter)- return;+ //ignore filter (the action is available even if a customer hasn't access to the admin area)+ if (actionFilter?.IgnoreFilter ?? _ignoreFilter)+ return;- if (!DataSettingsManager.DatabaseIsInstalled())- return;+ if (!DataSettingsManager.DatabaseIsInstalled())+ return;- if (!_securityConfig.AuthorizeAdminMenu)- return;+ if (!_securityConfig.AuthorizeAdminMenu)+ return;- var controllerName = filterContext.RouteData.Values["controller"]?.ToString();- var actionName = filterContext.RouteData.Values["action"]?.ToString();+ var controllerName = filterContext.RouteData.Values["controller"]?.ToString();+ var actionName = filterContext.RouteData.Values["action"]?.ToString();- await ValidateMenuSiteMapPermissions(filterContext, controllerName, actionName);- }+ await ValidateMenuSiteMapPermissions(filterContext, controllerName, actionName);+ }- private async Task ValidateMenuSiteMapPermissions(AuthorizationFilterContext filterContext, string controllerName,- string actionName)+ private async Task ValidateMenuSiteMapPermissions(AuthorizationFilterContext filterContext,+ string controllerName,+ string actionName)+ {+ var menuSiteMap = await FindSiteMap(controllerName, actionName);+ if (menuSiteMap != null && menuSiteMap.PermissionNames.Any()){- var menuSiteMap = await FindSiteMap(controllerName, actionName);- if (menuSiteMap != null && menuSiteMap.PermissionNames.Any())+ if (menuSiteMap.AllPermissions){- if (menuSiteMap.AllPermissions)- {- if (!await menuSiteMap.PermissionNames.AllAsync(async x =>- await _permissionService.Authorize(x, _workContext.CurrentCustomer)))- filterContext.Result = new ForbidResult();- }- else- {- if (!await menuSiteMap.PermissionNames.AnyAsync(async x =>- await _permissionService.Authorize(x, _workContext.CurrentCustomer)))- filterContext.Result = new ForbidResult();- }+ if (!await menuSiteMap.PermissionNames.AllAsync(async x =>+ await _permissionService.Authorize(x, _workContext.CurrentCustomer)))+ filterContext.Result = new ForbidResult();+ }+ else+ {+ if (!await menuSiteMap.PermissionNames.AnyAsync(async x =>+ await _permissionService.Authorize(x, _workContext.CurrentCustomer)))+ filterContext.Result = new ForbidResult();}}+ }- private async Task<AdminSiteMap> FindSiteMap(string controllerName,- string actionName)- {- var adminSiteMap = await _adminSiteMapService.GetSiteMap();- return adminSiteMap.Select(siteMap =>- FindSiteMapByControllerAndActionName(siteMap, controllerName, actionName))- .FirstOrDefault(siteMap => siteMap != null);- }-- private static AdminSiteMap FindSiteMapByControllerAndActionName(AdminSiteMap siteMap,- string controllerName, string actionName)- {- if (siteMap.ControllerName == controllerName && siteMap.ActionName == actionName)- return siteMap;+ private async Task<AdminSiteMap> FindSiteMap(string controllerName,+ string actionName)+ {+ var adminSiteMap = await _adminSiteMapService.GetSiteMap();+ return adminSiteMap.Select(siteMap =>+ FindSiteMapByControllerAndActionName(siteMap, controllerName, actionName))+ .FirstOrDefault(siteMap => siteMap != null);+ }- return siteMap.ChildNodes- .Select(child => FindSiteMapByControllerAndActionName(child, controllerName, actionName))- .FirstOrDefault(result => result != null);- }+ private static AdminSiteMap FindSiteMapByControllerAndActionName(AdminSiteMap siteMap,+ string controllerName, string actionName)+ {+ if (siteMap.ControllerName == controllerName && siteMap.ActionName == actionName)+ return siteMap;- #endregion+ return siteMap.ChildNodes+ .Select(child => FindSiteMapByControllerAndActionName(child, controllerName, actionName))+ .FirstOrDefault(result => result != null);}#endregion}++ #endregion}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Filters/AuthorizeVendorAttribute.cs b/src/Web/Grand.Web.Common/Filters/AuthorizeVendorAttribute.csindex 3c50aa4f0..1a5bf2e30 100644--- a/src/Web/Grand.Web.Common/Filters/AuthorizeVendorAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/AuthorizeVendorAttribute.cs@@ -7,90 +7,90 @@ using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.Routing;-namespace Grand.Web.Common.Filters+namespace Grand.Web.Common.Filters;++/// <summary>+/// Represents a filter attribute confirming that user with "Vendor" customer group has appropriate vendor account+/// associated (and active)+/// </summary>+public class AuthorizeVendorAttribute : TypeFilterAttribute{/// <summary>- /// Represents a filter attribute confirming that user with "Vendor" customer group has appropriate vendor account associated (and active)+ /// Create instance of the filter attribute/// </summary>- public class AuthorizeVendorAttribute : TypeFilterAttribute+ /// <param name="ignore">Whether to ignore the execution of filter actions</param>+ public AuthorizeVendorAttribute(bool ignore = false) : base(typeof(AuthorizeVendorFilter)){- private readonly bool _ignoreFilter;+ IgnoreFilter = ignore;+ Arguments = [ignore];+ }- /// <summary>- /// Create instance of the filter attribute- /// </summary>- /// <param name="ignore">Whether to ignore the execution of filter actions</param>- public AuthorizeVendorAttribute(bool ignore = false) : base(typeof(AuthorizeVendorFilter))+ public bool IgnoreFilter { get; }++ #region Filter++ /// <summary>+ /// Represents a filter confirming that user with "Vendor" customer group has appropriate vendor account associated+ /// (and active)+ /// </summary>+ private class AuthorizeVendorFilter : IAsyncAuthorizationFilter+ {+ #region Ctor++ public AuthorizeVendorFilter(bool ignoreFilter, IWorkContext workContext, IGroupService groupService,+ IPermissionService permissionService){- _ignoreFilter = ignore;- Arguments = [ignore];+ _ignoreFilter = ignoreFilter;+ _workContext = workContext;+ _groupService = groupService;+ _permissionService = permissionService;}- public bool IgnoreFilter => _ignoreFilter;+ #endregion- #region Filter+ #region Methods/// <summary>- /// Represents a filter confirming that user with "Vendor" customer group has appropriate vendor account associated (and active)+ /// Called early in the filter pipeline to confirm request is authorized/// </summary>- private class AuthorizeVendorFilter : IAsyncAuthorizationFilter+ /// <param name="context">Authorization filter context</param>+ public async Task OnAuthorizationAsync(AuthorizationFilterContext context){- #region Fields-- private readonly bool _ignoreFilter;- private readonly IPermissionService _permissionService;- private readonly IWorkContext _workContext;- private readonly IGroupService _groupService;- #endregion-- #region Ctor-- public AuthorizeVendorFilter(bool ignoreFilter, IWorkContext workContext, IGroupService groupService, IPermissionService permissionService)- {- _ignoreFilter = ignoreFilter;- _workContext = workContext;- _groupService = groupService;- _permissionService = permissionService;- }-- #endregion-- #region Methods-- /// <summary>- /// Called early in the filter pipeline to confirm request is authorized- /// </summary>- /// <param name="context">Authorization filter context</param>- public async Task OnAuthorizationAsync(AuthorizationFilterContext context)- {- //ignore filter actions- ArgumentNullException.ThrowIfNull(context);-- //check whether this filter has been overridden for the Action- var actionFilter = context.ActionDescriptor.FilterDescriptors- .Where(f => f.Scope == FilterScope.Action)- .Select(f => f.Filter).OfType<AuthorizeVendorAttribute>().FirstOrDefault();-- //ignore filter (the action is available even if the current customer isn't a vendor)- if (actionFilter?.IgnoreFilter ?? _ignoreFilter)- return;-- if (!DataSettingsManager.DatabaseIsInstalled())- return;-- //authorize permission of access to the vendor area- if (!await _permissionService.Authorize(StandardPermission.ManageAccessVendorPanel))- context.Result = new RedirectToRouteResult("VendorLogin", new RouteValueDictionary());-- //ensure that this user has active vendor record associated- if (!await _groupService.IsVendor(_workContext.CurrentCustomer) || _workContext.CurrentVendor == null)- context.Result = new RedirectToRouteResult("VendorLogin", new RouteValueDictionary());-- }-- #endregion+ //ignore filter actions+ ArgumentNullException.ThrowIfNull(context);++ //check whether this filter has been overridden for the Action+ var actionFilter = context.ActionDescriptor.FilterDescriptors+ .Where(f => f.Scope == FilterScope.Action)+ .Select(f => f.Filter).OfType<AuthorizeVendorAttribute>().FirstOrDefault();++ //ignore filter (the action is available even if the current customer isn't a vendor)+ if (actionFilter?.IgnoreFilter ?? _ignoreFilter)+ return;++ if (!DataSettingsManager.DatabaseIsInstalled())+ return;++ //authorize permission of access to the vendor area+ if (!await _permissionService.Authorize(StandardPermission.ManageAccessVendorPanel))+ context.Result = new RedirectToRouteResult("VendorLogin", new RouteValueDictionary());++ //ensure that this user has active vendor record associated+ if (!await _groupService.IsVendor(_workContext.CurrentCustomer) || _workContext.CurrentVendor == null)+ context.Result = new RedirectToRouteResult("VendorLogin", new RouteValueDictionary());}#endregion++ #region Fields++ private readonly bool _ignoreFilter;+ private readonly IPermissionService _permissionService;+ private readonly IWorkContext _workContext;+ private readonly IGroupService _groupService;++ #endregion}++ #endregion}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Filters/ClosedStoreAttribute.cs b/src/Web/Grand.Web.Common/Filters/ClosedStoreAttribute.csindex b15916ce1..b2e55eda1 100644--- a/src/Web/Grand.Web.Common/Filters/ClosedStoreAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/ClosedStoreAttribute.cs@@ -9,140 +9,139 @@ using Microsoft.AspNetCore.Mvc.Controllers;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.Routing;-namespace Grand.Web.Common.Filters+namespace Grand.Web.Common.Filters;++/// <summary>+/// Represents a filter attribute that confirms access to a closed store+/// </summary>+public class ClosedStoreAttribute : TypeFilterAttribute{/// <summary>- /// Represents a filter attribute that confirms access to a closed store+ /// Create instance of the filter attribute/// </summary>- public class ClosedStoreAttribute : TypeFilterAttribute+ /// <param name="ignore">Whether to ignore the execution of filter actions</param>+ public ClosedStoreAttribute(bool ignore = false) : base(typeof(CheckAccessClosedStoreFilter)){- private readonly bool _ignoreFilter;- /// <summary>- /// Create instance of the filter attribute- /// </summary>- /// <param name="ignore">Whether to ignore the execution of filter actions</param>- public ClosedStoreAttribute(bool ignore = false) : base(typeof(CheckAccessClosedStoreFilter))+ IgnoreFilter = ignore;+ Arguments = [ignore];+ }++ public bool IgnoreFilter { get; }++ #region Filter++ /// <summary>+ /// Represents a filter that confirms access to closed store+ /// </summary>+ private class CheckAccessClosedStoreFilter : IAsyncActionFilter+ {+ #region Ctor++ public CheckAccessClosedStoreFilter(bool ignoreFilter,+ IPermissionService permissionService,+ IWorkContext workContext,+ IPageService pageService,+ StoreInformationSettings storeInformationSettings){- _ignoreFilter = ignore;- Arguments = [ignore];+ _ignoreFilter = ignoreFilter;+ _permissionService = permissionService;+ _workContext = workContext;+ _pageService = pageService;+ _storeInformationSettings = storeInformationSettings;}- public bool IgnoreFilter => _ignoreFilter;+ #endregion- #region Filter+ #region Methods/// <summary>- /// Represents a filter that confirms access to closed store+ /// Called before the action executes, after model binding is complete/// </summary>- private class CheckAccessClosedStoreFilter : IAsyncActionFilter+ /// <param name="context">A context for action filters</param>+ /// <param name="next">Action execution delegate</param>+ public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next){- #region Fields+ //check whether this filter has been overridden for the Action+ var actionFilter = context.ActionDescriptor.FilterDescriptors+ .Where(f => f.Scope == FilterScope.Action)+ .Select(f => f.Filter).OfType<ClosedStoreAttribute>().FirstOrDefault();- private readonly bool _ignoreFilter;- private readonly IPermissionService _permissionService;- private readonly IWorkContext _workContext;- private readonly IPageService _pageService;- private readonly StoreInformationSettings _storeInformationSettings;-- #endregion-- #region Ctor-- public CheckAccessClosedStoreFilter(bool ignoreFilter,- IPermissionService permissionService,- IWorkContext workContext,- IPageService pageService,- StoreInformationSettings storeInformationSettings)+ if (actionFilter?.IgnoreFilter ?? _ignoreFilter){- _ignoreFilter = ignoreFilter;- _permissionService = permissionService;- _workContext = workContext;- _pageService = pageService;- _storeInformationSettings = storeInformationSettings;+ await next();+ return;}- #endregion-- #region Methods+ if (!DataSettingsManager.DatabaseIsInstalled())+ {+ await next();+ return;+ }- /// <summary>- /// Called before the action executes, after model binding is complete- /// </summary>- /// <param name="context">A context for action filters</param>- /// <param name="next">Action execution delegate</param>- public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)+ //store isn't closed+ if (!_storeInformationSettings.StoreClosed){- //check whether this filter has been overridden for the Action- var actionFilter = context.ActionDescriptor.FilterDescriptors- .Where(f => f.Scope == FilterScope.Action)- .Select(f => f.Filter).OfType<ClosedStoreAttribute>().FirstOrDefault();+ await next();+ return;+ }- if (actionFilter?.IgnoreFilter ?? _ignoreFilter)- {- await next();- return;- }+ //get action and controller names+ var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;+ var actionName = actionDescriptor?.ActionName;+ var controllerName = actionDescriptor?.ControllerName;- if (!DataSettingsManager.DatabaseIsInstalled())- {- await next();- return;- }+ if (string.IsNullOrEmpty(actionName) || string.IsNullOrEmpty(controllerName) ||+ (controllerName.Equals("Common", StringComparison.OrdinalIgnoreCase) &&+ actionName.Equals("StoreClosed", StringComparison.OrdinalIgnoreCase)))+ {+ await next();+ return;+ }- //store isn't closed- if (!_storeInformationSettings.StoreClosed)+ //pages accessible when a store is closed+ if (controllerName.Equals("Page", StringComparison.OrdinalIgnoreCase) &&+ actionName.Equals("PageDetails", StringComparison.OrdinalIgnoreCase))+ {+ //get identifiers of pages are accessible when a store is closed+ var now = DateTime.UtcNow;+ var allowedPageIds = (await _pageService.GetAllPages(_workContext.CurrentStore.Id))+ .Where(t => t.AccessibleWhenStoreClosed &&+ (!t.StartDateUtc.HasValue || t.StartDateUtc < now) &&+ (!t.EndDateUtc.HasValue || t.EndDateUtc > now))+ .Select(page => page.Id);++ //check whether requested page is allowed+ var requestedPageId = context.RouteData.Values["pageId"] as string;+ if (!string.IsNullOrEmpty(requestedPageId) && allowedPageIds.Contains(requestedPageId)){await next();return;}+ }- //get action and controller names- var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;- var actionName = actionDescriptor?.ActionName;- var controllerName = actionDescriptor?.ControllerName;-- if (string.IsNullOrEmpty(actionName) || string.IsNullOrEmpty(controllerName) ||- (controllerName.Equals("Common", StringComparison.OrdinalIgnoreCase) &&- actionName.Equals("StoreClosed", StringComparison.OrdinalIgnoreCase)))- {- await next();- return;- }+ //check whether current customer has access to a closed store+ if (await _permissionService.Authorize(StandardPermission.AccessClosedStore))+ {+ await next();+ return;+ }- //pages accessible when a store is closed- if (controllerName.Equals("Page", StringComparison.OrdinalIgnoreCase) &&- actionName.Equals("PageDetails", StringComparison.OrdinalIgnoreCase))- {- //get identifiers of pages are accessible when a store is closed- var now = DateTime.UtcNow;- var allowedPageIds = (await _pageService.GetAllPages(_workContext.CurrentStore.Id))- .Where(t => t.AccessibleWhenStoreClosed &&- (!t.StartDateUtc.HasValue || t.StartDateUtc < now) && (!t.EndDateUtc.HasValue || t.EndDateUtc > now))- .Select(page => page.Id);-- //check whether requested page is allowed- var requestedPageId = context.RouteData.Values["pageId"] as string;- if (!string.IsNullOrEmpty(requestedPageId) && allowedPageIds.Contains(requestedPageId))- {- await next();- return;- }- }+ //store is closed and no access, so redirect to 'StoreClosed' page+ context.Result = new RedirectToRouteResult("StoreClosed", new RouteValueDictionary());+ }- //check whether current customer has access to a closed store- if (await _permissionService.Authorize(StandardPermission.AccessClosedStore))- {- await next();- return;- }+ #endregion- //store is closed and no access, so redirect to 'StoreClosed' page- context.Result = new RedirectToRouteResult("StoreClosed", new RouteValueDictionary());- }+ #region Fields- #endregion- }+ private readonly bool _ignoreFilter;+ private readonly IPermissionService _permissionService;+ private readonly IWorkContext _workContext;+ private readonly IPageService _pageService;+ private readonly StoreInformationSettings _storeInformationSettings;#endregion}++ #endregion}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Filters/CustomerActivityAttribute.cs b/src/Web/Grand.Web.Common/Filters/CustomerActivityAttribute.csindex d3ed715b6..55f9f1cec 100644--- a/src/Web/Grand.Web.Common/Filters/CustomerActivityAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/CustomerActivityAttribute.cs@@ -1,122 +1,129 @@using Grand.Business.Core.Extensions;using Grand.Business.Core.Interfaces.Common.Directory;using Grand.Business.Core.Interfaces.Customers;+using Grand.Data;using Grand.Domain.Common;using Grand.Domain.Customers;-using Grand.Data;using Grand.Infrastructure;using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Http.Extensions;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;-namespace Grand.Web.Common.Filters+namespace Grand.Web.Common.Filters;++/// <summary>+/// Represents filter attribute that saves last customer activity date+/// </summary>+public class CustomerActivityAttribute : TypeFilterAttribute{/// <summary>- /// Represents filter attribute that saves last customer activity date+ /// Create instance of the filter attribute/// </summary>- public class CustomerActivityAttribute : TypeFilterAttribute+ public CustomerActivityAttribute() : base(typeof(CustomerActivityFilter)){- /// <summary>- /// Create instance of the filter attribute- /// </summary>- public CustomerActivityAttribute() : base(typeof(CustomerActivityFilter))+ }++ #region Filter++ /// <summary>+ /// Represents a filter that saves last customer activity date+ /// </summary>+ private class CustomerActivityFilter : IAsyncActionFilter+ {+ #region Ctor++ public CustomerActivityFilter(+ ICustomerService customerService,+ IWorkContext workContext,+ IUserFieldService userFieldService,+ CustomerSettings customerSettings){+ _customerService = customerService;+ _workContext = workContext;+ _userFieldService = userFieldService;+ _customerSettings = customerSettings;}- #region Filter+ #endregion++ #region Methods/// <summary>- /// Represents a filter that saves last customer activity date+ /// Called before the action executes, after model binding is complete/// </summary>- private class CustomerActivityFilter : IAsyncActionFilter+ /// <param name="context">A context for action filters</param>+ /// <param name="next"></param>+ public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next){- #region Fields+ await next();- private readonly ICustomerService _customerService;- private readonly IWorkContext _workContext;- private readonly IUserFieldService _userFieldService;- private readonly CustomerSettings _customerSettings;+ if (!DataSettingsManager.DatabaseIsInstalled())+ return;- #endregion+ //only in GET requests+ if (!HttpMethods.IsGet(context.HttpContext.Request.Method))+ return;- #region Ctor+ //whether is need to store last visited page URL+ if (!_customerSettings.StoreLastVisitedPage)+ return;- public CustomerActivityFilter(- ICustomerService customerService,- IWorkContext workContext,- IUserFieldService userFieldService,- CustomerSettings customerSettings)+ //update last activity date+ if (_workContext.CurrentCustomer.LastActivityDateUtc.AddMinutes(3.0) < DateTime.UtcNow)+ await _customerService.UpdateCustomerField(_workContext.CurrentCustomer, x => x.LastActivityDateUtc,+ DateTime.UtcNow);++ //get current IP address+ var currentIpAddress = context.HttpContext?.Connection?.RemoteIpAddress?.ToString();++ //update customer's IP address+ if (!string.IsNullOrEmpty(currentIpAddress) &&+ !currentIpAddress.Equals(_workContext.CurrentCustomer.LastIpAddress,+ StringComparison.OrdinalIgnoreCase)){- _customerService = customerService;- _workContext = workContext;- _userFieldService = userFieldService;- _customerSettings = customerSettings;+ _workContext.CurrentCustomer.LastIpAddress = currentIpAddress;+ await _customerService.UpdateCustomerField(_workContext.CurrentCustomer, x => x.LastIpAddress,+ currentIpAddress);}- #endregion+ //get current page+ var pageUrl = context.HttpContext?.Request?.GetDisplayUrl();+ if (string.IsNullOrEmpty(pageUrl))+ return;++ //get previous last page+ var previousPageUrl =+ _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LastVisitedPage);- #region Methods+ //save new one if don't match+ if (!pageUrl.Equals(previousPageUrl, StringComparison.OrdinalIgnoreCase))+ await _userFieldService.SaveField(_workContext.CurrentCustomer,+ SystemCustomerFieldNames.LastVisitedPage, pageUrl);- /// <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)+ if (context.HttpContext.Request?.GetTypedHeaders().Referer?.ToString() is { } referer &&+ !referer.Contains(context.HttpContext.Request.Host.ToString())){- await next();-- if (!DataSettingsManager.DatabaseIsInstalled())- return;-- //only in GET requests- if (!HttpMethods.IsGet(context.HttpContext.Request.Method))- return;-- //whether is need to store last visited page URL- if (!_customerSettings.StoreLastVisitedPage)- return;-- //update last activity date- if (_workContext.CurrentCustomer.LastActivityDateUtc.AddMinutes(3.0) < DateTime.UtcNow)- {- await _customerService.UpdateCustomerField(_workContext.CurrentCustomer, x => x.LastActivityDateUtc, DateTime.UtcNow);- }-- //get current IP address- var currentIpAddress = context.HttpContext?.Connection?.RemoteIpAddress?.ToString();-- //update customer's IP address- if (!string.IsNullOrEmpty(currentIpAddress) && !currentIpAddress.Equals(_workContext.CurrentCustomer.LastIpAddress, StringComparison.OrdinalIgnoreCase))- {- _workContext.CurrentCustomer.LastIpAddress = currentIpAddress;- await _customerService.UpdateCustomerField(_workContext.CurrentCustomer, x => x.LastIpAddress, currentIpAddress);- }- //get current page- var pageUrl = context.HttpContext?.Request?.GetDisplayUrl();- if (string.IsNullOrEmpty(pageUrl))- return;-- //get previous last page- var previousPageUrl = _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LastVisitedPage);-- //save new one if don't match- if (!pageUrl.Equals(previousPageUrl, StringComparison.OrdinalIgnoreCase))- await _userFieldService.SaveField(_workContext.CurrentCustomer, SystemCustomerFieldNames.LastVisitedPage, pageUrl);-- if (context.HttpContext.Request?.GetTypedHeaders().Referer?.ToString() is { } referer && !referer.Contains(context.HttpContext.Request.Host.ToString()))- {- var previousUrlReferrer = await _workContext.CurrentCustomer.GetUserField<string>(_userFieldService, SystemCustomerFieldNames.LastUrlReferrer);- if (previousUrlReferrer != referer)- {- await _userFieldService.SaveField(_workContext.CurrentCustomer, SystemCustomerFieldNames.LastUrlReferrer, referer);- }- }+ var previousUrlReferrer =+ await _workContext.CurrentCustomer.GetUserField<string>(_userFieldService,+ SystemCustomerFieldNames.LastUrlReferrer);+ if (previousUrlReferrer != referer)+ await _userFieldService.SaveField(_workContext.CurrentCustomer,+ SystemCustomerFieldNames.LastUrlReferrer, referer);}- #endregion}#endregion++ #region Fields++ private readonly ICustomerService _customerService;+ private readonly IWorkContext _workContext;+ private readonly IUserFieldService _userFieldService;+ private readonly CustomerSettings _customerSettings;++ #endregion}++ #endregion}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Filters/DenySystemAccountAttribute.cs b/src/Web/Grand.Web.Common/Filters/DenySystemAccountAttribute.csindex 7299eea91..491a6b547 100644--- a/src/Web/Grand.Web.Common/Filters/DenySystemAccountAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/DenySystemAccountAttribute.cs@@ -1,87 +1,83 @@-using Grand.Domain.Customers;-using Grand.Data;+using Grand.Data;+using Grand.Domain.Customers;using Grand.Infrastructure;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.Routing;-namespace Grand.Web.Common.Filters+namespace Grand.Web.Common.Filters;++/// <summary>+/// Represents a filter attribute that deny system account to some resources+/// </summary>+public class DenySystemAccountAttribute : TypeFilterAttribute{/// <summary>- /// Represents a filter attribute that deny system account to some resources+ /// Create instance of the filter attribute/// </summary>- public class DenySystemAccountAttribute : TypeFilterAttribute+ /// <param name="ignore">Whether to ignore the execution of filter actions</param>+ public DenySystemAccountAttribute(bool ignore = false) : base(typeof(DenySystemAccountFilter)){- private readonly bool _ignoreFilter;+ IgnoreFilter = ignore;+ Arguments = [ignore];+ }- /// <summary>- /// Create instance of the filter attribute- /// </summary>- /// <param name="ignore">Whether to ignore the execution of filter actions</param>- public DenySystemAccountAttribute(bool ignore = false) : base(typeof(DenySystemAccountFilter))+ public bool IgnoreFilter { get; }++ #region Filter++ /// <summary>+ /// Represents a filter that deny access for system accounts to resources+ /// </summary>+ private class DenySystemAccountFilter : IAsyncAuthorizationFilter+ {+ #region Ctor++ public DenySystemAccountFilter(bool ignoreFilter, IWorkContext workContext){- _ignoreFilter = ignore;- Arguments = [ignore];+ _ignoreFilter = ignoreFilter;+ _workContext = workContext;}- public bool IgnoreFilter => _ignoreFilter;+ #endregion- #region Filter+ #region Methods/// <summary>- /// Represents a filter that deny access for system accounts to resources+ /// Called early in the filter pipeline to confirm request is authorized/// </summary>- private class DenySystemAccountFilter : IAsyncAuthorizationFilter+ /// <param name="context">Authorization filter context</param>+ public Task OnAuthorizationAsync(AuthorizationFilterContext context){- #region Fields-- private readonly bool _ignoreFilter;- private readonly IWorkContext _workContext;+ //ignore filter (the action available even when navigation is not allowed)+ ArgumentNullException.ThrowIfNull(context);- #endregion+ var actionFilter = context.ActionDescriptor.FilterDescriptors+ .Where(f => f.Scope == FilterScope.Action)+ .Select(f => f.Filter).OfType<DenySystemAccountAttribute>().FirstOrDefault();- #region Ctor-- public DenySystemAccountFilter(bool ignoreFilter, IWorkContext workContext)- {- _ignoreFilter = ignoreFilter;- _workContext = workContext;- }-- #endregion-- #region Methods-- /// <summary>- /// Called early in the filter pipeline to confirm request is authorized- /// </summary>- /// <param name="context">Authorization filter context</param>- public Task OnAuthorizationAsync(AuthorizationFilterContext context)- {- //ignore filter (the action available even when navigation is not allowed)- ArgumentNullException.ThrowIfNull(context);-- var actionFilter = context.ActionDescriptor.FilterDescriptors- .Where(f => f.Scope == FilterScope.Action)- .Select(f => f.Filter).OfType<DenySystemAccountAttribute>().FirstOrDefault();+ //ignore filter+ if (actionFilter?.IgnoreFilter ?? _ignoreFilter)+ return Task.CompletedTask;- //ignore filter- if (actionFilter?.IgnoreFilter ?? _ignoreFilter)- return Task.CompletedTask;+ if (!DataSettingsManager.DatabaseIsInstalled())+ return Task.CompletedTask;- if (!DataSettingsManager.DatabaseIsInstalled())- return Task.CompletedTask;+ if (_workContext.CurrentCustomer.IsSystemAccount())+ context.Result = new RedirectToRouteResult("HomePage", new RouteValueDictionary());- if (_workContext.CurrentCustomer.IsSystemAccount())- context.Result = new RedirectToRouteResult("HomePage", new RouteValueDictionary());+ return Task.CompletedTask;+ }- return Task.CompletedTask;+ #endregion- }+ #region Fields- #endregion- }+ private readonly bool _ignoreFilter;+ private readonly IWorkContext _workContext;#endregion}++ #endregion}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs b/src/Web/Grand.Web.Common/Filters/LanguageAttribute.csindex b9357162f..19e579bf1 100644--- a/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs@@ -1,4 +1,5 @@-using Grand.Business.Core.Interfaces.Common.Localization;+using Flurl;+using Grand.Business.Core.Interfaces.Common.Localization;using Grand.Data;using Grand.Domain.Localization;using Grand.Infrastructure;@@ -9,132 +10,129 @@ using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using System.Net;-namespace Grand.Web.Common.Filters+namespace Grand.Web.Common.Filters;++/// <summary>+/// Represents filter attribute that checks SEO friendly URLs for multiple languages and properly redirect if necessary+/// </summary>+public class LanguageAttribute : TypeFilterAttribute{/// <summary>- /// Represents filter attribute that checks SEO friendly URLs for multiple languages and properly redirect if necessary+ /// Create instance of the filter attribute/// </summary>- public class LanguageAttribute : TypeFilterAttribute+ public LanguageAttribute() : base(typeof(LanguageSeoCodeFilter)){- /// <summary>- /// Create instance of the filter attribute- /// </summary>- public LanguageAttribute() : base(typeof(LanguageSeoCodeFilter))+ }++ #region Filter++ /// <summary>+ /// Represents a filter that checks SEO friendly URLs for multiple languages and properly redirect if necessary+ /// </summary>+ private class LanguageSeoCodeFilter : IAsyncActionFilter+ {+ #region Ctor++ public LanguageSeoCodeFilter(+ IWorkContext workContext, ILanguageService languageService,+ AppConfig config){+ _workContext = workContext;+ _languageService = languageService;+ _config = config;}- #region Filter+ #endregion- /// <summary>- /// Represents a filter that checks SEO friendly URLs for multiple languages and properly redirect if necessary- /// </summary>- private class LanguageSeoCodeFilter : IAsyncActionFilter- {- #region Fields+ #region Fields- private readonly IWorkContext _workContext;- private readonly ILanguageService _languageService;- private readonly AppConfig _config;+ private readonly IWorkContext _workContext;+ private readonly ILanguageService _languageService;+ private readonly AppConfig _config;- #endregion+ #endregion- #region Ctor+ #region Methods- public LanguageSeoCodeFilter(- IWorkContext workContext, ILanguageService languageService,- AppConfig config)+ /// <summary>+ /// Called before the action executes, after model binding is complete+ /// </summary>+ /// <param name="context">A context for action filters</param>+ /// <param name="next">Action execution delegate</param>+ public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)+ {+ if (!DataSettingsManager.DatabaseIsInstalled()){- _workContext = workContext;- _languageService = languageService;- _config = config;+ await next();+ return;}- #endregion+ //only in GET requests+ if (!HttpMethods.IsGet(context.HttpContext.Request.Method))+ {+ await next();+ return;+ }- #region Methods+ //whether SEO friendly URLs are enabled+ if (!_config.SeoFriendlyUrlsForLanguagesEnabled)+ {+ await next();+ return;+ }- /// <summary>- /// Called before the action executes, after model binding is complete- /// </summary>- /// <param name="context">A context for action filters</param>- /// <param name="next">Action execution delegate</param>- public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)+ var lang = context.RouteData.Values["language"];+ if (lang == null){- if (!DataSettingsManager.DatabaseIsInstalled())- {- await next();- return;- }-- //only in GET requests- if (!HttpMethods.IsGet(context.HttpContext.Request.Method))- {- await next();- return;- }-- //whether SEO friendly URLs are enabled- if (!_config.SeoFriendlyUrlsForLanguagesEnabled)- {- await next();- return;- }-- var lang = context.RouteData.Values["language"];- if (lang == null)- {- await next();- return;- }-- //check whether current page URL is already localized URL- var pageUrl = context.HttpContext.Request?.GetEncodedPathAndQuery();- if (await IsLocalized(pageUrl, context.HttpContext.Request.PathBase))- {- await next();- return;- }-- pageUrl = AddLanguageSeo(pageUrl, _workContext.WorkingLanguage);- context.Result = new RedirectResult(pageUrl, false);+ await next();+ return;}- private async Task<bool> IsLocalized(string url, PathString pathBase)+ //check whether current page URL is already localized URL+ var pageUrl = context.HttpContext.Request?.GetEncodedPathAndQuery();+ if (await IsLocalized(pageUrl, context.HttpContext.Request.PathBase)){- _ = new PathString(url).StartsWithSegments(pathBase, out PathString result);- url = WebUtility.UrlDecode(result);+ await next();+ return;+ }- var firstSegment = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? string.Empty;- if (string.IsNullOrEmpty(firstSegment))- return false;+ pageUrl = AddLanguageSeo(pageUrl, _workContext.WorkingLanguage);+ context.Result = new RedirectResult(pageUrl, false);+ }- //suppose that the first segment is the language code and try to get language- var language = (await _languageService.GetAllLanguages())- .FirstOrDefault(urlLanguage => urlLanguage.UniqueSeoCode.Equals(firstSegment, StringComparison.OrdinalIgnoreCase));+ private async Task<bool> IsLocalized(string url, PathString pathBase)+ {+ _ = new PathString(url).StartsWithSegments(pathBase, out var result);+ url = WebUtility.UrlDecode(result);- return language?.Published ?? false;- }+ var firstSegment = url.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ??+ string.Empty;+ if (string.IsNullOrEmpty(firstSegment))+ return false;- private static string AddLanguageSeo(string url, Language language)- {- ArgumentNullException.ThrowIfNull(language);+ //suppose that the first segment is the language code and try to get language+ var language = (await _languageService.GetAllLanguages())+ .FirstOrDefault(urlLanguage =>+ urlLanguage.UniqueSeoCode.Equals(firstSegment, StringComparison.OrdinalIgnoreCase));- //remove application path from raw URL- if (!string.IsNullOrEmpty(url))- {- url = Flurl.Url.EncodeIllegalCharacters(url);- }+ return language?.Published ?? false;+ }- //add language code- url = $"/{language.UniqueSeoCode}/{url.TrimStart('/')}";+ private static string AddLanguageSeo(string url, Language language)+ {+ ArgumentNullException.ThrowIfNull(language);- return url;- }- #endregion- }+ //remove application path from raw URL+ if (!string.IsNullOrEmpty(url)) url = Url.EncodeIllegalCharacters(url);+ //add language code+ url = $"/{language.UniqueSeoCode}/{url.TrimStart('/')}";+ return url;+ }#endregion}++ #endregion}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Filters/PasswordExpiredAttribute.cs b/src/Web/Grand.Web.Common/Filters/PasswordExpiredAttribute.csindex 148291d0c..777ad3b4b 100644--- a/src/Web/Grand.Web.Common/Filters/PasswordExpiredAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/PasswordExpiredAttribute.cs@@ -7,85 +7,82 @@ using Microsoft.AspNetCore.Mvc.Controllers;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.Routing;-namespace Grand.Web.Common.Filters+namespace Grand.Web.Common.Filters;++/// <summary>+/// Represents filter attribute that validates customer password expiration+/// </summary>+public class PasswordExpiredAttribute : TypeFilterAttribute{/// <summary>- /// Represents filter attribute that validates customer password expiration+ /// Create instance of the filter attribute/// </summary>- public class PasswordExpiredAttribute : TypeFilterAttribute+ public PasswordExpiredAttribute() : base(typeof(PasswordFilter)){- /// <summary>- /// Create instance of the filter attribute- /// </summary>- public PasswordExpiredAttribute() : base(typeof(PasswordFilter))+ }++ #region Filter++ /// <summary>+ /// Represents a filter that validates customer password expiration+ /// </summary>+ private class PasswordFilter : IAsyncAuthorizationFilter+ {+ #region Ctor++ public PasswordFilter(IWorkContext workContext, IMediator mediator){+ _workContext = workContext;+ _mediator = mediator;}- #region Filter+ #endregion++ #region Methods/// <summary>- /// Represents a filter that validates customer password expiration+ /// Called before the action executes, after model binding is complete/// </summary>- private class PasswordFilter : IAsyncAuthorizationFilter+ /// <param name="context">A context for action filters</param>+ public async Task OnAuthorizationAsync(AuthorizationFilterContext context){- #region Fields-- private readonly IWorkContext _workContext;- private readonly IMediator _mediator;+ if (!DataSettingsManager.DatabaseIsInstalled())+ return;- #endregion+ //get action and controller names+ var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;+ var actionName = actionDescriptor?.ActionName;+ var controllerName = actionDescriptor?.ControllerName;- #region Ctor+ if (string.IsNullOrEmpty(actionName) || string.IsNullOrEmpty(controllerName))+ return;- public PasswordFilter(IWorkContext workContext, IMediator mediator)+ //don't validate on ChangePassword page and store closed+ if (!(controllerName.Equals("Account", StringComparison.OrdinalIgnoreCase) &&+ actionName.Equals("ChangePassword", StringComparison.OrdinalIgnoreCase))+ &&+ !(controllerName.Equals("Common", StringComparison.OrdinalIgnoreCase) &&+ actionName.Equals("StoreClosed", StringComparison.OrdinalIgnoreCase))+ ){- _workContext = workContext;- _mediator = mediator;+ //check password expiration+ var passwordIsExpired = await _mediator.Send(new GetPasswordIsExpiredQuery+ { Customer = _workContext.CurrentCustomer });+ if (passwordIsExpired)+ //redirect to ChangePassword page if expires+ context.Result = new RedirectToRouteResult("CustomerChangePassword", new RouteValueDictionary());}+ }- #endregion-- #region Methods+ #endregion- /// <summary>- /// Called before the action executes, after model binding is complete- /// </summary>- /// <param name="context">A context for action filters</param>- public async Task OnAuthorizationAsync(AuthorizationFilterContext context)- {-- if (!DataSettingsManager.DatabaseIsInstalled())- return;-- //get action and controller names- var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;- var actionName = actionDescriptor?.ActionName;- var controllerName = actionDescriptor?.ControllerName;-- if (string.IsNullOrEmpty(actionName) || string.IsNullOrEmpty(controllerName))- return;-- //don't validate on ChangePassword page and store closed- if (!(controllerName.Equals("Account", StringComparison.OrdinalIgnoreCase) &&- actionName.Equals("ChangePassword", StringComparison.OrdinalIgnoreCase))- &&- !(controllerName.Equals("Common", StringComparison.OrdinalIgnoreCase) &&- actionName.Equals("StoreClosed", StringComparison.OrdinalIgnoreCase))- )- {- //check password expiration- var passwordIsExpired = await _mediator.Send(new GetPasswordIsExpiredQuery { Customer = _workContext.CurrentCustomer });- if (passwordIsExpired)- {- //redirect to ChangePassword page if expires- context.Result = new RedirectToRouteResult("CustomerChangePassword", new RouteValueDictionary());- }- }- }+ #region Fields- #endregion- }+ private readonly IWorkContext _workContext;+ private readonly IMediator _mediator;#endregion}++ #endregion}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Filters/PublicStoreAttribute.cs b/src/Web/Grand.Web.Common/Filters/PublicStoreAttribute.csindex 7a440bec2..b1e0fcbf1 100644--- a/src/Web/Grand.Web.Common/Filters/PublicStoreAttribute.cs+++ b/src/Web/Grand.Web.Common/Filters/PublicStoreAttribute.cs@@ -6,89 +6,89 @@ using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.Routing;-namespace Grand.Web.Common.Filters+namespace Grand.Web.Common.Filters;++/// <summary>+/// Represents a filter attribute that confirms access to public store+/// </summary>+public class PublicStoreAttribute : TypeFilterAttribute{/// <summary>- /// Represents a filter attribute that confirms access to public store+ /// Create instance of the filter attribute/// </summary>- public class PublicStoreAttribute : TypeFilterAttribute+ /// <param name="ignore">Whether to ignore the execution of filter actions</param>+ public PublicStoreAttribute(bool ignore = false) : base(typeof(AccessPublicStoreFilter)){- private readonly bool _ignoreFilter;+ IgnoreFilter = ignore;+ Arguments = [ignore];+ }- /// <summary>- /// Create instance of the filter attribute- /// </summary>- /// <param name="ignore">Whether to ignore the execution of filter actions</param>- public PublicStoreAttribute(bool ignore = false) : base(typeof(AccessPublicStoreFilter))+ public bool IgnoreFilter { get; }++ #region Filter++ /// <summary>+ /// Represents a filter that confirms access to public store+ /// </summary>+ private class AccessPublicStoreFilter : IAsyncAuthorizationFilter+ {+ #region Ctor++ public AccessPublicStoreFilter(bool ignoreFilter, IPermissionService permissionService,+ StoreInformationSettings storeInformationSettings){- _ignoreFilter = ignore;- Arguments = [ignore];+ _ignoreFilter = ignoreFilter;+ _permissionService = permissionService;+ _storeInformationSettings = storeInformationSettings;}- public bool IgnoreFilter => _ignoreFilter;+ #endregion- #region Filter+ #region Methods/// <summary>- /// Represents a filter that confirms access to public store+ /// Called early in the filter pipeline to confirm request is authorized/// </summary>- private class AccessPublicStoreFilter : IAsyncAuthorizationFilter+ /// <param name="filterContext">Authorization filter context</param>+ public async Task OnAuthorizationAsync(AuthorizationFilterContext filterContext){- #region Fields-- private readonly bool _ignoreFilter;- private readonly IPermissionService _permissionService;- private readonly StoreInformationSettings _storeInformationSettings;- #endregion-- #region Ctor-- public AccessPublicStoreFilter(bool ignoreFilter, IPermissionService permissionService, StoreInformationSettings storeInformationSettings)- {- _ignoreFilter = ignoreFilter;- _permissionService = permissionService;- _storeInformationSettings = storeInformationSettings;- }-- #endregion-- #region Methods+ //ignore filter (the action available even when navigation is not allowed)+ ArgumentNullException.ThrowIfNull(filterContext);- /// <summary>- /// Called early in the filter pipeline to confirm request is authorized- /// </summary>- /// <param name="filterContext">Authorization filter context</param>- public async Task OnAuthorizationAsync(AuthorizationFilterContext filterContext)- {- //ignore filter (the action available even when navigation is not allowed)- ArgumentNullException.ThrowIfNull(filterContext);+ //check whether this filter has been overridden for the Action+ var actionFilter = filterContext.ActionDescriptor.FilterDescriptors+ .Where(f => f.Scope == FilterScope.Action)+ .Select(f => f.Filter).OfType<PublicStoreAttribute>().FirstOrDefault();- //check whether this filter has been overridden for the Action- var actionFilter = filterContext.ActionDescriptor.FilterDescriptors- .Where(f => f.Scope == FilterScope.Action)- .Select(f => f.Filter).OfType<PublicStoreAttribute>().FirstOrDefault();+ //ignore filter (the action is available even if navigation is not allowed)+ if (actionFilter?.IgnoreFilter ?? _ignoreFilter)+ return;- //ignore filter (the action is available even if navigation is not allowed)- if (actionFilter?.IgnoreFilter ?? _ignoreFilter)- return;+ if (!DataSettingsManager.DatabaseIsInstalled())+ return;- if (!DataSettingsManager.DatabaseIsInstalled())- return;+ //check whether current customer has access to a public store+ if (await _permissionService.Authorize(StandardPermission.PublicStoreAllowNavigation))+ return;- //check whether current customer has access to a public store- if (await _permissionService.Authorize(StandardPermission.PublicStoreAllowNavigation))- return;+ filterContext.Result = _storeInformationSettings.StoreClosed+ ? new RedirectToRouteResult("StoreClosed", new RouteValueDictionary())+ :+ //customer has not access to a public store+ new RedirectToRouteResult("Login", new RouteValueDictionary());+ }- filterContext.Result = _storeInformationSettings.StoreClosed ? new RedirectToRouteResult("StoreClosed", new RouteValueDictionary()) :- //customer has not access to a public store- new RedirectToRouteResult("Login", new RouteValueDictionary());+ #endregion- }+ #region Fields- #endregion- }+ private readonly bool _ignoreFilter;+ private readonly IPermissionService _permissionService;+ private readonly StoreInformationSettings _storeInformationSettings;#endregion}++ #endregion}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.csindex f19977ec8..a0264f1ba 100644--- a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs+++ b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs@@ -18,273 +18,270 @@ using Microsoft.Extensions.Hosting;using Microsoft.Extensions.Logging;using Microsoft.Net.Http.Headers;-namespace Grand.Web.Common.Infrastructure+namespace Grand.Web.Common.Infrastructure;++/// <summary>+/// Represents extensions of IApplicationBuilder+/// </summary>+public static class ApplicationBuilderExtensions{/// <summary>- /// Represents extensions of IApplicationBuilder+ /// Add exception handling/// </summary>- public static class ApplicationBuilderExtensions+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ public static void UseGrandExceptionHandler(this IApplicationBuilder application){- /// <summary>- /// Add exception handling- /// </summary>- /// <param name="application">Builder for configuring an application's request pipeline</param>- public static void UseGrandExceptionHandler(this IApplicationBuilder application)+ var serviceProvider = application.ApplicationServices;+ var appConfig = serviceProvider.GetRequiredService<AppConfig>();+ var hostingEnvironment = serviceProvider.GetRequiredService<IWebHostEnvironment>();+ var useDetailedExceptionPage = appConfig.DisplayFullErrorStack || hostingEnvironment.IsDevelopment();+ if (useDetailedExceptionPage)+ //get detailed exceptions for developing and testing purposes+ application.UseDeveloperExceptionPage();+ else+ //or use special exception handler+ application.UseExceptionHandler("/errorpage.htm");++ //log errors+ application.UseExceptionHandler(handler =>{- var serviceProvider = application.ApplicationServices;- var appConfig = serviceProvider.GetRequiredService<AppConfig>();- var hostingEnvironment = serviceProvider.GetRequiredService<IWebHostEnvironment>();- var useDetailedExceptionPage = appConfig.DisplayFullErrorStack || hostingEnvironment.IsDevelopment();- if (useDetailedExceptionPage)- {- //get detailed exceptions for developing and testing purposes- application.UseDeveloperExceptionPage();- }- else+ handler.Run(async context =>{- //or use special exception handler- application.UseExceptionHandler("/errorpage.htm");- }+ var exception = context.Features.Get<IExceptionHandlerFeature>()?.Error;+ if (exception == null)+ return;- //log errors- application.UseExceptionHandler(handler =>- {- handler.Run(async context =>+ string authHeader = context.Request.Headers["Authorization"];+ var apiRequest = authHeader != null && authHeader.Split(' ')[0] == "Bearer";+ if (apiRequest){- var exception = context.Features.Get<IExceptionHandlerFeature>()?.Error;- if (exception == null)- return;+ await context.Response.WriteAsync(exception.Message);+ return;+ }- string authHeader = context.Request.Headers["Authorization"];- var apiRequest = authHeader != null && authHeader.Split(' ')[0] == "Bearer";- if (apiRequest)- {- await context.Response.WriteAsync(exception.Message);- return;- }- try- {- //check whether database is installed- if (DataSettingsManager.DatabaseIsInstalled())- {- var logger = context.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("UseExceptionHandler");- //log error- logger.LogError(exception, exception.Message);- }- }- finally+ try+ {+ //check whether database is installed+ if (DataSettingsManager.DatabaseIsInstalled()){- //rethrow the exception to show the error page- throw exception;+ var logger = context.RequestServices.GetRequiredService<ILoggerFactory>()+ .CreateLogger("UseExceptionHandler");+ //log error+ logger.LogError(exception, exception.Message);}- });+ }+ finally+ {+ //rethrow the exception to show the error page+ throw exception;+ }});- }+ });+ }- /// <summary>- /// Adds a special handler that checks for responses with the 404 status code that do not have a body- /// </summary>- /// <param name="application">Builder for configuring an application's request pipeline</param>- public static void UsePageNotFound(this IApplicationBuilder application)+ /// <summary>+ /// Adds a special handler that checks for responses with the 404 status code that do not have a body+ /// </summary>+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ public static void UsePageNotFound(this IApplicationBuilder application)+ {+ application.UseStatusCodePages(async context =>{- application.UseStatusCodePages(async context =>+ //handle 404 Not Found+ if (context.HttpContext.Response.StatusCode == 404){- //handle 404 Not Found- if (context.HttpContext.Response.StatusCode == 404)- {- string authHeader = context.HttpContext.Request.Headers[HeaderNames.Authorization];- var apiRequest = authHeader != null && authHeader.Split(' ')[0] == JwtBearerDefaults.AuthenticationScheme;+ string authHeader = context.HttpContext.Request.Headers[HeaderNames.Authorization];+ var apiRequest = authHeader != null &&+ authHeader.Split(' ')[0] == JwtBearerDefaults.AuthenticationScheme;- var contentTypeProvider = new FileExtensionContentTypeProvider();- var staticResource = contentTypeProvider.TryGetContentType(context.HttpContext.Request.Path, out _);+ var contentTypeProvider = new FileExtensionContentTypeProvider();+ var staticResource = contentTypeProvider.TryGetContentType(context.HttpContext.Request.Path, out _);- if (!apiRequest && !staticResource)- {- const string location = "/page-not-found";- context.HttpContext.Response.Redirect(context.HttpContext.Request.PathBase + location);- }+ if (!apiRequest && !staticResource)+ {+ const string location = "/page-not-found";+ context.HttpContext.Response.Redirect(context.HttpContext.Request.PathBase + location);}- await Task.CompletedTask;- });- }+ }- /// <summary>- /// Adds a special handler that checks for responses with the 400 status code (bad request)- /// </summary>- /// <param name="application">Builder for configuring an application's request pipeline</param>- public static void UseBadRequestResult(this IApplicationBuilder application)- {- application.UseStatusCodePages(context =>- {- //handle 400 (Bad request)- if (context.HttpContext.Response.StatusCode != StatusCodes.Status400BadRequest)- return Task.CompletedTask;-- string authHeader = context.HttpContext.Request.Headers[HeaderNames.Authorization];- var apiRequest = authHeader != null && authHeader.Split(' ')[0] == JwtBearerDefaults.AuthenticationScheme;+ await Task.CompletedTask;+ });+ }- if (apiRequest) return Task.CompletedTask;- var logger = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("UseBadRequestResult");- logger.LogError("Error 400. Bad request");+ /// <summary>+ /// Adds a special handler that checks for responses with the 400 status code (bad request)+ /// </summary>+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ public static void UseBadRequestResult(this IApplicationBuilder application)+ {+ application.UseStatusCodePages(context =>+ {+ //handle 400 (Bad request)+ if (context.HttpContext.Response.StatusCode != StatusCodes.Status400BadRequest)return Task.CompletedTask;- });- }- /// <summary>- /// Configure authentication- /// </summary>- /// <param name="application">Builder for configuring an application's request pipeline</param>- public static void UseGrandAuthentication(this IApplicationBuilder application)- {- application.UseAuthentication();- application.UseAuthorization();- }+ string authHeader = context.HttpContext.Request.Headers[HeaderNames.Authorization];+ var apiRequest = authHeader != null && authHeader.Split(' ')[0] == JwtBearerDefaults.AuthenticationScheme;- /// <summary>- /// Configure MVC endpoint- /// </summary>- /// <param name="application">Builder for configuring an application's request pipeline</param>- public static void UseGrandEndpoints(this IApplicationBuilder application)- {- application.UseEndpoints(endpoints =>- {- var typeSearcher = endpoints.ServiceProvider.GetRequiredService<ITypeSearcher>();- var endpointProviders = typeSearcher.ClassesOfType<IEndpointProvider>();- var instances = endpointProviders- .Where(PluginExtensions.OnlyInstalledPlugins)- .Select(endpointProvider => (IEndpointProvider)Activator.CreateInstance(endpointProvider))- .OrderByDescending(endpointProvider => endpointProvider!.Priority);+ if (apiRequest) return Task.CompletedTask;+ var logger = context.HttpContext.RequestServices.GetRequiredService<ILoggerFactory>()+ .CreateLogger("UseBadRequestResult");+ logger.LogError("Error 400. Bad request");+ return Task.CompletedTask;+ });+ }- foreach (var endpointProvider in instances)- endpointProvider.RegisterEndpoint(endpoints);- });- }+ /// <summary>+ /// Configure authentication+ /// </summary>+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ public static void UseGrandAuthentication(this IApplicationBuilder application)+ {+ application.UseAuthentication();+ application.UseAuthorization();+ }- /// <summary>- /// Configure MVC endpoint- /// </summary>- /// <param name="application">Builder for configuring an application's request pipeline</param>- public static void UseGrandDetection(this IApplicationBuilder application)+ /// <summary>+ /// Configure MVC endpoint+ /// </summary>+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ public static void UseGrandEndpoints(this IApplicationBuilder application)+ {+ application.UseEndpoints(endpoints =>{- application.UseDetection();- }+ var typeSearcher = endpoints.ServiceProvider.GetRequiredService<ITypeSearcher>();+ var endpointProviders = typeSearcher.ClassesOfType<IEndpointProvider>();+ var instances = endpointProviders+ .Where(PluginExtensions.OnlyInstalledPlugins)+ .Select(endpointProvider => (IEndpointProvider)Activator.CreateInstance(endpointProvider))+ .OrderByDescending(endpointProvider => endpointProvider!.Priority);- /// <summary>- /// Configure static file serving- /// </summary>- /// <param name="application">Builder for configuring an application's request pipeline</param>- /// <param name="appConfig">AppConfig</param>- public static void UseGrandStaticFiles(this IApplicationBuilder application, AppConfig appConfig)- {- //static files- application.UseStaticFiles(new StaticFileOptions {+ foreach (var endpointProvider in instances)+ endpointProvider.RegisterEndpoint(endpoints);+ });+ }++ /// <summary>+ /// Configure MVC endpoint+ /// </summary>+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ public static void UseGrandDetection(this IApplicationBuilder application)+ {+ application.UseDetection();+ }++ /// <summary>+ /// Configure static file serving+ /// </summary>+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ /// <param name="appConfig">AppConfig</param>+ public static void UseGrandStaticFiles(this IApplicationBuilder application, AppConfig appConfig)+ {+ //static files+ application.UseStaticFiles(new StaticFileOptions {+ OnPrepareResponse = ctx =>+ {+ if (!string.IsNullOrEmpty(appConfig.StaticFilesCacheControl))+ ctx.Context.Response.Headers.Append(HeaderNames.CacheControl, appConfig.StaticFilesCacheControl);+ }+ });+ //plugins+ if (Directory.Exists(CommonPath.PluginsPath))+ application.UseStaticFiles(new StaticFileOptions {+ FileProvider = new PhysicalFileProvider(CommonPath.PluginsPath),+ RequestPath = new PathString("/Plugins"),OnPrepareResponse = ctx =>{if (!string.IsNullOrEmpty(appConfig.StaticFilesCacheControl))- ctx.Context.Response.Headers.Append(HeaderNames.CacheControl, appConfig.StaticFilesCacheControl);+ ctx.Context.Response.Headers.Append(HeaderNames.CacheControl,+ appConfig.StaticFilesCacheControl);}-});+ }- //plugins- if (Directory.Exists(CommonPath.PluginsPath))- application.UseStaticFiles(new StaticFileOptions {- FileProvider = new PhysicalFileProvider(CommonPath.PluginsPath),- RequestPath = new PathString("/Plugins"),- OnPrepareResponse = ctx =>- {- if (!string.IsNullOrEmpty(appConfig.StaticFilesCacheControl))- ctx.Context.Response.Headers.Append(HeaderNames.CacheControl, appConfig.StaticFilesCacheControl);- }- });-- }-- /// <summary>- /// Configure UseForwardedHeaders- /// </summary>- /// <param name="application">Builder for configuring an application's request pipeline</param>- public static void UseGrandForwardedHeaders(this IApplicationBuilder application)- {- application.UseForwardedHeaders(new ForwardedHeadersOptions {- ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto- });- }+ /// <summary>+ /// Configure UseForwardedHeaders+ /// </summary>+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ public static void UseGrandForwardedHeaders(this IApplicationBuilder application)+ {+ application.UseForwardedHeaders(new ForwardedHeadersOptions {+ ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto+ });+ }- /// <summary>- /// Configure Health checks- /// </summary>- /// <param name="application">Builder for configuring an application's request pipeline</param>- public static void UseGrandHealthChecks(this IApplicationBuilder application)- {- application.UseHealthChecks("/health/live");- }+ /// <summary>+ /// Configure Health checks+ /// </summary>+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ public static void UseGrandHealthChecks(this IApplicationBuilder application)+ {+ application.UseHealthChecks("/health/live");+ }- /// <summary>- /// Configures the default security headers for your application.- /// </summary>- /// <param name="application">Builder for configuring an application's request pipeline</param>- public static void UseDefaultSecurityHeaders(this IApplicationBuilder application)- {- var policyCollection = new HeaderPolicyCollection()- .AddXssProtectionBlock()- .AddFrameOptionsDeny()- .AddContentTypeOptionsNoSniff()- .AddStrictTransportSecurityMaxAgeIncludeSubDomains(maxAgeInSeconds: 60 * 60 * 24 * 365) // max-age = one year in seconds- .AddReferrerPolicyStrictOriginWhenCrossOrigin()- .AddContentSecurityPolicy(builder =>- {- builder.AddUpgradeInsecureRequests();- builder.AddDefaultSrc().Self();- builder.AddConnectSrc().From("*");- builder.AddFontSrc().From("*");- builder.AddFrameAncestors().From("*");- builder.AddFrameSrc().From("*");- builder.AddMediaSrc().From("*");- builder.AddImgSrc().From("*").Data();- builder.AddObjectSrc().From("*");- builder.AddScriptSrc().From("*").UnsafeInline().UnsafeEval();- builder.AddStyleSrc().From("*").UnsafeEval().UnsafeInline();- })- .AddPermissionsPolicy(builder =>- {- builder.AddAutoplay().Self();- builder.AddCamera().Self();- builder.AddEncryptedMedia().Self();- builder.AddFullscreen().All();- builder.AddGeolocation().Self();- builder.AddGyroscope().None();- builder.AddMagnetometer().None();- builder.AddMicrophone().Self();- builder.AddMidi().None();- builder.AddPayment().Self();- builder.AddPictureInPicture().None();- builder.AddSyncXHR().None();- builder.AddUsb().None();- })- .RemoveServerHeader();+ /// <summary>+ /// Configures the default security headers for your application.+ /// </summary>+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ public static void UseDefaultSecurityHeaders(this IApplicationBuilder application)+ {+ var policyCollection = new HeaderPolicyCollection()+ .AddXssProtectionBlock()+ .AddFrameOptionsDeny()+ .AddContentTypeOptionsNoSniff()+ .AddStrictTransportSecurityMaxAgeIncludeSubDomains() // max-age = one year in seconds+ .AddReferrerPolicyStrictOriginWhenCrossOrigin()+ .AddContentSecurityPolicy(builder =>+ {+ builder.AddUpgradeInsecureRequests();+ builder.AddDefaultSrc().Self();+ builder.AddConnectSrc().From("*");+ builder.AddFontSrc().From("*");+ builder.AddFrameAncestors().From("*");+ builder.AddFrameSrc().From("*");+ builder.AddMediaSrc().From("*");+ builder.AddImgSrc().From("*").Data();+ builder.AddObjectSrc().From("*");+ builder.AddScriptSrc().From("*").UnsafeInline().UnsafeEval();+ builder.AddStyleSrc().From("*").UnsafeEval().UnsafeInline();+ })+ .AddPermissionsPolicy(builder =>+ {+ builder.AddAutoplay().Self();+ builder.AddCamera().Self();+ builder.AddEncryptedMedia().Self();+ builder.AddFullscreen().All();+ builder.AddGeolocation().Self();+ builder.AddGyroscope().None();+ builder.AddMagnetometer().None();+ builder.AddMicrophone().Self();+ builder.AddMidi().None();+ builder.AddPayment().Self();+ builder.AddPictureInPicture().None();+ builder.AddSyncXHR().None();+ builder.AddUsb().None();+ })+ .RemoveServerHeader();- application.UseSecurityHeaders(policyCollection);- }-- /// <summary>- /// Configure middleware checking whether database is installed- /// </summary>- /// <param name="application">Builder for configuring an application's request pipeline</param>- public static void UseInstallUrl(this IApplicationBuilder application)- {- application.UseMiddleware<InstallUrlMiddleware>();- }+ application.UseSecurityHeaders(policyCollection);+ }- /// <summary>- /// Configures whether use or not the Header X-Powered-By and its value.- /// </summary>- /// <param name="application">Builder for configuring an application's request pipeline</param>- public static void UsePoweredBy(this IApplicationBuilder application)- {- application.UseMiddleware<PoweredByMiddleware>();- }+ /// <summary>+ /// Configure middleware checking whether database is installed+ /// </summary>+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ public static void UseInstallUrl(this IApplicationBuilder application)+ {+ application.UseMiddleware<InstallUrlMiddleware>();+ }+ /// <summary>+ /// Configures whether use or not the Header X-Powered-By and its value.+ /// </summary>+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ public static void UsePoweredBy(this IApplicationBuilder application)+ {+ application.UseMiddleware<PoweredByMiddleware>();}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs b/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.csindex c2fb4f8ce..7c87adc98 100644--- a/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs+++ b/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs@@ -1,122 +1,125 @@using Grand.Business.Core.Interfaces.System.ScheduleTasks;-using Grand.Infrastructure;using Grand.Domain.Tasks;+using Grand.Infrastructure;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;using Microsoft.Extensions.Logging;-namespace Grand.Web.Common.Infrastructure+namespace Grand.Web.Common.Infrastructure;++public class BackgroundServiceTask : BackgroundService{- public class BackgroundServiceTask : BackgroundService+ private readonly IServiceProvider _serviceProvider;+ private readonly string _taskType;++ public BackgroundServiceTask(string taskType, IServiceProvider serviceProvider){- private readonly IServiceProvider _serviceProvider;- private readonly string _taskType;- public BackgroundServiceTask(string taskType, IServiceProvider serviceProvider)- {- _taskType = taskType;- _serviceProvider = serviceProvider;- }+ _taskType = taskType;+ _serviceProvider = serviceProvider;+ }- protected override async Task ExecuteAsync(CancellationToken stoppingToken)- {- while (!stoppingToken.IsCancellationRequested)+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)+ {+ while (!stoppingToken.IsCancellationRequested)+ try{- try+ using var scope = _serviceProvider.CreateScope();+ var serviceProvider = scope.ServiceProvider;+ var logger = serviceProvider.GetService<ILogger<BackgroundServiceTask>>();+ var scheduleTaskService = serviceProvider.GetService<IScheduleTaskService>();+ var task = await scheduleTaskService.GetTaskByType(_taskType);+ if (task == null){- using var scope = _serviceProvider.CreateScope();- var serviceProvider = scope.ServiceProvider;- var logger = serviceProvider.GetService<ILogger<BackgroundServiceTask>>();- var scheduleTaskService = serviceProvider.GetService<IScheduleTaskService>();- var task = await scheduleTaskService.GetTaskByType(_taskType);- if (task == null)- {- logger.LogInformation("Task {TaskType} is not exists in the database", _taskType);- break;- }+ logger.LogInformation("Task {TaskType} is not exists in the database", _taskType);+ break;+ }- var machineName = Environment.MachineName;- var timeInterval = task.TimeInterval > 0 ? task.TimeInterval : 1;- if (task.Enabled && (string.IsNullOrEmpty(task.LeasedByMachineName) || machineName == task.LeasedByMachineName))+ var machineName = Environment.MachineName;+ var timeInterval = task.TimeInterval > 0 ? task.TimeInterval : 1;+ if (task.Enabled && (string.IsNullOrEmpty(task.LeasedByMachineName) ||+ machineName == task.LeasedByMachineName))+ {+ var typeofTask = Type.GetType(_taskType);+ if (typeofTask != null){- var typeofTask = Type.GetType(_taskType);- if (typeofTask != null)+ var scheduleTask = serviceProvider.GetServices<IScheduleTask>()+ .FirstOrDefault(x => x.GetType() == typeofTask);+ if (scheduleTask != null){- var scheduleTask = serviceProvider.GetServices<IScheduleTask>().FirstOrDefault(x => x.GetType() == typeofTask);- if (scheduleTask != null)+ //assign current customer (background task) / current store (from task)+ await WorkContext(serviceProvider, task);+ var runTask = true;+ if (task.LastStartUtc.HasValue){-- //assign current customer (background task) / current store (from task)- await WorkContext(serviceProvider, task);- var runTask = true;- if(task.LastStartUtc.HasValue)+ var dateTimeNow = DateTime.UtcNow;+ if (dateTimeNow < task.LastStartUtc.Value.AddMinutes(task.TimeInterval)){- var dateTimeNow = DateTime.UtcNow;- if (dateTimeNow < task.LastStartUtc.Value.AddMinutes(task.TimeInterval))- {- runTask = false;- timeInterval = (int)(task.LastStartUtc.Value.AddMinutes(task.TimeInterval) - dateTimeNow).TotalMinutes;- }- else- {- runTask = true;- timeInterval = task.TimeInterval > 0 ? task.TimeInterval : 1;- }+ runTask = false;+ timeInterval =+ (int)(task.LastStartUtc.Value.AddMinutes(task.TimeInterval) - dateTimeNow)+ .TotalMinutes;}-- if (runTask)+ else{- task.LastStartUtc = DateTime.UtcNow;- try- {- //TODO - add settings- //logger.Information($"Task {_taskType} execute");- await scheduleTask.Execute();- task.LastSuccessUtc = DateTime.UtcNow;- task.LastNonSuccessEndUtc = null;- }- catch (Exception exc)- {- task.LastNonSuccessEndUtc = DateTime.UtcNow;- task.Enabled = !task.StopOnError;- logger.LogError(exc, "Error while running the \'{TaskScheduleTaskName}\' schedule task", task.ScheduleTaskName);- }+ runTask = true;+ timeInterval = task.TimeInterval > 0 ? task.TimeInterval : 1;}}- else++ if (runTask){- task.Enabled = !task.StopOnError;- task.LastNonSuccessEndUtc = DateTime.UtcNow;- logger.LogError("Type {TaskType} is not registered", _taskType);+ task.LastStartUtc = DateTime.UtcNow;+ try+ {+ //TODO - add settings+ //logger.Information($"Task {_taskType} execute");+ await scheduleTask.Execute();+ task.LastSuccessUtc = DateTime.UtcNow;+ task.LastNonSuccessEndUtc = null;+ }+ catch (Exception exc)+ {+ task.LastNonSuccessEndUtc = DateTime.UtcNow;+ task.Enabled = !task.StopOnError;+ logger.LogError(exc,+ "Error while running the \'{TaskScheduleTaskName}\' schedule task",+ task.ScheduleTaskName);+ }}}else{task.Enabled = !task.StopOnError;task.LastNonSuccessEndUtc = DateTime.UtcNow;- logger.LogError("Type {TaskType} is null (type not exists)", _taskType);+ logger.LogError("Type {TaskType} is not registered", _taskType);}- await scheduleTaskService.UpdateTask(task);- await Task.Delay(TimeSpan.FromMinutes(timeInterval), stoppingToken);}else- break;+ {+ task.Enabled = !task.StopOnError;+ task.LastNonSuccessEndUtc = DateTime.UtcNow;+ logger.LogError("Type {TaskType} is null (type not exists)", _taskType);+ }+ await scheduleTaskService.UpdateTask(task);+ await Task.Delay(TimeSpan.FromMinutes(timeInterval), stoppingToken);}- catch (Exception)+ else{- await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);+ break;}--}- }+ catch (Exception)+ {+ await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);+ }+ }- private async Task WorkContext(IServiceProvider serviceProvider, ScheduleTask scheduleTask)- {- var workContext = serviceProvider.GetRequiredService<IWorkContextSetter>();- var storeHelper = serviceProvider.GetRequiredService<IStoreHelper>();- await workContext.SetCurrentCustomer();- await storeHelper.SetCurrentStore(scheduleTask.StoreId);- }+ private async Task WorkContext(IServiceProvider serviceProvider, ScheduleTask scheduleTask)+ {+ var workContext = serviceProvider.GetRequiredService<IWorkContextSetter>();+ var storeHelper = serviceProvider.GetRequiredService<IStoreHelper>();+ await workContext.SetCurrentCustomer();+ await storeHelper.SetCurrentStore(scheduleTask.StoreId);}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs b/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.csindex 012ee821f..b30fb860d 100644--- a/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs+++ b/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs@@ -3,8 +3,8 @@ using FluentValidation;using Grand.Business.Core.Interfaces.Authentication;using Grand.Business.Core.Interfaces.Common.Configuration;using Grand.Business.Core.Utilities.Authentication;-using Grand.Domain.Configuration;using Grand.Data;+using Grand.Domain.Configuration;using Grand.Infrastructure;using Grand.Infrastructure.Configuration;using Grand.Infrastructure.Plugins;@@ -24,322 +24,305 @@ using StackExchange.Redis;using System.Text.Encodings.Web;using System.Text.Unicode;-namespace Grand.Web.Common.Infrastructure+namespace Grand.Web.Common.Infrastructure;++/// <summary>+/// Represents extensions of IServiceCollection+/// </summary>+public static class ServiceCollectionExtensions{/// <summary>- /// Represents extensions of IServiceCollection+ /// Adds services required for anti-forgery support/// </summary>- public static class ServiceCollectionExtensions+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="config">Security config</param>+ public static void AddAntiForgery(this IServiceCollection services, SecurityConfig config){- /// <summary>- /// Adds services required for anti-forgery support- /// </summary>- /// <param name="services">Collection of service descriptors</param>- /// <param name="config">Security config</param>- public static void AddAntiForgery(this IServiceCollection services, SecurityConfig config)+ //override cookie name+ services.AddAntiforgery(options =>{- //override cookie name- services.AddAntiforgery(options =>- {- options.Cookie = new CookieBuilder {- Name = $"{config.CookiePrefix}Antiforgery"- };- options.HeaderName = "X-CSRF-TOKEN";- if (DataSettingsManager.DatabaseIsInstalled())- {- //whether to allow the use of anti-forgery cookies from SSL protected page on the other store pages which are not- options.Cookie.SecurePolicy = config.CookieSecurePolicyAlways- ? CookieSecurePolicy.Always- : CookieSecurePolicy.SameAsRequest;- }- });- }-- /// <summary>- /// Adds services required for application session state- /// </summary>- /// <param name="services">Collection of service descriptors</param>- /// <param name="config">Security config</param>- public static void AddHttpSession(this IServiceCollection services, SecurityConfig config)- {- services.AddSession(options =>- {- options.Cookie = new CookieBuilder {- Name = $"{config.CookiePrefix}Session",- HttpOnly = true- };- if (DataSettingsManager.DatabaseIsInstalled())- {- options.Cookie.SecurePolicy = config.CookieSecurePolicyAlways- ? CookieSecurePolicy.Always- : CookieSecurePolicy.SameAsRequest;- }- });- }+ options.Cookie = new CookieBuilder {+ Name = $"{config.CookiePrefix}Antiforgery"+ };+ options.HeaderName = "X-CSRF-TOKEN";+ if (DataSettingsManager.DatabaseIsInstalled())+ //whether to allow the use of anti-forgery cookies from SSL protected page on the other store pages which are not+ options.Cookie.SecurePolicy = config.CookieSecurePolicyAlways+ ? CookieSecurePolicy.Always+ : CookieSecurePolicy.SameAsRequest;+ });+ }- /// <summary>- /// Adds services required for themes support- /// </summary>- /// <param name="services">Collection of service descriptors</param>- public static void AddThemes(this IServiceCollection services)+ /// <summary>+ /// Adds services required for application session state+ /// </summary>+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="config">Security config</param>+ public static void AddHttpSession(this IServiceCollection services, SecurityConfig config)+ {+ services.AddSession(options =>{- if (!DataSettingsManager.DatabaseIsInstalled())- return;+ options.Cookie = new CookieBuilder {+ Name = $"{config.CookiePrefix}Session",+ HttpOnly = true+ };+ if (DataSettingsManager.DatabaseIsInstalled())+ options.Cookie.SecurePolicy = config.CookieSecurePolicyAlways+ ? CookieSecurePolicy.Always+ : CookieSecurePolicy.SameAsRequest;+ });+ }- //themes support- services.Configure<RazorViewEngineOptions>(options =>- {- options.ViewLocationExpanders.Add(new ViewLocationExpander());- });- }+ /// <summary>+ /// Adds services required for themes support+ /// </summary>+ /// <param name="services">Collection of service descriptors</param>+ public static void AddThemes(this IServiceCollection services)+ {+ if (!DataSettingsManager.DatabaseIsInstalled())+ return;- /// <summary>- /// Adds data protection services- /// </summary>- public static void AddGrandDataProtection(this IServiceCollection services, IConfiguration configuration)+ //themes support+ services.Configure<RazorViewEngineOptions>(options =>{- var redisConfig = new RedisConfig();- configuration.GetSection("Redis").Bind(redisConfig);-- var azureConfig = new AzureConfig();- configuration.GetSection("Azure").Bind(azureConfig);+ options.ViewLocationExpanders.Add(new ViewLocationExpander());+ });+ }- if (redisConfig.PersistKeysToRedis)- {- services.AddDataProtection(opt => opt.ApplicationDiscriminator = "grandnode")- .PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(redisConfig.PersistKeysToRedisUrl));- }- else if (azureConfig.PersistKeysToAzureKeyVault || azureConfig.PersistKeysToAzureBlobStorage)- {- if (azureConfig.PersistKeysToAzureKeyVault)- services.AddDataProtection()- // This blob must already exist before the application is run- .PersistKeysToAzureBlobStorage(azureConfig.PersistKeysAzureBlobStorageConnectionString,- azureConfig.DataProtectionContainerName, azureConfig.DataProtectionBlobName)- .ProtectKeysWithAzureKeyVault(new Uri(azureConfig.KeyIdentifier),- new DefaultAzureCredential());- else- {- services.AddDataProtection()- .PersistKeysToAzureBlobStorage(azureConfig.PersistKeysAzureBlobStorageConnectionString,- azureConfig.DataProtectionContainerName, azureConfig.DataProtectionBlobName);- }- }- else- {- var securityConfig = new SecurityConfig();- configuration.GetSection("Security").Bind(securityConfig);+ /// <summary>+ /// Adds data protection services+ /// </summary>+ public static void AddGrandDataProtection(this IServiceCollection services, IConfiguration configuration)+ {+ var redisConfig = new RedisConfig();+ configuration.GetSection("Redis").Bind(redisConfig);- var dataProtectionKeysPath = string.IsNullOrEmpty(securityConfig.KeyPersistenceLocation)- ? CommonPath.DataProtectionKeysPath- : securityConfig.KeyPersistenceLocation;- var dataProtectionKeysFolder = new DirectoryInfo(dataProtectionKeysPath);+ var azureConfig = new AzureConfig();+ configuration.GetSection("Azure").Bind(azureConfig);- //configure the data protection system to persist keys to the specified directory- services.AddDataProtection().PersistKeysToFileSystem(dataProtectionKeysFolder);- }+ if (redisConfig.PersistKeysToRedis)+ {+ services.AddDataProtection(opt => opt.ApplicationDiscriminator = "grandnode")+ .PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(redisConfig.PersistKeysToRedisUrl));}-- /// <summary>- /// Adds authentication service- /// </summary>- /// <param name="services">Collection of service descriptors</param>- /// <param name="configuration">Configuration</param>- public static void AddGrandAuthentication(this IServiceCollection services, IConfiguration configuration)+ else if (azureConfig.PersistKeysToAzureKeyVault || azureConfig.PersistKeysToAzureBlobStorage)+ {+ if (azureConfig.PersistKeysToAzureKeyVault)+ services.AddDataProtection()+ // This blob must already exist before the application is run+ .PersistKeysToAzureBlobStorage(azureConfig.PersistKeysAzureBlobStorageConnectionString,+ azureConfig.DataProtectionContainerName, azureConfig.DataProtectionBlobName)+ .ProtectKeysWithAzureKeyVault(new Uri(azureConfig.KeyIdentifier),+ new DefaultAzureCredential());+ else+ services.AddDataProtection()+ .PersistKeysToAzureBlobStorage(azureConfig.PersistKeysAzureBlobStorageConnectionString,+ azureConfig.DataProtectionContainerName, azureConfig.DataProtectionBlobName);+ }+ else{var securityConfig = new SecurityConfig();configuration.GetSection("Security").Bind(securityConfig);- //set default authentication schemes- var authenticationBuilder = services.AddAuthentication(options =>- {- options.DefaultScheme = GrandCookieAuthenticationDefaults.AuthenticationScheme;- options.DefaultSignInScheme = GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme;- });+ var dataProtectionKeysPath = string.IsNullOrEmpty(securityConfig.KeyPersistenceLocation)+ ? CommonPath.DataProtectionKeysPath+ : securityConfig.KeyPersistenceLocation;+ var dataProtectionKeysFolder = new DirectoryInfo(dataProtectionKeysPath);- //add main cookie authentication- authenticationBuilder.AddCookie(GrandCookieAuthenticationDefaults.AuthenticationScheme, options =>- {- options.Cookie.Name =- securityConfig.CookiePrefix + GrandCookieAuthenticationDefaults.AuthenticationScheme;- options.Cookie.HttpOnly = true;- options.LoginPath = GrandCookieAuthenticationDefaults.LoginPath;- options.AccessDeniedPath = GrandCookieAuthenticationDefaults.AccessDeniedPath;-- options.Cookie.SecurePolicy = securityConfig.CookieSecurePolicyAlways- ? CookieSecurePolicy.Always- : CookieSecurePolicy.SameAsRequest;- options.Cookie.SameSite = securityConfig.CookieSameSite;- });+ //configure the data protection system to persist keys to the specified directory+ services.AddDataProtection().PersistKeysToFileSystem(dataProtectionKeysFolder);+ }+ }- //add external authentication- authenticationBuilder.AddCookie(GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme, options =>- {- options.Cookie.Name = securityConfig.CookiePrefix +- GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme;- options.Cookie.HttpOnly = true;- options.LoginPath = GrandCookieAuthenticationDefaults.LoginPath;- options.AccessDeniedPath = GrandCookieAuthenticationDefaults.AccessDeniedPath;- options.Cookie.SecurePolicy = securityConfig.CookieSecurePolicyAlways- ? CookieSecurePolicy.Always- : CookieSecurePolicy.SameAsRequest;- options.Cookie.SameSite = securityConfig.CookieSameSiteExternalAuth;+ /// <summary>+ /// Adds authentication service+ /// </summary>+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="configuration">Configuration</param>+ public static void AddGrandAuthentication(this IServiceCollection services, IConfiguration configuration)+ {+ var securityConfig = new SecurityConfig();+ configuration.GetSection("Security").Bind(securityConfig);- });+ //set default authentication schemes+ var authenticationBuilder = services.AddAuthentication(options =>+ {+ options.DefaultScheme = GrandCookieAuthenticationDefaults.AuthenticationScheme;+ options.DefaultSignInScheme = GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme;+ });- //register external authentication plugins now- var typeSearcher = new TypeSearcher();- var externalAuthConfigurations = typeSearcher.ClassesOfType<IAuthenticationBuilder>();- var externalAuthInstances = externalAuthConfigurations- .Where(PluginExtensions.OnlyInstalledPlugins)- .Select(x => (IAuthenticationBuilder)Activator.CreateInstance(x))- .OrderBy(x => x?.Priority);-- //add new Authentication- foreach (var instance in externalAuthInstances)- instance?.AddAuthentication(authenticationBuilder, configuration);- }+ //add main cookie authentication+ authenticationBuilder.AddCookie(GrandCookieAuthenticationDefaults.AuthenticationScheme, options =>+ {+ options.Cookie.Name =+ securityConfig.CookiePrefix + GrandCookieAuthenticationDefaults.AuthenticationScheme;+ options.Cookie.HttpOnly = true;+ options.LoginPath = GrandCookieAuthenticationDefaults.LoginPath;+ options.AccessDeniedPath = GrandCookieAuthenticationDefaults.AccessDeniedPath;++ options.Cookie.SecurePolicy = securityConfig.CookieSecurePolicyAlways+ ? CookieSecurePolicy.Always+ : CookieSecurePolicy.SameAsRequest;+ options.Cookie.SameSite = securityConfig.CookieSameSite;+ });++ //add external authentication+ authenticationBuilder.AddCookie(GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme, options =>+ {+ options.Cookie.Name = securityConfig.CookiePrefix ++ GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme;+ options.Cookie.HttpOnly = true;+ options.LoginPath = GrandCookieAuthenticationDefaults.LoginPath;+ options.AccessDeniedPath = GrandCookieAuthenticationDefaults.AccessDeniedPath;+ options.Cookie.SecurePolicy = securityConfig.CookieSecurePolicyAlways+ ? CookieSecurePolicy.Always+ : CookieSecurePolicy.SameAsRequest;+ options.Cookie.SameSite = securityConfig.CookieSameSiteExternalAuth;+ });++ //register external authentication plugins now+ var typeSearcher = new TypeSearcher();+ var externalAuthConfigurations = typeSearcher.ClassesOfType<IAuthenticationBuilder>();+ var externalAuthInstances = externalAuthConfigurations+ .Where(PluginExtensions.OnlyInstalledPlugins)+ .Select(x => (IAuthenticationBuilder)Activator.CreateInstance(x))+ .OrderBy(x => x?.Priority);++ //add new Authentication+ foreach (var instance in externalAuthInstances)+ instance?.AddAuthentication(authenticationBuilder, configuration);+ }- /// <summary>- /// Add and configure MVC for the application- /// </summary>- /// <param name="services">Collection of service descriptors</param>- /// <param name="configuration">Configuration</param>- /// <returns>A builder for configuring MVC services</returns>- public static IMvcBuilder AddGrandMvc(this IServiceCollection services, IConfiguration configuration)+ /// <summary>+ /// Add and configure MVC for the application+ /// </summary>+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="configuration">Configuration</param>+ /// <returns>A builder for configuring MVC services</returns>+ public static IMvcBuilder AddGrandMvc(this IServiceCollection services, IConfiguration configuration)+ {+ //add basic MVC feature+ var mvcBuilder = services.AddControllersWithViews().AddJsonOptions(options =>{- //add basic MVC feature- var mvcBuilder = services.AddControllersWithViews().AddJsonOptions(options =>- {- options.JsonSerializerOptions.PropertyNamingPolicy = null;- options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;- });+ options.JsonSerializerOptions.PropertyNamingPolicy = null;+ options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;+ });- //add view localization- mvcBuilder.AddViewLocalization();+ //add view localization+ mvcBuilder.AddViewLocalization();- var securityConfig = new SecurityConfig();- configuration.GetSection("Security").Bind(securityConfig);+ var securityConfig = new SecurityConfig();+ configuration.GetSection("Security").Bind(securityConfig);- if (securityConfig.EnableRuntimeCompilation) mvcBuilder.AddRazorRuntimeCompilation();+ if (securityConfig.EnableRuntimeCompilation) mvcBuilder.AddRazorRuntimeCompilation();- if (securityConfig.UseHsts)- {- services.AddHsts(options =>- {- options.Preload = true;- options.IncludeSubDomains = true;- });- }-- if (securityConfig.UseHttpsRedirection)+ if (securityConfig.UseHsts)+ services.AddHsts(options =>{- services.AddHttpsRedirection(options =>- {- options.RedirectStatusCode = securityConfig.HttpsRedirectionRedirect;- options.HttpsPort = securityConfig.HttpsRedirectionHttpsPort;- });- }-- var appConfig = new AppConfig();- configuration.GetSection("Application").Bind(appConfig);-- //use session-based temp data provider- if (appConfig.UseSessionStateTempDataProvider)- {- mvcBuilder.AddSessionStateTempDataProvider();- }-- //Add fluentValidation- var typeSearcher = new TypeSearcher();- var assemblies = typeSearcher.GetAssemblies();- services.AddValidatorsFromAssemblies(assemblies);-- //register controllers as services, it'll allow to override them- mvcBuilder.AddControllersAsServices();-- return mvcBuilder;- }+ options.Preload = true;+ options.IncludeSubDomains = true;+ });- public static void AddSettings(this IServiceCollection services)- {- var typeSearcher = new TypeSearcher();- var settings = typeSearcher.ClassesOfType<ISettings>();- var instances = settings.Select(x => (ISettings)Activator.CreateInstance(x));- foreach (var item in instances)+ if (securityConfig.UseHttpsRedirection)+ services.AddHttpsRedirection(options =>{- services.AddScoped(item!.GetType(), (x) =>- {- var type = item.GetType();- var storeId = "";- var settingService = x.GetRequiredService<ISettingService>();- var store = x.GetRequiredService<IStoreHelper>().StoreHost;- if (store != null)- storeId = store.Id;-- return settingService.LoadSetting(type, storeId);- });- }- }+ options.RedirectStatusCode = securityConfig.HttpsRedirectionRedirect;+ options.HttpsPort = securityConfig.HttpsRedirectionHttpsPort;+ });- public static void AddGrandHealthChecks(this IServiceCollection services)- {- var connection = DataSettingsManager.LoadSettings();- var hcBuilder = services.AddHealthChecks();- hcBuilder.AddCheck("self", () => HealthCheckResult.Healthy());- hcBuilder.AddMongoDb(connection.ConnectionString,- name: "mongodb-check",- tags: new[] { "mongodb" });- }+ var appConfig = new AppConfig();+ configuration.GetSection("Application").Bind(appConfig);- public static void AddGrandApplicationInsights(this IServiceCollection services, IConfiguration configuration)- {- var applicationInsights = new ApplicationInsightsConfig();- configuration.GetSection("ApplicationInsights").Bind(applicationInsights);- if (!string.IsNullOrEmpty(applicationInsights.ConnectionString))+ //use session-based temp data provider+ if (appConfig.UseSessionStateTempDataProvider) mvcBuilder.AddSessionStateTempDataProvider();++ //Add fluentValidation+ var typeSearcher = new TypeSearcher();+ var assemblies = typeSearcher.GetAssemblies();+ services.AddValidatorsFromAssemblies(assemblies);++ //register controllers as services, it'll allow to override them+ mvcBuilder.AddControllersAsServices();++ return mvcBuilder;+ }++ public static void AddSettings(this IServiceCollection services)+ {+ var typeSearcher = new TypeSearcher();+ var settings = typeSearcher.ClassesOfType<ISettings>();+ var instances = settings.Select(x => (ISettings)Activator.CreateInstance(x));+ foreach (var item in instances)+ services.AddScoped(item!.GetType(), x =>{- services.AddApplicationInsightsTelemetry();- services.AddServiceProfiler();- services.AddLogging(builder =>- {- builder.AddApplicationInsights(- configureTelemetryConfiguration: (config) =>- {- config.ConnectionString = applicationInsights.ConnectionString;- },- configureApplicationInsightsLoggerOptions: (options) =>- {- options.IncludeScopes = false;- options.TrackExceptionsAsExceptionTelemetry = false;- }- );- });- }- }+ var type = item.GetType();+ var storeId = "";+ var settingService = x.GetRequiredService<ISettingService>();+ var store = x.GetRequiredService<IStoreHelper>().StoreHost;+ if (store != null)+ storeId = store.Id;++ return settingService.LoadSetting(type, storeId);+ });+ }- /// <summary>- /// Adds services for WebEncoderOptions- /// </summary>- /// <param name="services">Collection of service descriptors</param>- public static void AddWebEncoder(this IServiceCollection services)- {- if (!DataSettingsManager.DatabaseIsInstalled())- return;+ public static void AddGrandHealthChecks(this IServiceCollection services)+ {+ var connection = DataSettingsManager.LoadSettings();+ var hcBuilder = services.AddHealthChecks();+ hcBuilder.AddCheck("self", () => HealthCheckResult.Healthy());+ hcBuilder.AddMongoDb(connection.ConnectionString,+ name: "mongodb-check",+ tags: new[] { "mongodb" });+ }- services.Configure<WebEncoderOptions>(options =>+ public static void AddGrandApplicationInsights(this IServiceCollection services, IConfiguration configuration)+ {+ var applicationInsights = new ApplicationInsightsConfig();+ configuration.GetSection("ApplicationInsights").Bind(applicationInsights);+ if (!string.IsNullOrEmpty(applicationInsights.ConnectionString))+ {+ services.AddApplicationInsightsTelemetry();+ services.AddServiceProfiler();+ services.AddLogging(builder =>{- options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);+ builder.AddApplicationInsights(+ config =>+ {+ config.ConnectionString = applicationInsights.ConnectionString;+ },+ options =>+ {+ options.IncludeScopes = false;+ options.TrackExceptionsAsExceptionTelemetry = false;+ }+ );});}+ }+ /// <summary>+ /// Adds services for WebEncoderOptions+ /// </summary>+ /// <param name="services">Collection of service descriptors</param>+ public static void AddWebEncoder(this IServiceCollection services)+ {+ if (!DataSettingsManager.DatabaseIsInstalled())+ return;- /// <summary>- /// Adds services for detection device- /// </summary>- /// <param name="services">Collection of service descriptors</param>- public static void AddDetectionDevice(this IServiceCollection services)+ services.Configure<WebEncoderOptions>(options =>{- services.AddDetection();- }+ options.TextEncoderSettings = new TextEncoderSettings(UnicodeRanges.All);+ });+ }+++ /// <summary>+ /// Adds services for detection device+ /// </summary>+ /// <param name="services">Collection of service descriptors</param>+ public static void AddDetectionDevice(this IServiceCollection services)+ {+ services.AddDetection();}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Link/IGroupLinkModel.cs b/src/Web/Grand.Web.Common/Link/IGroupLinkModel.csindex 1ec5d2d37..6c9cdf40b 100644--- a/src/Web/Grand.Web.Common/Link/IGroupLinkModel.cs+++ b/src/Web/Grand.Web.Common/Link/IGroupLinkModel.cs@@ -1,7 +1,6 @@-namespace Grand.Web.Common.Link+namespace Grand.Web.Common.Link;++public interface IGroupLinkModel{- public interface IGroupLinkModel- {- string[] CustomerGroups { get; set; }- }-}+ string[] CustomerGroups { get; set; }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Link/IStoreLinkModel.cs b/src/Web/Grand.Web.Common/Link/IStoreLinkModel.csindex 2932a6057..29e63f32d 100644--- a/src/Web/Grand.Web.Common/Link/IStoreLinkModel.cs+++ b/src/Web/Grand.Web.Common/Link/IStoreLinkModel.cs@@ -1,7 +1,6 @@-namespace Grand.Web.Common.Link+namespace Grand.Web.Common.Link;++public interface IStoreLinkModel{- public interface IStoreLinkModel- {- string[] Stores { get; set; }- }-}+ string[] Stores { get; set; }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Localization/LocService.cs b/src/Web/Grand.Web.Common/Localization/LocService.csindex ccb4541a7..a9d0eee1a 100644--- a/src/Web/Grand.Web.Common/Localization/LocService.cs+++ b/src/Web/Grand.Web.Common/Localization/LocService.cs@@ -1,49 +1,41 @@using Grand.Business.Core.Interfaces.Common.Localization;using Microsoft.Extensions.Localization;-namespace Grand.Web.Common.Localization+namespace Grand.Web.Common.Localization;++public class LocService : StringLocalizer<string>{- public class LocService : StringLocalizer<string>+ private readonly ITranslationService _translationService;++ public LocService(IStringLocalizerFactory factory) : base(factory){- private readonly ITranslationService _translationService;-- public LocService(IStringLocalizerFactory factory) : base(factory)- {+ }+ public LocService(IStringLocalizerFactory factory, ITranslationService translationService) : base(factory)+ {+ _translationService = translationService;+ }++ public override LocalizedString this[string name] {+ get {+ var resFormat = _translationService.GetResource(name.ToLowerInvariant());+ return new LocalizedString(name, resFormat ?? name, resFormat == null);}- public LocService(IStringLocalizerFactory factory, ITranslationService translationService) : base(factory)- {- _translationService = translationService;- }+ }- public override LocalizedString this[string name]- {- get+ public override LocalizedString this[string name, params object[] arguments] {+ get {+ var resFormat = _translationService.GetResource(name.ToLowerInvariant());+ if (string.IsNullOrEmpty(resFormat)) return new LocalizedString(name, string.Empty, resFormat == null);+ try{- var resFormat = _translationService.GetResource(name.ToLowerInvariant());- return new LocalizedString(name, resFormat ?? name, resFormat == null);+ return new LocalizedString(name, string.Format(resFormat, arguments),+ false);}- }-- public override LocalizedString this[string name, params object[] arguments]- {- get+ catch{- var resFormat = _translationService.GetResource(name.ToLowerInvariant());- if (string.IsNullOrEmpty(resFormat))- {- return new LocalizedString(name, string.Empty, resFormat == null);- }- try- {- return new LocalizedString(name, string.Format(resFormat, arguments),- false);- }- catch- {- return new LocalizedString(name, resFormat, false);- }+ return new LocalizedString(name, resFormat, false);}}}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Menu/IAdminMenuProvider.cs b/src/Web/Grand.Web.Common/Menu/IAdminMenuProvider.csindex 86db5ab1e..4c123cf53 100644--- a/src/Web/Grand.Web.Common/Menu/IAdminMenuProvider.cs+++ b/src/Web/Grand.Web.Common/Menu/IAdminMenuProvider.cs@@ -1,16 +1,15 @@using Grand.Infrastructure.Plugins;-namespace Grand.Web.Common.Menu+namespace Grand.Web.Common.Menu;++/// <summary>+/// Interface for provider which have some items in the admin area menu+/// </summary>+public interface IAdminMenuProvider : IProvider{/// <summary>- /// Interface for provider which have some items in the admin area menu+ /// Manage sitemap. You can use "SystemName" of menu items to manage existing sitemap or add a new menu item./// </summary>- public interface IAdminMenuProvider : IProvider- {- /// <summary>- /// Manage sitemap. You can use "SystemName" of menu items to manage existing sitemap or add a new menu item.- /// </summary>- /// <param name="rootNode">Root node of the sitemap.</param>- Task ManageSiteMap(SiteMapNode rootNode);- }-}+ /// <param name="rootNode">Root node of the sitemap.</param>+ Task ManageSiteMap(SiteMapNode rootNode);+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Menu/SiteMap.cs b/src/Web/Grand.Web.Common/Menu/SiteMap.csindex 7817dcab0..496ca7cb1 100644--- a/src/Web/Grand.Web.Common/Menu/SiteMap.cs+++ b/src/Web/Grand.Web.Common/Menu/SiteMap.cs@@ -2,97 +2,92 @@using Grand.Business.Core.Interfaces.System.Admin;using Grand.Domain.Admin;-namespace Grand.Web.Common.Menu-{- public class SiteMap- {- private readonly IAdminSiteMapService _adminSiteMapService;- private readonly IPermissionService _permissionService;- public SiteMap(- IAdminSiteMapService adminSiteMapService,- IPermissionService permissionService)- {- _adminSiteMapService = adminSiteMapService;- _permissionService = permissionService;- }+namespace Grand.Web.Common.Menu;- public SiteMapNode RootNode { get; set; }+public class SiteMap+{+ private readonly IAdminSiteMapService _adminSiteMapService;+ private readonly IPermissionService _permissionService;- public virtual async Task Load()- {- var adminSiteMaps = await _adminSiteMapService.GetSiteMap();- var sitemap = new SiteMapNode {- SystemName = "Home",- ResourceName = "Admin.Home",- ControllerName = "Home",- ActionName = "Overview"- };- await PrepareRootNode(sitemap, adminSiteMaps);- }+ public SiteMap(+ IAdminSiteMapService adminSiteMapService,+ IPermissionService permissionService)+ {+ _adminSiteMapService = adminSiteMapService;+ _permissionService = permissionService;+ }+ public SiteMapNode RootNode { get; set; }- private async Task PrepareRootNode(SiteMapNode siteMap, IList<AdminSiteMap> adminSiteMaps)- {- if (adminSiteMaps != null)- {- foreach (var item in adminSiteMaps)- {- var mainSite = new SiteMapNode();- siteMap.ChildNodes.Add(mainSite);- await Iterate(mainSite, item);- }- }- RootNode = siteMap;- }+ public virtual async Task Load()+ {+ var adminSiteMaps = await _adminSiteMapService.GetSiteMap();+ var sitemap = new SiteMapNode {+ SystemName = "Home",+ ResourceName = "Admin.Home",+ ControllerName = "Home",+ ActionName = "Overview"+ };+ await PrepareRootNode(sitemap, adminSiteMaps);+ }- private async Task Iterate(SiteMapNode siteMap, AdminSiteMap siteMapNode)- {- await PopulateNode(siteMap, siteMapNode);- foreach (var item in siteMapNode.ChildNodes.OrderBy(x=>x.DisplayOrder))+ private async Task PrepareRootNode(SiteMapNode siteMap, IList<AdminSiteMap> adminSiteMaps)+ {+ if (adminSiteMaps != null)+ foreach (var item in adminSiteMaps){var mainSite = new SiteMapNode();siteMap.ChildNodes.Add(mainSite);await Iterate(mainSite, item);}- }- private async Task PopulateNode(SiteMapNode siteMap, AdminSiteMap siteNode)+ RootNode = siteMap;+ }++ private async Task Iterate(SiteMapNode siteMap, AdminSiteMap siteMapNode)+ {+ await PopulateNode(siteMap, siteMapNode);++ foreach (var item in siteMapNode.ChildNodes.OrderBy(x => x.DisplayOrder)){- siteMap.ActionName = siteNode.ActionName;- siteMap.AllPermissions = siteNode.AllPermissions;- siteMap.ControllerName = siteNode.ControllerName;- siteMap.IconClass = siteNode.IconClass;- siteMap.OpenUrlInNewTab = siteNode.OpenUrlInNewTab;- siteMap.ResourceName = siteNode.ResourceName;- siteMap.SystemName = siteNode.SystemName;- siteMap.Url = siteNode.Url;+ var mainSite = new SiteMapNode();+ siteMap.ChildNodes.Add(mainSite);+ await Iterate(mainSite, item);+ }+ }- if (siteNode.PermissionNames.Any())+ private async Task PopulateNode(SiteMapNode siteMap, AdminSiteMap siteNode)+ {+ siteMap.ActionName = siteNode.ActionName;+ siteMap.AllPermissions = siteNode.AllPermissions;+ siteMap.ControllerName = siteNode.ControllerName;+ siteMap.IconClass = siteNode.IconClass;+ siteMap.OpenUrlInNewTab = siteNode.OpenUrlInNewTab;+ siteMap.ResourceName = siteNode.ResourceName;+ siteMap.SystemName = siteNode.SystemName;+ siteMap.Url = siteNode.Url;++ if (siteNode.PermissionNames.Any())+ {+ if (siteNode.AllPermissions){- if (siteNode.AllPermissions)- {- siteMap.Visible = true;- foreach (var permissionName in siteNode.PermissionNames)- {- if (!await _permissionService.Authorize(permissionName.Trim()))- siteMap.Visible = false;- }- }- else- {- siteMap.Visible = false;- foreach (var permissionName in siteNode.PermissionNames)- {- if (await _permissionService.Authorize(permissionName.Trim()))- siteMap.Visible = true;- }- }+ siteMap.Visible = true;+ foreach (var permissionName in siteNode.PermissionNames)+ if (!await _permissionService.Authorize(permissionName.Trim()))+ siteMap.Visible = false;}else{- siteMap.Visible = true;+ siteMap.Visible = false;+ foreach (var permissionName in siteNode.PermissionNames)+ if (await _permissionService.Authorize(permissionName.Trim()))+ siteMap.Visible = true;}}+ else+ {+ siteMap.Visible = true;+ }}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Menu/SiteMapNode.cs b/src/Web/Grand.Web.Common/Menu/SiteMapNode.csindex 92a744e5c..788525fdf 100644--- a/src/Web/Grand.Web.Common/Menu/SiteMapNode.cs+++ b/src/Web/Grand.Web.Common/Menu/SiteMapNode.cs@@ -1,71 +1,71 @@//code from Telerik MVC Extensions-namespace Grand.Web.Common.Menu++namespace Grand.Web.Common.Menu;++public class SiteMapNode{- public class SiteMapNode+ /// <summary>+ /// Initializes a new instance of the <see cref="SiteMapNode" /> class.+ /// </summary>+ public SiteMapNode(){- /// <summary>- /// Initializes a new instance of the <see cref="SiteMapNode"/> class.- /// </summary>- public SiteMapNode()- {- ChildNodes = new List<SiteMapNode>();- PermissionNames = new List<string>();- }+ ChildNodes = new List<SiteMapNode>();+ PermissionNames = new List<string>();+ }- /// <summary>- /// Gets or sets the system name.- /// </summary>- public string SystemName { get; set; }+ /// <summary>+ /// Gets or sets the system name.+ /// </summary>+ public string SystemName { get; set; }- /// <summary>- /// Gets or sets the resource name.- /// </summary>- public string ResourceName { get; set; }+ /// <summary>+ /// Gets or sets the resource name.+ /// </summary>+ public string ResourceName { get; set; }- /// <summary>- /// Gets or sets the name of the controller.- /// </summary>- public string ControllerName { get; set; }+ /// <summary>+ /// Gets or sets the name of the controller.+ /// </summary>+ public string ControllerName { get; set; }- /// <summary>- /// Gets or sets the name of the action.- /// </summary>- public string ActionName { get; set; }+ /// <summary>+ /// Gets or sets the name of the action.+ /// </summary>+ public string ActionName { get; set; }- /// <summary>- /// Gets or sets the URL.- /// </summary>- public string Url { get; set; }+ /// <summary>+ /// Gets or sets the URL.+ /// </summary>+ public string Url { get; set; }- /// <summary>- /// Gets or sets the child nodes.- /// </summary>- public IList<SiteMapNode> ChildNodes { get; set; }+ /// <summary>+ /// Gets or sets the child nodes.+ /// </summary>+ public IList<SiteMapNode> ChildNodes { get; set; }- /// <summary>- /// Gets or sets the icon class (Font Awesome: http://fontawesome.io/)- /// </summary>- public string IconClass { get; set; }+ /// <summary>+ /// Gets or sets the icon class (Font Awesome: http://fontawesome.io/)+ /// </summary>+ public string IconClass { get; set; }- /// <summary>- /// Gets or sets the item is visible- /// </summary>- public bool Visible { get; set; }+ /// <summary>+ /// Gets or sets the item is visible+ /// </summary>+ public bool Visible { get; set; }- /// <summary>- /// Gets or sets a value indicating whether to open url in new tab (window) or not- /// </summary>- public bool OpenUrlInNewTab { get; set; }+ /// <summary>+ /// Gets or sets a value indicating whether to open url in new tab (window) or not+ /// </summary>+ public bool OpenUrlInNewTab { get; set; }- /// <summary>- /// Gets or sets permissions- /// </summary>- public IList<string> PermissionNames { get; set; }+ /// <summary>+ /// Gets or sets permissions+ /// </summary>+ public IList<string> PermissionNames { get; set; }- /// <summary>- /// Gets or sets all permissions- /// </summary>- public bool AllPermissions { get; set; }- }-}+ /// <summary>+ /// Gets or sets all permissions+ /// </summary>+ public bool AllPermissions { get; set; }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Middleware/ContextLoggingMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/ContextLoggingMiddleware.csindex 283111ccf..46b86870c 100644--- a/src/Web/Grand.Web.Common/Middleware/ContextLoggingMiddleware.cs+++ b/src/Web/Grand.Web.Common/Middleware/ContextLoggingMiddleware.cs@@ -7,11 +7,12 @@ namespace Grand.Web.Common.Middleware;public class ContextLoggingMiddleware{- private readonly RequestDelegate _next;private const string CustomerPropertyName = "Customer";private const string StorePropertyName = "Store";private const string CurrencyPropertyName = "Currency";private const string LanguagePropertyName = "Language";+ private readonly RequestDelegate _next;+public ContextLoggingMiddleware(RequestDelegate next){_next = next;diff --git a/src/Web/Grand.Web.Common/Middleware/DbVersionCheckMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/DbVersionCheckMiddleware.csindex c6d9d5e48..1913628b6 100644--- a/src/Web/Grand.Web.Common/Middleware/DbVersionCheckMiddleware.cs+++ b/src/Web/Grand.Web.Common/Middleware/DbVersionCheckMiddleware.cs@@ -1,48 +1,39 @@-using Grand.Domain.Common;-using Grand.Data;+using Grand.Data;+using Grand.Domain.Common;using Grand.Infrastructure;using Grand.Infrastructure.Caching;using Grand.Infrastructure.Caching.Constants;using Microsoft.AspNetCore.Http;-namespace Grand.Web.Common.Middleware+namespace Grand.Web.Common.Middleware;++public class DbVersionCheckMiddleware{- public class DbVersionCheckMiddleware- {- private readonly RequestDelegate _next;+ private readonly RequestDelegate _next;- public DbVersionCheckMiddleware(RequestDelegate next)- {- _next = next;- }+ public DbVersionCheckMiddleware(RequestDelegate next)+ {+ _next = next;+ }- public async Task Invoke(- HttpContext context,- ICacheBase cacheBase,+ public async Task Invoke(+ HttpContext context,+ ICacheBase cacheBase,+ IRepository<GrandNodeVersion> repository)+ {+ if (context?.Request == null) return;- IRepository<GrandNodeVersion> repository)+ var version = cacheBase.Get(CacheKey.GRAND_NODE_VERSION, () => repository.Table.FirstOrDefault());+ if (version == null){- if (context?.Request == null)- {- return;- }-- var version = cacheBase.Get(CacheKey.GRAND_NODE_VERSION, () => repository.Table.FirstOrDefault());- if (version == null)- {- await context.Response.WriteAsync("The database does not exist.");- return;- }-- if (!version.DataBaseVersion.Equals(GrandVersion.SupportedDBVersion))- {- await context.Response.WriteAsync("The database version is not supported in this software version. " +- $"Supported version: {GrandVersion.SupportedDBVersion} , your version: {version.DataBaseVersion}");- }- else- {- await _next(context);- }+ await context.Response.WriteAsync("The database does not exist.");+ return;}++ if (!version.DataBaseVersion.Equals(GrandVersion.SupportedDBVersion))+ await context.Response.WriteAsync("The database version is not supported in this software version. " ++ $"Supported version: {GrandVersion.SupportedDBVersion} , your version: {version.DataBaseVersion}");+ else+ await _next(context);}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Middleware/InstallUrlMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/InstallUrlMiddleware.csindex 8312a3324..858419ba4 100644--- a/src/Web/Grand.Web.Common/Middleware/InstallUrlMiddleware.cs+++ b/src/Web/Grand.Web.Common/Middleware/InstallUrlMiddleware.cs@@ -2,50 +2,49 @@using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Http.Extensions;-namespace Grand.Web.Common.Middleware+namespace Grand.Web.Common.Middleware;++public class InstallUrlMiddleware{- public class InstallUrlMiddleware- {- #region Fields+ #region Fields- private readonly RequestDelegate _next;+ private readonly RequestDelegate _next;- #endregion+ #endregion- #region Ctor+ #region Ctor- public InstallUrlMiddleware(RequestDelegate next)- {- _next = next;- }+ public InstallUrlMiddleware(RequestDelegate next)+ {+ _next = next;+ }- #endregion+ #endregion- #region Methods+ #region Methods- /// <summary>- /// Invoke middleware actions- /// </summary>- /// <param name="context">HTTP context</param>- /// <returns>Task</returns>- public async Task InvokeAsync(HttpContext context)+ /// <summary>+ /// Invoke middleware actions+ /// </summary>+ /// <param name="context">HTTP context</param>+ /// <returns>Task</returns>+ public async Task InvokeAsync(HttpContext context)+ {+ //whether database is installed+ if (!DataSettingsManager.DatabaseIsInstalled()){- //whether database is installed- if (!DataSettingsManager.DatabaseIsInstalled())+ const string installUrl = "/install";+ if (!context.Request.GetEncodedPathAndQuery().StartsWith(installUrl, StringComparison.OrdinalIgnoreCase)){- const string installUrl = "/install";- if (!context.Request.GetEncodedPathAndQuery().StartsWith(installUrl, StringComparison.OrdinalIgnoreCase))- {- //redirect- context.Response.Redirect(installUrl);- return;- }+ //redirect+ context.Response.Redirect(installUrl);+ return;}-- //or call the next middleware in the request pipeline- await _next(context);}- #endregion+ //or call the next middleware in the request pipeline+ await _next(context);}-}++ #endregion+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Middleware/PoweredByMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/PoweredByMiddleware.csindex ae3cc7e84..780ccb6f7 100644--- a/src/Web/Grand.Web.Common/Middleware/PoweredByMiddleware.cs+++ b/src/Web/Grand.Web.Common/Middleware/PoweredByMiddleware.cs@@ -1,46 +1,43 @@//Contribution: Orchard project (https://github.com/OrchardCMS/OrchardCore)+using Microsoft.AspNetCore.Http;-namespace Grand.Web.Common.Middleware+namespace Grand.Web.Common.Middleware;++/// <summary>+/// Adds the X-Powered-By header with values grandnode.+/// </summary>+public class PoweredByMiddleware{- /// <summary>- /// Adds the X-Powered-By header with values grandnode.- /// </summary>- public class PoweredByMiddleware+ private readonly RequestDelegate _next;++ public PoweredByMiddleware(RequestDelegate next){- private readonly RequestDelegate _next;-- public PoweredByMiddleware(RequestDelegate next)- {- _next = next;- }-- public async Task InvokeAsync(HttpContext context, IPoweredByMiddlewareOptions options)- {- if (options.Enabled)- {- context.Response.Headers[options.HeaderName] = options.HeaderValue;- }-- await _next.Invoke(context);- }+ _next = next;}- public interface IPoweredByMiddlewareOptions+ public async Task InvokeAsync(HttpContext context, IPoweredByMiddlewareOptions options){- bool Enabled { get; set; }- string HeaderName { get; }- string HeaderValue { get; set; }+ if (options.Enabled) context.Response.Headers[options.HeaderName] = options.HeaderValue;++ await _next.Invoke(context);}+}- public class PoweredByMiddlewareOptions: IPoweredByMiddlewareOptions- {- private const string PoweredByHeaderName = "X-Powered-By";- private const string PoweredByHeaderValue = "GrandNode";+public interface IPoweredByMiddlewareOptions+{+ bool Enabled { get; set; }+ string HeaderName { get; }+ string HeaderValue { get; set; }+}++public class PoweredByMiddlewareOptions : IPoweredByMiddlewareOptions+{+ private const string PoweredByHeaderName = "X-Powered-By";+ private const string PoweredByHeaderValue = "GrandNode";- public string HeaderName => PoweredByHeaderName;- public string HeaderValue { get; set; } = PoweredByHeaderValue;+ public string HeaderName => PoweredByHeaderName;+ public string HeaderValue { get; set; } = PoweredByHeaderValue;- public bool Enabled { get; set; } = true;- }+ public bool Enabled { get; set; } = true;}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.csindex 7feb669c1..7e956ff65 100644--- a/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs+++ b/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs@@ -1,55 +1,51 @@using Grand.Infrastructure;using Microsoft.AspNetCore.Http;-namespace Grand.Web.Common.Middleware+namespace Grand.Web.Common.Middleware;++public class WorkContextMiddleware{- public class WorkContextMiddleware+ #region Fields++ private readonly RequestDelegate _next;++ #endregion++ #region Ctor++ /// <summary>+ /// Ctor+ /// </summary>+ /// <param name="next">Next</param>+ public WorkContextMiddleware(RequestDelegate next){- #region Fields-- private readonly RequestDelegate _next;-- #endregion-- #region Ctor-- /// <summary>- /// Ctor- /// </summary>- /// <param name="next">Next</param>- public WorkContextMiddleware(RequestDelegate next)- {- _next = next;- }-- #endregion-- #region Methods-- /// <summary>- /// Invoke middleware actions- /// </summary>- /// <param name="context">HTTP context</param>- /// <param name="workContext">workContext</param>- /// <returns>Task</returns>- public async Task InvokeAsync(HttpContext context, IWorkContextSetter workContext)- {- if (context?.Request == null)- {- return;- }-- //set current context- var customer = await workContext.SetCurrentCustomer();- await workContext.SetCurrentVendor(customer);- _ = await workContext.SetWorkingLanguage(customer);- await workContext.SetWorkingCurrency(customer);- await workContext.SetTaxDisplayType(customer);-- //call the next middleware in the request pipeline- await _next(context);- }-- #endregion+ _next = next;}-}++ #endregion++ #region Methods++ /// <summary>+ /// Invoke middleware actions+ /// </summary>+ /// <param name="context">HTTP context</param>+ /// <param name="workContext">workContext</param>+ /// <returns>Task</returns>+ public async Task InvokeAsync(HttpContext context, IWorkContextSetter workContext)+ {+ if (context?.Request == null) return;++ //set current context+ var customer = await workContext.SetCurrentCustomer();+ await workContext.SetCurrentVendor(customer);+ _ = await workContext.SetWorkingLanguage(customer);+ await workContext.SetWorkingCurrency(customer);+ await workContext.SetTaxDisplayType(customer);++ //call the next middleware in the request pipeline+ await _next(context);+ }++ #endregion+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Models/CustomerGroupModel.cs b/src/Web/Grand.Web.Common/Models/CustomerGroupModel.csindex b9c2755ca..1d75e796b 100644--- a/src/Web/Grand.Web.Common/Models/CustomerGroupModel.cs+++ b/src/Web/Grand.Web.Common/Models/CustomerGroupModel.cs@@ -1,8 +1,7 @@-namespace Grand.Web.Common.Models+namespace Grand.Web.Common.Models;++public class CustomerGroupModel{- public partial class CustomerGroupModel- {- public string Id { get; set; }- public string Name { get; set; }- }-}+ public string Id { get; set; }+ public string Name { get; set; }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Models/DatePickerDropDownsModel.cs b/src/Web/Grand.Web.Common/Models/DatePickerDropDownsModel.csindex b9b04c05f..97d65729d 100644--- a/src/Web/Grand.Web.Common/Models/DatePickerDropDownsModel.cs+++ b/src/Web/Grand.Web.Common/Models/DatePickerDropDownsModel.cs@@ -1,30 +1,29 @@using Grand.Infrastructure.Models;using Microsoft.AspNetCore.Mvc.Rendering;-namespace Grand.Web.Common.Models+namespace Grand.Web.Common.Models;++public class DatePickerDropDownsModel : BaseEntityModel{- public partial class DatePickerDropDownsModel : BaseEntityModel- {- public string Attribute { get; set; }+ public string Attribute { get; set; }- public string Day { get; set; }+ public string Day { get; set; }- public IList<SelectListItem> SelectListDay { get; set; } = new List<SelectListItem>();+ public IList<SelectListItem> SelectListDay { get; set; } = new List<SelectListItem>();- public string Month { get; set; }- public IList<SelectListItem> SelectListMonth { get; set; } = new List<SelectListItem>();+ public string Month { get; set; }+ public IList<SelectListItem> SelectListMonth { get; set; } = new List<SelectListItem>();- public string Year { get; set; }- public IList<SelectListItem> SelectListYear { get; set; } = new List<SelectListItem>();+ public string Year { get; set; }+ public IList<SelectListItem> SelectListYear { get; set; } = new List<SelectListItem>();- public int Begin_Year { get; set; }+ public int Begin_Year { get; set; }- public int End_Year { get; set; }+ public int End_Year { get; set; }- public int SelectedDay { get; set; }+ public int SelectedDay { get; set; }- public int SelectedMonth { get; set; }+ public int SelectedMonth { get; set; }- public int SelectedYear { get; set; }- }-}+ public int SelectedYear { get; set; }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Models/DeleteConfirmationModel.cs b/src/Web/Grand.Web.Common/Models/DeleteConfirmationModel.csindex cd49dd04e..45cabb682 100644--- a/src/Web/Grand.Web.Common/Models/DeleteConfirmationModel.cs+++ b/src/Web/Grand.Web.Common/Models/DeleteConfirmationModel.cs@@ -1,11 +1,10 @@using Grand.Infrastructure.Models;-namespace Grand.Web.Common.Models+namespace Grand.Web.Common.Models;++public class DeleteConfirmationModel : BaseEntityModel{- public class DeleteConfirmationModel : BaseEntityModel- {- public string ControllerName { get; set; }- public string ActionName { get; set; }- public string WindowId { get; set; }- }+ public string ControllerName { get; set; }+ public string ActionName { get; set; }+ public string WindowId { get; set; }}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Models/ILocalizedModel.cs b/src/Web/Grand.Web.Common/Models/ILocalizedModel.csindex 1614d86f0..b865b67ef 100644--- a/src/Web/Grand.Web.Common/Models/ILocalizedModel.cs+++ b/src/Web/Grand.Web.Common/Models/ILocalizedModel.cs@@ -1,13 +1,12 @@//Contribution https://github.com/smartstore/SmartStoreNET/blob/2.0.x/src/Presentation/SmartStore.Web.Framework/Localization/ILocalizedModel.cs-namespace Grand.Web.Common.Models-{- public interface ILocalizedModel- {+namespace Grand.Web.Common.Models;- }- public interface ILocalizedModel<TLocalizedModel> : ILocalizedModel- {- IList<TLocalizedModel> Locales { get; set; }- }+public interface ILocalizedModel+{}++public interface ILocalizedModel<TLocalizedModel> : ILocalizedModel+{+ IList<TLocalizedModel> Locales { get; set; }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Models/ILocalizedModelLocal.cs b/src/Web/Grand.Web.Common/Models/ILocalizedModelLocal.csindex 901aef270..9edf0f273 100644--- a/src/Web/Grand.Web.Common/Models/ILocalizedModelLocal.cs+++ b/src/Web/Grand.Web.Common/Models/ILocalizedModelLocal.cs@@ -1,9 +1,8 @@//Contribution https://github.com/smartstore/SmartStoreNET/blob/2.0.x/src/Presentation/SmartStore.Web.Framework/Localization/ILocalizedModelLocal.cs-namespace Grand.Web.Common.Models+namespace Grand.Web.Common.Models;++public interface ILocalizedModelLocal{- public interface ILocalizedModelLocal- {- string LanguageId { get; set; }- }-}+ string LanguageId { get; set; }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Models/ISlugModelLocal.cs b/src/Web/Grand.Web.Common/Models/ISlugModelLocal.csindex be2776235..4bbdd4451 100644--- a/src/Web/Grand.Web.Common/Models/ISlugModelLocal.cs+++ b/src/Web/Grand.Web.Common/Models/ISlugModelLocal.cs@@ -1,7 +1,6 @@-namespace Grand.Web.Common.Models+namespace Grand.Web.Common.Models;++public interface ISlugModelLocal{- public interface ISlugModelLocal- {- string SeName { get; set; }- }-}+ string SeName { get; set; }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Models/StoreModel.cs b/src/Web/Grand.Web.Common/Models/StoreModel.csindex b1bc46d2c..9ce625cdd 100644--- a/src/Web/Grand.Web.Common/Models/StoreModel.cs+++ b/src/Web/Grand.Web.Common/Models/StoreModel.cs@@ -1,8 +1,7 @@-namespace Grand.Web.Common.Models+namespace Grand.Web.Common.Models;++public class StoreModel{- public class StoreModel- {- public string Id { get; set; }- public string Name { get; set; }- }-}+ public string Id { get; set; }+ public string Name { get; set; }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Page/IPageHeadBuilder.cs b/src/Web/Grand.Web.Common/Page/IPageHeadBuilder.csindex 393d86a49..d282c76d5 100644--- a/src/Web/Grand.Web.Common/Page/IPageHeadBuilder.cs+++ b/src/Web/Grand.Web.Common/Page/IPageHeadBuilder.cs@@ -1,36 +1,33 @@//Contribution https://github.com/smartstore/SmartStoreNET/blob/2.0.x/src/Presentation/SmartStore.Web.Framework/UI/IPageAssetsBuilder.cs-namespace Grand.Web.Common.Page-{- /// <summary>- /// Page head builder- /// </summary>- public interface IPageHeadBuilder- {- void AddTitleParts(string part);- void AppendTitleParts(string part);- string GenerateTitle(bool addDefaultTitle);- void AddMetaDescriptionParts(string part);- void AppendMetaDescriptionParts(string part);- string GenerateMetaDescription();-- void AddMetaKeywordParts(string part);- void AppendMetaKeywordParts(string part);- string GenerateMetaKeywords();+namespace Grand.Web.Common.Page;- void AddCanonicalUrlParts(string part);- void AppendCanonicalUrlParts(string part);- string GenerateCanonicalUrls();+/// <summary>+/// Page head builder+/// </summary>+public interface IPageHeadBuilder+{+ string EditPageUrl { get; set; }+ void AddTitleParts(string part);+ void AppendTitleParts(string part);+ string GenerateTitle(bool addDefaultTitle);+ void AddMetaDescriptionParts(string part);+ void AppendMetaDescriptionParts(string part);+ string GenerateMetaDescription();- void AddHeadCustomParts(string part);- void AppendHeadCustomParts(string part);- string GenerateHeadCustom();+ void AddMetaKeywordParts(string part);+ void AppendMetaKeywordParts(string part);+ string GenerateMetaKeywords();- void AddPageCssClassParts(string part);- void AppendPageCssClassParts(string part);- string GeneratePageCssClasses();+ void AddCanonicalUrlParts(string part);+ void AppendCanonicalUrlParts(string part);+ string GenerateCanonicalUrls();- string EditPageUrl { get; set; }+ void AddHeadCustomParts(string part);+ void AppendHeadCustomParts(string part);+ string GenerateHeadCustom();- }-}+ void AddPageCssClassParts(string part);+ void AppendPageCssClassParts(string part);+ string GeneratePageCssClasses();+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Page/NotifyType.cs b/src/Web/Grand.Web.Common/Page/NotifyType.csindex a92790882..f59f34ca8 100644--- a/src/Web/Grand.Web.Common/Page/NotifyType.cs+++ b/src/Web/Grand.Web.Common/Page/NotifyType.cs@@ -1,9 +1,8 @@-namespace Grand.Web.Common.Page+namespace Grand.Web.Common.Page;++public enum NotifyType{- public enum NotifyType- {- Success,- Error,- Warning- }-}+ Success,+ Error,+ Warning+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Page/PageHeadBuilder.cs b/src/Web/Grand.Web.Common/Page/PageHeadBuilder.csindex a5a4fd6d5..6d8ccf321 100644--- a/src/Web/Grand.Web.Common/Page/PageHeadBuilder.cs+++ b/src/Web/Grand.Web.Common/Page/PageHeadBuilder.cs@@ -1,219 +1,214 @@using Grand.Domain.Seo;-namespace Grand.Web.Common.Page+namespace Grand.Web.Common.Page;++/// <summary>+/// Page head builder+/// </summary>+public class PageHeadBuilder : IPageHeadBuilder{+ #region Ctor+/// <summary>- /// Page head builder+ /// Constuctor/// </summary>- public class PageHeadBuilder : IPageHeadBuilder+ /// <param name="seoSettings">SEO settings</param>+ public PageHeadBuilder(SeoSettings seoSettings){- #region Fields+ _title = new List<string>();+ _metaDescription = new List<string>();+ _metaKeyword = new List<string>();+ _canonicalUrl = new List<string>();+ _headCustom = new List<string>();+ _pageCssClass = new List<string>();++ if (!string.IsNullOrEmpty(seoSettings.CustomHeadTags)) AppendHeadCustomParts(seoSettings.CustomHeadTags);+ _seoSettings = seoSettings;+ }- private readonly List<string> _title;- private readonly List<string> _metaDescription;- private readonly List<string> _metaKeyword;- private readonly List<string> _canonicalUrl;- private readonly List<string> _headCustom;- private readonly List<string> _pageCssClass;- private string _editPageUrl;+ #endregion- private readonly SeoSettings _seoSettings;- #endregion+ #region Fields- #region Ctor+ private readonly List<string> _title;+ private readonly List<string> _metaDescription;+ private readonly List<string> _metaKeyword;+ private readonly List<string> _canonicalUrl;+ private readonly List<string> _headCustom;+ private readonly List<string> _pageCssClass;- /// <summary>- /// Constuctor- /// </summary>- /// <param name="seoSettings">SEO settings</param>- public PageHeadBuilder(SeoSettings seoSettings)- {- _title = new List<string>();- _metaDescription = new List<string>();- _metaKeyword = new List<string>();- _canonicalUrl = new List<string>();- _headCustom = new List<string>();- _pageCssClass = new List<string>();-- if (!string.IsNullOrEmpty(seoSettings.CustomHeadTags))- {- AppendHeadCustomParts(seoSettings.CustomHeadTags);- }- _seoSettings = seoSettings;- }+ private readonly SeoSettings _seoSettings;- #endregion+ #endregion- #region Methods+ #region Methods- public virtual void AddTitleParts(string part)- {- if (string.IsNullOrEmpty(part))- return;+ public virtual void AddTitleParts(string part)+ {+ if (string.IsNullOrEmpty(part))+ return;- _title.Add(part);- }- public virtual void AppendTitleParts(string part)- {- if (string.IsNullOrEmpty(part))- return;+ _title.Add(part);+ }- _title.Insert(0, part);+ public virtual void AppendTitleParts(string part)+ {+ if (string.IsNullOrEmpty(part))+ return;++ _title.Insert(0, part);+ }++ public virtual string GenerateTitle(bool addDefaultTitle)+ {+ string result;+ var titleParts = string.Join(_seoSettings.PageTitleSeparator, _title.AsEnumerable().Reverse().ToList());+ if (!string.IsNullOrEmpty(titleParts))+ {+ if (addDefaultTitle)+ result = _seoSettings.PageTitleSeoAdjustment+ ? string.Join(_seoSettings.PageTitleSeparator, _seoSettings.DefaultTitle, titleParts)+ : string.Join(_seoSettings.PageTitleSeparator, titleParts, _seoSettings.DefaultTitle);+ else+ result = titleParts;}- public virtual string GenerateTitle(bool addDefaultTitle)+ else{- string result;- var titleParts = string.Join(_seoSettings.PageTitleSeparator, _title.AsEnumerable().Reverse().ToList());- if (!string.IsNullOrEmpty(titleParts))- {- if (addDefaultTitle)- {- result = _seoSettings.PageTitleSeoAdjustment ? string.Join(_seoSettings.PageTitleSeparator, _seoSettings.DefaultTitle, titleParts) : string.Join(_seoSettings.PageTitleSeparator, titleParts, _seoSettings.DefaultTitle);- }- else- {- result = titleParts;- }- }- else- {- result = _seoSettings.DefaultTitle;- }- return result;+ result = _seoSettings.DefaultTitle;}- public virtual void AddMetaDescriptionParts(string part)- {- if (string.IsNullOrEmpty(part))- return;+ return result;+ }- _metaDescription.Add(part);- }+ public virtual void AddMetaDescriptionParts(string part)+ {+ if (string.IsNullOrEmpty(part))+ return;- public virtual void AppendMetaDescriptionParts(string part)- {- if (string.IsNullOrEmpty(part))- return;+ _metaDescription.Add(part);+ }- _metaDescription.Insert(0, part);- }+ public virtual void AppendMetaDescriptionParts(string part)+ {+ if (string.IsNullOrEmpty(part))+ return;- public virtual string GenerateMetaDescription()- {- var description = string.Join(", ", _metaDescription.AsEnumerable().Reverse().ToList());- var result = !string.IsNullOrEmpty(description) ? description : _seoSettings.DefaultMetaDescription;- return result;- }+ _metaDescription.Insert(0, part);+ }- public virtual void AddMetaKeywordParts(string part)- {- if (string.IsNullOrEmpty(part))- return;+ public virtual string GenerateMetaDescription()+ {+ var description = string.Join(", ", _metaDescription.AsEnumerable().Reverse().ToList());+ var result = !string.IsNullOrEmpty(description) ? description : _seoSettings.DefaultMetaDescription;+ return result;+ }- _metaKeyword.Add(part);- }+ public virtual void AddMetaKeywordParts(string part)+ {+ if (string.IsNullOrEmpty(part))+ return;- public virtual void AppendMetaKeywordParts(string part)- {- if (string.IsNullOrEmpty(part))- return;+ _metaKeyword.Add(part);+ }- _metaKeyword.Insert(0, part);- }+ public virtual void AppendMetaKeywordParts(string part)+ {+ if (string.IsNullOrEmpty(part))+ return;- public virtual string GenerateMetaKeywords()- {- var keyword = string.Join(", ", _metaKeyword.AsEnumerable().Reverse().ToList());- var result = !string.IsNullOrEmpty(keyword) ? keyword : _seoSettings.DefaultMetaKeywords;- return result;- }+ _metaKeyword.Insert(0, part);+ }- public virtual void AddCanonicalUrlParts(string part)- {- if (string.IsNullOrEmpty(part))- return;+ public virtual string GenerateMetaKeywords()+ {+ var keyword = string.Join(", ", _metaKeyword.AsEnumerable().Reverse().ToList());+ var result = !string.IsNullOrEmpty(keyword) ? keyword : _seoSettings.DefaultMetaKeywords;+ return result;+ }- _canonicalUrl.Add(part);- }+ public virtual void AddCanonicalUrlParts(string part)+ {+ if (string.IsNullOrEmpty(part))+ return;- public virtual void AppendCanonicalUrlParts(string part)- {- if (string.IsNullOrEmpty(part))- return;+ _canonicalUrl.Add(part);+ }- _canonicalUrl.Insert(0, part);- }+ public virtual void AppendCanonicalUrlParts(string part)+ {+ if (string.IsNullOrEmpty(part))+ return;++ _canonicalUrl.Insert(0, part);+ }- public virtual string GenerateCanonicalUrls()+ public virtual string GenerateCanonicalUrls()+ {+ var result = new StringBuilder();+ foreach (var canonicalUrl in _canonicalUrl){- var result = new StringBuilder();- foreach (var canonicalUrl in _canonicalUrl)- {- result.Append($"<link rel=\"canonical\" href=\"{canonicalUrl}\" />");- result.Append(Environment.NewLine);- }- return result.ToString();+ result.Append($"<link rel=\"canonical\" href=\"{canonicalUrl}\" />");+ result.Append(Environment.NewLine);}- public virtual void AddHeadCustomParts(string part)- {- if (string.IsNullOrEmpty(part))- return;+ return result.ToString();+ }- _headCustom.Add(part);- }+ public virtual void AddHeadCustomParts(string part)+ {+ if (string.IsNullOrEmpty(part))+ return;- public virtual void AppendHeadCustomParts(string part)- {- if (string.IsNullOrEmpty(part))- return;+ _headCustom.Add(part);+ }- _headCustom.Insert(0, part);- }+ public virtual void AppendHeadCustomParts(string part)+ {+ if (string.IsNullOrEmpty(part))+ return;- public virtual string GenerateHeadCustom()- {- var distinctParts = _headCustom.Distinct().ToList();- if (!distinctParts.Any())- return "";-- var result = new StringBuilder();- foreach (var path in distinctParts)- {- result.Append(path);- result.Append(Environment.NewLine);- }- return result.ToString();- }+ _headCustom.Insert(0, part);+ }- public virtual void AddPageCssClassParts(string part)- {- if (string.IsNullOrEmpty(part))- return;+ public virtual string GenerateHeadCustom()+ {+ var distinctParts = _headCustom.Distinct().ToList();+ if (!distinctParts.Any())+ return "";- _pageCssClass.Add(part);+ var result = new StringBuilder();+ foreach (var path in distinctParts)+ {+ result.Append(path);+ result.Append(Environment.NewLine);}- public virtual void AppendPageCssClassParts(string part)- {- if (string.IsNullOrEmpty(part))- return;+ return result.ToString();+ }- _pageCssClass.Insert(0, part);- }+ public virtual void AddPageCssClassParts(string part)+ {+ if (string.IsNullOrEmpty(part))+ return;- public virtual string GeneratePageCssClasses()- {- var result = string.Join(" ", _pageCssClass.AsEnumerable().Reverse().ToArray());- return result;- }+ _pageCssClass.Add(part);+ }- public virtual string EditPageUrl- {- get => _editPageUrl;- set => _editPageUrl = value;- }+ public virtual void AppendPageCssClassParts(string part)+ {+ if (string.IsNullOrEmpty(part))+ return;- #endregion+ _pageCssClass.Insert(0, part);}++ public virtual string GeneratePageCssClasses()+ {+ var result = string.Join(" ", _pageCssClass.AsEnumerable().Reverse().ToArray());+ return result;+ }++ public virtual string EditPageUrl { get; set; }++ #endregion}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Page/Paging/BasePageableModel.cs b/src/Web/Grand.Web.Common/Page/Paging/BasePageableModel.csindex 8bcacc954..daa705016 100644--- a/src/Web/Grand.Web.Common/Page/Paging/BasePageableModel.cs+++ b/src/Web/Grand.Web.Common/Page/Paging/BasePageableModel.cs@@ -1,59 +1,55 @@//Contributor : MVCContrib+using Grand.Domain;using Grand.SharedKernel.Attributes;-namespace Grand.Web.Common.Page.Paging+namespace Grand.Web.Common.Page.Paging;++public abstract class BasePageableModel : IPageableModel{- public abstract class BasePageableModel : IPageableModel+ #region Methods++ public void LoadPagedList<T>(IPagedList<T> pagedList){- #region Methods-- public void LoadPagedList<T>(IPagedList<T> pagedList)- {- FirstItem = pagedList.PageIndex * pagedList.PageSize + 1;- HasNextPage = pagedList.HasNextPage;- HasPreviousPage = pagedList.HasPreviousPage;- LastItem = Math.Min(pagedList.TotalCount, pagedList.PageIndex * pagedList.PageSize + pagedList.PageSize);- PageNumber = pagedList.PageIndex + 1;- PageSize = pagedList.PageSize;- TotalItems = pagedList.TotalCount;- TotalPages = pagedList.TotalPages;- }+ FirstItem = pagedList.PageIndex * pagedList.PageSize + 1;+ HasNextPage = pagedList.HasNextPage;+ HasPreviousPage = pagedList.HasPreviousPage;+ LastItem = Math.Min(pagedList.TotalCount, pagedList.PageIndex * pagedList.PageSize + pagedList.PageSize);+ PageNumber = pagedList.PageIndex + 1;+ PageSize = pagedList.PageSize;+ TotalItems = pagedList.TotalCount;+ TotalPages = pagedList.TotalPages;+ }++ #endregion++ #region Properties++ [IgnoreApiUrl] [IgnoreApi] public int FirstItem { get; set; }- #endregion-- #region Properties- [IgnoreApiUrl]- [IgnoreApi]- public int FirstItem { get; set; }- [IgnoreApiUrl]- [IgnoreApi]- public bool HasNextPage { get; set; }- [IgnoreApiUrl]- [IgnoreApi]- public bool HasPreviousPage { get; set; }- [IgnoreApiUrl]- [IgnoreApi]- public int LastItem { get; set; }- [IgnoreApiUrl]- [IgnoreApi]- public int PageIndex- {- get- {- if (PageNumber > 0)- return PageNumber - 1;-- return 0;- }+ [IgnoreApiUrl] [IgnoreApi] public bool HasNextPage { get; set; }++ [IgnoreApiUrl] [IgnoreApi] public bool HasPreviousPage { get; set; }++ [IgnoreApiUrl] [IgnoreApi] public int LastItem { get; set; }++ [IgnoreApiUrl]+ [IgnoreApi]+ public int PageIndex {+ get {+ if (PageNumber > 0)+ return PageNumber - 1;++ return 0;}- public int PageNumber { get; set; }- public int PageSize { get; set; }- [IgnoreApiUrl]- public int TotalItems { get; set; }- [IgnoreApiUrl]- public int TotalPages { get; set; }-- #endregion}++ public int PageNumber { get; set; }+ public int PageSize { get; set; }++ [IgnoreApiUrl] public int TotalItems { get; set; }++ [IgnoreApiUrl] public int TotalPages { get; set; }++ #endregion}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Page/Paging/IPageableModel.cs b/src/Web/Grand.Web.Common/Page/Paging/IPageableModel.csindex bedc502aa..3e60774df 100644--- a/src/Web/Grand.Web.Common/Page/Paging/IPageableModel.cs+++ b/src/Web/Grand.Web.Common/Page/Paging/IPageableModel.cs@@ -2,63 +2,68 @@using Grand.SharedKernel.Attributes;-namespace Grand.Web.Common.Page.Paging+namespace Grand.Web.Common.Page.Paging;++/// <summary>+/// A collection of objects that has been split into pages.+/// </summary>+public interface IPageableModel{/// <summary>- /// A collection of objects that has been split into pages.+ /// The current page index (starts from 0)+ /// </summary>+ [IgnoreApi]+ int PageIndex { get; }++ /// <summary>+ /// The current page number (starts from 1)+ /// </summary>+ int PageNumber { get; }++ /// <summary>+ /// The number of items in each page.+ /// </summary>+ int PageSize { get; }++ /// <summary>+ /// The total number of items.+ /// </summary>+ int TotalItems { get; }++ /// <summary>+ /// The total number of pages.+ /// </summary>+ int TotalPages { get; }++ /// <summary>+ /// The index of the first item in the page.+ /// </summary>+ [IgnoreApi]+ int FirstItem { get; }++ /// <summary>+ /// The index of the last item in the page./// </summary>- public interface IPageableModel- {- /// <summary>- /// The current page index (starts from 0)- /// </summary>- [IgnoreApi]- int PageIndex { get; }- /// <summary>- /// The current page number (starts from 1)- /// </summary>- int PageNumber { get; }- /// <summary>- /// The number of items in each page.- /// </summary>- int PageSize { get; }- /// <summary>- /// The total number of items.- /// </summary>- int TotalItems { get; }- /// <summary>- /// The total number of pages.- /// </summary>- int TotalPages { get; }- /// <summary>- /// The index of the first item in the page.- /// </summary>- [IgnoreApi]- int FirstItem { get; }- /// <summary>- /// The index of the last item in the page.- /// </summary>- [IgnoreApi]- int LastItem { get; }- /// <summary>- /// Whether there are pages before the current page.- /// </summary>- [IgnoreApi]- bool HasPreviousPage { get; }- /// <summary>- /// Whether there are pages after the current page.- /// </summary>- [IgnoreApi]- bool HasNextPage { get; }- }+ [IgnoreApi]+ int LastItem { get; }+ /// <summary>+ /// Whether there are pages before the current page.+ /// </summary>+ [IgnoreApi]+ bool HasPreviousPage { get; }- /// <summary>- /// Generic form of <see cref="IPageableModel"/>- /// </summary>- /// <typeparam name="T">Type of object being paged</typeparam>- public interface IPagination<T> : IPageableModel- {+ /// <summary>+ /// Whether there are pages after the current page.+ /// </summary>+ [IgnoreApi]+ bool HasNextPage { get; }+}- }+/// <summary>+/// Generic form of <see cref="IPageableModel" />+/// </summary>+/// <typeparam name="T">Type of object being paged</typeparam>+public interface IPagination<T> : IPageableModel+{}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Page/ResourceLocation.cs b/src/Web/Grand.Web.Common/Page/ResourceLocation.csindex e7afe32b8..44219bf40 100644--- a/src/Web/Grand.Web.Common/Page/ResourceLocation.cs+++ b/src/Web/Grand.Web.Common/Page/ResourceLocation.cs@@ -1,14 +1,14 @@-namespace Grand.Web.Common.Page+namespace Grand.Web.Common.Page;++public enum ResourceLocation{- public enum ResourceLocation- {- /// <summary>- /// Header- /// </summary>- Head,- /// <summary>- /// Footer- /// </summary>- Footer- }-}+ /// <summary>+ /// Header+ /// </summary>+ Head,++ /// <summary>+ /// Footer+ /// </summary>+ Footer+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Routing/LanguageParameterTransformer.cs b/src/Web/Grand.Web.Common/Routing/LanguageParameterTransformer.csindex 5d7f65e31..304d8e4f2 100644--- a/src/Web/Grand.Web.Common/Routing/LanguageParameterTransformer.cs+++ b/src/Web/Grand.Web.Common/Routing/LanguageParameterTransformer.cs@@ -1,21 +1,20 @@using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Routing;-namespace Grand.Web.Common.Routing+namespace Grand.Web.Common.Routing;++public class LanguageParameterTransformer : IOutboundParameterTransformer{- public class LanguageParameterTransformer : IOutboundParameterTransformer- {- private readonly IHttpContextAccessor _httpContextAccessor;+ private readonly IHttpContextAccessor _httpContextAccessor;- public LanguageParameterTransformer(IHttpContextAccessor httpContextAccessor)- {- _httpContextAccessor = httpContextAccessor;- }+ public LanguageParameterTransformer(IHttpContextAccessor httpContextAccessor)+ {+ _httpContextAccessor = httpContextAccessor;+ }- public string TransformOutbound(object value)- {- var lang = _httpContextAccessor.HttpContext?.Request.RouteValues["language"];- return lang != null ? lang.ToString() : value?.ToString();- }+ public string TransformOutbound(object value)+ {+ var lang = _httpContextAccessor.HttpContext?.Request.RouteValues["language"];+ return lang != null ? lang.ToString() : value?.ToString();}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Routing/SlugRouteTransformer.cs b/src/Web/Grand.Web.Common/Routing/SlugRouteTransformer.csindex 266cc1087..217af0ea7 100644--- a/src/Web/Grand.Web.Common/Routing/SlugRouteTransformer.cs+++ b/src/Web/Grand.Web.Common/Routing/SlugRouteTransformer.cs@@ -6,168 +6,168 @@ using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Mvc.Routing;using Microsoft.AspNetCore.Routing;-namespace Grand.Web.Common.Routing+namespace Grand.Web.Common.Routing;++public class SlugRouteTransformer : DynamicRouteValueTransformer{- public class SlugRouteTransformer : DynamicRouteValueTransformer+ private readonly AppConfig _config;+ private readonly ILanguageService _languageService;+ private readonly ISlugService _slugService;++ public SlugRouteTransformer(+ ISlugService slugService,+ ILanguageService languageService,+ AppConfig config){- private readonly ISlugService _slugService;- private readonly ILanguageService _languageService;- private readonly AppConfig _config;+ _slugService = slugService;+ _languageService = languageService;+ _config = config;+ }- public SlugRouteTransformer(- ISlugService slugService,- ILanguageService languageService,- AppConfig config)- {- _slugService = slugService;- _languageService = languageService;- _config = config;- }+ private async ValueTask<string> GetSeName(string entityId, string entityName, string languageId)+ {+ var result = string.Empty;+ if (!string.IsNullOrEmpty(languageId))+ result = await _slugService.GetActiveSlug(entityId, entityName, languageId);+ //set default value if required+ if (string.IsNullOrEmpty(result)) result = await _slugService.GetActiveSlug(entityId, entityName, "");- private async ValueTask<string> GetSeName(string entityId, string entityName, string languageId)- {- var result = string.Empty;- if (!string.IsNullOrEmpty(languageId))- {- result = await _slugService.GetActiveSlug(entityId, entityName, languageId);- }- //set default value if required- if (string.IsNullOrEmpty(result))- {- result = await _slugService.GetActiveSlug(entityId, entityName, "");- }+ return result;+ }- return result;- }+ public override async ValueTask<RouteValueDictionary> TransformAsync(HttpContext context,+ RouteValueDictionary values)+ {+ var slug = values["SeName"];+ if (slug == null)+ return values;- public override async ValueTask<RouteValueDictionary> TransformAsync(HttpContext context, RouteValueDictionary values)- {- var slug = values["SeName"];- if (slug == null)- return values;+ var entityUrl = await _slugService.GetBySlugCached(slug.ToString());- var entityUrl = await _slugService.GetBySlugCached(slug.ToString());+ //no URL Entity found+ if (entityUrl == null)+ return null;- //no URL Entity found- if (entityUrl == null)+ //if URL Entity is not active find the latest one+ if (!entityUrl.IsActive)+ {+ var activeSlug =+ await _slugService.GetActiveSlug(entityUrl.EntityId, entityUrl.EntityName, entityUrl.LanguageId);+ if (string.IsNullOrEmpty(activeSlug))return null;- //if URL Entity is not active find the latest one- if (!entityUrl.IsActive)- {- var activeSlug = await _slugService.GetActiveSlug(entityUrl.EntityId, entityUrl.EntityName, entityUrl.LanguageId);- if (string.IsNullOrEmpty(activeSlug))- return null;-- values["controller"] = "Common";- values["action"] = "InternalRedirect";- values["url"] = $"{context.Request.PathBase}/{activeSlug}{context.Request.QueryString}";- values["permanentRedirect"] = true;- context.Items["grand.RedirectFromGenericPathRoute"] = true;- return values;- }+ values["controller"] = "Common";+ values["action"] = "InternalRedirect";+ values["url"] = $"{context.Request.PathBase}/{activeSlug}{context.Request.QueryString}";+ values["permanentRedirect"] = true;+ context.Items["grand.RedirectFromGenericPathRoute"] = true;+ return values;+ }- //ensure that the slug is the same for the current language,- //otherwise it can cause some issues when customers choose a new language but a slug stays the same- if (_config.SeoFriendlyUrlsForLanguagesEnabled)+ //ensure that the slug is the same for the current language,+ //otherwise it can cause some issues when customers choose a new language but a slug stays the same+ if (_config.SeoFriendlyUrlsForLanguagesEnabled)+ {+ var urlLanguage = values["language"];+ if (urlLanguage != null && !string.IsNullOrEmpty(urlLanguage.ToString())){- var urlLanguage = values["language"];- if (urlLanguage != null && !string.IsNullOrEmpty(urlLanguage.ToString()))- {- var language = (await _languageService.GetAllLanguages()).FirstOrDefault(x => x.UniqueSeoCode.ToLowerInvariant() == urlLanguage.ToString()?.ToLowerInvariant()) ??- (await _languageService.GetAllLanguages()).FirstOrDefault();+ var language = (await _languageService.GetAllLanguages()).FirstOrDefault(x =>+ x.UniqueSeoCode.ToLowerInvariant() == urlLanguage.ToString()?.ToLowerInvariant()) ??+ (await _languageService.GetAllLanguages()).FirstOrDefault();- var slugForCurrentLanguage = await GetSeName(entityUrl.EntityId, entityUrl.EntityName, language?.Id);- if (!string.IsNullOrEmpty(slugForCurrentLanguage) && !slugForCurrentLanguage.Equals(slug.ToString(), StringComparison.OrdinalIgnoreCase))- {- values["controller"] = "Common";- values["action"] = "InternalRedirect";- values["url"] = $"{context.Request.PathBase}/{slugForCurrentLanguage}{context.Request.QueryString}";- values["permanentRedirect"] = false;- context.Items["grand.RedirectFromGenericPathRoute"] = true;- return values;- }+ var slugForCurrentLanguage = await GetSeName(entityUrl.EntityId, entityUrl.EntityName, language?.Id);+ if (!string.IsNullOrEmpty(slugForCurrentLanguage) &&+ !slugForCurrentLanguage.Equals(slug.ToString(), StringComparison.OrdinalIgnoreCase))+ {+ values["controller"] = "Common";+ values["action"] = "InternalRedirect";+ values["url"] = $"{context.Request.PathBase}/{slugForCurrentLanguage}{context.Request.QueryString}";+ values["permanentRedirect"] = false;+ context.Items["grand.RedirectFromGenericPathRoute"] = true;+ return values;}}+ }- switch (entityUrl.EntityName)- {- case EntityTypes.Product:- values["controller"] = "Product";- values["action"] = "ProductDetails";- values["productid"] = entityUrl.EntityId;- values["SeName"] = entityUrl.Slug;- break;- case EntityTypes.Category:- values["controller"] = "Catalog";- values["action"] = "Category";- values["categoryid"] = entityUrl.EntityId;- values["SeName"] = entityUrl.Slug;- break;- case EntityTypes.Brand:- values["controller"] = "Catalog";- values["action"] = "Brand";- values["brandid"] = entityUrl.EntityId;- values["SeName"] = entityUrl.Slug;- break;- case EntityTypes.Collection:- values["controller"] = "Catalog";- values["action"] = "Collection";- values["collectionid"] = entityUrl.EntityId;- values["SeName"] = entityUrl.Slug;- break;- case EntityTypes.Vendor:- values["controller"] = "Catalog";- values["action"] = "Vendor";- values["vendorid"] = entityUrl.EntityId;- values["SeName"] = entityUrl.Slug;- break;- case EntityTypes.NewsItem:- values["controller"] = "News";- values["action"] = "NewsItem";- values["newsItemId"] = entityUrl.EntityId;- values["SeName"] = entityUrl.Slug;- break;- case EntityTypes.BlogPost:- values["controller"] = "Blog";- values["action"] = "BlogPost";- values["blogPostId"] = entityUrl.EntityId;- values["SeName"] = entityUrl.Slug;- break;- case EntityTypes.Page:- values["controller"] = "Page";- values["action"] = "PageDetails";- values["pageId"] = entityUrl.EntityId;- values["SeName"] = entityUrl.Slug;- break;- case EntityTypes.KnowledgeBaseArticle:- values["controller"] = "Knowledgebase";- values["action"] = "KnowledgebaseArticle";- values["articleId"] = entityUrl.EntityId;- values["SeName"] = entityUrl.Slug;- break;- case EntityTypes.KnowledgeBaseCategory:- values["controller"] = "Knowledgebase";- values["action"] = "ArticlesByCategory";- values["categoryId"] = entityUrl.EntityId;- values["SeName"] = entityUrl.Slug;- break;- case EntityTypes.Course:- values["controller"] = "Course";- values["action"] = "Details";- values["courseId"] = entityUrl.EntityId;+ switch (entityUrl.EntityName)+ {+ case EntityTypes.Product:+ values["controller"] = "Product";+ values["action"] = "ProductDetails";+ values["productid"] = entityUrl.EntityId;+ values["SeName"] = entityUrl.Slug;+ break;+ case EntityTypes.Category:+ values["controller"] = "Catalog";+ values["action"] = "Category";+ values["categoryid"] = entityUrl.EntityId;+ values["SeName"] = entityUrl.Slug;+ break;+ case EntityTypes.Brand:+ values["controller"] = "Catalog";+ values["action"] = "Brand";+ values["brandid"] = entityUrl.EntityId;+ values["SeName"] = entityUrl.Slug;+ break;+ case EntityTypes.Collection:+ values["controller"] = "Catalog";+ values["action"] = "Collection";+ values["collectionid"] = entityUrl.EntityId;+ values["SeName"] = entityUrl.Slug;+ break;+ case EntityTypes.Vendor:+ values["controller"] = "Catalog";+ values["action"] = "Vendor";+ values["vendorid"] = entityUrl.EntityId;+ values["SeName"] = entityUrl.Slug;+ break;+ case EntityTypes.NewsItem:+ values["controller"] = "News";+ values["action"] = "NewsItem";+ values["newsItemId"] = entityUrl.EntityId;+ values["SeName"] = entityUrl.Slug;+ break;+ case EntityTypes.BlogPost:+ values["controller"] = "Blog";+ values["action"] = "BlogPost";+ values["blogPostId"] = entityUrl.EntityId;+ values["SeName"] = entityUrl.Slug;+ break;+ case EntityTypes.Page:+ values["controller"] = "Page";+ values["action"] = "PageDetails";+ values["pageId"] = entityUrl.EntityId;+ values["SeName"] = entityUrl.Slug;+ break;+ case EntityTypes.KnowledgeBaseArticle:+ values["controller"] = "Knowledgebase";+ values["action"] = "KnowledgebaseArticle";+ values["articleId"] = entityUrl.EntityId;+ values["SeName"] = entityUrl.Slug;+ break;+ case EntityTypes.KnowledgeBaseCategory:+ values["controller"] = "Knowledgebase";+ values["action"] = "ArticlesByCategory";+ values["categoryId"] = entityUrl.EntityId;+ values["SeName"] = entityUrl.Slug;+ break;+ case EntityTypes.Course:+ values["controller"] = "Course";+ values["action"] = "Details";+ values["courseId"] = entityUrl.EntityId;+ values["SeName"] = entityUrl.Slug;+ break;+ default:+ if (!string.IsNullOrEmpty(entityUrl.Controller) && !string.IsNullOrEmpty(entityUrl.Action))+ {+ values["controller"] = entityUrl.Controller;+ values["action"] = entityUrl.Action;values["SeName"] = entityUrl.Slug;- break;- default:- if (!string.IsNullOrEmpty(entityUrl.Controller) && !string.IsNullOrEmpty(entityUrl.Action))- {- values["controller"] = entityUrl.Controller;- values["action"] = entityUrl.Action;- values["SeName"] = entityUrl.Slug;- }- break;- }- return values;+ }++ break;}++ return values;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Security/Authorization/CustomerGroupAuthorizeAttribute.cs b/src/Web/Grand.Web.Common/Security/Authorization/CustomerGroupAuthorizeAttribute.csindex 8b294304e..5079a022d 100644--- a/src/Web/Grand.Web.Common/Security/Authorization/CustomerGroupAuthorizeAttribute.cs+++ b/src/Web/Grand.Web.Common/Security/Authorization/CustomerGroupAuthorizeAttribute.cs@@ -4,40 +4,39 @@ using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Web.Common.Security.Authorization+namespace Grand.Web.Common.Security.Authorization;++[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]+public class CustomerGroupAuthorizeAttribute : Attribute, IAsyncAuthorizationFilter{- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]- public class CustomerGroupAuthorizeAttribute : Attribute, IAsyncAuthorizationFilter+ public CustomerGroupAuthorizeAttribute(string group){- public CustomerGroupAuthorizeAttribute(string group)- {- GroupName = group;- }-- public string GroupName { get; set; }+ GroupName = group;+ }- public async Task OnAuthorizationAsync(AuthorizationFilterContext context)- {- ArgumentNullException.ThrowIfNull(context);+ public string GroupName { get; set; }- if (string.IsNullOrEmpty(GroupName))- return;+ public async Task OnAuthorizationAsync(AuthorizationFilterContext context)+ {+ ArgumentNullException.ThrowIfNull(context);- var groupService = context.HttpContext.RequestServices.GetRequiredService<IGroupService>();- var workContext = context.HttpContext.RequestServices.GetRequiredService<IWorkContext>();+ if (string.IsNullOrEmpty(GroupName))+ return;- if (await groupService.IsInCustomerGroup(workContext.CurrentCustomer, GroupName, true))- return;+ var groupService = context.HttpContext.RequestServices.GetRequiredService<IGroupService>();+ var workContext = context.HttpContext.RequestServices.GetRequiredService<IWorkContext>();- var result = (context.HttpContext.Request.ContentType?.Contains("application/json") ?? false) ||- context.HttpContext.Request.Headers.Accept.ToString().Contains("application/json", StringComparison.InvariantCultureIgnoreCase) ||- context.HttpContext.Request.Method.Equals("POST", StringComparison.InvariantCultureIgnoreCase);+ if (await groupService.IsInCustomerGroup(workContext.CurrentCustomer, GroupName))+ return;- if (result)- context.Result = new ObjectResult("") { StatusCode = 403 };- else- context.Result = new RedirectToRouteResult("Login", new { returnUrl = context.HttpContext.Request.Path });+ var result = (context.HttpContext.Request.ContentType?.Contains("application/json") ?? false) ||+ context.HttpContext.Request.Headers.Accept.ToString().Contains("application/json",+ StringComparison.InvariantCultureIgnoreCase) ||+ context.HttpContext.Request.Method.Equals("POST", StringComparison.InvariantCultureIgnoreCase);- }+ if (result)+ context.Result = new ObjectResult("") { StatusCode = 403 };+ else+ context.Result = new RedirectToRouteResult("Login", new { returnUrl = context.HttpContext.Request.Path });}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeActionAttribute.cs b/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeActionAttribute.csindex c65f0e663..62cb8a7ad 100644--- a/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeActionAttribute.cs+++ b/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeActionAttribute.cs@@ -6,53 +6,54 @@ using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.Routing;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Web.Common.Security.Authorization+namespace Grand.Web.Common.Security.Authorization;++[AttributeUsage(AttributeTargets.Method)]+public class PermissionAuthorizeActionAttribute : Attribute, IAsyncAuthorizationFilter{- [AttributeUsage(AttributeTargets.Method)]- public class PermissionAuthorizeActionAttribute : Attribute, IAsyncAuthorizationFilter+ public PermissionAuthorizeActionAttribute(string actionName){- public PermissionAuthorizeActionAttribute(string actionName)- {- PermissionAction = actionName;- }+ PermissionAction = actionName;+ }- // Get or set the permission property by manipulating- public string PermissionAction { get; set; }+ // Get or set the permission property by manipulating+ public string PermissionAction { get; set; }- public async Task OnAuthorizationAsync(AuthorizationFilterContext context)- {- //ignore filter (the action available even when navigation is not allowed)- ArgumentNullException.ThrowIfNull(context);+ public async Task OnAuthorizationAsync(AuthorizationFilterContext context)+ {+ //ignore filter (the action available even when navigation is not allowed)+ ArgumentNullException.ThrowIfNull(context);- if (string.IsNullOrEmpty(PermissionAction))- return;+ if (string.IsNullOrEmpty(PermissionAction))+ return;- //check whether PermissionAuthorizeAttribute filter exists- var permissionAuthorize = context.Filters- .OfType<PermissionAuthorizeAttribute>().FirstOrDefault();+ //check whether PermissionAuthorizeAttribute filter exists+ var permissionAuthorize = context.Filters+ .OfType<PermissionAuthorizeAttribute>().FirstOrDefault();- if (permissionAuthorize == null || string.IsNullOrEmpty(permissionAuthorize.Permission))- return;+ if (permissionAuthorize == null || string.IsNullOrEmpty(permissionAuthorize.Permission))+ return;- var permissionService = context.HttpContext.RequestServices.GetRequiredService<IPermissionService>();+ var permissionService = context.HttpContext.RequestServices.GetRequiredService<IPermissionService>();- //check whether current customer has access to a public store- if (await permissionService.AuthorizeAction(permissionAuthorize.Permission, PermissionAction))- return;+ //check whether current customer has access to a public store+ if (await permissionService.AuthorizeAction(permissionAuthorize.Permission, PermissionAction))+ return;- //authorize permission of access to the admin area- if (!await permissionService.Authorize(StandardPermission.ManageAccessAdminPanel))- context.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());+ //authorize permission of access to the admin area+ if (!await permissionService.Authorize(StandardPermission.ManageAccessAdminPanel))+ {+ context.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());+ }+ else+ {+ var isAjaxCall = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";+ if (!isAjaxCall)+ context.Result = new RedirectToActionResult("AccessDenied", "Home",+ new { pageUrl = context.HttpContext.Request.Path });else- {- var isAjaxCall = context.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";- if (!isAjaxCall)- context.Result = new RedirectToActionResult("AccessDenied", "Home", new { pageUrl = context.HttpContext.Request.Path });- else- {- context.Result = new JsonResult(new DataSourceResult { Errors = $"Access denied to the resource {context.HttpContext.Request.Path}" });- }- }+ context.Result = new JsonResult(new DataSourceResult+ { Errors = $"Access denied to the resource {context.HttpContext.Request.Path}" });}}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeAttribute.cs b/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeAttribute.csindex 30c46dc09..98c328197 100644--- a/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeAttribute.cs+++ b/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeAttribute.cs@@ -5,37 +5,37 @@ using Microsoft.AspNetCore.Mvc.Filters;using Microsoft.AspNetCore.Routing;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Web.Common.Security.Authorization+namespace Grand.Web.Common.Security.Authorization;++[AttributeUsage(AttributeTargets.Class)]+public class PermissionAuthorizeAttribute : Attribute, IAsyncAuthorizationFilter{- [AttributeUsage(AttributeTargets.Class)]- public class PermissionAuthorizeAttribute : Attribute, IAsyncAuthorizationFilter+ public PermissionAuthorizeAttribute(string permission){- public PermissionAuthorizeAttribute(string permission)- {- Permission = permission;- }+ Permission = permission;+ }- // Get or set the permission property by manipulating- public string Permission { get; set; }+ // Get or set the permission property by manipulating+ public string Permission { get; set; }- public async Task OnAuthorizationAsync(AuthorizationFilterContext context)- {- //ignore filter (the action available even when navigation is not allowed)- ArgumentNullException.ThrowIfNull(context);+ public async Task OnAuthorizationAsync(AuthorizationFilterContext context)+ {+ //ignore filter (the action available even when navigation is not allowed)+ ArgumentNullException.ThrowIfNull(context);- if (string.IsNullOrEmpty(Permission))- return;+ if (string.IsNullOrEmpty(Permission))+ return;- var permissionService = context.HttpContext.RequestServices.GetRequiredService<IPermissionService>();- //check whether current customer has access to a public store- if (await permissionService.Authorize(Permission))- return;+ var permissionService = context.HttpContext.RequestServices.GetRequiredService<IPermissionService>();+ //check whether current customer has access to a public store+ if (await permissionService.Authorize(Permission))+ return;- //authorize permission of access to the admin area- if (!await permissionService.Authorize(StandardPermission.ManageAccessAdminPanel))- context.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());- else- context.Result = new RedirectToActionResult("AccessDenied", "Home", new { pageUrl = context.HttpContext.Request.Path });- }+ //authorize permission of access to the admin area+ if (!await permissionService.Authorize(StandardPermission.ManageAccessAdminPanel))+ context.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());+ else+ context.Result = new RedirectToActionResult("AccessDenied", "Home",+ new { pageUrl = context.HttpContext.Request.Path });}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Security/Captcha/CaptchaSettings.cs b/src/Web/Grand.Web.Common/Security/Captcha/CaptchaSettings.csindex 656f79572..f83193114 100644--- a/src/Web/Grand.Web.Common/Security/Captcha/CaptchaSettings.cs+++ b/src/Web/Grand.Web.Common/Security/Captcha/CaptchaSettings.cs@@ -1,93 +1,109 @@using Grand.Domain.Configuration;-namespace Grand.Web.Common.Security.Captcha+namespace Grand.Web.Common.Security.Captcha;++/// <summary>+/// CAPTCHA settings+/// </summary>+public class CaptchaSettings : ISettings{/// <summary>- /// CAPTCHA settings- /// </summary>- public class CaptchaSettings : ISettings- {- /// <summary>- /// Is CAPTCHA enabled?- /// </summary>- public bool Enabled { get; set; }- /// <summary>- /// A value indicating whether CAPTCHA should be displayed on the login page- /// </summary>- public bool ShowOnLoginPage { get; set; }- /// <summary>- /// A value indicating whether CAPTCHA should be displayed on the registration page- /// </summary>- public bool ShowOnRegistrationPage { get; set; }- /// <summary>- /// A value indicating whether CAPTCHA should be displayed on the password recovery page- /// </summary>- public bool ShowOnPasswordRecoveryPage { get; set; }- /// <summary>- /// A value indicating whether CAPTCHA should be displayed on the contacts page- /// </summary>- public bool ShowOnContactUsPage { get; set; }- /// <summary>- /// A value indicating whether CAPTCHA should be displayed on the wishlist page- /// </summary>- public bool ShowOnEmailWishlistToFriendPage { get; set; }- /// <summary>- /// A value indicating whether CAPTCHA should be displayed on the "email a friend" page- /// </summary>- public bool ShowOnEmailProductToFriendPage { get; set; }- /// <summary>- /// A value indicating whether CAPTCHA should be displayed on the "ask question" page- /// </summary>- public bool ShowOnAskQuestionPage { get; set; }- /// <summary>- /// A value indicating whether CAPTCHA should be displayed on the "comment blog" page- /// </summary>- public bool ShowOnBlogCommentPage { get; set; }- /// <summary>- /// A value indicating whether CAPTCHA should be displayed on the "comment blog" page- /// </summary>- public bool ShowOnArticleCommentPage { get; set; }- /// <summary>- /// A value indicating whether CAPTCHA should be displayed on the "comment news" page- /// </summary>- public bool ShowOnNewsCommentPage { get; set; }- /// <summary>- /// A value indicating whether CAPTCHA should be displayed on the product reviews page- /// </summary>- public bool ShowOnProductReviewPage { get; set; }- /// <summary>- /// A value indicating whether CAPTCHA should be displayed on the "Apply for vendor account" page- /// </summary>- public bool ShowOnApplyVendorPage { get; set; }-- /// <summary>- /// A value indicating whether CAPTCHA should be displayed on the vendor reviews page- /// </summary>- public bool ShowOnVendorReviewPage { get; set; }-- /// <summary>- /// reCAPTCHA public key- /// </summary>- public string ReCaptchaPublicKey { get; set; }- /// <summary>- /// reCAPTCHA private key- /// </summary>- public string ReCaptchaPrivateKey { get; set; }- /// <summary>- /// reCAPTCHA theme- /// </summary>- public string ReCaptchaTheme { get; set; }- /// <summary>- /// reCAPTCHA score- /// </summary>- public decimal ReCaptchaScore { get; set; }- /// <summary>- /// reCAPTCHA version- /// </summary>- public GoogleReCaptchaVersion ReCaptchaVersion { get; set; }- /// <summary>- /// reCAPTCHA language- /// </summary>- public string ReCaptchaLanguage { get; set; }- }+ /// Is CAPTCHA enabled?+ /// </summary>+ public bool Enabled { get; set; }++ /// <summary>+ /// A value indicating whether CAPTCHA should be displayed on the login page+ /// </summary>+ public bool ShowOnLoginPage { get; set; }++ /// <summary>+ /// A value indicating whether CAPTCHA should be displayed on the registration page+ /// </summary>+ public bool ShowOnRegistrationPage { get; set; }++ /// <summary>+ /// A value indicating whether CAPTCHA should be displayed on the password recovery page+ /// </summary>+ public bool ShowOnPasswordRecoveryPage { get; set; }++ /// <summary>+ /// A value indicating whether CAPTCHA should be displayed on the contacts page+ /// </summary>+ public bool ShowOnContactUsPage { get; set; }++ /// <summary>+ /// A value indicating whether CAPTCHA should be displayed on the wishlist page+ /// </summary>+ public bool ShowOnEmailWishlistToFriendPage { get; set; }++ /// <summary>+ /// A value indicating whether CAPTCHA should be displayed on the "email a friend" page+ /// </summary>+ public bool ShowOnEmailProductToFriendPage { get; set; }++ /// <summary>+ /// A value indicating whether CAPTCHA should be displayed on the "ask question" page+ /// </summary>+ public bool ShowOnAskQuestionPage { get; set; }++ /// <summary>+ /// A value indicating whether CAPTCHA should be displayed on the "comment blog" page+ /// </summary>+ public bool ShowOnBlogCommentPage { get; set; }++ /// <summary>+ /// A value indicating whether CAPTCHA should be displayed on the "comment blog" page+ /// </summary>+ public bool ShowOnArticleCommentPage { get; set; }++ /// <summary>+ /// A value indicating whether CAPTCHA should be displayed on the "comment news" page+ /// </summary>+ public bool ShowOnNewsCommentPage { get; set; }++ /// <summary>+ /// A value indicating whether CAPTCHA should be displayed on the product reviews page+ /// </summary>+ public bool ShowOnProductReviewPage { get; set; }++ /// <summary>+ /// A value indicating whether CAPTCHA should be displayed on the "Apply for vendor account" page+ /// </summary>+ public bool ShowOnApplyVendorPage { get; set; }++ /// <summary>+ /// A value indicating whether CAPTCHA should be displayed on the vendor reviews page+ /// </summary>+ public bool ShowOnVendorReviewPage { get; set; }++ /// <summary>+ /// reCAPTCHA public key+ /// </summary>+ public string ReCaptchaPublicKey { get; set; }++ /// <summary>+ /// reCAPTCHA private key+ /// </summary>+ public string ReCaptchaPrivateKey { get; set; }++ /// <summary>+ /// reCAPTCHA theme+ /// </summary>+ public string ReCaptchaTheme { get; set; }++ /// <summary>+ /// reCAPTCHA score+ /// </summary>+ public decimal ReCaptchaScore { get; set; }++ /// <summary>+ /// reCAPTCHA version+ /// </summary>+ public GoogleReCaptchaVersion ReCaptchaVersion { get; set; }++ /// <summary>+ /// reCAPTCHA language+ /// </summary>+ public string ReCaptchaLanguage { get; set; }}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Security/Captcha/CaptchaSettingsExtension.cs b/src/Web/Grand.Web.Common/Security/Captcha/CaptchaSettingsExtension.csindex b646af40c..afd110c76 100644--- a/src/Web/Grand.Web.Common/Security/Captcha/CaptchaSettingsExtension.cs+++ b/src/Web/Grand.Web.Common/Security/Captcha/CaptchaSettingsExtension.cs@@ -1,17 +1,16 @@using Grand.Business.Core.Interfaces.Common.Localization;-namespace Grand.Web.Common.Security.Captcha+namespace Grand.Web.Common.Security.Captcha;++public static class CaptchaSettingsExtension{- public static class CaptchaSettingsExtension+ public static string GetWrongCaptchaMessage(this CaptchaSettings captchaSettings,+ ITranslationService translationService){- public static string GetWrongCaptchaMessage(this CaptchaSettings captchaSettings,- ITranslationService translationService)- {- return captchaSettings.ReCaptchaVersion switch {- GoogleReCaptchaVersion.V2 => translationService.GetResource("Common.WrongCaptchaV2"),- GoogleReCaptchaVersion.V3 => translationService.GetResource("Common.WrongCaptchaV3"),- _ => string.Empty- };- }+ return captchaSettings.ReCaptchaVersion switch {+ GoogleReCaptchaVersion.V2 => translationService.GetResource("Common.WrongCaptchaV2"),+ GoogleReCaptchaVersion.V3 => translationService.GetResource("Common.WrongCaptchaV3"),+ _ => string.Empty+ };}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaResponse.cs b/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaResponse.csindex 168470326..0a173a207 100644--- a/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaResponse.cs+++ b/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaResponse.cs@@ -1,12 +1,12 @@using System.Text.Json.Serialization;-namespace Grand.Web.Common.Security.Captcha+namespace Grand.Web.Common.Security.Captcha;++public class GoogleReCaptchaResponse{- public class GoogleReCaptchaResponse- {- public bool Success { get; set; }- [JsonPropertyName("error-codes")]- public List<string> ErrorCodes { get; set; } = new();- public decimal Score { get; set; }- }+ public bool Success { get; set; }++ [JsonPropertyName("error-codes")] public List<string> ErrorCodes { get; set; } = new();++ public decimal Score { get; set; }}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaValidator.cs b/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaValidator.csindex dac5fb0a7..168d7146e 100644--- a/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaValidator.cs+++ b/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaValidator.cs@@ -3,58 +3,58 @@ using Microsoft.AspNetCore.Http;using System.Net.Http;using System.Text.Json;-namespace Grand.Web.Common.Security.Captcha+namespace Grand.Web.Common.Security.Captcha;++public class GoogleReCaptchaValidator{- public class GoogleReCaptchaValidator+ private const string RecaptchaVerifyUrl =+ "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}&remoteip={2}";++ private readonly CaptchaSettings _captchaSettings;+ private readonly HttpClient _httpClient;+ private readonly IHttpContextAccessor _httpContextAccessor;++ public GoogleReCaptchaValidator(CaptchaSettings captchaSettings,+ IHttpContextAccessor httpContextAccessor,+ HttpClient httpClient){- private const string RecaptchaVerifyUrl = "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}&remoteip={2}";+ _captchaSettings = captchaSettings;+ _httpContextAccessor = httpContextAccessor;+ _httpClient = httpClient;+ }- private readonly CaptchaSettings _captchaSettings;- private readonly IHttpContextAccessor _httpContextAccessor;- private readonly HttpClient _httpClient;+ public async Task<GoogleReCaptchaResponse> Validate(string response)+ {+ GoogleReCaptchaResponse result;+ if (_httpContextAccessor.HttpContext == null) return null;+ var requestUri = string.Format(RecaptchaVerifyUrl, _captchaSettings.ReCaptchaPrivateKey, response,+ _httpContextAccessor.HttpContext.Connection.RemoteIpAddress);- public GoogleReCaptchaValidator(CaptchaSettings captchaSettings,- IHttpContextAccessor httpContextAccessor,- HttpClient httpClient)+ try{- _captchaSettings = captchaSettings;- _httpContextAccessor = httpContextAccessor;- _httpClient = httpClient;+ var responseMessage = await _httpClient.GetAsync(requestUri);+ responseMessage.EnsureSuccessStatusCode();+ var contentResult = await responseMessage.Content.ReadAsStringAsync();+ result = ParseResponseResult(contentResult);}-- public async Task<GoogleReCaptchaResponse> Validate(string response)+ catch (Exception exc){- GoogleReCaptchaResponse result;- if (_httpContextAccessor.HttpContext == null) return null;- var requestUri = string.Format(RecaptchaVerifyUrl, _captchaSettings.ReCaptchaPrivateKey, response,- _httpContextAccessor.HttpContext.Connection.RemoteIpAddress);-- try- {- var responseMessage = await _httpClient.GetAsync(requestUri);- responseMessage.EnsureSuccessStatusCode();- var contentResult = await responseMessage.Content.ReadAsStringAsync();- result = ParseResponseResult(contentResult);-- }- catch (Exception exc)- {- result = new GoogleReCaptchaResponse { Success = false };- result.ErrorCodes.Add("Unknown error" + exc.Message);- }-- return result;+ result = new GoogleReCaptchaResponse { Success = false };+ result.ErrorCodes.Add("Unknown error" + exc.Message);}- private GoogleReCaptchaResponse ParseResponseResult(string responseString)- {- var result = JsonSerializer.Deserialize<GoogleReCaptchaResponse>(responseString, ProviderExtensions.JsonSerializerOptionsProvider.Options);- if (_captchaSettings.ReCaptchaVersion != GoogleReCaptchaVersion.V3) return result;-- if (_captchaSettings.ReCaptchaScore > 0)- result.Success = result.Success && result.Score >= _captchaSettings.ReCaptchaScore;+ return result;+ }- return result;- }+ private GoogleReCaptchaResponse ParseResponseResult(string responseString)+ {+ var result = JsonSerializer.Deserialize<GoogleReCaptchaResponse>(responseString,+ ProviderExtensions.JsonSerializerOptionsProvider.Options);+ if (_captchaSettings.ReCaptchaVersion != GoogleReCaptchaVersion.V3) return result;++ if (_captchaSettings.ReCaptchaScore > 0)+ result.Success = result.Success && result.Score >= _captchaSettings.ReCaptchaScore;++ return result;}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaVersion.cs b/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaVersion.csindex 2d6c4ee16..eb45025f5 100644--- a/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaVersion.cs+++ b/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaVersion.cs@@ -1,17 +1,17 @@-namespace Grand.Web.Common.Security.Captcha+namespace Grand.Web.Common.Security.Captcha;++/// <summary>+/// Represents a reCAPTCHA version+/// </summary>+public enum GoogleReCaptchaVersion{/// <summary>- /// Represents a reCAPTCHA version+ /// Version 2.0/// </summary>- public enum GoogleReCaptchaVersion- {- /// <summary>- /// Version 2.0- /// </summary>- V2 = 2,- /// <summary>- /// Version 3.0- /// </summary>- V3 = 3- }+ V2 = 2,++ /// <summary>+ /// Version 3.0+ /// </summary>+ V3 = 3}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Security/Captcha/GoogleRecaptchaControl.cs b/src/Web/Grand.Web.Common/Security/Captcha/GoogleRecaptchaControl.csindex b653edc38..7d9903723 100644--- a/src/Web/Grand.Web.Common/Security/Captcha/GoogleRecaptchaControl.cs+++ b/src/Web/Grand.Web.Common/Security/Captcha/GoogleRecaptchaControl.cs@@ -1,125 +1,127 @@using Grand.Web.Common.Extensions;using Microsoft.AspNetCore.Mvc.Rendering;-namespace Grand.Web.Common.Security.Captcha+namespace Grand.Web.Common.Security.Captcha;++public class GoogleRecaptchaControl{- public class GoogleRecaptchaControl+ private const string RecaptchaApiUrlVersion =+ "https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit";++ private readonly GoogleReCaptchaVersion _version;++ public GoogleRecaptchaControl(GoogleReCaptchaVersion version = GoogleReCaptchaVersion.V2){- private const string RecaptchaApiUrlVersion = "https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit";+ _version = version;+ }- public string Id { get; set; }- public string Theme { get; set; }- public string PublicKey { get; set; }- public string Language { get; set; }+ public string Id { get; set; }+ public string Theme { get; set; }+ public string PublicKey { get; set; }+ public string Language { get; set; }- private readonly GoogleReCaptchaVersion _version;+ public string RenderControl()+ {+ SetTheme();- public GoogleRecaptchaControl(GoogleReCaptchaVersion version = GoogleReCaptchaVersion.V2)- {- _version = version;- }+ return _version switch {+ GoogleReCaptchaVersion.V2 => RenderV2(),+ GoogleReCaptchaVersion.V3 => RenderV3(),+ _ => throw new NotSupportedException("Specified version is not supported")+ };+ }- public string RenderControl()- {- SetTheme();+ private string RenderV2()+ {+ var scriptCallbackTag = new TagBuilder("script") {+ TagRenderMode = TagRenderMode.Normal+ };+ scriptCallbackTag.InnerHtml.AppendHtml(+ $"var onloadCallback = function() {{grecaptcha.render('{Id}', {{'sitekey' : '{PublicKey}', 'theme' : '{Theme}' }});}};");++ var captchaTag = new TagBuilder("div") {+ TagRenderMode = TagRenderMode.Normal+ };+ captchaTag.Attributes.Add("id", Id);++ var scriptLoadApiTag = new TagBuilder("script") {+ TagRenderMode = TagRenderMode.Normal+ };+ scriptLoadApiTag.Attributes.Add("src",+ RecaptchaApiUrlVersion + (string.IsNullOrEmpty(Language) ? "" : $"&hl={Language}"));+ scriptLoadApiTag.Attributes.Add("async", null);+ scriptLoadApiTag.Attributes.Add("defer", null);++ return scriptCallbackTag.RenderHtmlContent() + captchaTag.RenderHtmlContent() ++ scriptLoadApiTag.RenderHtmlContent();+ }- return _version switch {- GoogleReCaptchaVersion.V2 => RenderV2(),- GoogleReCaptchaVersion.V3 => RenderV3(),- _ => throw new NotSupportedException("Specified version is not supported")- };- }+ private string RenderV3()+ {+ var scriptCallbackTag = new TagBuilder("script") {+ TagRenderMode = TagRenderMode.Normal+ };+ var clientId = Guid.NewGuid().ToString();+ var script = new StringBuilder();+ script.AppendLine("function onloadCallback() {");+ script.AppendLine($"var clientId = grecaptcha.render('{clientId}', {{");+ script.AppendLine($"'sitekey': '{PublicKey}',");+ script.AppendLine("'badge': 'inline',");+ script.AppendLine($"'theme': '{Theme}',");+ script.AppendLine("'size': 'invisible'");+ script.AppendLine(" });");++ script.AppendLine("grecaptcha.ready(function() {");++ script.AppendLine(" grecaptcha.execute(clientId, {");+ script.AppendLine(" action: 'homepage'");+ script.AppendLine(" })");+ script.AppendLine(" .then(function(token) {");+ script.AppendLine($" document.getElementById('{Id}').value = token;");+ script.AppendLine(" })");+ script.AppendLine("})}");+ scriptCallbackTag.InnerHtml.AppendHtml(script.ToString());++ var captchaTagInput = new TagBuilder("input") {+ TagRenderMode = TagRenderMode.Normal+ };+ captchaTagInput.Attributes.Add("type", "hidden");+ captchaTagInput.Attributes.Add("id", Id);+ captchaTagInput.Attributes.Add("name", Id);++ var captchaTagDiv = new TagBuilder("div");+ captchaTagDiv.Attributes.Add("id", $"{clientId}");++ var scriptLoadApiTag = new TagBuilder("script") {+ TagRenderMode = TagRenderMode.Normal+ };+ scriptLoadApiTag.TagRenderMode = TagRenderMode.Normal;+ scriptLoadApiTag.Attributes.Add("src",+ RecaptchaApiUrlVersion + (string.IsNullOrEmpty(Language) ? "" : $"&hl={Language}"));++ return scriptLoadApiTag.RenderHtmlContent() + scriptCallbackTag.RenderHtmlContent() ++ captchaTagInput.RenderHtmlContent() + captchaTagDiv.RenderHtmlContent();+ }- private string RenderV2()- {- var scriptCallbackTag = new TagBuilder("script") {- TagRenderMode = TagRenderMode.Normal- };- scriptCallbackTag.InnerHtml.AppendHtml($"var onloadCallback = function() {{grecaptcha.render('{Id}', {{'sitekey' : '{PublicKey}', 'theme' : '{Theme}' }});}};");-- var captchaTag = new TagBuilder("div") {- TagRenderMode = TagRenderMode.Normal- };- captchaTag.Attributes.Add("id", Id);-- var scriptLoadApiTag = new TagBuilder("script") {- TagRenderMode = TagRenderMode.Normal- };- scriptLoadApiTag.Attributes.Add("src", RecaptchaApiUrlVersion + (string.IsNullOrEmpty(Language) ? "" : $"&hl={Language}"));- scriptLoadApiTag.Attributes.Add("async", null);- scriptLoadApiTag.Attributes.Add("defer", null);-- return scriptCallbackTag.RenderHtmlContent() + captchaTag.RenderHtmlContent() + scriptLoadApiTag.RenderHtmlContent();- }+ private void SetTheme()+ {+ var themes = new[] { "white", "blackglass", "red", "clean", "light", "dark" };- private string RenderV3()- {- var scriptCallbackTag = new TagBuilder("script") {- TagRenderMode = TagRenderMode.Normal- };- var clientId = Guid.NewGuid().ToString();- var script = new StringBuilder();- script.AppendLine("function onloadCallback() {");- script.AppendLine($"var clientId = grecaptcha.render('{clientId}', {{");- script.AppendLine($"'sitekey': '{PublicKey}',");- script.AppendLine("'badge': 'inline',");- script.AppendLine($"'theme': '{Theme}',");- script.AppendLine("'size': 'invisible'");- script.AppendLine(" });");-- script.AppendLine("grecaptcha.ready(function() {");-- script.AppendLine(" grecaptcha.execute(clientId, {");- script.AppendLine(" action: 'homepage'");- script.AppendLine(" })");- script.AppendLine(" .then(function(token) {");- script.AppendLine($" document.getElementById('{Id}').value = token;");- script.AppendLine(" })");- script.AppendLine("})}");- scriptCallbackTag.InnerHtml.AppendHtml(script.ToString());-- var captchaTagInput = new TagBuilder("input") {- TagRenderMode = TagRenderMode.Normal- };- captchaTagInput.Attributes.Add("type", "hidden");- captchaTagInput.Attributes.Add("id", Id);- captchaTagInput.Attributes.Add("name", Id);-- var captchaTagDiv = new TagBuilder("div");- captchaTagDiv.Attributes.Add("id", $"{clientId}");-- var scriptLoadApiTag = new TagBuilder("script") {- TagRenderMode = TagRenderMode.Normal- };- scriptLoadApiTag.TagRenderMode = TagRenderMode.Normal;- scriptLoadApiTag.Attributes.Add("src", RecaptchaApiUrlVersion + (string.IsNullOrEmpty(Language) ? "" : $"&hl={Language}"));-- return scriptLoadApiTag.RenderHtmlContent() + scriptCallbackTag.RenderHtmlContent() + captchaTagInput.RenderHtmlContent() + captchaTagDiv.RenderHtmlContent();- }+ Theme ??= "light";- private void SetTheme()+ switch (Theme.ToLower()){- var themes = new[] { "white", "blackglass", "red", "clean", "light", "dark" };-- Theme ??= "light";-- switch (Theme.ToLower())- {- case "clean":- case "red":- case "white":- Theme = "light";- break;- case "blackglass":- Theme = "dark";- break;- default:- if (!themes.Contains(Theme.ToLower()))- {- Theme = "light";- }- break;- }+ case "clean":+ case "red":+ case "white":+ Theme = "light";+ break;+ case "blackglass":+ Theme = "dark";+ break;+ default:+ if (!themes.Contains(Theme.ToLower())) Theme = "light";+ break;}}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Startup/AuthenticationStartup.cs b/src/Web/Grand.Web.Common/Startup/AuthenticationStartup.csindex 970f8fefb..c939421db 100644--- a/src/Web/Grand.Web.Common/Startup/AuthenticationStartup.cs+++ b/src/Web/Grand.Web.Common/Startup/AuthenticationStartup.cs@@ -8,53 +8,51 @@ using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Web.Common.Startup+namespace Grand.Web.Common.Startup;++/// <summary>+/// Represents object for the configuring authentication middleware on application startup+/// </summary>+public class AuthenticationStartup : IStartupApplication{/// <summary>- /// Represents object for the configuring authentication middleware on application startup+ /// 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>+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration)+ {+ var config = new AppConfig();+ configuration.GetSection("Application").Bind(config);++ //add authentication+ services.AddGrandAuthentication(configuration);+ }++ /// <summary>+ /// Configure the using of added middleware/// </summary>- public class AuthenticationStartup : IStartupApplication+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ /// <param name="webHostEnvironment">WebHostEnvironment</param>+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment){- /// <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>- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- var config = new AppConfig();- configuration.GetSection("Application").Bind(config);-- //add authentication- services.AddGrandAuthentication(configuration);- }-- /// <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>- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {- //check whether database is installed- if (!DataSettingsManager.DatabaseIsInstalled())- return;-- //configure authentication- application.UseGrandAuthentication();-- //set work context- application.UseMiddleware<WorkContextMiddleware>();- //set culture- application.UseMiddleware<CultureSettingMiddleware>();-- }-- /// <summary>- /// Gets order of this startup configuration implementation- /// </summary>- public int Priority => 500;- public bool BeforeConfigure => true;+ //check whether database is installed+ if (!DataSettingsManager.DatabaseIsInstalled())+ return;++ //configure authentication+ application.UseGrandAuthentication();+ //set work context+ application.UseMiddleware<WorkContextMiddleware>();+ //set culture+ application.UseMiddleware<CultureSettingMiddleware>();}-}++ /// <summary>+ /// Gets order of this startup configuration implementation+ /// </summary>+ public int Priority => 500;++ public bool BeforeConfigure => true;+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Startup/DbCheckStartup.cs b/src/Web/Grand.Web.Common/Startup/DbCheckStartup.csindex 09ee53835..932fd97a3 100644--- a/src/Web/Grand.Web.Common/Startup/DbCheckStartup.cs+++ b/src/Web/Grand.Web.Common/Startup/DbCheckStartup.cs@@ -7,27 +7,26 @@ using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Web.Common.Startup+namespace Grand.Web.Common.Startup;++public class DbCheckStartup : IStartupApplication{- public class DbCheckStartup : IStartupApplication- {- public int Priority => 0;- public bool BeforeConfigure => false;+ public int Priority => 0;+ public bool BeforeConfigure => false;- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {- if (!DataSettingsManager.DatabaseIsInstalled())- return;+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {+ if (!DataSettingsManager.DatabaseIsInstalled())+ return;- var serviceProvider = application.ApplicationServices;- var performanceConfig = serviceProvider.GetRequiredService<PerformanceConfig>();+ var serviceProvider = application.ApplicationServices;+ var performanceConfig = serviceProvider.GetRequiredService<PerformanceConfig>();- if(!performanceConfig.IgnoreDbVersionCheckMiddleware)- application.UseMiddleware<DbVersionCheckMiddleware>();- }+ if (!performanceConfig.IgnoreDbVersionCheckMiddleware)+ application.UseMiddleware<DbVersionCheckMiddleware>();+ }- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- }+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration)+ {}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Startup/ErrorHandlerStartup.cs b/src/Web/Grand.Web.Common/Startup/ErrorHandlerStartup.csindex 3e7c134d7..3f458c4d2 100644--- a/src/Web/Grand.Web.Common/Startup/ErrorHandlerStartup.cs+++ b/src/Web/Grand.Web.Common/Startup/ErrorHandlerStartup.cs@@ -1,48 +1,47 @@-using Grand.Web.Common.Infrastructure;-using Grand.Infrastructure;+using Grand.Infrastructure;+using Grand.Web.Common.Infrastructure;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Web.Common.Startup+namespace Grand.Web.Common.Startup;++/// <summary>+/// Represents object for the configuring exceptions and errors handling on application startup+/// </summary>+public class ErrorHandlerStartup : IStartupApplication{/// <summary>- /// Represents object for the configuring exceptions and errors handling on application startup+ /// Add and configure any of the middleware/// </summary>- public class ErrorHandlerStartup : IStartupApplication+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="configuration">Configuration root of the application</param>+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration){- /// <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>- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- }+ }- /// <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>- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {- //exception handling- application.UseGrandExceptionHandler();+ /// <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>+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {+ //exception handling+ application.UseGrandExceptionHandler();- //handle 400 errors (bad request)- application.UseBadRequestResult();+ //handle 400 errors (bad request)+ application.UseBadRequestResult();- //handle 404 errors- application.UsePageNotFound();- }+ //handle 404 errors+ application.UsePageNotFound();+ }- /// <summary>- /// Gets order of this startup configuration implementation- /// </summary>- public int Priority => -10;- public bool BeforeConfigure => true;+ /// <summary>+ /// Gets order of this startup configuration implementation+ /// </summary>+ public int Priority => -10;- }-}+ public bool BeforeConfigure => true;+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Startup/ForwardedHeadersStartup.cs b/src/Web/Grand.Web.Common/Startup/ForwardedHeadersStartup.csindex 4840163c4..4253c4fa2 100644--- a/src/Web/Grand.Web.Common/Startup/ForwardedHeadersStartup.cs+++ b/src/Web/Grand.Web.Common/Startup/ForwardedHeadersStartup.cs@@ -7,51 +7,46 @@ using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Web.Common.Startup+namespace Grand.Web.Common.Startup;++public class ForwardedHeadersStartup : IStartupApplication{- public class ForwardedHeadersStartup : 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>+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration){- /// <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>- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {-- }+ }- /// <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>- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {- //check whether database is installed- if (!DataSettingsManager.DatabaseIsInstalled())- return;+ /// <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>+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {+ //check whether database is installed+ if (!DataSettingsManager.DatabaseIsInstalled())+ return;- var serviceProvider = application.ApplicationServices;- var securityConfig = serviceProvider.GetRequiredService<SecurityConfig>();- if (securityConfig.ForceUseHTTPS)+ var serviceProvider = application.ApplicationServices;+ var securityConfig = serviceProvider.GetRequiredService<SecurityConfig>();+ if (securityConfig.ForceUseHTTPS)+ application.Use((context, next) =>{- application.Use((context, next) =>- {- context.Request.Scheme = "https";- return next(context);- });- }- if (securityConfig.UseForwardedHeaders)- application.UseGrandForwardedHeaders();-- }+ context.Request.Scheme = "https";+ return next(context);+ });+ if (securityConfig.UseForwardedHeaders)+ application.UseGrandForwardedHeaders();+ }- /// <summary>- /// Gets order of this startup configuration implementation- /// </summary>- public int Priority => -20;- public bool BeforeConfigure => true;+ /// <summary>+ /// Gets order of this startup configuration implementation+ /// </summary>+ public int Priority => -20;- }-}+ public bool BeforeConfigure => true;+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Startup/GrandCommonStartup.cs b/src/Web/Grand.Web.Common/Startup/GrandCommonStartup.csindex 7f1cad91a..fee85e5c8 100644--- a/src/Web/Grand.Web.Common/Startup/GrandCommonStartup.cs+++ b/src/Web/Grand.Web.Common/Startup/GrandCommonStartup.cs@@ -1,132 +1,119 @@-using Grand.Web.Common.Infrastructure;-using Grand.Web.Common.Routing;-using Grand.Infrastructure;+using Grand.Infrastructure;using Grand.Infrastructure.Configuration;+using Grand.Web.Common.Infrastructure;+using Grand.Web.Common.Routing;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Web.Common.Startup+namespace Grand.Web.Common.Startup;++/// <summary>+/// Represents object for the configuring common features and middleware on application startup+/// </summary>+public class GrandCommonStartup : IStartupApplication{/// <summary>- /// Represents object for the configuring common features and middleware on application startup+ /// Add and configure any of the middleware/// </summary>- public class GrandCommonStartup : IStartupApplication+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="configuration">Configuration root of the application</param>+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration){- /// <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>- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- var securityConfig = new SecurityConfig();- configuration.GetSection("Security").Bind(securityConfig);+ var securityConfig = new SecurityConfig();+ configuration.GetSection("Security").Bind(securityConfig);++ //add settings+ services.AddSettings();++ //compression+ services.AddResponseCompression();- //add settings- services.AddSettings();+ //add options feature+ services.AddOptions();- //compression- services.AddResponseCompression();+ //add HTTP session state feature+ services.AddHttpSession(securityConfig);- //add options feature- services.AddOptions();+ //add anti-forgery+ services.AddAntiForgery(securityConfig);- //add HTTP session state feature- services.AddHttpSession(securityConfig);+ //add localization+ services.AddLocalization();- //add anti-forgery- services.AddAntiForgery(securityConfig);+ //add theme support+ services.AddThemes();- //add localization- services.AddLocalization();+ //add WebEncoderOptions+ services.AddWebEncoder();- //add theme support- services.AddThemes();+ //add detection device+ services.AddDetectionDevice();- //add WebEncoderOptions- services.AddWebEncoder();+ //add routing+ services.AddRouting(options =>+ {+ options.ConstraintMap["lang"] = typeof(LanguageParameterTransformer);+ });- //add detection device- services.AddDetectionDevice();+ //add data protection+ services.AddGrandDataProtection(configuration);+ }- //add routing- services.AddRouting(options =>- {- options.ConstraintMap["lang"] = typeof(LanguageParameterTransformer);- });+ /// <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>+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {+ var serviceProvider = application.ApplicationServices;+ var appConfig = serviceProvider.GetRequiredService<AppConfig>();+ var performanceConfig = serviceProvider.GetRequiredService<PerformanceConfig>();+ var securityConfig = serviceProvider.GetRequiredService<SecurityConfig>();- //add data protection- services.AddGrandDataProtection(configuration);- }+ //add HealthChecks+ application.UseGrandHealthChecks();- /// <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>- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {- var serviceProvider = application.ApplicationServices;- var appConfig = serviceProvider.GetRequiredService<AppConfig>();- var performanceConfig = serviceProvider.GetRequiredService<PerformanceConfig>();- var securityConfig = serviceProvider.GetRequiredService<SecurityConfig>();-- //add HealthChecks- application.UseGrandHealthChecks();-- //default security headers- if (securityConfig.UseDefaultSecurityHeaders)- {- application.UseDefaultSecurityHeaders();- }-- //use hsts- if (securityConfig.UseHsts)- {- application.UseHsts();- }- //enforce HTTPS in ASP.NET Core- if (securityConfig.UseHttpsRedirection)- {- application.UseHttpsRedirection();- }-- //compression- if (performanceConfig.UseResponseCompression)- {- //gzip by default- application.UseResponseCompression();- }-- //use static files feature- application.UseGrandStaticFiles(appConfig);-- //check whether database is installed- if (!performanceConfig.IgnoreInstallUrlMiddleware)- application.UseInstallUrl();-- //use HTTP session- application.UseSession();-- //use powered by- if (!performanceConfig.IgnoreUsePoweredByMiddleware)- application.UsePoweredBy();-- //add responsive middleware (for detection)- application.UseGrandDetection();-- //use routing- application.UseRouting();-- }-- /// <summary>- /// Gets order of this startup configuration implementation- /// </summary>- public int Priority => 100;- public bool BeforeConfigure => true;+ //default security headers+ if (securityConfig.UseDefaultSecurityHeaders) application.UseDefaultSecurityHeaders();+ //use hsts+ if (securityConfig.UseHsts) application.UseHsts();+ //enforce HTTPS in ASP.NET Core+ if (securityConfig.UseHttpsRedirection) application.UseHttpsRedirection();++ //compression+ if (performanceConfig.UseResponseCompression)+ //gzip by default+ application.UseResponseCompression();++ //use static files feature+ application.UseGrandStaticFiles(appConfig);++ //check whether database is installed+ if (!performanceConfig.IgnoreInstallUrlMiddleware)+ application.UseInstallUrl();++ //use HTTP session+ application.UseSession();++ //use powered by+ if (!performanceConfig.IgnoreUsePoweredByMiddleware)+ application.UsePoweredBy();++ //add responsive middleware (for detection)+ application.UseGrandDetection();++ //use routing+ application.UseRouting();}-}++ /// <summary>+ /// Gets order of this startup configuration implementation+ /// </summary>+ public int Priority => 100;++ public bool BeforeConfigure => true;+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Startup/GrandMvcStartup.cs b/src/Web/Grand.Web.Common/Startup/GrandMvcStartup.csindex 2ca00cb21..0c1b323e0 100644--- a/src/Web/Grand.Web.Common/Startup/GrandMvcStartup.cs+++ b/src/Web/Grand.Web.Common/Startup/GrandMvcStartup.cs@@ -1,51 +1,49 @@-using Grand.Web.Common.Infrastructure;-using Grand.Infrastructure;+using Grand.Infrastructure;+using Grand.Web.Common.Infrastructure;using Microsoft.AspNetCore.Builder;using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Web.Common.Startup+namespace Grand.Web.Common.Startup;++/// <summary>+/// Represents object for the configuring MVC on application startup+/// </summary>+public class GrandMvcStartup : IStartupApplication{/// <summary>- /// Represents object for the configuring MVC on application startup+ /// Add and configure any of the middleware/// </summary>- public class GrandMvcStartup : IStartupApplication+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="configuration">Configuration root of the application</param>+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration){- /// <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>- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- //add healthChecks- services.AddGrandHealthChecks();-- //add ApplicationInsights- services.AddGrandApplicationInsights(configuration);+ //add healthChecks+ services.AddGrandHealthChecks();- //add and configure MVC feature- services.AddGrandMvc(configuration);+ //add ApplicationInsights+ services.AddGrandApplicationInsights(configuration);- }+ //add and configure MVC feature+ services.AddGrandMvc(configuration);+ }- /// <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>- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {- //endpoint routing- application.UseGrandEndpoints();- }+ /// <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>+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {+ //endpoint routing+ application.UseGrandEndpoints();+ }- /// <summary>- /// Gets order of this startup configuration implementation- /// </summary>- public int Priority => 1000;- public bool BeforeConfigure => true;+ /// <summary>+ /// Gets order of this startup configuration implementation+ /// </summary>+ public int Priority => 1000;- }-}+ public bool BeforeConfigure => true;+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Startup/HostFilteringStartup.cs b/src/Web/Grand.Web.Common/Startup/HostFilteringStartup.csindex d6d5d513d..b2583c291 100644--- a/src/Web/Grand.Web.Common/Startup/HostFilteringStartup.cs+++ b/src/Web/Grand.Web.Common/Startup/HostFilteringStartup.cs@@ -7,52 +7,48 @@ using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Web.Common.Startup+namespace Grand.Web.Common.Startup;++/// <summary>+/// Represents object for the configuring host filtering middleware on application+/// </summary>+public class HostFilteringStartup : IStartupApplication{/// <summary>- /// Represents object for the configuring host filtering middleware on application+ /// Add and configure any of the middleware/// </summary>- public class HostFilteringStartup : IStartupApplication+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="configuration">Configuration root of the application</param>+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration){- /// <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>- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- var securityConfig = new SecurityConfig();- configuration.GetSection("Security").Bind(securityConfig);+ var securityConfig = new SecurityConfig();+ configuration.GetSection("Security").Bind(securityConfig);- //configuration[- var hosts = securityConfig.AllowedHosts?- .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);- if (hosts?.Length > 0)- {- services.Configure<HostFilteringOptions>(options => options.AllowedHosts = hosts);- }- }+ //configuration[+ var hosts = securityConfig.AllowedHosts?+ .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);+ if (hosts?.Length > 0) services.Configure<HostFilteringOptions>(options => options.AllowedHosts = hosts);+ }- /// <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>- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {- //check whether database is installed- if (!DataSettingsManager.DatabaseIsInstalled())- return;+ /// <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>+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {+ //check whether database is installed+ if (!DataSettingsManager.DatabaseIsInstalled())+ return;- //configure authentication- application.UseHostFiltering();- }+ //configure authentication+ application.UseHostFiltering();+ }- /// <summary>- /// Gets order of this startup configuration implementation- /// </summary>- public int Priority => -40;- public bool BeforeConfigure => true;+ /// <summary>+ /// Gets order of this startup configuration implementation+ /// </summary>+ public int Priority => -40;- }-}+ public bool BeforeConfigure => true;+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Startup/LoggerStartup.cs b/src/Web/Grand.Web.Common/Startup/LoggerStartup.csindex eb8da16cc..6764092f5 100644--- a/src/Web/Grand.Web.Common/Startup/LoggerStartup.cs+++ b/src/Web/Grand.Web.Common/Startup/LoggerStartup.cs@@ -7,46 +7,44 @@ using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Web.Common.Startup+namespace Grand.Web.Common.Startup;++/// <summary>+/// Represents object for the configuring logger middleware on application startup+/// </summary>+public class LoggerStartup : IStartupApplication{/// <summary>- /// Represents object for the configuring logger middleware on application startup+ /// Add and configure any of the middleware/// </summary>- public class LoggerStartup : IStartupApplication+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="configuration">Configuration root of the application</param>+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration){- /// <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>- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {-- }-- /// <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>- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {- //check whether database is installed- if (!DataSettingsManager.DatabaseIsInstalled())- return;+ }- var appConfig = application.ApplicationServices.GetRequiredService<AppConfig>();-- //set context logging- if(appConfig.EnableContextLoggingMiddleware)- application.UseMiddleware<ContextLoggingMiddleware>();- }+ /// <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>+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {+ //check whether database is installed+ if (!DataSettingsManager.DatabaseIsInstalled())+ return;- /// <summary>- /// Gets order of this startup configuration implementation- /// </summary>- public int Priority => 501;- public bool BeforeConfigure => false;+ var appConfig = application.ApplicationServices.GetRequiredService<AppConfig>();+ //set context logging+ if (appConfig.EnableContextLoggingMiddleware)+ application.UseMiddleware<ContextLoggingMiddleware>();}-}++ /// <summary>+ /// Gets order of this startup configuration implementation+ /// </summary>+ public int Priority => 501;++ public bool BeforeConfigure => false;+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Startup/MigrationApplicationStartup.cs b/src/Web/Grand.Web.Common/Startup/MigrationApplicationStartup.csindex 590c6b4ad..c91473e90 100644--- a/src/Web/Grand.Web.Common/Startup/MigrationApplicationStartup.cs+++ b/src/Web/Grand.Web.Common/Startup/MigrationApplicationStartup.cs@@ -7,45 +7,43 @@ using Microsoft.AspNetCore.Hosting;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Web.Common.Startup+namespace Grand.Web.Common.Startup;++/// <summary>+/// Represents object for the configuring/load migration process on application startup+/// </summary>+public class MigrationApplicationStartup : IStartupApplication{/// <summary>- /// Represents object for the configuring/load migration process on application startup+ /// Add and configure any of the middleware/// </summary>- public class MigrationApplicationStartup : IStartupApplication+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="configuration">Configuration root of the application</param>+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration){- /// <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>- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- }-- /// <summary>- /// Configure the using- /// </summary>- /// <param name="application">Builder for configuring an application's request pipeline</param>- /// <param name="webHostEnvironment">WebHostEnvironment</param>- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {- if (!DataSettingsManager.DatabaseIsInstalled())- return;+ }- var serviceProvider = application.ApplicationServices;- var appConfig = serviceProvider.GetRequiredService<AppConfig>();- if (appConfig.SkipMigrationProcess) return;- var migrationProcess = serviceProvider.GetRequiredService<IMigrationProcess>();- migrationProcess.RunMigrationProcess();- }+ /// <summary>+ /// Configure the using+ /// </summary>+ /// <param name="application">Builder for configuring an application's request pipeline</param>+ /// <param name="webHostEnvironment">WebHostEnvironment</param>+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {+ if (!DataSettingsManager.DatabaseIsInstalled())+ return;- /// <summary>- /// Gets order of this startup configuration implementation- /// </summary>- public int Priority => 1000;+ var serviceProvider = application.ApplicationServices;+ var appConfig = serviceProvider.GetRequiredService<AppConfig>();+ if (appConfig.SkipMigrationProcess) return;+ var migrationProcess = serviceProvider.GetRequiredService<IMigrationProcess>();+ migrationProcess.RunMigrationProcess();+ }- public bool BeforeConfigure => false;+ /// <summary>+ /// Gets order of this startup configuration implementation+ /// </summary>+ public int Priority => 1000;- }-}+ public bool BeforeConfigure => false;+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Startup/StartupApplication.cs b/src/Web/Grand.Web.Common/Startup/StartupApplication.csindex e7e984784..90dc4fad1 100644--- a/src/Web/Grand.Web.Common/Startup/StartupApplication.cs+++ b/src/Web/Grand.Web.Common/Startup/StartupApplication.cs@@ -24,111 +24,109 @@ using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Localization;using StackExchange.Redis;-namespace Grand.Web.Common.Startup+namespace Grand.Web.Common.Startup;++/// <summary>+/// Startup application+/// </summary>+public class StartupApplication : IStartupApplication{/// <summary>- /// Startup application+ /// Register services and interfaces/// </summary>- public class StartupApplication : IStartupApplication+ /// <param name="services">Service Collection</param>+ /// <param name="configuration">Config</param>+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration){- /// <summary>- /// Register services and interfaces- /// </summary>- /// <param name="services">Service Collection</param>- /// <param name="configuration">Config</param>- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- RegisterCache(services, configuration);+ RegisterCache(services, configuration);- RegisterContextService(services);+ RegisterContextService(services);- RegisterFramework(services);- }+ RegisterFramework(services);+ }- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {+ }- }- public int Priority => 0;- public bool BeforeConfigure => false;+ public int Priority => 0;+ public bool BeforeConfigure => false;- private void RegisterCache(IServiceCollection serviceCollection, IConfiguration configuration)- {- var config = new RedisConfig();- configuration.GetSection("Redis").Bind(config);-- serviceCollection.AddSingleton<ICacheBase, MemoryCacheBase>();-- if (config.RedisPubSubEnabled)- {- var redis = ConnectionMultiplexer.Connect(config.RedisPubSubConnectionString);- serviceCollection.AddSingleton(_ => redis.GetSubscriber());- serviceCollection.AddSingleton<IMessageBus, RedisMessageBus>();- serviceCollection.AddSingleton<ICacheBase, RedisMessageCacheManager>();- return;- }- var rabbit = new RabbitConfig();- configuration.GetSection("Rabbit").Bind(rabbit);- if (rabbit.RabbitCachePubSubEnabled && rabbit.RabbitEnabled)- {- serviceCollection.AddSingleton<ICacheBase, RabbitMqMessageCacheManager>();- }- }+ private void RegisterCache(IServiceCollection serviceCollection, IConfiguration configuration)+ {+ var config = new RedisConfig();+ configuration.GetSection("Redis").Bind(config);- private void RegisterContextService(IServiceCollection serviceCollection)+ serviceCollection.AddSingleton<ICacheBase, MemoryCacheBase>();++ if (config.RedisPubSubEnabled){- //work context- serviceCollection.AddScoped<IWorkContext, WorkContext>();- serviceCollection.AddScoped<IWorkContextSetter>(provider => provider.GetService<IWorkContext>() as WorkContext);-- //helper for Settings- serviceCollection.AddScoped<IStoreHelper, StoreHelper>();-- //View factory- serviceCollection.AddScoped<IViewFactory, ViewFactory>();-- //Default view area- serviceCollection.AddScoped<IAreaViewFactory, DefaultAreaViewFactory>();-- //Theme context factory- serviceCollection.AddScoped<IThemeContextFactory, ThemeContextFactory>();-- //Default theme context- serviceCollection.AddScoped<IThemeContext, ThemeContext>();-- //Default theme view- serviceCollection.AddScoped<IThemeView, DefaultThemeView>();+ var redis = ConnectionMultiplexer.Connect(config.RedisPubSubConnectionString);+ serviceCollection.AddSingleton(_ => redis.GetSubscriber());+ serviceCollection.AddSingleton<IMessageBus, RedisMessageBus>();+ serviceCollection.AddSingleton<ICacheBase, RedisMessageCacheManager>();+ return;}+ var rabbit = new RabbitConfig();+ configuration.GetSection("Rabbit").Bind(rabbit);+ if (rabbit.RabbitCachePubSubEnabled && rabbit.RabbitEnabled)+ serviceCollection.AddSingleton<ICacheBase, RabbitMqMessageCacheManager>();+ }++ private void RegisterContextService(IServiceCollection serviceCollection)+ {+ //work context+ serviceCollection.AddScoped<IWorkContext, WorkContext>();+ serviceCollection.AddScoped<IWorkContextSetter>(provider => provider.GetService<IWorkContext>() as WorkContext);++ //helper for Settings+ serviceCollection.AddScoped<IStoreHelper, StoreHelper>();++ //View factory+ serviceCollection.AddScoped<IViewFactory, ViewFactory>();- private void RegisterFramework(IServiceCollection serviceCollection)+ //Default view area+ serviceCollection.AddScoped<IAreaViewFactory, DefaultAreaViewFactory>();++ //Theme context factory+ serviceCollection.AddScoped<IThemeContextFactory, ThemeContextFactory>();++ //Default theme context+ serviceCollection.AddScoped<IThemeContext, ThemeContext>();++ //Default theme view+ serviceCollection.AddScoped<IThemeView, DefaultThemeView>();+ }+++ private void RegisterFramework(IServiceCollection serviceCollection)+ {+ serviceCollection.AddScoped<IPageHeadBuilder, PageHeadBuilder>();++ serviceCollection.AddScoped<SlugRouteTransformer>();++ serviceCollection.AddScoped<IResourceManager, ResourceManager>();++ serviceCollection.AddScoped<IValidatorFactory, ValidatorFactory>();++ if (DataSettingsManager.DatabaseIsInstalled())+ {+ serviceCollection.AddScoped<LocService>();+ }+ else{- serviceCollection.AddScoped<IPageHeadBuilder, PageHeadBuilder>();-- serviceCollection.AddScoped<SlugRouteTransformer>();-- serviceCollection.AddScoped<IResourceManager, ResourceManager>();-- serviceCollection.AddScoped<IValidatorFactory, ValidatorFactory>();-- if (DataSettingsManager.DatabaseIsInstalled())- serviceCollection.AddScoped<LocService>();- else- {- var provider = serviceCollection.BuildServiceProvider();- var tmp = provider.GetRequiredService<IStringLocalizerFactory>();- serviceCollection.AddScoped(_ => new LocService(tmp));- }-- //powered by- serviceCollection.AddSingleton<IPoweredByMiddlewareOptions, PoweredByMiddlewareOptions>();-- //request reCAPTCHA service- serviceCollection.AddHttpClient<GoogleReCaptchaValidator>();-- serviceCollection.AddScoped<IViewRenderService, ViewRenderService>();+ var provider = serviceCollection.BuildServiceProvider();+ var tmp = provider.GetRequiredService<IStringLocalizerFactory>();+ serviceCollection.AddScoped(_ => new LocService(tmp));}- }+ //powered by+ serviceCollection.AddSingleton<IPoweredByMiddlewareOptions, PoweredByMiddlewareOptions>();-}+ //request reCAPTCHA service+ serviceCollection.AddHttpClient<GoogleReCaptchaValidator>();++ serviceCollection.AddScoped<IViewRenderService, ViewRenderService>();+ }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Startup/TaskHandler.cs b/src/Web/Grand.Web.Common/Startup/TaskHandler.csindex 84a615331..e33d7105b 100644--- a/src/Web/Grand.Web.Common/Startup/TaskHandler.cs+++ b/src/Web/Grand.Web.Common/Startup/TaskHandler.cs@@ -8,31 +8,30 @@ using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;-namespace Grand.Web.Common.Startup+namespace Grand.Web.Common.Startup;++public static class TaskHandler{- public static class TaskHandler+ public static void RegisterTasks(this IServiceCollection services, IConfiguration configuration){+ //database is already installed, so start scheduled tasks+ if (!DataSettingsManager.DatabaseIsInstalled()) return;- public static void RegisterTasks(this IServiceCollection services, IConfiguration configuration)- {- //database is already installed, so start scheduled tasks- if (!DataSettingsManager.DatabaseIsInstalled()) return;-- var appConfig = new AppConfig();- configuration.GetSection("Application").Bind(appConfig);-- if (appConfig.DisableHostedService) return;- var typeSearcher = new TypeSearcher();- var scheduleTasks = typeSearcher.ClassesOfType<IScheduleTask>();+ var appConfig = new AppConfig();+ configuration.GetSection("Application").Bind(appConfig);- var scheduleTasksInstalled = scheduleTasks- .Where(PluginExtensions.OnlyInstalledPlugins); //ignore not installed plugins+ if (appConfig.DisableHostedService) return;+ var typeSearcher = new TypeSearcher();+ var scheduleTasks = typeSearcher.ClassesOfType<IScheduleTask>();- foreach (var task in scheduleTasksInstalled)- {- var assemblyName = task.Assembly.GetName().Name;- services.AddSingleton<IHostedService, BackgroundServiceTask>(sp => new BackgroundServiceTask($"{task.FullName}, {assemblyName}", sp));- }+ var scheduleTasksInstalled = scheduleTasks+ .Where(PluginExtensions.OnlyInstalledPlugins); //ignore not installed plugins++ foreach (var task in scheduleTasksInstalled)+ {+ var assemblyName = task.Assembly.GetName().Name;+ services.AddSingleton<IHostedService, BackgroundServiceTask>(sp =>+ new BackgroundServiceTask($"{task.FullName}, {assemblyName}", sp));}}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Startup/UrlRewriteStartup.cs b/src/Web/Grand.Web.Common/Startup/UrlRewriteStartup.csindex 9ab6d3ec0..ed49fbc2e 100644--- a/src/Web/Grand.Web.Common/Startup/UrlRewriteStartup.cs+++ b/src/Web/Grand.Web.Common/Startup/UrlRewriteStartup.cs@@ -6,61 +6,62 @@ using Microsoft.AspNetCore.Rewrite;using Microsoft.Extensions.Configuration;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Web.Common.Startup+namespace Grand.Web.Common.Startup;++/// <summary>+/// Represents object for the configuring/load url rewrite rules from external file on application startup+/// </summary>+public class UrlRewriteStartup : IStartupApplication{/// <summary>- /// Represents object for the configuring/load url rewrite rules from external file on application startup+ /// Add and configure any of the middleware/// </summary>- public class UrlRewriteStartup : IStartupApplication+ /// <param name="services">Collection of service descriptors</param>+ /// <param name="configuration">Configuration root of the application</param>+ public void ConfigureServices(IServiceCollection services, IConfiguration configuration){- /// <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>- public void ConfigureServices(IServiceCollection services, IConfiguration configuration)- {- }+ }- /// <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>- public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)- {- var serviceProvider = application.ApplicationServices;- var urlConfig = serviceProvider.GetRequiredService<UrlRewriteConfig>();- var urlRewriteOptions = new RewriteOptions();- var rewriteOptions = false;- if (urlConfig.UseUrlRewrite)- {- if (File.Exists("App_Data/UrlRewrite.xml"))- {- using var streamReader = File.OpenText("App_Data/UrlRewrite.xml");- rewriteOptions = true;- urlRewriteOptions.AddIISUrlRewrite(streamReader);- }- }- if (urlConfig.UrlRewriteHttpsOptions)- {- rewriteOptions = true;- urlRewriteOptions.AddRedirectToHttps(urlConfig.UrlRewriteHttpsOptionsStatusCode, urlConfig.UrlRewriteHttpsOptionsPort);- }- if (urlConfig.UrlRedirectToHttpsPermanent)+ /// <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>+ public void Configure(IApplicationBuilder application, IWebHostEnvironment webHostEnvironment)+ {+ var serviceProvider = application.ApplicationServices;+ var urlConfig = serviceProvider.GetRequiredService<UrlRewriteConfig>();+ var urlRewriteOptions = new RewriteOptions();+ var rewriteOptions = false;+ if (urlConfig.UseUrlRewrite)+ if (File.Exists("App_Data/UrlRewrite.xml")){+ using var streamReader = File.OpenText("App_Data/UrlRewrite.xml");rewriteOptions = true;- urlRewriteOptions.AddRedirectToHttpsPermanent();+ urlRewriteOptions.AddIISUrlRewrite(streamReader);}- if (rewriteOptions)- application.UseRewriter(urlRewriteOptions);++ if (urlConfig.UrlRewriteHttpsOptions)+ {+ rewriteOptions = true;+ urlRewriteOptions.AddRedirectToHttps(urlConfig.UrlRewriteHttpsOptionsStatusCode,+ urlConfig.UrlRewriteHttpsOptionsPort);}- /// <summary>- /// Gets order of this startup configuration implementation- /// </summary>- public int Priority => -50;- public bool BeforeConfigure => true;+ if (urlConfig.UrlRedirectToHttpsPermanent)+ {+ rewriteOptions = true;+ urlRewriteOptions.AddRedirectToHttpsPermanent();+ }+ if (rewriteOptions)+ application.UseRewriter(urlRewriteOptions);}-}++ /// <summary>+ /// Gets order of this startup configuration implementation+ /// </summary>+ public int Priority => -50;++ public bool BeforeConfigure => true;+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/StoreHelper.cs b/src/Web/Grand.Web.Common/StoreHelper.csindex 1e2a2d879..f0b2ff39b 100644--- a/src/Web/Grand.Web.Common/StoreHelper.cs+++ b/src/Web/Grand.Web.Common/StoreHelper.cs@@ -4,58 +4,36 @@ using Grand.Infrastructure;using Grand.Infrastructure.Configuration;using Microsoft.AspNetCore.Http;-namespace Grand.Web.Common-{- public class StoreHelper : IStoreHelper- {- #region Fields-- private readonly IHttpContextAccessor _httpContextAccessor;- private readonly IStoreService _storeService;- private readonly SecurityConfig _securityConfig;- private Store _cachedStore;- private DomainHost _cachedDomainHost;-- private const string StoreCookieName = ".Grand.Store";-- #endregion-- #region Ctor-- public StoreHelper(- IHttpContextAccessor httpContextAccessor,- IStoreService storeService,- SecurityConfig securityConfig)- {- _httpContextAccessor = httpContextAccessor;- _storeService = storeService;- _securityConfig = securityConfig;- }-- #endregion+namespace Grand.Web.Common;+public class StoreHelper : IStoreHelper+{+ #region Ctor- #region Utilities+ public StoreHelper(+ IHttpContextAccessor httpContextAccessor,+ IStoreService storeService,+ SecurityConfig securityConfig)+ {+ _httpContextAccessor = httpContextAccessor;+ _storeService = storeService;+ _securityConfig = securityConfig;+ }- protected virtual string GetStoreCookie()- {- return _httpContextAccessor.HttpContext?.Request.Cookies[StoreCookieName];- }- #endregion+ #endregion- public Store StoreHost {- get {- if (_cachedStore != null) return _cachedStore;- //try to determine the current store by HOST header- var host = _httpContextAccessor.HttpContext?.Request.Host.Host;+ public Store StoreHost {+ get {+ if (_cachedStore != null) return _cachedStore;+ //try to determine the current store by HOST header+ var host = _httpContextAccessor.HttpContext?.Request.Host.Host;- var allStores = _storeService.GetAll();- var stores = allStores.Where(s => s.ContainsHostValue(host)).ToList();- if (!stores.Any())- {- _cachedStore = allStores.FirstOrDefault();- }- else switch (stores.Count)+ var allStores = _storeService.GetAll();+ var stores = allStores.Where(s => s.ContainsHostValue(host)).ToList();+ if (!stores.Any())+ _cachedStore = allStores.FirstOrDefault();+ else+ switch (stores.Count){case 1:_cachedStore = stores.FirstOrDefault();@@ -69,81 +47,102 @@ namespace Grand.Web.Common_cachedStore = storeCookie ?? stores.FirstOrDefault();}else+ {_cachedStore = stores.FirstOrDefault();+ }break;}}- return _cachedStore ?? throw new Exception("No store could be loaded");- }- }- public DomainHost DomainHost {- get {- if (_cachedDomainHost != null) return _cachedDomainHost;- //try to determine the current HOST header- var host = _httpContextAccessor.HttpContext?.Request.GetTypedHeaders().Host.ToString();- if (StoreHost != null)- {- _cachedDomainHost = StoreHost.HostValue(host) ?? new DomainHost {- Id = int.MinValue.ToString(),- Url = StoreHost.SslEnabled ? StoreHost.SecureUrl : StoreHost.Url,- HostName = "temporary-store"- };- }+ return _cachedStore ?? throw new Exception("No store could be loaded");+ }+ }- return _cachedDomainHost ??= new DomainHost {+ public DomainHost DomainHost {+ get {+ if (_cachedDomainHost != null) return _cachedDomainHost;+ //try to determine the current HOST header+ var host = _httpContextAccessor.HttpContext?.Request.GetTypedHeaders().Host.ToString();+ if (StoreHost != null)+ _cachedDomainHost = StoreHost.HostValue(host) ?? new DomainHost {Id = int.MinValue.ToString(),- Url = host,- HostName = "temporary"+ Url = StoreHost.SslEnabled ? StoreHost.SecureUrl : StoreHost.Url,+ HostName = "temporary-store"};- }++ return _cachedDomainHost ??= new DomainHost {+ Id = int.MinValue.ToString(),+ Url = host,+ HostName = "temporary"+ };}+ }- /// <summary>- /// Set the current store by BackgroundService- /// </summary>- /// <returns></returns>- public virtual async Task<Store> SetCurrentStore(string storeId)+ /// <summary>+ /// Set the current store by BackgroundService+ /// </summary>+ /// <returns></returns>+ public virtual async Task<Store> SetCurrentStore(string storeId)+ {+ if (!string.IsNullOrEmpty(storeId)){- if (!string.IsNullOrEmpty(storeId))- {- var store = await _storeService.GetStoreById(storeId);- if (store != null)- _cachedStore = store;- }- _cachedStore ??= (await _storeService.GetAllStores()).FirstOrDefault();+ var store = await _storeService.GetStoreById(storeId);+ if (store != null)+ _cachedStore = store;+ }- return _cachedStore ?? throw new Exception("No store could be loaded by BackgroundService");+ _cachedStore ??= (await _storeService.GetAllStores()).FirstOrDefault();- }+ return _cachedStore ?? throw new Exception("No store could be loaded by BackgroundService");+ }- /// <summary>- /// Set store cookie- /// </summary>- /// <param name="storeId">Store ident</param>- public virtual async Task SetStoreCookie(string storeId)- {- if (_httpContextAccessor.HttpContext == null)- return;+ /// <summary>+ /// Set store cookie+ /// </summary>+ /// <param name="storeId">Store ident</param>+ public virtual async Task SetStoreCookie(string storeId)+ {+ if (_httpContextAccessor.HttpContext == null)+ return;- var store = await _storeService.GetStoreById(storeId);- if (store == null)- return;+ var store = await _storeService.GetStoreById(storeId);+ if (store == null)+ return;- //remove current cookie- _httpContextAccessor.HttpContext.Response.Cookies.Delete(StoreCookieName);+ //remove current cookie+ _httpContextAccessor.HttpContext.Response.Cookies.Delete(StoreCookieName);- //get date of cookie expiration- var cookieExpiresDate = DateTime.UtcNow.AddHours(_securityConfig.CookieAuthExpires);+ //get date of cookie expiration+ var cookieExpiresDate = DateTime.UtcNow.AddHours(_securityConfig.CookieAuthExpires);- //set new cookie value- var options = new CookieOptions {- HttpOnly = true,- Expires = cookieExpiresDate- };- _httpContextAccessor.HttpContext.Response.Cookies.Append(StoreCookieName, storeId, options);- }+ //set new cookie value+ var options = new CookieOptions {+ HttpOnly = true,+ Expires = cookieExpiresDate+ };+ _httpContextAccessor.HttpContext.Response.Cookies.Append(StoreCookieName, storeId, options);+ }++ #region Utilities++ protected virtual string GetStoreCookie()+ {+ return _httpContextAccessor.HttpContext?.Request.Cookies[StoreCookieName];}-}++ #endregion++ #region Fields++ private readonly IHttpContextAccessor _httpContextAccessor;+ private readonly IStoreService _storeService;+ private readonly SecurityConfig _securityConfig;+ private Store _cachedStore;+ private DomainHost _cachedDomainHost;++ private const string StoreCookieName = ".Grand.Store";++ #endregion+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminDeleteConfirmationTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminDeleteConfirmationTagHelper.csindex 699c4e5a5..a242dcdae 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminDeleteConfirmationTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminDeleteConfirmationTagHelper.cs@@ -6,79 +6,75 @@ using Microsoft.AspNetCore.Mvc.Rendering;using Microsoft.AspNetCore.Mvc.ViewFeatures;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers.Admin+namespace Grand.Web.Common.TagHelpers.Admin;++[HtmlTargetElement("admin-delete-confirmation")]+public class AdminDeleteConfirmationTagHelper : TagHelper{- [HtmlTargetElement("admin-delete-confirmation")]- public class AdminDeleteConfirmationTagHelper : TagHelper+ private readonly IHtmlHelper _htmlHelper;++ private readonly ITranslationService _translationService;++ public AdminDeleteConfirmationTagHelper(IHtmlHelper htmlHelper, ITranslationService translationService)+ {+ _htmlHelper = htmlHelper;+ _translationService = translationService;+ }++ [ViewContext] public ViewContext ViewContext { get; set; }++ [HtmlAttributeName("action-name")] public string Action { get; set; }++ [HtmlAttributeName("button-id")] public string ButtonId { get; set; }++ [HtmlAttributeName("id")] public string ModelId { get; set; }++ public override async Task ProcessAsync(TagHelperContext tagHelperContext, TagHelperOutput output){- [ViewContext]- public ViewContext ViewContext { get; set; }-- [HtmlAttributeName("action-name")]- public string Action { get; set; }-- [HtmlAttributeName("button-id")]- public string ButtonId { get; set; }-- [HtmlAttributeName("id")]- public string ModelId { get; set; }-- private readonly IHtmlHelper _htmlHelper;-- private readonly ITranslationService _translationService;-- public AdminDeleteConfirmationTagHelper(IHtmlHelper htmlHelper, ITranslationService translationService)- {- _htmlHelper = htmlHelper;- _translationService = translationService;- }-- public override async Task ProcessAsync(TagHelperContext tagHelperContext, TagHelperOutput output)- {- if (string.IsNullOrEmpty(Action))- Action = "Delete";-- var windowId = new HtmlString(ViewContext.ViewData.ModelMetadata.ModelType.Name.ToLower() + "-delete-confirmation").ToHtmlString();-- var modelId = string.IsNullOrEmpty(ModelId) ? ViewContext.RouteData.Values["Id"]?.ToString() : ModelId;-- var deleteConfirmationModel = new DeleteConfirmationModel- {- Id = modelId,- ControllerName = ViewContext.RouteData.Values["controller"]?.ToString(),- ActionName = Action,- WindowId = windowId- };-- (_htmlHelper as IViewContextAware)?.Contextualize(ViewContext);-- output.TagName = "div";- output.TagMode = TagMode.StartTagAndEndTag;- output.Attributes.SetAttribute("id", windowId);- output.Attributes.SetAttribute("style", "display:none");-- output.Content.SetHtmlContent((await _htmlHelper.PartialAsync("Partials/Delete", deleteConfirmationModel)).ToHtmlString());-- var window = new StringBuilder();- window.AppendLine("<script>");- window.AppendLine("$(document).ready(function() {");- window.AppendLine($"$('#{ButtonId}').click(function (e) ");- window.AppendLine("{");- window.AppendLine("e.preventDefault();");- window.AppendLine($"var window = $('#{windowId}');");- window.AppendLine("if (!window.data('kendoWindow')) {");- window.AppendLine("window.kendoWindow({");- window.AppendLine("modal: true,");- window.AppendLine($"title: '{_translationService.GetResource("Admin.Common.AreYouSure")}',");- window.AppendLine("actions: ['Close']");- window.AppendLine("});");- window.AppendLine("}");- window.AppendLine("window.data('kendoWindow').center().open();");- window.AppendLine("});");- window.AppendLine("});");- window.AppendLine("</script>");- output.PostContent.SetHtmlContent(window.ToString());-- }+ if (string.IsNullOrEmpty(Action))+ Action = "Delete";++ var windowId =+ new HtmlString(ViewContext.ViewData.ModelMetadata.ModelType.Name.ToLower() + "-delete-confirmation")+ .ToHtmlString();++ var modelId = string.IsNullOrEmpty(ModelId) ? ViewContext.RouteData.Values["Id"]?.ToString() : ModelId;++ var deleteConfirmationModel = new DeleteConfirmationModel {+ Id = modelId,+ ControllerName = ViewContext.RouteData.Values["controller"]?.ToString(),+ ActionName = Action,+ WindowId = windowId+ };++ (_htmlHelper as IViewContextAware)?.Contextualize(ViewContext);++ output.TagName = "div";+ output.TagMode = TagMode.StartTagAndEndTag;+ output.Attributes.SetAttribute("id", windowId);+ output.Attributes.SetAttribute("style", "display:none");++ output.Content.SetHtmlContent((await _htmlHelper.PartialAsync("Partials/Delete", deleteConfirmationModel))+ .ToHtmlString());++ var window = new StringBuilder();+ window.AppendLine("<script>");+ window.AppendLine("$(document).ready(function() {");+ window.AppendLine($"$('#{ButtonId}').click(function (e) ");+ window.AppendLine("{");+ window.AppendLine("e.preventDefault();");+ window.AppendLine($"var window = $('#{windowId}');");+ window.AppendLine("if (!window.data('kendoWindow')) {");+ window.AppendLine("window.kendoWindow({");+ window.AppendLine("modal: true,");+ window.AppendLine($"title: '{_translationService.GetResource("Admin.Common.AreYouSure")}',");+ window.AppendLine("actions: ['Close']");+ window.AppendLine("});");+ window.AppendLine("}");+ window.AppendLine("window.data('kendoWindow').center().open();");+ window.AppendLine("});");+ window.AppendLine("});");+ window.AppendLine("</script>");+ output.PostContent.SetHtmlContent(window.ToString());}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminInputTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminInputTagHelper.csindex 33feb76eb..a144f719d 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminInputTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminInputTagHelper.cs@@ -7,194 +7,176 @@ using Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers;using Microsoft.AspNetCore.Razor.TagHelpers;using System.Reflection;-namespace Grand.Web.Common.TagHelpers.Admin+namespace Grand.Web.Common.TagHelpers.Admin;++/// <summary>+/// input tag helper+/// </summary>+[HtmlTargetElement("admin-input", Attributes = ForAttributeName, TagStructure = TagStructure.WithoutEndTag)]+public class AdminInputTagHelper : TagHelper{+ private const string ForAttributeName = "asp-for";+ private const string DisabledAttributeName = "asp-disabled";+ private const string RequiredAttributeName = "asp-required";+ private const string RenderFormControlClassAttributeName = "asp-render-form-control-class";+ private const string TemplateAttributeName = "asp-template";+ private const string PostfixAttributeName = "asp-postfix";+ private const string PostSelectItem = "asp-selectitem";++ private readonly IHtmlHelper _htmlHelper;/// <summary>- /// input tag helper+ /// Ctor/// </summary>- [HtmlTargetElement("admin-input", Attributes = ForAttributeName, TagStructure = TagStructure.WithoutEndTag)]- public class AdminInputTagHelper : TagHelper+ /// <param name="htmlHelper">HTML helper</param>+ public AdminInputTagHelper(IHtmlHelper htmlHelper){- private const string ForAttributeName = "asp-for";- private const string DisabledAttributeName = "asp-disabled";- private const string RequiredAttributeName = "asp-required";- private const string RenderFormControlClassAttributeName = "asp-render-form-control-class";- private const string TemplateAttributeName = "asp-template";- private const string PostfixAttributeName = "asp-postfix";- private const string PostSelectItem = "asp-selectitem";-- private readonly IHtmlHelper _htmlHelper;-- /// <summary>- /// An expression to be evaluated against the current model- /// </summary>- [HtmlAttributeName(ForAttributeName)]- public ModelExpression For { get; set; }-- /// <summary>- /// Indicates whether the field is disabled- /// </summary>- [HtmlAttributeName(DisabledAttributeName)]- public string IsDisabled { set; get; }-- /// <summary>- /// Indicates whether the field is required- /// </summary>- [HtmlAttributeName(RequiredAttributeName)]- public string IsRequired { set; get; }-- /// <summary>- /// Indicates whether the "form-control" class shold be added to the input- /// </summary>- [HtmlAttributeName(RenderFormControlClassAttributeName)]- public string RenderFormControlClass { set; get; }-- /// <summary>- /// Editor template for the field- /// </summary>- [HtmlAttributeName(TemplateAttributeName)]- public string Template { set; get; }-- [HtmlAttributeName(PostSelectItem)]- public IList<SelectListItem> SelectItems { set; get; }-- /// <summary>- /// Postfix- /// </summary>- [HtmlAttributeName(PostfixAttributeName)]- public string Postfix { set; get; }-- /// <summary>- /// ViewContext- /// </summary>- [HtmlAttributeNotBound]- [ViewContext]- public ViewContext ViewContext { get; set; }-- /// <summary>- /// Ctor- /// </summary>- /// <param name="htmlHelper">HTML helper</param>- public AdminInputTagHelper(IHtmlHelper htmlHelper)- {- _htmlHelper = htmlHelper;- }+ _htmlHelper = htmlHelper;+ }- /// <summary>- /// Process- /// </summary>- /// <param name="context">Context</param>- /// <param name="output">Output</param>- public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)- {- ArgumentNullException.ThrowIfNull(context);+ /// <summary>+ /// An expression to be evaluated against the current model+ /// </summary>+ [HtmlAttributeName(ForAttributeName)]+ public ModelExpression For { get; set; }- ArgumentNullException.ThrowIfNull(output);+ /// <summary>+ /// Indicates whether the field is disabled+ /// </summary>+ [HtmlAttributeName(DisabledAttributeName)]+ public string IsDisabled { set; get; }- //clear the output- output.SuppressOutput();+ /// <summary>+ /// Indicates whether the field is required+ /// </summary>+ [HtmlAttributeName(RequiredAttributeName)]+ public string IsRequired { set; get; }- //required asterisk- bool.TryParse(IsRequired, out var required);- if (required)- {- output.PreElement.SetHtmlContent("<div class='input-group input-group-required'>");- output.PostElement.SetHtmlContent("<div class=\"input-group-btn\"><span class=\"required\">*</span></div></div>");- }+ /// <summary>+ /// Indicates whether the "form-control" class shold be added to the input+ /// </summary>+ [HtmlAttributeName(RenderFormControlClassAttributeName)]+ public string RenderFormControlClass { set; get; }- //contextualize IHtmlHelper- var viewContextAware = _htmlHelper as IViewContextAware;- viewContextAware?.Contextualize(ViewContext);-- //add form-control class- bool.TryParse(RenderFormControlClass, out var renderFormControlClass);- object htmlAttributes = null;- if (string.IsNullOrEmpty(RenderFormControlClass) && For.Metadata.ModelType.Name.Equals("String") || renderFormControlClass)- htmlAttributes = new { @class = "form-control k-input" };-- //disabled attribute- bool.TryParse(IsDisabled, out var disabled);- if (disabled)- {- if(htmlAttributes == null)- htmlAttributes = new { disabled = "disabled" };- else- {- htmlAttributes = new { @class = "form-control k-input", disabled = "disabled" };- }- }- var viewEngine = GetPrivateFieldValue(_htmlHelper, "_viewEngine") as IViewEngine;- var bufferScope = GetPrivateFieldValue(_htmlHelper, "_bufferScope") as IViewBufferScope;- if (SelectItems != null)- {- if (SelectItems.Any())- {- _htmlHelper.ViewData["SelectList"] = SelectItems;- }- else- {- if (_htmlHelper.ViewData.ContainsKey("SelectList"))- {- _htmlHelper.ViewData["SelectList"] = new List<SelectListItem>();- }- else- {- _htmlHelper.ViewData.Add("SelectList", new List<SelectListItem>());- }- }- }+ /// <summary>+ /// Editor template for the field+ /// </summary>+ [HtmlAttributeName(TemplateAttributeName)]+ public string Template { set; get; }++ [HtmlAttributeName(PostSelectItem)] public IList<SelectListItem> SelectItems { set; get; }++ /// <summary>+ /// Postfix+ /// </summary>+ [HtmlAttributeName(PostfixAttributeName)]+ public string Postfix { set; get; }- var templateBuilder = new TemplateBuilder(- viewEngine,- bufferScope,- _htmlHelper.ViewContext,- _htmlHelper.ViewData,- For.ModelExplorer,- For.Name,- Template,- readOnly: false,- additionalViewData: new { htmlAttributes, postfix = this.Postfix });-- var htmlOutput = await templateBuilder.Build();- output.Content.SetHtmlContent(htmlOutput.RenderHtmlContent());+ /// <summary>+ /// ViewContext+ /// </summary>+ [HtmlAttributeNotBound]+ [ViewContext]+ public ViewContext ViewContext { get; set; }++ /// <summary>+ /// Process+ /// </summary>+ /// <param name="context">Context</param>+ /// <param name="output">Output</param>+ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ ArgumentNullException.ThrowIfNull(context);++ ArgumentNullException.ThrowIfNull(output);++ //clear the output+ output.SuppressOutput();++ //required asterisk+ bool.TryParse(IsRequired, out var required);+ if (required)+ {+ output.PreElement.SetHtmlContent("<div class='input-group input-group-required'>");+ output.PostElement.SetHtmlContent(+ "<div class=\"input-group-btn\"><span class=\"required\">*</span></div></div>");}+ //contextualize IHtmlHelper+ var viewContextAware = _htmlHelper as IViewContextAware;+ viewContextAware?.Contextualize(ViewContext);+ //add form-control class+ bool.TryParse(RenderFormControlClass, out var renderFormControlClass);+ object htmlAttributes = null;+ if ((string.IsNullOrEmpty(RenderFormControlClass) && For.Metadata.ModelType.Name.Equals("String")) ||+ renderFormControlClass)+ htmlAttributes = new { @class = "form-control k-input" };- private object GetPrivateFieldValue(object target, string fieldName)+ //disabled attribute+ bool.TryParse(IsDisabled, out var disabled);+ if (disabled){- if (target == null)+ if (htmlAttributes == null)+ htmlAttributes = new { disabled = "disabled" };+ else+ htmlAttributes = new { @class = "form-control k-input", disabled = "disabled" };+ }++ var viewEngine = GetPrivateFieldValue(_htmlHelper, "_viewEngine") as IViewEngine;+ var bufferScope = GetPrivateFieldValue(_htmlHelper, "_bufferScope") as IViewBufferScope;+ if (SelectItems != null)+ {+ if (SelectItems.Any()){- throw new ArgumentNullException(nameof(target), "The assignment target cannot be null.");+ _htmlHelper.ViewData["SelectList"] = SelectItems;}-- if (string.IsNullOrEmpty(fieldName))+ else{- throw new ArgumentException("fieldName", "The field name cannot be null or empty.");+ if (_htmlHelper.ViewData.ContainsKey("SelectList"))+ _htmlHelper.ViewData["SelectList"] = new List<SelectListItem>();+ else+ _htmlHelper.ViewData.Add("SelectList", new List<SelectListItem>());}+ }- var t = target.GetType();- FieldInfo fi = null;+ var templateBuilder = new TemplateBuilder(+ viewEngine,+ bufferScope,+ _htmlHelper.ViewContext,+ _htmlHelper.ViewData,+ For.ModelExplorer,+ For.Name,+ Template,+ false,+ new { htmlAttributes, postfix = Postfix });++ var htmlOutput = await templateBuilder.Build();+ output.Content.SetHtmlContent(htmlOutput.RenderHtmlContent());+ }- while (t != null)- {- fi = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);- if (fi != null) break;+ private object GetPrivateFieldValue(object target, string fieldName)+ {+ if (target == null) throw new ArgumentNullException(nameof(target), "The assignment target cannot be null.");- t = t.BaseType;- }+ if (string.IsNullOrEmpty(fieldName))+ throw new ArgumentException("fieldName", "The field name cannot be null or empty.");- if (fi == null)- {- throw new Exception($"Field '{fieldName}' not found in type hierarchy.");- }+ var t = target.GetType();+ FieldInfo fi = null;- return fi.GetValue(target);- }+ while (t != null)+ {+ fi = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);- }+ if (fi != null) break;+ t = t.BaseType;+ }++ if (fi == null) throw new Exception($"Field '{fieldName}' not found in type hierarchy.");+ return fi.GetValue(target);+ }}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminLabelTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminLabelTagHelper.csindex c8cd28736..812063394 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminLabelTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminLabelTagHelper.cs@@ -4,68 +4,57 @@ using Microsoft.AspNetCore.Mvc.TagHelpers;using Microsoft.AspNetCore.Mvc.ViewFeatures;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers.Admin-{-- [HtmlTargetElement("admin-label", Attributes = ForAttributeName)]- public class LabelRequiredTagHelper : LabelTagHelper- {- private const string ForAttributeName = "asp-for";- private const string DisplayHintAttributeName = "asp-display-hint";- private const string RequiredAttributeName = "asp-required";+namespace Grand.Web.Common.TagHelpers.Admin;- private readonly IWorkContext _workContext;- private readonly ITranslationService _translationService;+[HtmlTargetElement("admin-label", Attributes = ForAttributeName)]+public class LabelRequiredTagHelper : LabelTagHelper+{+ private const string ForAttributeName = "asp-for";+ private const string DisplayHintAttributeName = "asp-display-hint";+ private const string RequiredAttributeName = "asp-required";+ private readonly ITranslationService _translationService;- public LabelRequiredTagHelper(IHtmlGenerator generator, IWorkContext workContext, ITranslationService translationService) : base(generator)- {- _workContext = workContext;- _translationService = translationService;- }+ private readonly IWorkContext _workContext;- [HtmlAttributeName(DisplayHintAttributeName)]- public bool DisplayHint { get; set; } = true;+ public LabelRequiredTagHelper(IHtmlGenerator generator, IWorkContext workContext,+ ITranslationService translationService) : base(generator)+ {+ _workContext = workContext;+ _translationService = translationService;+ }- [HtmlAttributeName(RequiredAttributeName)]- public bool RequiredAttribute { get; set; }+ [HtmlAttributeName(DisplayHintAttributeName)]+ public bool DisplayHint { get; set; } = true;- public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)- {- await base.ProcessAsync(context, output);- output.TagName = "label";- output.TagMode = TagMode.StartTagAndEndTag;- var classValue = output.Attributes.ContainsName("class")- ? $"{output.Attributes["class"].Value}"- : "control-label col-md-3 col-sm-3";- if (RequiredAttribute)- {- classValue += " required";- }- output.Attributes.SetAttribute("class", classValue);+ [HtmlAttributeName(RequiredAttributeName)]+ public bool RequiredAttribute { get; set; }- var resourceDisplayName = For.Metadata.GetDisplayName();+ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ await base.ProcessAsync(context, output);+ output.TagName = "label";+ output.TagMode = TagMode.StartTagAndEndTag;+ var classValue = output.Attributes.ContainsName("class")+ ? $"{output.Attributes["class"].Value}"+ : "control-label col-md-3 col-sm-3";+ if (RequiredAttribute) classValue += " required";+ output.Attributes.SetAttribute("class", classValue);- var langId = _workContext.WorkingLanguage.Id;+ var resourceDisplayName = For.Metadata.GetDisplayName();- var resource = _translationService.GetResource(- resourceDisplayName.ToLowerInvariant(), langId, returnEmptyIfNotFound: true);+ var langId = _workContext.WorkingLanguage.Id;- if (!string.IsNullOrEmpty(resource))- {- output.Content.SetContent(resource);- }+ var resource = _translationService.GetResource(+ resourceDisplayName.ToLowerInvariant(), langId, returnEmptyIfNotFound: true);- if (DisplayHint)- {+ if (!string.IsNullOrEmpty(resource)) output.Content.SetContent(resource);- var hintResource = _translationService.GetResource(- resourceDisplayName + ".Hint", langId, returnEmptyIfNotFound: true);+ if (DisplayHint)+ {+ var hintResource = _translationService.GetResource(+ resourceDisplayName + ".Hint", langId, returnEmptyIfNotFound: true);- if (!string.IsNullOrEmpty(hintResource))- {- output.Content.AppendHtml($"<p class='hint'>{hintResource}</p>");- }- }+ if (!string.IsNullOrEmpty(hintResource)) output.Content.AppendHtml($"<p class='hint'>{hintResource}</p>");}}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminSelectTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminSelectTagHelper.csindex 39ac074b3..151fdafcf 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminSelectTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminSelectTagHelper.cs@@ -1,37 +1,30 @@-using Grand.Business.Core.Interfaces.Common.Localization;-using Grand.Infrastructure;+using Microsoft.AspNetCore.Mvc.TagHelpers;using Microsoft.AspNetCore.Mvc.ViewFeatures;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers.Admin+namespace Grand.Web.Common.TagHelpers.Admin;++[HtmlTargetElement("admin-select", Attributes = ForAttributeName)]+public class AdminSelectTagHelper : SelectTagHelper{+ private const string ForAttributeName = "asp-for";+ private const string DisplayHintAttributeName = "asp-display-hint";- [HtmlTargetElement("admin-select", Attributes = ForAttributeName)]- public class AdminSelectTagHelper : Microsoft.AspNetCore.Mvc.TagHelpers.SelectTagHelper+ public AdminSelectTagHelper(IHtmlGenerator generator) : base(generator){- private const string ForAttributeName = "asp-for";- private const string DisplayHintAttributeName = "asp-display-hint";-- public AdminSelectTagHelper(IHtmlGenerator generator) : base(generator)- {- }-- [HtmlAttributeName(DisplayHintAttributeName)]- public bool DisplayHint { get; set; } = true;-- public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)- {- await base.ProcessAsync(context, output);- output.TagName = "select";- output.TagMode = TagMode.StartTagAndEndTag;- var classValue = "form-control k-input ";- if (context.AllAttributes.TryGetAttribute("class", out var forAttribute))- {- classValue += forAttribute.Value.ToString();- }- output.Attributes.SetAttribute("class", classValue);- }}+ [HtmlAttributeName(DisplayHintAttributeName)]+ public bool DisplayHint { get; set; } = true;+ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ await base.ProcessAsync(context, output);+ output.TagName = "select";+ output.TagMode = TagMode.StartTagAndEndTag;+ var classValue = "form-control k-input ";+ if (context.AllAttributes.TryGetAttribute("class", out var forAttribute))+ classValue += forAttribute.Value.ToString();+ output.Attributes.SetAttribute("class", classValue);+ }}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabAppendTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabAppendTagHelper.csindex 285e5c73f..ea25c2857 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabAppendTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabAppendTagHelper.cs@@ -1,42 +1,34 @@using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers.Admin+namespace Grand.Web.Common.TagHelpers.Admin;++[HtmlTargetElement("admin-tab-append", Attributes = "tab-strip-name, tab-name, tab-content")]+public class AdminTabAppendTagHelper : TagHelper{- [HtmlTargetElement("admin-tab-append", Attributes = "tab-strip-name, tab-name, tab-content")]- public class AdminTabAppendTagHelper : TagHelper+ private const string TabStripName = "tab-strip-name";+ private const string TabName = "tab-name";+ private const string TabContent = "tab-content";+++ [HtmlAttributeName(TabName)] public string Name { get; set; }++ [HtmlAttributeName(TabContent)] public string Content { get; set; }++ [HtmlAttributeName(TabStripName)] public string StripName { get; set; }++ public override void Process(TagHelperContext tagHelperContext, TagHelperOutput output){- private const string TabStripName = "tab-strip-name";- private const string TabName = "tab-name";- private const string TabContent = "tab-content";-- [HtmlAttributeName(TabName)]- public string Name { get; set; }-- [HtmlAttributeName(TabContent)]- public string Content { get; set; }-- [HtmlAttributeName(TabStripName)]- public string StripName { get; set; }--- public AdminTabAppendTagHelper()- {- }-- public override void Process(TagHelperContext tagHelperContext, TagHelperOutput output)- {- output.SuppressOutput();-- var builder = new StringBuilder();- builder.Append("<script>");- builder.Append(" $(document).ready(function() {");- builder.Append($" $('#{StripName}').kendoTabStrip().data('kendoTabStrip').append({{");- builder.Append($" text: '{Name}',");- builder.Append($" content: '{Content}'");- builder.Append(" });");- builder.Append(" });");- builder.Append("</script>");- output.Content.AppendHtml(builder.ToString());- }+ output.SuppressOutput();++ var builder = new StringBuilder();+ builder.Append("<script>");+ builder.Append(" $(document).ready(function() {");+ builder.Append($" $('#{StripName}').kendoTabStrip().data('kendoTabStrip').append({{");+ builder.Append($" text: '{Name}',");+ builder.Append($" content: '{Content}'");+ builder.Append(" });");+ builder.Append(" });");+ builder.Append("</script>");+ output.Content.AppendHtml(builder.ToString());}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabContentTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabContentTagHelper.csindex 9b6bdbd60..a442e6aaa 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabContentTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabContentTagHelper.cs@@ -2,21 +2,18 @@using Microsoft.AspNetCore.Mvc.ViewFeatures;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers.Admin-{- [HtmlTargetElement("content", ParentTag = "tabstrip-item")]- public class AdminTabContentTagHelper : TagHelper- {- [ViewContext]- public ViewContext ViewContext { get; set; }+namespace Grand.Web.Common.TagHelpers.Admin;- public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)- {- var content = await output.GetChildContentAsync();- var list = (List<string>)ViewContext.ViewData[typeof(AdminTabContentTagHelper).FullName];- list.Add(content.GetContent());- output.SuppressOutput();- }+[HtmlTargetElement("content", ParentTag = "tabstrip-item")]+public class AdminTabContentTagHelper : TagHelper+{+ [ViewContext] public ViewContext ViewContext { get; set; }+ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ var content = await output.GetChildContentAsync();+ var list = (List<string>)ViewContext.ViewData[typeof(AdminTabContentTagHelper).FullName];+ list.Add(content.GetContent());+ output.SuppressOutput();}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemTagHelper.csindex 81ec08626..0c8421699 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemTagHelper.cs@@ -2,52 +2,38 @@using Microsoft.AspNetCore.Mvc.ViewFeatures;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers.Admin+namespace Grand.Web.Common.TagHelpers.Admin;++[HtmlTargetElement("tabstrip-item")]+public class AdminTabStripItemTagHelper : TagHelper{- [HtmlTargetElement("tabstrip-item")]- public class AdminTabStripItemTagHelper : TagHelper+ [ViewContext] public ViewContext ViewContext { get; set; }++ [HtmlAttributeName("Text")] public string Text { get; set; }++ [HtmlAttributeName("tab-index")] public int CurrentIndex { set; get; }++ private int GetSelectedTabIndex()+ {+ var index = 0;+ var dataKey = "Grand.selected-tab-index";+ if (ViewContext.ViewData[dataKey] is int) index = (int)ViewContext.ViewData[dataKey];+ if (ViewContext.TempData[dataKey] is int) index = (int)ViewContext.TempData[dataKey];++ if (index < 0)+ index = 0;++ return index;+ }++ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output){- [ViewContext]- public ViewContext ViewContext { get; set; }-- [HtmlAttributeName("Text")]- public string Text { get; set; }-- [HtmlAttributeName("tab-index")]- public int CurrentIndex { set; get; }-- private int GetSelectedTabIndex()- {- var index = 0;- var dataKey = "Grand.selected-tab-index";- if (this.ViewContext.ViewData[dataKey] is int)- {- index = (int)this.ViewContext.ViewData[dataKey];- }- if (this.ViewContext.TempData[dataKey] is int)- {- index = (int)this.ViewContext.TempData[dataKey];- }-- if (index < 0)- index = 0;-- return index;- }-- public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)- {- _ = await output.GetChildContentAsync();- output.TagName = "li";-- var selectedIndex = GetSelectedTabIndex();- if (selectedIndex == CurrentIndex)- {- output.Attributes.SetAttribute("class", "k-state-active");- }-- output.Content.AppendHtml(Text);- }+ _ = await output.GetChildContentAsync();+ output.TagName = "li";++ var selectedIndex = GetSelectedTabIndex();+ if (selectedIndex == CurrentIndex) output.Attributes.SetAttribute("class", "k-state-active");+ output.Content.AppendHtml(Text);}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemsTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemsTagHelper.csindex 54035aae5..b77cec98e 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemsTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemsTagHelper.cs@@ -1,14 +1,13 @@using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers.Admin+namespace Grand.Web.Common.TagHelpers.Admin;++[HtmlTargetElement("items", ParentTag = "admin-tabstrip")]+public class AdminTabStripItemsTagHelper : TagHelper{- [HtmlTargetElement("items", ParentTag = "admin-tabstrip")]- public class AdminTabStripItemsTagHelper : TagHelper+ public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output){- public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)- {- output.TagName = "ul";- return Task.CompletedTask;- }+ output.TagName = "ul";+ return Task.CompletedTask;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripTagHelper.csindex eb800ffac..cdaed8498 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripTagHelper.cs@@ -6,108 +6,96 @@ using Microsoft.AspNetCore.Razor.TagHelpers;using Wangkanai.Detection.Models;using Wangkanai.Detection.Services;-namespace Grand.Web.Common.TagHelpers.Admin+namespace Grand.Web.Common.TagHelpers.Admin;++[HtmlTargetElement("admin-tabstrip")]+public class AdminTabStripTagHelper : TagHelper{- [HtmlTargetElement("admin-tabstrip")]- public class AdminTabStripTagHelper : TagHelper- {- private readonly IMediator _mediator;- private readonly IDetectionService _detectionService;+ private readonly IDetectionService _detectionService;+ private readonly IMediator _mediator;- public AdminTabStripTagHelper(IMediator mediator, IDetectionService detectionService)- {- _mediator = mediator;- _detectionService = detectionService;- }+ public AdminTabStripTagHelper(IMediator mediator, IDetectionService detectionService)+ {+ _mediator = mediator;+ _detectionService = detectionService;+ }- [HtmlAttributeName("SetTabPos")]- public bool SetTabPos { get; set; } = false;+ [HtmlAttributeName("SetTabPos")] public bool SetTabPos { get; set; } = false;- [HtmlAttributeName("BindGrid")]- public bool BindGrid { get; set; } = false;+ [HtmlAttributeName("BindGrid")] public bool BindGrid { get; set; } = false;- [HtmlAttributeName("Name")]- public string Name { get; set; }+ [HtmlAttributeName("Name")] public string Name { get; set; }- [ViewContext]- public ViewContext ViewContext { get; set; }+ [ViewContext] public ViewContext ViewContext { get; set; }- public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ ViewContext.ViewData[typeof(AdminTabContentTagHelper).FullName] = new List<string>();+ var _ = await output.GetChildContentAsync();+ var list = (List<string>)ViewContext.ViewData[typeof(AdminTabContentTagHelper).FullName];+ if (_detectionService.Device.Type == Device.Mobile || _detectionService.Device.Type == Device.Tablet)+ SetTabPos = false;++ var selectedTabIndex = GetSelectedTabIndex();++ output.TagName = "div";+ output.Attributes.SetAttribute("id", Name);+ output.Attributes.SetAttribute("style", "display:none");+ var rnd = new Random().Next(0, 100);+ var sb = new StringBuilder();+ sb.AppendLine("<script>");+ sb.AppendLine("$(document).ready(function () {");+ sb.AppendLine($"$('#{Name}').show();");+ sb.AppendLine($"var tab_{rnd} = $('#{Name}').kendoTabStrip({{ ");+ sb.AppendLine($" tabPosition: '{(SetTabPos ? "left" : "top")}',");+ sb.AppendLine(" animation: { open: { effects: 'fadeIn'} },");+ sb.AppendLine(" select: tabstrip_on_tab_select,");+ if (BindGrid)+ sb.AppendLine(" show: tabstrip_on_tab_show");+ sb.AppendLine(" }).data('kendoTabStrip');");++ var eventMessage = new AdminTabStripCreated(Name);+ await _mediator.Publish(eventMessage);+ foreach (var eventBlock in eventMessage.BlocksToRender){- ViewContext.ViewData[typeof(AdminTabContentTagHelper).FullName] = new List<string>();- var _ = await output.GetChildContentAsync();- var list = (List<string>)ViewContext.ViewData[typeof(AdminTabContentTagHelper).FullName];- if (_detectionService.Device.Type == Device.Mobile || _detectionService.Device.Type == Device.Tablet)- SetTabPos = false;-- var selectedTabIndex = GetSelectedTabIndex();-- output.TagName = "div";- output.Attributes.SetAttribute("id", Name);- output.Attributes.SetAttribute("style", "display:none");- var rnd = new Random().Next(0, 100);- var sb = new StringBuilder();- sb.AppendLine("<script>");- sb.AppendLine("$(document).ready(function () {");- sb.AppendLine($"$('#{Name}').show();");- sb.AppendLine($"var tab_{rnd} = $('#{Name}').kendoTabStrip({{ ");- sb.AppendLine($" tabPosition: '{(SetTabPos ? "left" : "top")}',");- sb.AppendLine(" animation: { open: { effects: 'fadeIn'} },");- sb.AppendLine(" select: tabstrip_on_tab_select,");- if (BindGrid)- sb.AppendLine(" show: tabstrip_on_tab_show");- sb.AppendLine(" }).data('kendoTabStrip');");-- var eventMessage = new AdminTabStripCreated(Name);- await _mediator.Publish(eventMessage);- foreach (var eventBlock in eventMessage.BlocksToRender)- {- sb.AppendLine($"tab_{rnd}.append({{");- sb.AppendLine($" text: '{eventBlock.tabname}',");- sb.AppendLine($" content: '{eventBlock.content}'");- sb.AppendLine("});");- }--- if (BindGrid && selectedTabIndex > 0)- {- sb.AppendLine("$(window).load(function() {");- sb.AppendLine($" var selectedtab_{rnd} = $('#{Name}').data('kendoTabStrip').select(); ");- sb.AppendLine($" tabstrip_on_tab_show(selectedtab_{rnd}, true); ");- sb.AppendLine("});");- }-- sb.AppendLine("})");---- sb.AppendLine("</script>");- sb.AppendLine($"<input type='hidden' id='selected-tab-index' name='selected-tab-index' value='{selectedTabIndex}'>");--- output.PostContent.AppendHtml(string.Concat(list));- output.PreElement.AppendHtml(sb.ToString());+ sb.AppendLine($"tab_{rnd}.append({{");+ sb.AppendLine($" text: '{eventBlock.tabname}',");+ sb.AppendLine($" content: '{eventBlock.content}'");+ sb.AppendLine("});");}- private int GetSelectedTabIndex()++ if (BindGrid && selectedTabIndex > 0){- var index = 0;- var dataKey = "Grand.selected-tab-index";- if (ViewContext.ViewData[dataKey] is int)- {- index = (int)ViewContext.ViewData[dataKey];- }- if (ViewContext.TempData[dataKey] is int)- {- index = (int)ViewContext.TempData[dataKey];- }-- //ensure it's not negative- if (index < 0)- index = 0;-- return index;+ sb.AppendLine("$(window).load(function() {");+ sb.AppendLine($" var selectedtab_{rnd} = $('#{Name}').data('kendoTabStrip').select(); ");+ sb.AppendLine($" tabstrip_on_tab_show(selectedtab_{rnd}, true); ");+ sb.AppendLine("});");}+ sb.AppendLine("})");+++ sb.AppendLine("</script>");+ sb.AppendLine(+ $"<input type='hidden' id='selected-tab-index' name='selected-tab-index' value='{selectedTabIndex}'>");+++ output.PostContent.AppendHtml(string.Concat(list));+ output.PreElement.AppendHtml(sb.ToString());+ }++ private int GetSelectedTabIndex()+ {+ var index = 0;+ var dataKey = "Grand.selected-tab-index";+ if (ViewContext.ViewData[dataKey] is int) index = (int)ViewContext.ViewData[dataKey];+ if (ViewContext.TempData[dataKey] is int) index = (int)ViewContext.TempData[dataKey];++ //ensure it's not negative+ if (index < 0)+ index = 0;++ return index;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTextAreaTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTextAreaTagHelper.csindex 7e23f4555..f7484ca11 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTextAreaTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTextAreaTagHelper.cs@@ -2,78 +2,78 @@using Microsoft.AspNetCore.Mvc.ViewFeatures;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers.Admin+namespace Grand.Web.Common.TagHelpers.Admin;++/// <summary>+/// nop-textarea tag helper+/// </summary>+[HtmlTargetElement("admin-textarea", Attributes = ForAttributeName)]+public class AdminTextAreaTagHelper : TextAreaTagHelper{+ private const string ForAttributeName = "asp-for";+ private const string RequiredAttributeName = "asp-required";+ private const string DisabledAttributeName = "asp-disabled";+/// <summary>- /// nop-textarea tag helper+ /// Ctor/// </summary>- [HtmlTargetElement("admin-textarea", Attributes = ForAttributeName)]- public class AdminTextAreaTagHelper : TextAreaTagHelper+ /// <param name="generator">HTML generator</param>+ public AdminTextAreaTagHelper(IHtmlGenerator generator) : base(generator){- private const string ForAttributeName = "asp-for";- private const string RequiredAttributeName = "asp-required";- private const string DisabledAttributeName = "asp-disabled";-- /// <summary>- /// Indicates whether the input is disabled- /// </summary>- [HtmlAttributeName(DisabledAttributeName)]- public string IsDisabled { set; get; }-- /// <summary>- /// Indicates whether the field is required- /// </summary>- [HtmlAttributeName(RequiredAttributeName)]- public string IsRequired { set; get; }+ }- /// <summary>- /// Ctor- /// </summary>- /// <param name="generator">HTML generator</param>- public AdminTextAreaTagHelper(IHtmlGenerator generator) : base(generator)- {- }+ /// <summary>+ /// Indicates whether the input is disabled+ /// </summary>+ [HtmlAttributeName(DisabledAttributeName)]+ public string IsDisabled { set; get; }- /// <summary>- /// Process- /// </summary>- /// <param name="context">Context</param>- /// <param name="output">Output</param>- public override void Process(TagHelperContext context, TagHelperOutput output)- {- //tag details- output.TagName = "textarea";- output.TagMode = TagMode.StartTagAndEndTag;+ /// <summary>+ /// Indicates whether the field is required+ /// </summary>+ [HtmlAttributeName(RequiredAttributeName)]+ public string IsRequired { set; get; }- //merge classes- var classValue = output.Attributes.ContainsName("class")- ? $"{output.Attributes["class"].Value}"- : "form-control k-input";- output.Attributes.SetAttribute("class", classValue);+ /// <summary>+ /// Process+ /// </summary>+ /// <param name="context">Context</param>+ /// <param name="output">Output</param>+ public override void Process(TagHelperContext context, TagHelperOutput output)+ {+ //tag details+ output.TagName = "textarea";+ output.TagMode = TagMode.StartTagAndEndTag;- //add disabled attribute- bool.TryParse(IsDisabled, out var disabled);- if (disabled)- {- var d = new TagHelperAttribute("disabled", "disabled");- output.Attributes.Add(d);- }+ //merge classes+ var classValue = output.Attributes.ContainsName("class")+ ? $"{output.Attributes["class"].Value}"+ : "form-control k-input";+ output.Attributes.SetAttribute("class", classValue);- //additional parameters- var rowsNumber = output.Attributes.ContainsName("rows") ? output.Attributes["rows"].Value : 4;- output.Attributes.SetAttribute("rows", rowsNumber);- var colsNumber = output.Attributes.ContainsName("cols") ? output.Attributes["cols"].Value : 20;- output.Attributes.SetAttribute("cols", colsNumber);+ //add disabled attribute+ bool.TryParse(IsDisabled, out var disabled);+ if (disabled)+ {+ var d = new TagHelperAttribute("disabled", "disabled");+ output.Attributes.Add(d);+ }- //required asterisk- bool.TryParse(IsRequired, out var required);- if (required)- {- output.PreElement.SetHtmlContent("<div class='input-group input-group-required'>");- output.PostElement.SetHtmlContent("<div class=\"input-group-btn\"><span class=\"required\">*</span></div></div>");- }+ //additional parameters+ var rowsNumber = output.Attributes.ContainsName("rows") ? output.Attributes["rows"].Value : 4;+ output.Attributes.SetAttribute("rows", rowsNumber);+ var colsNumber = output.Attributes.ContainsName("cols") ? output.Attributes["cols"].Value : 20;+ output.Attributes.SetAttribute("cols", colsNumber);- base.Process(context, output);+ //required asterisk+ bool.TryParse(IsRequired, out var required);+ if (required)+ {+ output.PreElement.SetHtmlContent("<div class='input-group input-group-required'>");+ output.PostElement.SetHtmlContent(+ "<div class=\"input-group-btn\"><span class=\"required\">*</span></div></div>");}++ base.Process(context, output);}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/DefaultDisplayTemplates.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/DefaultDisplayTemplates.csindex adcfc3a5e..a5c13ab11 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/DefaultDisplayTemplates.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/DefaultDisplayTemplates.cs@@ -12,281 +12,246 @@ using System.Collections;using System.Diagnostics;using System.Globalization;-namespace Grand.Web.Common.TagHelpers.Admin.Extend+namespace Grand.Web.Common.TagHelpers.Admin.Extend;++internal static class DefaultDisplayTemplates{- internal static class DefaultDisplayTemplates+ public static async Task<IHtmlContent> BooleanTemplate(IHtmlHelper htmlHelper){- public static async Task<IHtmlContent> BooleanTemplate(IHtmlHelper htmlHelper)- {- bool? value = null;- if (htmlHelper.ViewData.Model != null)- {- value = Convert.ToBoolean(htmlHelper.ViewData.Model, CultureInfo.InvariantCulture);- }-- return htmlHelper.ViewData.ModelMetadata.IsNullableValueType ?- await BooleanTemplateDropDownList(value) :- await BooleanTemplateCheckbox(value ?? false);- }-- private static async Task<IHtmlContent> BooleanTemplateCheckbox(bool value)- {- var inputTag = new TagBuilder("input");- inputTag.AddCssClass("check-box");- inputTag.Attributes["disabled"] = "disabled";- inputTag.Attributes["type"] = "checkbox";- if (value)- {- inputTag.Attributes["checked"] = "checked";- }+ bool? value = null;+ if (htmlHelper.ViewData.Model != null)+ value = Convert.ToBoolean(htmlHelper.ViewData.Model, CultureInfo.InvariantCulture);- inputTag.TagRenderMode = TagRenderMode.SelfClosing;- return await Task.FromResult(inputTag);- }+ return htmlHelper.ViewData.ModelMetadata.IsNullableValueType+ ? await BooleanTemplateDropDownList(value)+ : await BooleanTemplateCheckbox(value ?? false);+ }- private static async Task<IHtmlContent> BooleanTemplateDropDownList(bool? value)- {- var selectTag = new TagBuilder("select");- selectTag.AddCssClass("list-box");- selectTag.AddCssClass("tri-state");- selectTag.Attributes["disabled"] = "disabled";+ private static async Task<IHtmlContent> BooleanTemplateCheckbox(bool value)+ {+ var inputTag = new TagBuilder("input");+ inputTag.AddCssClass("check-box");+ inputTag.Attributes["disabled"] = "disabled";+ inputTag.Attributes["type"] = "checkbox";+ if (value) inputTag.Attributes["checked"] = "checked";++ inputTag.TagRenderMode = TagRenderMode.SelfClosing;+ return await Task.FromResult(inputTag);+ }- foreach (var item in TriStateValues(value))- {- selectTag.InnerHtml.AppendHtml(DefaultHtmlGenerator.GenerateOption(item, item.Text));- }+ private static async Task<IHtmlContent> BooleanTemplateDropDownList(bool? value)+ {+ var selectTag = new TagBuilder("select");+ selectTag.AddCssClass("list-box");+ selectTag.AddCssClass("tri-state");+ selectTag.Attributes["disabled"] = "disabled";- return await Task.FromResult(selectTag);- }+ foreach (var item in TriStateValues(value))+ selectTag.InnerHtml.AppendHtml(DefaultHtmlGenerator.GenerateOption(item, item.Text));- // Will soon need to be shared with the default editor templates implementations.- internal static List<SelectListItem> TriStateValues(bool? value)- {- return [- new SelectListItem("Not Set", string.Empty, !value.HasValue),- new SelectListItem("True", "true", value == true),- new SelectListItem("False", "false", value == false)- ];- }+ return await Task.FromResult(selectTag);+ }- public static async Task<IHtmlContent> CollectionTemplate(IHtmlHelper htmlHelper)- {- var model = htmlHelper.ViewData.Model;- if (model == null)- {- return HtmlString.Empty;- }+ // Will soon need to be shared with the default editor templates implementations.+ internal static List<SelectListItem> TriStateValues(bool? value)+ {+ return [+ new SelectListItem("Not Set", string.Empty, !value.HasValue),+ new SelectListItem("True", "true", value == true),+ new SelectListItem("False", "false", value == false)+ ];+ }- var enumerable = model as IEnumerable;- if (enumerable == null)- {- // Only way we could reach here is if user passed templateName: "Collection" to a Display() overload.- throw new InvalidOperationException($"Collection {model.GetType().FullName}");- }+ public static async Task<IHtmlContent> CollectionTemplate(IHtmlHelper htmlHelper)+ {+ var model = htmlHelper.ViewData.Model;+ if (model == null) return HtmlString.Empty;- var elementMetadata = htmlHelper.ViewData.ModelMetadata.ElementMetadata;- Debug.Assert(elementMetadata != null);- var typeInCollectionIsNullableValueType = elementMetadata.IsNullableValueType;+ var enumerable = model as IEnumerable;+ if (enumerable == null)+ // Only way we could reach here is if user passed templateName: "Collection" to a Display() overload.+ throw new InvalidOperationException($"Collection {model.GetType().FullName}");- var serviceProvider = htmlHelper.ViewContext.HttpContext.RequestServices;- var metadataProvider = serviceProvider.GetRequiredService<IModelMetadataProvider>();+ var elementMetadata = htmlHelper.ViewData.ModelMetadata.ElementMetadata;+ Debug.Assert(elementMetadata != null);+ var typeInCollectionIsNullableValueType = elementMetadata.IsNullableValueType;- // Use typeof(string) instead of typeof(object) for IEnumerable collections. Neither type is Nullable<T>.- if (elementMetadata.ModelType == typeof(object))- {- elementMetadata = metadataProvider.GetMetadataForType(typeof(string));- }+ var serviceProvider = htmlHelper.ViewContext.HttpContext.RequestServices;+ var metadataProvider = serviceProvider.GetRequiredService<IModelMetadataProvider>();- var oldPrefix = htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix;- try- {- htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix = string.Empty;+ // Use typeof(string) instead of typeof(object) for IEnumerable collections. Neither type is Nullable<T>.+ if (elementMetadata.ModelType == typeof(object))+ elementMetadata = metadataProvider.GetMetadataForType(typeof(string));- var collection = model as ICollection;- var result = collection == null ? new HtmlContentBuilder() : new HtmlContentBuilder(collection.Count);- var viewEngine = serviceProvider.GetRequiredService<ICompositeViewEngine>();- var viewBufferScope = serviceProvider.GetRequiredService<IViewBufferScope>();+ var oldPrefix = htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix;+ try+ {+ htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix = string.Empty;- var index = 0;- foreach (var item in enumerable)- {- var itemMetadata = elementMetadata;- if (item != null && !typeInCollectionIsNullableValueType)- {- itemMetadata = metadataProvider.GetMetadataForType(item.GetType());- }-- var modelExplorer = new ModelExplorer(- metadataProvider,- container: htmlHelper.ViewData.ModelExplorer,- metadata: itemMetadata,- model: item);- var fieldName = string.Format(CultureInfo.InvariantCulture, "{0}[{1}]", oldPrefix, index++);-- var templateBuilder = new TemplateBuilder(- viewEngine,- viewBufferScope,- htmlHelper.ViewContext,- htmlHelper.ViewData,- modelExplorer,- htmlFieldName: fieldName,- templateName: null,- readOnly: true,- additionalViewData: null);- result.AppendHtml(await templateBuilder.Build());- }+ var collection = model as ICollection;+ var result = collection == null ? new HtmlContentBuilder() : new HtmlContentBuilder(collection.Count);+ var viewEngine = serviceProvider.GetRequiredService<ICompositeViewEngine>();+ var viewBufferScope = serviceProvider.GetRequiredService<IViewBufferScope>();- return result;- }- finally+ var index = 0;+ foreach (var item in enumerable){- htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix = oldPrefix;- }- }+ var itemMetadata = elementMetadata;+ if (item != null && !typeInCollectionIsNullableValueType)+ itemMetadata = metadataProvider.GetMetadataForType(item.GetType());- public static async Task<IHtmlContent> DecimalTemplate(IHtmlHelper htmlHelper)- {- if (htmlHelper.ViewData.TemplateInfo.FormattedModelValue == htmlHelper.ViewData.Model)- {- htmlHelper.ViewData.TemplateInfo.FormattedModelValue =- string.Format(CultureInfo.CurrentCulture, "{0:0.00}", htmlHelper.ViewData.Model);+ var modelExplorer = new ModelExplorer(+ metadataProvider,+ htmlHelper.ViewData.ModelExplorer,+ itemMetadata,+ item);+ var fieldName = string.Format(CultureInfo.InvariantCulture, "{0}[{1}]", oldPrefix, index++);++ var templateBuilder = new TemplateBuilder(+ viewEngine,+ viewBufferScope,+ htmlHelper.ViewContext,+ htmlHelper.ViewData,+ modelExplorer,+ fieldName,+ null,+ true,+ null);+ result.AppendHtml(await templateBuilder.Build());}- return await StringTemplate(htmlHelper);- }- public static async Task<IHtmlContent> EmailAddressTemplate(IHtmlHelper htmlHelper)- {- var uriString = "mailto:" + (htmlHelper.ViewData.Model == null ?- string.Empty :- htmlHelper.ViewData.Model.ToString());- var linkedText = htmlHelper.ViewData.TemplateInfo.FormattedModelValue == null ?- string.Empty :- htmlHelper.ViewData.TemplateInfo.FormattedModelValue.ToString();-- return await Task.FromResult(HyperlinkTemplate(uriString, linkedText));+ return result;}-- public static async Task<IHtmlContent> HiddenInputTemplate(IHtmlHelper htmlHelper)+ finally{- if (htmlHelper.ViewData.ModelMetadata.HideSurroundingHtml)- {- return HtmlString.Empty;- }- return await StringTemplate(htmlHelper);+ htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix = oldPrefix;}+ }- public static async Task<IHtmlContent> HtmlTemplate(IHtmlHelper htmlHelper)- {- return await Task.FromResult(new HtmlString(htmlHelper.ViewData.TemplateInfo.FormattedModelValue.ToString()));- }+ public static async Task<IHtmlContent> DecimalTemplate(IHtmlHelper htmlHelper)+ {+ if (htmlHelper.ViewData.TemplateInfo.FormattedModelValue == htmlHelper.ViewData.Model)+ htmlHelper.ViewData.TemplateInfo.FormattedModelValue =+ string.Format(CultureInfo.CurrentCulture, "{0:0.00}", htmlHelper.ViewData.Model);+ return await StringTemplate(htmlHelper);+ }- public static async Task<IHtmlContent> ObjectTemplate(IHtmlHelper htmlHelper)- {- var viewData = htmlHelper.ViewData;- var templateInfo = viewData.TemplateInfo;- var modelExplorer = viewData.ModelExplorer;+ public static async Task<IHtmlContent> EmailAddressTemplate(IHtmlHelper htmlHelper)+ {+ var uriString = "mailto:" ++ (htmlHelper.ViewData.Model == null ? string.Empty : htmlHelper.ViewData.Model.ToString());+ var linkedText = htmlHelper.ViewData.TemplateInfo.FormattedModelValue == null+ ? string.Empty+ : htmlHelper.ViewData.TemplateInfo.FormattedModelValue.ToString();- if (modelExplorer.Model == null)- {- return new HtmlString(modelExplorer.Metadata.NullDisplayText);- }+ return await Task.FromResult(HyperlinkTemplate(uriString, linkedText));+ }- if (templateInfo.TemplateDepth > 1)- {- var text = modelExplorer.GetSimpleDisplayText();- if (modelExplorer.Metadata.HtmlEncode)- {- text = htmlHelper.Encode(text);- }+ public static async Task<IHtmlContent> HiddenInputTemplate(IHtmlHelper htmlHelper)+ {+ if (htmlHelper.ViewData.ModelMetadata.HideSurroundingHtml) return HtmlString.Empty;+ return await StringTemplate(htmlHelper);+ }- return new HtmlString(text);- }+ public static async Task<IHtmlContent> HtmlTemplate(IHtmlHelper htmlHelper)+ {+ return await Task.FromResult(new HtmlString(htmlHelper.ViewData.TemplateInfo.FormattedModelValue.ToString()));+ }- var serviceProvider = htmlHelper.ViewContext.HttpContext.RequestServices;- var viewEngine = serviceProvider.GetRequiredService<ICompositeViewEngine>();- var viewBufferScope = serviceProvider.GetRequiredService<IViewBufferScope>();+ public static async Task<IHtmlContent> ObjectTemplate(IHtmlHelper htmlHelper)+ {+ var viewData = htmlHelper.ViewData;+ var templateInfo = viewData.TemplateInfo;+ var modelExplorer = viewData.ModelExplorer;- var content = new HtmlContentBuilder(modelExplorer.Metadata.Properties.Count);- foreach (var propertyExplorer in modelExplorer.Properties)- {- var propertyMetadata = propertyExplorer.Metadata;- if (!ShouldShow(propertyExplorer, templateInfo))- {- continue;- }+ if (modelExplorer.Model == null) return new HtmlString(modelExplorer.Metadata.NullDisplayText);- var templateBuilder = new TemplateBuilder(- viewEngine,- viewBufferScope,- htmlHelper.ViewContext,- htmlHelper.ViewData,- propertyExplorer,- htmlFieldName: propertyMetadata.PropertyName,- templateName: null,- readOnly: true,- additionalViewData: null);-- var templateBuilderResult = await templateBuilder.Build();- if (!propertyMetadata.HideSurroundingHtml)- {- var label = propertyMetadata.GetDisplayName();- if (!string.IsNullOrEmpty(label))- {- var labelTag = new TagBuilder("div");- labelTag.InnerHtml.SetContent(label);- labelTag.AddCssClass("display-label");- content.AppendLine(labelTag);- }-- var valueDivTag = new TagBuilder("div");- valueDivTag.AddCssClass("display-field");- valueDivTag.InnerHtml.SetHtmlContent(templateBuilderResult);- content.AppendLine(valueDivTag);- }- else- {- content.AppendHtml(templateBuilderResult);- }- }+ if (templateInfo.TemplateDepth > 1)+ {+ var text = modelExplorer.GetSimpleDisplayText();+ if (modelExplorer.Metadata.HtmlEncode) text = htmlHelper.Encode(text);- return content;+ return new HtmlString(text);}- private static bool ShouldShow(ModelExplorer modelExplorer, TemplateInfo templateInfo)- {- return- modelExplorer.Metadata.ShowForDisplay &&- !modelExplorer.Metadata.IsComplexType &&- !templateInfo.Visited(modelExplorer);- }+ var serviceProvider = htmlHelper.ViewContext.HttpContext.RequestServices;+ var viewEngine = serviceProvider.GetRequiredService<ICompositeViewEngine>();+ var viewBufferScope = serviceProvider.GetRequiredService<IViewBufferScope>();- public static async Task<IHtmlContent> StringTemplate(IHtmlHelper htmlHelper)+ var content = new HtmlContentBuilder(modelExplorer.Metadata.Properties.Count);+ foreach (var propertyExplorer in modelExplorer.Properties){- var value = htmlHelper.ViewData.TemplateInfo.FormattedModelValue;- if (value == null)+ var propertyMetadata = propertyExplorer.Metadata;+ if (!ShouldShow(propertyExplorer, templateInfo)) continue;++ var templateBuilder = new TemplateBuilder(+ viewEngine,+ viewBufferScope,+ htmlHelper.ViewContext,+ htmlHelper.ViewData,+ propertyExplorer,+ propertyMetadata.PropertyName,+ null,+ true,+ null);++ var templateBuilderResult = await templateBuilder.Build();+ if (!propertyMetadata.HideSurroundingHtml){- return HtmlString.Empty;+ var label = propertyMetadata.GetDisplayName();+ if (!string.IsNullOrEmpty(label))+ {+ var labelTag = new TagBuilder("div");+ labelTag.InnerHtml.SetContent(label);+ labelTag.AddCssClass("display-label");+ content.AppendLine(labelTag);+ }++ var valueDivTag = new TagBuilder("div");+ valueDivTag.AddCssClass("display-field");+ valueDivTag.InnerHtml.SetHtmlContent(templateBuilderResult);+ content.AppendLine(valueDivTag);+ }+ else+ {+ content.AppendHtml(templateBuilderResult);}- return await Task.FromResult(new StringHtmlContent(value.ToString()));}- public static async Task<IHtmlContent> UrlTemplate(IHtmlHelper htmlHelper)- {- var uriString = htmlHelper.ViewData.Model == null ? string.Empty : htmlHelper.ViewData.Model.ToString();- var linkedText = htmlHelper.ViewData.TemplateInfo.FormattedModelValue == null ?- string.Empty :- htmlHelper.ViewData.TemplateInfo.FormattedModelValue.ToString();+ return content;+ }- return await Task.FromResult(HyperlinkTemplate(uriString, linkedText));- }+ private static bool ShouldShow(ModelExplorer modelExplorer, TemplateInfo templateInfo)+ {+ return+ modelExplorer.Metadata.ShowForDisplay &&+ !modelExplorer.Metadata.IsComplexType &&+ !templateInfo.Visited(modelExplorer);+ }- // Neither uriString nor linkedText need be encoded prior to calling this method.- private static IHtmlContent HyperlinkTemplate(string uriString, string linkedText)- {- var hyperlinkTag = new TagBuilder("a");- hyperlinkTag.MergeAttribute("href", uriString);- hyperlinkTag.InnerHtml.SetContent(linkedText);- return hyperlinkTag;- }+ public static async Task<IHtmlContent> StringTemplate(IHtmlHelper htmlHelper)+ {+ var value = htmlHelper.ViewData.TemplateInfo.FormattedModelValue;+ if (value == null) return HtmlString.Empty;+ return await Task.FromResult(new StringHtmlContent(value.ToString()));+ }++ public static async Task<IHtmlContent> UrlTemplate(IHtmlHelper htmlHelper)+ {+ var uriString = htmlHelper.ViewData.Model == null ? string.Empty : htmlHelper.ViewData.Model.ToString();+ var linkedText = htmlHelper.ViewData.TemplateInfo.FormattedModelValue == null+ ? string.Empty+ : htmlHelper.ViewData.TemplateInfo.FormattedModelValue.ToString();++ return await Task.FromResult(HyperlinkTemplate(uriString, linkedText));+ }++ // Neither uriString nor linkedText need be encoded prior to calling this method.+ private static IHtmlContent HyperlinkTemplate(string uriString, string linkedText)+ {+ var hyperlinkTag = new TagBuilder("a");+ hyperlinkTag.MergeAttribute("href", uriString);+ hyperlinkTag.InnerHtml.SetContent(linkedText);+ return hyperlinkTag;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/DefaultEditorTemplates.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/DefaultEditorTemplates.csindex 08a316e3f..c603650c6 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/DefaultEditorTemplates.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/DefaultEditorTemplates.cs@@ -13,472 +13,417 @@ using System.Diagnostics;using System.Globalization;using System.Text.Encodings.Web;-namespace Grand.Web.Common.TagHelpers.Admin.Extend+namespace Grand.Web.Common.TagHelpers.Admin.Extend;++internal static class DefaultEditorTemplates{- internal static class DefaultEditorTemplates- {- private const string HtmlAttributeKey = "htmlAttributes";- private const string UsePasswordValue = "Switch.Microsoft.AspNetCore.Mvc.UsePasswordValue";+ private const string HtmlAttributeKey = "htmlAttributes";+ private const string UsePasswordValue = "Switch.Microsoft.AspNetCore.Mvc.UsePasswordValue";- public static async Task<IHtmlContent> BooleanTemplate(IHtmlHelper htmlHelper)- {- bool? value = null;- if (htmlHelper.ViewData.Model != null)- {- value = Convert.ToBoolean(htmlHelper.ViewData.Model, CultureInfo.InvariantCulture);- }+ public static async Task<IHtmlContent> BooleanTemplate(IHtmlHelper htmlHelper)+ {+ bool? value = null;+ if (htmlHelper.ViewData.Model != null)+ value = Convert.ToBoolean(htmlHelper.ViewData.Model, CultureInfo.InvariantCulture);- return htmlHelper.ViewData.ModelMetadata.IsNullableValueType ?- await BooleanTemplateDropDownList(htmlHelper, value) :- await BooleanTemplateCheckbox(htmlHelper, value ?? false);- }+ return htmlHelper.ViewData.ModelMetadata.IsNullableValueType+ ? await BooleanTemplateDropDownList(htmlHelper, value)+ : await BooleanTemplateCheckbox(htmlHelper, value ?? false);+ }- private static async Task<IHtmlContent> BooleanTemplateCheckbox(IHtmlHelper htmlHelper, bool value)- {- return await Task.FromResult(htmlHelper.CheckBox(- expression: null,- isChecked: value,- htmlAttributes: CreateHtmlAttributes(htmlHelper, "check-box")));- }+ private static async Task<IHtmlContent> BooleanTemplateCheckbox(IHtmlHelper htmlHelper, bool value)+ {+ return await Task.FromResult(htmlHelper.CheckBox(+ null,+ value,+ CreateHtmlAttributes(htmlHelper, "check-box")));+ }- private static async Task<IHtmlContent> BooleanTemplateDropDownList(IHtmlHelper htmlHelper, bool? value)- {- return await Task.FromResult(htmlHelper.DropDownList(- expression: null,- selectList: DefaultDisplayTemplates.TriStateValues(value),- optionLabel: null,- htmlAttributes: CreateHtmlAttributes(htmlHelper, "list-box tri-state")));- }+ private static async Task<IHtmlContent> BooleanTemplateDropDownList(IHtmlHelper htmlHelper, bool? value)+ {+ return await Task.FromResult(htmlHelper.DropDownList(+ null,+ DefaultDisplayTemplates.TriStateValues(value),+ null,+ CreateHtmlAttributes(htmlHelper, "list-box tri-state")));+ }- public static async Task<IHtmlContent> CollectionTemplate(IHtmlHelper htmlHelper)- {- var viewData = htmlHelper.ViewData;- var model = viewData.Model;- if (model == null)- {- return HtmlString.Empty;- }+ public static async Task<IHtmlContent> CollectionTemplate(IHtmlHelper htmlHelper)+ {+ var viewData = htmlHelper.ViewData;+ var model = viewData.Model;+ if (model == null) return HtmlString.Empty;- var enumerable = model as IEnumerable;- if (enumerable == null)- {- // Only way we could reach here is if user passed templateName: "Collection" to an Editor() overload.- throw new InvalidOperationException($"Collection, {model.GetType().FullName}");- }+ var enumerable = model as IEnumerable;+ if (enumerable == null)+ // Only way we could reach here is if user passed templateName: "Collection" to an Editor() overload.+ throw new InvalidOperationException($"Collection, {model.GetType().FullName}");- var elementMetadata = htmlHelper.ViewData.ModelMetadata.ElementMetadata;- Debug.Assert(elementMetadata != null);- var typeInCollectionIsNullableValueType = elementMetadata.IsNullableValueType;+ var elementMetadata = htmlHelper.ViewData.ModelMetadata.ElementMetadata;+ Debug.Assert(elementMetadata != null);+ var typeInCollectionIsNullableValueType = elementMetadata.IsNullableValueType;- var serviceProvider = htmlHelper.ViewContext.HttpContext.RequestServices;- var metadataProvider = serviceProvider.GetRequiredService<IModelMetadataProvider>();+ var serviceProvider = htmlHelper.ViewContext.HttpContext.RequestServices;+ var metadataProvider = serviceProvider.GetRequiredService<IModelMetadataProvider>();- // Use typeof(string) instead of typeof(object) for IEnumerable collections. Neither type is Nullable<T>.- if (elementMetadata.ModelType == typeof(object))- {- elementMetadata = metadataProvider.GetMetadataForType(typeof(string));- }+ // Use typeof(string) instead of typeof(object) for IEnumerable collections. Neither type is Nullable<T>.+ if (elementMetadata.ModelType == typeof(object))+ elementMetadata = metadataProvider.GetMetadataForType(typeof(string));- var oldPrefix = viewData.TemplateInfo.HtmlFieldPrefix;- try- {- viewData.TemplateInfo.HtmlFieldPrefix = string.Empty;+ var oldPrefix = viewData.TemplateInfo.HtmlFieldPrefix;+ try+ {+ viewData.TemplateInfo.HtmlFieldPrefix = string.Empty;- var collection = model as ICollection;- var result = collection == null ? new HtmlContentBuilder() : new HtmlContentBuilder(collection.Count);- var viewEngine = serviceProvider.GetRequiredService<ICompositeViewEngine>();- var viewBufferScope = serviceProvider.GetRequiredService<IViewBufferScope>();+ var collection = model as ICollection;+ var result = collection == null ? new HtmlContentBuilder() : new HtmlContentBuilder(collection.Count);+ var viewEngine = serviceProvider.GetRequiredService<ICompositeViewEngine>();+ var viewBufferScope = serviceProvider.GetRequiredService<IViewBufferScope>();- var index = 0;- foreach (var item in enumerable)- {- var itemMetadata = elementMetadata;- if (item != null && !typeInCollectionIsNullableValueType)- {- itemMetadata = metadataProvider.GetMetadataForType(item.GetType());- }+ var index = 0;+ foreach (var item in enumerable)+ {+ var itemMetadata = elementMetadata;+ if (item != null && !typeInCollectionIsNullableValueType)+ itemMetadata = metadataProvider.GetMetadataForType(item.GetType());- var modelExplorer = new ModelExplorer(- metadataProvider,- container: htmlHelper.ViewData.ModelExplorer,- metadata: itemMetadata,- model: item);- var fieldName = string.Format(CultureInfo.InvariantCulture, "{0}[{1}]", oldPrefix, index++);-- var templateBuilder = new TemplateBuilder(- viewEngine,- viewBufferScope,- htmlHelper.ViewContext,- htmlHelper.ViewData,- modelExplorer,- htmlFieldName: fieldName,- templateName: null,- readOnly: false,- additionalViewData: null);- result.AppendHtml(await templateBuilder.Build());- }+ var modelExplorer = new ModelExplorer(+ metadataProvider,+ htmlHelper.ViewData.ModelExplorer,+ itemMetadata,+ item);+ var fieldName = string.Format(CultureInfo.InvariantCulture, "{0}[{1}]", oldPrefix, index++);- return result;- }- finally- {- viewData.TemplateInfo.HtmlFieldPrefix = oldPrefix;+ var templateBuilder = new TemplateBuilder(+ viewEngine,+ viewBufferScope,+ htmlHelper.ViewContext,+ htmlHelper.ViewData,+ modelExplorer,+ fieldName,+ null,+ false,+ null);+ result.AppendHtml(await templateBuilder.Build());}- }- public static async Task<IHtmlContent> DecimalTemplate(IHtmlHelper htmlHelper)+ return result;+ }+ finally{- if (htmlHelper.ViewData.TemplateInfo.FormattedModelValue == htmlHelper.ViewData.Model)- {- htmlHelper.ViewData.TemplateInfo.FormattedModelValue =- string.Format(CultureInfo.CurrentCulture, "{0:0.00}", htmlHelper.ViewData.Model);- }-- return await StringTemplate(htmlHelper);+ viewData.TemplateInfo.HtmlFieldPrefix = oldPrefix;}+ }- public static async Task<IHtmlContent> HiddenInputTemplate(IHtmlHelper htmlHelper)- {- var viewData = htmlHelper.ViewData;- var model = viewData.Model;+ public static async Task<IHtmlContent> DecimalTemplate(IHtmlHelper htmlHelper)+ {+ if (htmlHelper.ViewData.TemplateInfo.FormattedModelValue == htmlHelper.ViewData.Model)+ htmlHelper.ViewData.TemplateInfo.FormattedModelValue =+ string.Format(CultureInfo.CurrentCulture, "{0:0.00}", htmlHelper.ViewData.Model);- IHtmlContent display;- if (viewData.ModelMetadata.HideSurroundingHtml)- {- display = null;- }- else- {- display = await DefaultDisplayTemplates.StringTemplate(htmlHelper);- }+ return await StringTemplate(htmlHelper);+ }- var htmlAttributesObject = viewData[HtmlAttributeKey];- var hidden = htmlHelper.Hidden(expression: null, value: model, htmlAttributes: htmlAttributesObject);- if (viewData.ModelMetadata.HideSurroundingHtml)- {- return hidden;- }+ public static async Task<IHtmlContent> HiddenInputTemplate(IHtmlHelper htmlHelper)+ {+ var viewData = htmlHelper.ViewData;+ var model = viewData.Model;++ IHtmlContent display;+ if (viewData.ModelMetadata.HideSurroundingHtml)+ display = null;+ else+ display = await DefaultDisplayTemplates.StringTemplate(htmlHelper);++ var htmlAttributesObject = viewData[HtmlAttributeKey];+ var hidden = htmlHelper.Hidden(null, model, htmlAttributesObject);+ if (viewData.ModelMetadata.HideSurroundingHtml) return hidden;++ return new HtmlContentBuilder(2)+ .AppendHtml(display)+ .AppendHtml(hidden);+ }- return new HtmlContentBuilder(capacity: 2)- .AppendHtml(display)- .AppendHtml(hidden);- }+ private static IDictionary<string, object> CreateHtmlAttributes(+ IHtmlHelper htmlHelper,+ string className,+ string inputType = null)+ {+ var htmlAttributesObject = htmlHelper.ViewData[HtmlAttributeKey];+ if (htmlAttributesObject != null) return MergeHtmlAttributes(htmlAttributesObject, className, inputType);- private static IDictionary<string, object> CreateHtmlAttributes(- IHtmlHelper htmlHelper,- string className,- string inputType = null)- {- var htmlAttributesObject = htmlHelper.ViewData[HtmlAttributeKey];- if (htmlAttributesObject != null)- {- return MergeHtmlAttributes(htmlAttributesObject, className, inputType);- }+ var htmlAttributes = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase) {+ { "class", className }+ };- var htmlAttributes = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase)- {- { "class", className }- };+ if (inputType != null) htmlAttributes.Add("type", inputType);- if (inputType != null)- {- htmlAttributes.Add("type", inputType);- }+ return htmlAttributes;+ }- return htmlAttributes;- }+ private static IDictionary<string, object> MergeHtmlAttributes(+ object htmlAttributesObject,+ string className,+ string inputType)+ {+ var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributesObject);- private static IDictionary<string, object> MergeHtmlAttributes(- object htmlAttributesObject,- string className,- string inputType)+ if (htmlAttributes.TryGetValue("class", out var htmlClassObject))+ {+ var htmlClassName = htmlClassObject + " " + className;+ htmlAttributes["class"] = htmlClassName;+ }+ else{- var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributesObject);+ htmlAttributes.Add("class", className);+ }- if (htmlAttributes.TryGetValue("class", out var htmlClassObject))- {- var htmlClassName = htmlClassObject + " " + className;- htmlAttributes["class"] = htmlClassName;- }- else- {- htmlAttributes.Add("class", className);- }+ // The input type from the provided htmlAttributes overrides the inputType parameter.+ if (inputType != null && !htmlAttributes.ContainsKey("type")) htmlAttributes.Add("type", inputType);- // The input type from the provided htmlAttributes overrides the inputType parameter.- if (inputType != null && !htmlAttributes.ContainsKey("type"))- {- htmlAttributes.Add("type", inputType);- }+ return htmlAttributes;+ }- return htmlAttributes;- }+ public static async Task<IHtmlContent> MultilineTemplate(IHtmlHelper htmlHelper)+ {+ return await Task.FromResult(htmlHelper.TextArea(+ string.Empty,+ htmlHelper.ViewContext.ViewData.TemplateInfo.FormattedModelValue.ToString(),+ 0,+ 0,+ CreateHtmlAttributes(htmlHelper, "text-box multi-line")));+ }++ public static async Task<IHtmlContent> ObjectTemplate(IHtmlHelper htmlHelper)+ {+ var viewData = htmlHelper.ViewData;+ var templateInfo = viewData.TemplateInfo;+ var modelExplorer = viewData.ModelExplorer;- public static async Task<IHtmlContent> MultilineTemplate(IHtmlHelper htmlHelper)+ if (templateInfo.TemplateDepth > 1){- return await Task.FromResult(htmlHelper.TextArea(- expression: string.Empty,- value: htmlHelper.ViewContext.ViewData.TemplateInfo.FormattedModelValue.ToString(),- rows: 0,- columns: 0,- htmlAttributes: CreateHtmlAttributes(htmlHelper, "text-box multi-line")));+ if (modelExplorer.Model == null) return new HtmlString(modelExplorer.Metadata.NullDisplayText);++ var text = modelExplorer.GetSimpleDisplayText();+ if (modelExplorer.Metadata.HtmlEncode) return new StringHtmlContent(text);++ return new HtmlString(text);}- public static async Task<IHtmlContent> ObjectTemplate(IHtmlHelper htmlHelper)- {- var viewData = htmlHelper.ViewData;- var templateInfo = viewData.TemplateInfo;- var modelExplorer = viewData.ModelExplorer;+ var serviceProvider = htmlHelper.ViewContext.HttpContext.RequestServices;+ var viewEngine = serviceProvider.GetRequiredService<ICompositeViewEngine>();+ var viewBufferScope = serviceProvider.GetRequiredService<IViewBufferScope>();- if (templateInfo.TemplateDepth > 1)+ var content = new HtmlContentBuilder(modelExplorer.Metadata.Properties.Count);+ foreach (var propertyExplorer in modelExplorer.Properties)+ {+ var propertyMetadata = propertyExplorer.Metadata;+ if (!ShouldShow(propertyExplorer, templateInfo)) continue;++ var templateBuilder = new TemplateBuilder(+ viewEngine,+ viewBufferScope,+ htmlHelper.ViewContext,+ htmlHelper.ViewData,+ propertyExplorer,+ propertyMetadata.PropertyName,+ null,+ false,+ null);++ var templateBuilderResult = await templateBuilder.Build();+ if (!propertyMetadata.HideSurroundingHtml){- if (modelExplorer.Model == null)- {- return new HtmlString(modelExplorer.Metadata.NullDisplayText);- }-- var text = modelExplorer.GetSimpleDisplayText();- if (modelExplorer.Metadata.HtmlEncode)+ var label = htmlHelper.Label(propertyMetadata.PropertyName, null, null);+ using (var writer = new HasContentTextWriter()){- return new StringHtmlContent(text);+ label.WriteTo(writer, HtmlEncoder.Default);+ if (writer.HasContent)+ {+ var labelTag = new TagBuilder("div");+ labelTag.AddCssClass("editor-label");+ labelTag.InnerHtml.SetHtmlContent(label);+ content.AppendLine(labelTag);+ }}- return new HtmlString(text);- }+ var valueDivTag = new TagBuilder("div");+ valueDivTag.AddCssClass("editor-field");- var serviceProvider = htmlHelper.ViewContext.HttpContext.RequestServices;- var viewEngine = serviceProvider.GetRequiredService<ICompositeViewEngine>();- var viewBufferScope = serviceProvider.GetRequiredService<IViewBufferScope>();+ valueDivTag.InnerHtml.AppendHtml(templateBuilderResult);+ valueDivTag.InnerHtml.AppendHtml(" ");+ valueDivTag.InnerHtml.AppendHtml(htmlHelper.ValidationMessage(+ propertyMetadata.PropertyName,+ null,+ null,+ null));- var content = new HtmlContentBuilder(modelExplorer.Metadata.Properties.Count);- foreach (var propertyExplorer in modelExplorer.Properties)+ content.AppendLine(valueDivTag);+ }+ else{- var propertyMetadata = propertyExplorer.Metadata;- if (!ShouldShow(propertyExplorer, templateInfo))- {- continue;- }+ content.AppendHtml(templateBuilderResult);+ }+ }- var templateBuilder = new TemplateBuilder(- viewEngine,- viewBufferScope,- htmlHelper.ViewContext,- htmlHelper.ViewData,- propertyExplorer,- htmlFieldName: propertyMetadata.PropertyName,- templateName: null,- readOnly: false,- additionalViewData: null);-- var templateBuilderResult = await templateBuilder.Build();- if (!propertyMetadata.HideSurroundingHtml)- {- var label = htmlHelper.Label(propertyMetadata.PropertyName, labelText: null, htmlAttributes: null);- using (var writer = new HasContentTextWriter())- {- label.WriteTo(writer, HtmlEncoder.Default);- if (writer.HasContent)- {- var labelTag = new TagBuilder("div");- labelTag.AddCssClass("editor-label");- labelTag.InnerHtml.SetHtmlContent(label);- content.AppendLine(labelTag);- }- }+ return content;+ }- var valueDivTag = new TagBuilder("div");- valueDivTag.AddCssClass("editor-field");+ public static async Task<IHtmlContent> PasswordTemplate(IHtmlHelper htmlHelper)+ {+ object value = null;+ if (AppContext.TryGetSwitch(UsePasswordValue, out var usePasswordValue) && usePasswordValue)+ value = htmlHelper.ViewData.TemplateInfo.FormattedModelValue;++ return await Task.FromResult(htmlHelper.Password(+ null,+ value,+ CreateHtmlAttributes(htmlHelper, "text-box single-line password")));+ }- valueDivTag.InnerHtml.AppendHtml(templateBuilderResult);- valueDivTag.InnerHtml.AppendHtml(" ");- valueDivTag.InnerHtml.AppendHtml(htmlHelper.ValidationMessage(- propertyMetadata.PropertyName,- message: null,- htmlAttributes: null,- tag: null));+ private static bool ShouldShow(ModelExplorer modelExplorer, TemplateInfo templateInfo)+ {+ return+ modelExplorer.Metadata.ShowForEdit &&+ !modelExplorer.Metadata.IsComplexType &&+ !templateInfo.Visited(modelExplorer);+ }- content.AppendLine(valueDivTag);- }- else- {- content.AppendHtml(templateBuilderResult);- }- }+ public static async Task<IHtmlContent> StringTemplate(IHtmlHelper htmlHelper)+ {+ return await Task.FromResult(GenerateTextBox(htmlHelper));+ }- return content;- }+ public static async Task<IHtmlContent> PhoneNumberInputTemplate(IHtmlHelper htmlHelper)+ {+ return await Task.FromResult(GenerateTextBox(htmlHelper, "tel"));+ }- public static async Task<IHtmlContent> PasswordTemplate(IHtmlHelper htmlHelper)- {- object value = null;- if (AppContext.TryGetSwitch(UsePasswordValue, out var usePasswordValue) && usePasswordValue)- {- value = htmlHelper.ViewData.TemplateInfo.FormattedModelValue;- }+ public static async Task<IHtmlContent> UrlInputTemplate(IHtmlHelper htmlHelper)+ {+ return await Task.FromResult(GenerateTextBox(htmlHelper, "url"));+ }- return await Task.FromResult(htmlHelper.Password(- expression: null,- value: value,- htmlAttributes: CreateHtmlAttributes(htmlHelper, "text-box single-line password")));- }+ public static async Task<IHtmlContent> EmailAddressInputTemplate(IHtmlHelper htmlHelper)+ {+ return await Task.FromResult(GenerateTextBox(htmlHelper, "email"));+ }- private static bool ShouldShow(ModelExplorer modelExplorer, TemplateInfo templateInfo)- {- return- modelExplorer.Metadata.ShowForEdit &&- !modelExplorer.Metadata.IsComplexType &&- !templateInfo.Visited(modelExplorer);- }+ public static async Task<IHtmlContent> DateTimeOffsetTemplate(IHtmlHelper htmlHelper)+ {+ ApplyRfc3339DateFormattingIfNeeded(htmlHelper, @"{0:yyyy-MM-ddTHH\:mm\:ss.fffK}");+ return await Task.FromResult(GenerateTextBox(htmlHelper, "text"));+ }- public static async Task<IHtmlContent> StringTemplate(IHtmlHelper htmlHelper)- {- return await Task.FromResult(GenerateTextBox(htmlHelper));- }+ public static async Task<IHtmlContent> DateTimeLocalInputTemplate(IHtmlHelper htmlHelper)+ {+ ApplyRfc3339DateFormattingIfNeeded(htmlHelper, @"{0:yyyy-MM-ddTHH\:mm\:ss.fff}");+ return await Task.FromResult(GenerateTextBox(htmlHelper, "datetime-local"));+ }- public static async Task<IHtmlContent> PhoneNumberInputTemplate(IHtmlHelper htmlHelper)- {- return await Task.FromResult(GenerateTextBox(htmlHelper, inputType: "tel"));- }+ public static async Task<IHtmlContent> DateInputTemplate(IHtmlHelper htmlHelper)+ {+ ApplyRfc3339DateFormattingIfNeeded(htmlHelper, "{0:yyyy-MM-dd}");+ return await Task.FromResult(GenerateTextBox(htmlHelper, "date"));+ }- public static async Task<IHtmlContent> UrlInputTemplate(IHtmlHelper htmlHelper)- {- return await Task.FromResult(GenerateTextBox(htmlHelper, inputType: "url"));- }+ public static async Task<IHtmlContent> TimeInputTemplate(IHtmlHelper htmlHelper)+ {+ ApplyRfc3339DateFormattingIfNeeded(htmlHelper, @"{0:HH\:mm\:ss.fff}");+ return await Task.FromResult(GenerateTextBox(htmlHelper, "time"));+ }- public static async Task<IHtmlContent> EmailAddressInputTemplate(IHtmlHelper htmlHelper)- {- return await Task.FromResult(GenerateTextBox(htmlHelper, inputType: "email"));- }+ public static async Task<IHtmlContent> MonthInputTemplate(IHtmlHelper htmlHelper)+ {+ // "month" is a new HTML5 input type that only will be rendered in Rfc3339 mode+ htmlHelper.Html5DateRenderingMode = Html5DateRenderingMode.Rfc3339;+ ApplyRfc3339DateFormattingIfNeeded(htmlHelper, "{0:yyyy-MM}");+ return await Task.FromResult(GenerateTextBox(htmlHelper, "month"));+ }- public static async Task<IHtmlContent> DateTimeOffsetTemplate(IHtmlHelper htmlHelper)- {- ApplyRfc3339DateFormattingIfNeeded(htmlHelper, @"{0:yyyy-MM-ddTHH\:mm\:ss.fffK}");- return await Task.FromResult(GenerateTextBox(htmlHelper, inputType: "text"));- }+ public static async Task<IHtmlContent> WeekInputTemplate(IHtmlHelper htmlHelper)+ {+ return await Task.FromResult(GenerateTextBox(htmlHelper, "week"));+ }- public static async Task<IHtmlContent> DateTimeLocalInputTemplate(IHtmlHelper htmlHelper)- {- ApplyRfc3339DateFormattingIfNeeded(htmlHelper, @"{0:yyyy-MM-ddTHH\:mm\:ss.fff}");- return await Task.FromResult(GenerateTextBox(htmlHelper, inputType: "datetime-local"));- }+ public static async Task<IHtmlContent> NumberInputTemplate(IHtmlHelper htmlHelper)+ {+ return await Task.FromResult(GenerateTextBox(htmlHelper, "number"));+ }- public static async Task<IHtmlContent> DateInputTemplate(IHtmlHelper htmlHelper)- {- ApplyRfc3339DateFormattingIfNeeded(htmlHelper, "{0:yyyy-MM-dd}");- return await Task.FromResult(GenerateTextBox(htmlHelper, inputType: "date"));- }+ public static async Task<IHtmlContent> FileInputTemplate(IHtmlHelper htmlHelper)+ {+ ArgumentNullException.ThrowIfNull(htmlHelper);- public static async Task<IHtmlContent> TimeInputTemplate(IHtmlHelper htmlHelper)- {- ApplyRfc3339DateFormattingIfNeeded(htmlHelper, @"{0:HH\:mm\:ss.fff}");- return await Task.FromResult(GenerateTextBox(htmlHelper, inputType: "time"));- }+ return await Task.FromResult(GenerateTextBox(htmlHelper, "file"));+ }- public static async Task<IHtmlContent> MonthInputTemplate(IHtmlHelper htmlHelper)- {- // "month" is a new HTML5 input type that only will be rendered in Rfc3339 mode- htmlHelper.Html5DateRenderingMode = Html5DateRenderingMode.Rfc3339;- ApplyRfc3339DateFormattingIfNeeded(htmlHelper, "{0:yyyy-MM}");- return await Task.FromResult(GenerateTextBox(htmlHelper, inputType: "month"));- }+ public static async Task<IHtmlContent> FileCollectionInputTemplate(IHtmlHelper htmlHelper)+ {+ ArgumentNullException.ThrowIfNull(htmlHelper);- public static async Task<IHtmlContent> WeekInputTemplate(IHtmlHelper htmlHelper)- {- return await Task.FromResult(GenerateTextBox(htmlHelper, inputType: "week"));- }+ var htmlAttributes =+ CreateHtmlAttributes(htmlHelper, "text-box single-line", "file");+ htmlAttributes["multiple"] = "multiple";- public static async Task<IHtmlContent> NumberInputTemplate(IHtmlHelper htmlHelper)- {- return await Task.FromResult(GenerateTextBox(htmlHelper, inputType: "number"));- }+ return await Task.FromResult(GenerateTextBox(htmlHelper, htmlHelper.ViewData.TemplateInfo.FormattedModelValue,+ htmlAttributes));+ }- public static async Task<IHtmlContent> FileInputTemplate(IHtmlHelper htmlHelper)- {- ArgumentNullException.ThrowIfNull(htmlHelper);+ private static void ApplyRfc3339DateFormattingIfNeeded(IHtmlHelper htmlHelper, string format)+ {+ if (htmlHelper.Html5DateRenderingMode != Html5DateRenderingMode.Rfc3339) return;- return await Task.FromResult(GenerateTextBox(htmlHelper, inputType: "file"));- }+ var metadata = htmlHelper.ViewData.ModelMetadata;+ var value = htmlHelper.ViewData.Model;+ if (htmlHelper.ViewData.TemplateInfo.FormattedModelValue != value && metadata.HasNonDefaultEditFormat) return;- public static async Task<IHtmlContent> FileCollectionInputTemplate(IHtmlHelper htmlHelper)- {- ArgumentNullException.ThrowIfNull(htmlHelper);+ if (value is DateTime || value is DateTimeOffset)+ htmlHelper.ViewData.TemplateInfo.FormattedModelValue =+ string.Format(CultureInfo.InvariantCulture, format, value);+ }- var htmlAttributes =- CreateHtmlAttributes(htmlHelper, className: "text-box single-line", inputType: "file");- htmlAttributes["multiple"] = "multiple";+ private static IHtmlContent GenerateTextBox(IHtmlHelper htmlHelper, string inputType = null)+ {+ return GenerateTextBox(htmlHelper, inputType, htmlHelper.ViewData.TemplateInfo.FormattedModelValue);+ }- return await Task.FromResult(GenerateTextBox(htmlHelper, htmlHelper.ViewData.TemplateInfo.FormattedModelValue, htmlAttributes));- }+ private static IHtmlContent GenerateTextBox(IHtmlHelper htmlHelper, string inputType, object value)+ {+ var htmlAttributes =+ CreateHtmlAttributes(htmlHelper, "text-box single-line", inputType);- private static void ApplyRfc3339DateFormattingIfNeeded(IHtmlHelper htmlHelper, string format)- {- if (htmlHelper.Html5DateRenderingMode != Html5DateRenderingMode.Rfc3339)- {- return;- }+ return GenerateTextBox(htmlHelper, value, htmlAttributes);+ }- var metadata = htmlHelper.ViewData.ModelMetadata;- var value = htmlHelper.ViewData.Model;- if (htmlHelper.ViewData.TemplateInfo.FormattedModelValue != value && metadata.HasNonDefaultEditFormat)- {- return;- }+ private static IHtmlContent GenerateTextBox(IHtmlHelper htmlHelper, object value, object htmlAttributes)+ {+ return htmlHelper.TextBox(+ null,+ value,+ null,+ htmlAttributes);+ }- if (value is DateTime || value is DateTimeOffset)- {- htmlHelper.ViewData.TemplateInfo.FormattedModelValue =- string.Format(CultureInfo.InvariantCulture, format, value);- }- }+ private class HasContentTextWriter : TextWriter+ {+ public bool HasContent { get; private set; }- private static IHtmlContent GenerateTextBox(IHtmlHelper htmlHelper, string inputType = null)- {- return GenerateTextBox(htmlHelper, inputType, htmlHelper.ViewData.TemplateInfo.FormattedModelValue);- }+ public override Encoding Encoding => Null.Encoding;- private static IHtmlContent GenerateTextBox(IHtmlHelper htmlHelper, string inputType, object value)+ public override void Write(char value){- var htmlAttributes =- CreateHtmlAttributes(htmlHelper, className: "text-box single-line", inputType: inputType);-- return GenerateTextBox(htmlHelper, value, htmlAttributes);+ HasContent = true;}- private static IHtmlContent GenerateTextBox(IHtmlHelper htmlHelper, object value, object htmlAttributes)+ public override void Write(char[] buffer, int index, int count){- return htmlHelper.TextBox(- expression: null,- value: value,- format: null,- htmlAttributes: htmlAttributes);+ if (count > 0) HasContent = true;}- private class HasContentTextWriter : TextWriter+ public override void Write(string value){- public bool HasContent { get; private set; }-- public override Encoding Encoding => Null.Encoding;-- public override void Write(char value)- {- HasContent = true;- }-- public override void Write(char[] buffer, int index, int count)- {- if (count > 0)- {- HasContent = true;- }- }-- public override void Write(string value)- {- if (!string.IsNullOrEmpty(value))- {- HasContent = true;- }- }+ if (!string.IsNullOrEmpty(value)) HasContent = true;}}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/DefaultHtmlGenerator.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/DefaultHtmlGenerator.csindex 883138822..b08dc3aee 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/DefaultHtmlGenerator.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/DefaultHtmlGenerator.cs@@ -16,1518 +16,1330 @@ using System.Globalization;using System.Reflection;using System.Text.Encodings.Web;-namespace Grand.Web.Common.TagHelpers.Admin.Extend+namespace Grand.Web.Common.TagHelpers.Admin.Extend;++public class DefaultHtmlGenerator : IHtmlGenerator{- public class DefaultHtmlGenerator : IHtmlGenerator+ private const string HiddenListItem = @"<li style=""display:none""></li>";++ private static readonly MethodInfo ConvertEnumFromStringMethod =+ typeof(DefaultHtmlGenerator).GetTypeInfo().GetDeclaredMethod(nameof(ConvertEnumFromString));++ // See: (http://www.w3.org/TR/html5/forms.html#the-input-element)+ private static readonly string[] _placeholderInputTypes =+ ["text", "search", "url", "tel", "email", "password", "number"];++ // See: (http://www.w3.org/TR/html5/sec-forms.html#apply)+ private static readonly string[] _maxLengthInputTypes =+ ["text", "search", "url", "tel", "email", "password"];++ private readonly IAntiforgery _antiforgery;+ private readonly HtmlEncoder _htmlEncoder;+ private readonly IModelMetadataProvider _metadataProvider;+ private readonly IUrlHelperFactory _urlHelperFactory;+ private readonly ValidationHtmlAttributeProvider _validationAttributeProvider;++ /// <summary>+ /// Initializes a new instance of the <see cref="DefaultHtmlGenerator" /> class.+ /// </summary>+ /// <param name="antiforgery">+ /// The <see cref="IAntiforgery" /> instance which is used to generate antiforgery+ /// tokens.+ /// </param>+ /// <param name="optionsAccessor">The accessor for <see cref="MvcViewOptions" />.</param>+ /// <param name="metadataProvider">The <see cref="IModelMetadataProvider" />.</param>+ /// <param name="urlHelperFactory">The <see cref="IUrlHelperFactory" />.</param>+ /// <param name="htmlEncoder">The <see cref="HtmlEncoder" />.</param>+ /// <param name="validationAttributeProvider">The <see cref="ValidationHtmlAttributeProvider" />.</param>+ public DefaultHtmlGenerator(+ IAntiforgery antiforgery,+ IOptions<MvcViewOptions> optionsAccessor,+ IModelMetadataProvider metadataProvider,+ IUrlHelperFactory urlHelperFactory,+ HtmlEncoder htmlEncoder,+ ValidationHtmlAttributeProvider validationAttributeProvider){- private const string HiddenListItem = @"<li style=""display:none""></li>";- private static readonly MethodInfo ConvertEnumFromStringMethod =- typeof(DefaultHtmlGenerator).GetTypeInfo().GetDeclaredMethod(nameof(ConvertEnumFromString));-- // See: (http://www.w3.org/TR/html5/forms.html#the-input-element)- private static readonly string[] _placeholderInputTypes =- ["text", "search", "url", "tel", "email", "password", "number"];-- // See: (http://www.w3.org/TR/html5/sec-forms.html#apply)- private static readonly string[] _maxLengthInputTypes =- ["text", "search", "url", "tel", "email", "password"];-- private readonly IAntiforgery _antiforgery;- private readonly IModelMetadataProvider _metadataProvider;- private readonly IUrlHelperFactory _urlHelperFactory;- private readonly HtmlEncoder _htmlEncoder;- private readonly ValidationHtmlAttributeProvider _validationAttributeProvider;-- /// <summary>- /// Initializes a new instance of the <see cref="DefaultHtmlGenerator"/> class.- /// </summary>- /// <param name="antiforgery">The <see cref="IAntiforgery"/> instance which is used to generate antiforgery- /// tokens.</param>- /// <param name="optionsAccessor">The accessor for <see cref="MvcViewOptions"/>.</param>- /// <param name="metadataProvider">The <see cref="IModelMetadataProvider"/>.</param>- /// <param name="urlHelperFactory">The <see cref="IUrlHelperFactory"/>.</param>- /// <param name="htmlEncoder">The <see cref="HtmlEncoder"/>.</param>- /// <param name="validationAttributeProvider">The <see cref="ValidationHtmlAttributeProvider"/>.</param>- public DefaultHtmlGenerator(- IAntiforgery antiforgery,- IOptions<MvcViewOptions> optionsAccessor,- IModelMetadataProvider metadataProvider,- IUrlHelperFactory urlHelperFactory,- HtmlEncoder htmlEncoder,- ValidationHtmlAttributeProvider validationAttributeProvider)- {- ArgumentNullException.ThrowIfNull(antiforgery);- ArgumentNullException.ThrowIfNull(optionsAccessor);- ArgumentNullException.ThrowIfNull(metadataProvider);- ArgumentNullException.ThrowIfNull(urlHelperFactory);- ArgumentNullException.ThrowIfNull(htmlEncoder);- ArgumentNullException.ThrowIfNull(validationAttributeProvider);-- _antiforgery = antiforgery;- _metadataProvider = metadataProvider;- _urlHelperFactory = urlHelperFactory;- _htmlEncoder = htmlEncoder;- _validationAttributeProvider = validationAttributeProvider;-- // Underscores are fine characters in id's.- IdAttributeDotReplacement = optionsAccessor.Value.HtmlHelperOptions.IdAttributeDotReplacement;- }+ ArgumentNullException.ThrowIfNull(antiforgery);+ ArgumentNullException.ThrowIfNull(optionsAccessor);+ ArgumentNullException.ThrowIfNull(metadataProvider);+ ArgumentNullException.ThrowIfNull(urlHelperFactory);+ ArgumentNullException.ThrowIfNull(htmlEncoder);+ ArgumentNullException.ThrowIfNull(validationAttributeProvider);++ _antiforgery = antiforgery;+ _metadataProvider = metadataProvider;+ _urlHelperFactory = urlHelperFactory;+ _htmlEncoder = htmlEncoder;+ _validationAttributeProvider = validationAttributeProvider;++ // Underscores are fine characters in id's.+ IdAttributeDotReplacement = optionsAccessor.Value.HtmlHelperOptions.IdAttributeDotReplacement;+ }- /// <summary>- /// Gets or sets a value that indicates whether the <c>maxlength</c> attribute should be rendered for- /// compatible HTML input elements, when they're bound to models marked with either- /// <see cref="StringLengthAttribute"/> or <see cref="MaxLengthAttribute"/> attributes.- /// </summary>- /// <value>The default value is <see langword="true"/>.</value>- /// <remarks>- /// <para>- /// If both attributes are specified, the one with the smaller value will be used for the rendered- /// <c>maxlength</c> attribute.- /// </para>- /// <para>- /// This property is currently ignored.- /// </para>- /// </remarks>- protected bool AllowRenderingMaxLengthAttribute { get; } = true;-- /// <inheritdoc />- public string IdAttributeDotReplacement { get; }-- /// <inheritdoc />- public string Encode(string value)- {- return !string.IsNullOrEmpty(value) ? _htmlEncoder.Encode(value) : string.Empty;- }+ /// <summary>+ /// Gets or sets a value that indicates whether the <c>maxlength</c> attribute should be rendered for+ /// compatible HTML input elements, when they're bound to models marked with either+ /// <see cref="StringLengthAttribute" /> or <see cref="MaxLengthAttribute" /> attributes.+ /// </summary>+ /// <value>The default value is <see langword="true" />.</value>+ /// <remarks>+ /// <para>+ /// If both attributes are specified, the one with the smaller value will be used for the rendered+ /// <c>maxlength</c> attribute.+ /// </para>+ /// <para>+ /// This property is currently ignored.+ /// </para>+ /// </remarks>+ protected bool AllowRenderingMaxLengthAttribute { get; } = true;++ /// <inheritdoc />+ public string IdAttributeDotReplacement { get; }++ /// <inheritdoc />+ public string Encode(string value)+ {+ return !string.IsNullOrEmpty(value) ? _htmlEncoder.Encode(value) : string.Empty;+ }- /// <inheritdoc />- public string Encode(object value)- {- return value != null ? _htmlEncoder.Encode(value.ToString()) : string.Empty;- }+ /// <inheritdoc />+ public string Encode(object value)+ {+ return value != null ? _htmlEncoder.Encode(value.ToString()) : string.Empty;+ }- /// <inheritdoc />- public string FormatValue(object value, string format)- {- return ViewDataDictionary.FormatValue(value, format);- }+ /// <inheritdoc />+ public string FormatValue(object value, string format)+ {+ return ViewDataDictionary.FormatValue(value, format);+ }- /// <inheritdoc />- public virtual TagBuilder GenerateActionLink(- ViewContext viewContext,- string linkText,- string actionName,- string controllerName,- string protocol,- string hostname,- string fragment,- object routeValues,- object htmlAttributes)- {- ArgumentNullException.ThrowIfNull(viewContext);- ArgumentNullException.ThrowIfNull(linkText);+ /// <inheritdoc />+ public virtual TagBuilder GenerateActionLink(+ ViewContext viewContext,+ string linkText,+ string actionName,+ string controllerName,+ string protocol,+ string hostname,+ string fragment,+ object routeValues,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);+ ArgumentNullException.ThrowIfNull(linkText);- var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext);- var url = urlHelper.Action(actionName, controllerName, routeValues, protocol, hostname, fragment);- return GenerateLink(linkText, url, htmlAttributes);- }+ var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext);+ var url = urlHelper.Action(actionName, controllerName, routeValues, protocol, hostname, fragment);+ return GenerateLink(linkText, url, htmlAttributes);+ }- /// <inheritdoc />- public virtual TagBuilder GeneratePageLink(- ViewContext viewContext,- string linkText,- string pageName,- string pageHandler,- string protocol,- string hostname,- string fragment,- object routeValues,- object htmlAttributes)- {- ArgumentNullException.ThrowIfNull(viewContext);- ArgumentNullException.ThrowIfNull(linkText);+ /// <inheritdoc />+ public virtual TagBuilder GeneratePageLink(+ ViewContext viewContext,+ string linkText,+ string pageName,+ string pageHandler,+ string protocol,+ string hostname,+ string fragment,+ object routeValues,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);+ ArgumentNullException.ThrowIfNull(linkText);- var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext);- var url = urlHelper.Page(pageName, pageHandler, routeValues, protocol, hostname, fragment);- return GenerateLink(linkText, url, htmlAttributes);- }+ var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext);+ var url = urlHelper.Page(pageName, pageHandler, routeValues, protocol, hostname, fragment);+ return GenerateLink(linkText, url, htmlAttributes);+ }++ /// <inheritdoc />+ public virtual IHtmlContent GenerateAntiforgery(ViewContext viewContext)+ {+ ArgumentNullException.ThrowIfNull(viewContext);- /// <inheritdoc />- public virtual IHtmlContent GenerateAntiforgery(ViewContext viewContext)+ var formContext = viewContext.FormContext;+ if (formContext.CanRenderAtEndOfForm){- ArgumentNullException.ThrowIfNull(viewContext);+ // Inside a BeginForm/BeginRouteForm or a <form> tag helper. So, the antiforgery token might have+ // already been created and appended to the 'end form' content (the AntiForgeryToken HTML helper does+ // this) OR the <form> tag helper might have already generated an antiforgery token.+ if (formContext.HasAntiforgeryToken) return HtmlString.Empty;- var formContext = viewContext.FormContext;- if (formContext.CanRenderAtEndOfForm)- {- // Inside a BeginForm/BeginRouteForm or a <form> tag helper. So, the antiforgery token might have- // already been created and appended to the 'end form' content (the AntiForgeryToken HTML helper does- // this) OR the <form> tag helper might have already generated an antiforgery token.- if (formContext.HasAntiforgeryToken)- {- return HtmlString.Empty;- }+ formContext.HasAntiforgeryToken = true;+ }- formContext.HasAntiforgeryToken = true;- }+ return _antiforgery.GetHtml(viewContext.HttpContext);+ }- return _antiforgery.GetHtml(viewContext.HttpContext);- }+ /// <inheritdoc />+ public virtual TagBuilder GenerateCheckBox(+ ViewContext viewContext,+ ModelExplorer modelExplorer,+ string expression,+ bool? isChecked,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);- /// <inheritdoc />- public virtual TagBuilder GenerateCheckBox(- ViewContext viewContext,- ModelExplorer modelExplorer,- string expression,- bool? isChecked,- object htmlAttributes)+ if (modelExplorer != null){- ArgumentNullException.ThrowIfNull(viewContext);+ // CheckBoxFor() case. That API does not support passing isChecked directly.+ Debug.Assert(!isChecked.HasValue);- if (modelExplorer != null)- {- // CheckBoxFor() case. That API does not support passing isChecked directly.- Debug.Assert(!isChecked.HasValue);+ if (modelExplorer.Model != null)+ if (bool.TryParse(modelExplorer.Model.ToString(), out var modelChecked))+ isChecked = modelChecked;+ }- if (modelExplorer.Model != null)- {- if (bool.TryParse(modelExplorer.Model.ToString(), out var modelChecked))- {- isChecked = modelChecked;- }- }- }+ var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);+ if (isChecked.HasValue && htmlAttributeDictionary != null)+ // Explicit isChecked value must override "checked" in dictionary.+ htmlAttributeDictionary.Remove("checked");++ // Use ViewData only in CheckBox case (metadata null) and when the user didn't pass an isChecked value.+ return GenerateInput(+ viewContext,+ InputType.CheckBox,+ modelExplorer,+ expression,+ "true",+ modelExplorer == null && !isChecked.HasValue,+ isChecked ?? false,+ true,+ false,+ null,+ htmlAttributeDictionary);+ }- var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);- if (isChecked.HasValue && htmlAttributeDictionary != null)- {- // Explicit isChecked value must override "checked" in dictionary.- htmlAttributeDictionary.Remove("checked");- }+ /// <inheritdoc />+ public virtual TagBuilder GenerateHiddenForCheckbox(+ ViewContext viewContext,+ ModelExplorer modelExplorer,+ string expression)+ {+ ArgumentNullException.ThrowIfNull(viewContext);- // Use ViewData only in CheckBox case (metadata null) and when the user didn't pass an isChecked value.- return GenerateInput(- viewContext,- InputType.CheckBox,- modelExplorer,- expression,- value: "true",- useViewData: modelExplorer == null && !isChecked.HasValue,- isChecked: isChecked ?? false,- setId: true,- isExplicitValue: false,- format: null,- htmlAttributes: htmlAttributeDictionary);- }+ var tagBuilder = new TagBuilder("input");+ tagBuilder.MergeAttribute("type", GetInputTypeString(InputType.Hidden));+ tagBuilder.MergeAttribute("value", "false");+ tagBuilder.TagRenderMode = TagRenderMode.SelfClosing;- /// <inheritdoc />- public virtual TagBuilder GenerateHiddenForCheckbox(- ViewContext viewContext,- ModelExplorer modelExplorer,- string expression)- {- ArgumentNullException.ThrowIfNull(viewContext);+ var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);+ if (!string.IsNullOrEmpty(fullName)) tagBuilder.MergeAttribute("name", fullName);- var tagBuilder = new TagBuilder("input");- tagBuilder.MergeAttribute("type", GetInputTypeString(InputType.Hidden));- tagBuilder.MergeAttribute("value", "false");- tagBuilder.TagRenderMode = TagRenderMode.SelfClosing;+ return tagBuilder;+ }- var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);- if (!string.IsNullOrEmpty(fullName))- {- tagBuilder.MergeAttribute("name", fullName);- }+ /// <inheritdoc />+ public virtual TagBuilder GenerateForm(+ ViewContext viewContext,+ string actionName,+ string controllerName,+ object routeValues,+ string method,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);- return tagBuilder;- }+ var defaultMethod = false;+ if (string.IsNullOrEmpty(method))+ defaultMethod = true;+ else if (string.Equals(method, "post", StringComparison.OrdinalIgnoreCase)) defaultMethod = true;- /// <inheritdoc />- public virtual TagBuilder GenerateForm(- ViewContext viewContext,- string actionName,- string controllerName,- object routeValues,- string method,- object htmlAttributes)+ string action;+ if (actionName == null && controllerName == null && routeValues == null && defaultMethod)+ {+ // Submit to the original URL in the special case that user called the BeginForm() overload without+ // parameters (except for the htmlAttributes parameter). Also reachable in the even-more-unusual case+ // that user called another BeginForm() overload with default argument values.+ var request = viewContext.HttpContext.Request;+ action = request.PathBase + request.Path + request.QueryString;+ }+ else{- ArgumentNullException.ThrowIfNull(viewContext);+ var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext);+ action = urlHelper.Action(actionName, controllerName, routeValues);+ }- var defaultMethod = false;- if (string.IsNullOrEmpty(method))- {- defaultMethod = true;- }- else if (string.Equals(method, "post", StringComparison.OrdinalIgnoreCase))- {- defaultMethod = true;- }+ return GenerateFormCore(viewContext, action, method, htmlAttributes);+ }- string action;- if (actionName == null && controllerName == null && routeValues == null && defaultMethod)- {- // Submit to the original URL in the special case that user called the BeginForm() overload without- // parameters (except for the htmlAttributes parameter). Also reachable in the even-more-unusual case- // that user called another BeginForm() overload with default argument values.- var request = viewContext.HttpContext.Request;- action = request.PathBase + request.Path + request.QueryString;- }- else- {- var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext);- action = urlHelper.Action(action: actionName, controller: controllerName, values: routeValues);- }+ /// <inheritdoc />+ public virtual TagBuilder GeneratePageForm(+ ViewContext viewContext,+ string pageName,+ string pageHandler,+ object routeValues,+ string fragment,+ string method,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);- return GenerateFormCore(viewContext, action, method, htmlAttributes);- }+ var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext);+ var action = urlHelper.Page(pageName, pageHandler, routeValues, null, null, fragment);- /// <inheritdoc />- public virtual TagBuilder GeneratePageForm(- ViewContext viewContext,- string pageName,- string pageHandler,- object routeValues,- string fragment,- string method,- object htmlAttributes)- {- ArgumentNullException.ThrowIfNull(viewContext);+ return GenerateFormCore(viewContext, action, method, htmlAttributes);+ }- var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext);- var action = urlHelper.Page(pageName, pageHandler, routeValues, protocol: null, host: null, fragment: fragment);+ /// <inheritdoc />+ public TagBuilder GenerateRouteForm(+ ViewContext viewContext,+ string routeName,+ object routeValues,+ string method,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);- return GenerateFormCore(viewContext, action, method, htmlAttributes);- }+ var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext);+ var action = urlHelper.RouteUrl(routeName, routeValues);- /// <inheritdoc />- public TagBuilder GenerateRouteForm(- ViewContext viewContext,- string routeName,- object routeValues,- string method,- object htmlAttributes)- {- ArgumentNullException.ThrowIfNull(viewContext);+ return GenerateFormCore(viewContext, action, method, htmlAttributes);+ }- var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext);- var action = urlHelper.RouteUrl(routeName, routeValues);+ /// <inheritdoc />+ public virtual TagBuilder GenerateHidden(+ ViewContext viewContext,+ ModelExplorer modelExplorer,+ string expression,+ object value,+ bool useViewData,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);++ // Special-case opaque values and arbitrary binary data.+ if (value is byte[] byteArrayValue) value = Convert.ToBase64String(byteArrayValue);++ var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);+ return GenerateInput(+ viewContext,+ InputType.Hidden,+ modelExplorer,+ expression,+ value,+ useViewData,+ false,+ true,+ true,+ null,+ htmlAttributeDictionary);+ }- return GenerateFormCore(viewContext, action, method, htmlAttributes);- }+ /// <inheritdoc />+ public virtual TagBuilder GenerateLabel(+ ViewContext viewContext,+ ModelExplorer modelExplorer,+ string expression,+ string labelText,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);+ ArgumentNullException.ThrowIfNull(modelExplorer);- /// <inheritdoc />- public virtual TagBuilder GenerateHidden(- ViewContext viewContext,- ModelExplorer modelExplorer,- string expression,- object value,- bool useViewData,- object htmlAttributes)+ var resolvedLabelText = labelText ??+ modelExplorer.Metadata.DisplayName ??+ modelExplorer.Metadata.PropertyName;+ if (resolvedLabelText == null && expression != null){- ArgumentNullException.ThrowIfNull(viewContext);+ var index = expression.LastIndexOf('.');+ // Expression does not contain a dot separator.+ resolvedLabelText = index == -1 ? expression : expression[(index + 1)..];+ }- // Special-case opaque values and arbitrary binary data.- if (value is byte[] byteArrayValue)- {- value = Convert.ToBase64String(byteArrayValue);- }+ var tagBuilder = new TagBuilder("label");+ var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);+ var idString = NameAndIdProvider.CreateSanitizedId(viewContext, fullName, IdAttributeDotReplacement);+ tagBuilder.Attributes.Add("for", idString);+ tagBuilder.InnerHtml.SetContent(resolvedLabelText);+ tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes), true);- var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);- return GenerateInput(- viewContext,- InputType.Hidden,- modelExplorer,- expression,- value,- useViewData,- isChecked: false,- setId: true,- isExplicitValue: true,- format: null,- htmlAttributes: htmlAttributeDictionary);- }+ return tagBuilder;+ }- /// <inheritdoc />- public virtual TagBuilder GenerateLabel(- ViewContext viewContext,- ModelExplorer modelExplorer,- string expression,- string labelText,- object htmlAttributes)- {- ArgumentNullException.ThrowIfNull(viewContext);- ArgumentNullException.ThrowIfNull(modelExplorer);+ /// <inheritdoc />+ public virtual TagBuilder GeneratePassword(+ ViewContext viewContext,+ ModelExplorer modelExplorer,+ string expression,+ object value,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);++ var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);+ return GenerateInput(+ viewContext,+ InputType.Password,+ modelExplorer,+ expression,+ value,+ false,+ false,+ true,+ true,+ null,+ htmlAttributeDictionary);+ }++ /// <inheritdoc />+ public virtual TagBuilder GenerateRadioButton(+ ViewContext viewContext,+ ModelExplorer modelExplorer,+ string expression,+ object value,+ bool? isChecked,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);- var resolvedLabelText = labelText ??- modelExplorer.Metadata.DisplayName ??- modelExplorer.Metadata.PropertyName;- if (resolvedLabelText == null && expression != null)+ var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);+ if (modelExplorer == null)+ {+ // RadioButton() case. Do not override checked attribute if isChecked is implicit.+ if (!isChecked.HasValue &&+ (htmlAttributeDictionary == null || !htmlAttributeDictionary.ContainsKey("checked"))){- var index = expression.LastIndexOf('.');- // Expression does not contain a dot separator.- resolvedLabelText = index == -1 ? expression : expression[(index + 1)..];+ // Note value may be null if isChecked is non-null.+ if (value == null) throw new ArgumentNullException(nameof(value));++ // isChecked not provided nor found in the given attributes; fall back to view data.+ var valueString = Convert.ToString(value, CultureInfo.CurrentCulture);+ isChecked = string.Equals(+ EvalString(viewContext, expression),+ valueString,+ StringComparison.OrdinalIgnoreCase);}+ }+ else+ {+ // RadioButtonFor() case. That API does not support passing isChecked directly.+ Debug.Assert(!isChecked.HasValue);- var tagBuilder = new TagBuilder("label");- var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);- var idString = NameAndIdProvider.CreateSanitizedId(viewContext, fullName, IdAttributeDotReplacement);- tagBuilder.Attributes.Add("for", idString);- tagBuilder.InnerHtml.SetContent(resolvedLabelText);- tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes), replaceExisting: true);+ // Need a value to determine isChecked.+ Debug.Assert(value != null);- return tagBuilder;+ var model = modelExplorer.Model;+ var valueString = Convert.ToString(value, CultureInfo.CurrentCulture);+ isChecked = model != null &&+ string.Equals(model.ToString(), valueString, StringComparison.OrdinalIgnoreCase);}- /// <inheritdoc />- public virtual TagBuilder GeneratePassword(- ViewContext viewContext,- ModelExplorer modelExplorer,- string expression,- object value,- object htmlAttributes)- {- ArgumentNullException.ThrowIfNull(viewContext);+ if (isChecked.HasValue && htmlAttributeDictionary != null)+ // Explicit isChecked value must override "checked" in dictionary.+ htmlAttributeDictionary.Remove("checked");++ return GenerateInput(+ viewContext,+ InputType.Radio,+ modelExplorer,+ expression,+ value,+ false,+ isChecked ?? false,+ true,+ true,+ null,+ htmlAttributeDictionary);+ }- var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);- return GenerateInput(- viewContext,- InputType.Password,- modelExplorer,- expression,- value,- useViewData: false,- isChecked: false,- setId: true,- isExplicitValue: true,- format: null,- htmlAttributes: htmlAttributeDictionary);- }+ /// <inheritdoc />+ public virtual TagBuilder GenerateRouteLink(+ ViewContext viewContext,+ string linkText,+ string routeName,+ string protocol,+ string hostName,+ string fragment,+ object routeValues,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);+ ArgumentNullException.ThrowIfNull(linkText);- /// <inheritdoc />- public virtual TagBuilder GenerateRadioButton(- ViewContext viewContext,- ModelExplorer modelExplorer,- string expression,- object value,- bool? isChecked,- object htmlAttributes)- {- ArgumentNullException.ThrowIfNull(viewContext);+ var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext);+ var url = urlHelper.RouteUrl(routeName, routeValues, protocol, hostName, fragment);+ return GenerateLink(linkText, url, htmlAttributes);+ }- var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);- if (modelExplorer == null)- {- // RadioButton() case. Do not override checked attribute if isChecked is implicit.- if (!isChecked.HasValue &&- (htmlAttributeDictionary == null || !htmlAttributeDictionary.ContainsKey("checked")))- {- // Note value may be null if isChecked is non-null.- if (value == null)- {- throw new ArgumentNullException(nameof(value));- }+ /// <inheritdoc />+ public TagBuilder GenerateSelect(+ ViewContext viewContext,+ ModelExplorer modelExplorer,+ string optionLabel,+ string expression,+ IEnumerable<SelectListItem> selectList,+ bool allowMultiple,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);++ var currentValues = GetCurrentValues(viewContext, modelExplorer, expression, allowMultiple);+ return GenerateSelect(+ viewContext,+ modelExplorer,+ optionLabel,+ expression,+ selectList,+ currentValues,+ allowMultiple,+ htmlAttributes);+ }- // isChecked not provided nor found in the given attributes; fall back to view data.- var valueString = Convert.ToString(value, CultureInfo.CurrentCulture);- isChecked = string.Equals(- EvalString(viewContext, expression),- valueString,- StringComparison.OrdinalIgnoreCase);- }- }- else- {- // RadioButtonFor() case. That API does not support passing isChecked directly.- Debug.Assert(!isChecked.HasValue);+ /// <inheritdoc />+ public virtual TagBuilder GenerateSelect(+ ViewContext viewContext,+ ModelExplorer modelExplorer,+ string optionLabel,+ string expression,+ IEnumerable<SelectListItem> selectList,+ ICollection<string> currentValues,+ bool allowMultiple,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);- // Need a value to determine isChecked.- Debug.Assert(value != null);+ var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);+ var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);+ if (!IsFullNameValid(fullName, htmlAttributeDictionary)) throw new ArgumentException("htmlFieldName");- var model = modelExplorer.Model;- var valueString = Convert.ToString(value, CultureInfo.CurrentCulture);- isChecked = model != null &&- string.Equals(model.ToString(), valueString, StringComparison.OrdinalIgnoreCase);- }+ // If we got a null selectList, try to use ViewData to get the list of items.+ selectList ??= GetSelectListItems(viewContext, expression);- if (isChecked.HasValue && htmlAttributeDictionary != null)- {- // Explicit isChecked value must override "checked" in dictionary.- htmlAttributeDictionary.Remove("checked");- }+ modelExplorer = modelExplorer ??+ ExpressionMetadataProvider.FromStringExpression(expression, viewContext.ViewData,+ _metadataProvider);- return GenerateInput(- viewContext,- InputType.Radio,- modelExplorer,- expression,- value,- useViewData: false,- isChecked: isChecked ?? false,- setId: true,- isExplicitValue: true,- format: null,- htmlAttributes: htmlAttributeDictionary);- }+ // Convert each ListItem to an <option> tag and wrap them with <optgroup> if requested.+ var listItemBuilder = GenerateGroupsAndOptions(optionLabel, selectList, currentValues);- /// <inheritdoc />- public virtual TagBuilder GenerateRouteLink(- ViewContext viewContext,- string linkText,- string routeName,- string protocol,- string hostName,- string fragment,- object routeValues,- object htmlAttributes)- {- ArgumentNullException.ThrowIfNull(viewContext);- ArgumentNullException.ThrowIfNull(linkText);+ var tagBuilder = new TagBuilder("select");+ tagBuilder.InnerHtml.SetHtmlContent(listItemBuilder);+ tagBuilder.MergeAttributes(htmlAttributeDictionary);+ NameAndIdProvider.GenerateId(viewContext, tagBuilder, fullName, IdAttributeDotReplacement);+ if (!string.IsNullOrEmpty(fullName)) tagBuilder.MergeAttribute("name", fullName, true);- var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext);- var url = urlHelper.RouteUrl(routeName, routeValues, protocol, hostName, fragment);- return GenerateLink(linkText, url, htmlAttributes);- }+ if (allowMultiple) tagBuilder.MergeAttribute("multiple", "multiple");- /// <inheritdoc />- public TagBuilder GenerateSelect(- ViewContext viewContext,- ModelExplorer modelExplorer,- string optionLabel,- string expression,- IEnumerable<SelectListItem> selectList,- bool allowMultiple,- object htmlAttributes)- {- ArgumentNullException.ThrowIfNull(viewContext);+ // If there are any errors for a named field, we add the css attribute.+ if (viewContext.ViewData.ModelState.TryGetValue(fullName, out var entry))+ if (entry.Errors.Count > 0)+ tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);- var currentValues = GetCurrentValues(viewContext, modelExplorer, expression, allowMultiple);- return GenerateSelect(- viewContext,- modelExplorer,- optionLabel,- expression,- selectList,- currentValues,- allowMultiple,- htmlAttributes);- }+ AddValidationAttributes(viewContext, tagBuilder, modelExplorer, expression);- /// <inheritdoc />- public virtual TagBuilder GenerateSelect(- ViewContext viewContext,- ModelExplorer modelExplorer,- string optionLabel,- string expression,- IEnumerable<SelectListItem> selectList,- ICollection<string> currentValues,- bool allowMultiple,- object htmlAttributes)- {- ArgumentNullException.ThrowIfNull(viewContext);+ return tagBuilder;+ }- var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);- var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);- if (!IsFullNameValid(fullName, htmlAttributeDictionary))- {- throw new ArgumentException("htmlFieldName");- }+ /// <inheritdoc />+ public virtual TagBuilder GenerateTextArea(+ ViewContext viewContext,+ ModelExplorer modelExplorer,+ string expression,+ int rows,+ int columns,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);- // If we got a null selectList, try to use ViewData to get the list of items.- selectList ??= GetSelectListItems(viewContext, expression);+ if (rows < 0) throw new ArgumentOutOfRangeException($"{nameof(rows)} TextAreaParameterOutOfRange");- modelExplorer = modelExplorer ??- ExpressionMetadataProvider.FromStringExpression(expression, viewContext.ViewData, _metadataProvider);+ if (columns < 0) throw new ArgumentOutOfRangeException(" nameof(columns) TextAreaParameterOutOfRange");- // Convert each ListItem to an <option> tag and wrap them with <optgroup> if requested.- var listItemBuilder = GenerateGroupsAndOptions(optionLabel, selectList, currentValues);+ var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);+ var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);+ if (!IsFullNameValid(fullName, htmlAttributeDictionary)) throw new ArgumentException("htmlFieldName");- var tagBuilder = new TagBuilder("select");- tagBuilder.InnerHtml.SetHtmlContent(listItemBuilder);- tagBuilder.MergeAttributes(htmlAttributeDictionary);- NameAndIdProvider.GenerateId(viewContext, tagBuilder, fullName, IdAttributeDotReplacement);- if (!string.IsNullOrEmpty(fullName))- {- tagBuilder.MergeAttribute("name", fullName, replaceExisting: true);- }+ viewContext.ViewData.ModelState.TryGetValue(fullName, out var entry);- if (allowMultiple)- {- tagBuilder.MergeAttribute("multiple", "multiple");- }+ var value = string.Empty;+ if (entry is { AttemptedValue: not null })+ value = entry.AttemptedValue;+ else if (modelExplorer.Model != null) value = modelExplorer.Model.ToString();- // If there are any errors for a named field, we add the css attribute.- if (viewContext.ViewData.ModelState.TryGetValue(fullName, out var entry))- {- if (entry.Errors.Count > 0)- {- tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);- }- }+ var tagBuilder = new TagBuilder("textarea");+ NameAndIdProvider.GenerateId(viewContext, tagBuilder, fullName, IdAttributeDotReplacement);+ tagBuilder.MergeAttributes(htmlAttributeDictionary, true);+ if (rows > 0) tagBuilder.MergeAttribute("rows", rows.ToString(CultureInfo.InvariantCulture), true);- AddValidationAttributes(viewContext, tagBuilder, modelExplorer, expression);+ if (columns > 0)+ tagBuilder.MergeAttribute(+ "cols",+ columns.ToString(CultureInfo.InvariantCulture),+ true);- return tagBuilder;- }+ if (!string.IsNullOrEmpty(fullName)) tagBuilder.MergeAttribute("name", fullName, true);- /// <inheritdoc />- public virtual TagBuilder GenerateTextArea(- ViewContext viewContext,- ModelExplorer modelExplorer,- string expression,- int rows,- int columns,- object htmlAttributes)- {- ArgumentNullException.ThrowIfNull(viewContext);+ AddPlaceholderAttribute(viewContext.ViewData, tagBuilder, modelExplorer, expression);+ AddMaxLengthAttribute(viewContext.ViewData, tagBuilder, modelExplorer, expression);+ AddValidationAttributes(viewContext, tagBuilder, modelExplorer, expression);- if (rows < 0)- {- throw new ArgumentOutOfRangeException($"{nameof(rows)} TextAreaParameterOutOfRange");- }+ // If there are any errors for a named field, we add this CSS attribute.+ if (entry is { Errors.Count: > 0 }) tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);- if (columns < 0)- {- throw new ArgumentOutOfRangeException(" nameof(columns) TextAreaParameterOutOfRange");- }+ // The first newline is always trimmed when a TextArea is rendered, so we add an extra one+ // in case the value being rendered is something like "\r\nHello"+ tagBuilder.InnerHtml.AppendLine();+ tagBuilder.InnerHtml.Append(value);- var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);- var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);- if (!IsFullNameValid(fullName, htmlAttributeDictionary))- {- throw new ArgumentException("htmlFieldName");- }+ return tagBuilder;+ }- viewContext.ViewData.ModelState.TryGetValue(fullName, out var entry);+ /// <inheritdoc />+ public virtual TagBuilder GenerateTextBox(+ ViewContext viewContext,+ ModelExplorer modelExplorer,+ string expression,+ object value,+ string format,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);++ var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);+ return GenerateInput(+ viewContext,+ InputType.Text,+ modelExplorer,+ expression,+ value,+ modelExplorer == null && value == null,+ false,+ true,+ true,+ format,+ htmlAttributeDictionary);+ }- var value = string.Empty;- if (entry is { AttemptedValue: not null })- {- value = entry.AttemptedValue;- }- else if (modelExplorer.Model != null)- {- value = modelExplorer.Model.ToString();- }+ /// <inheritdoc />+ public virtual TagBuilder GenerateValidationMessage(+ ViewContext viewContext,+ ModelExplorer modelExplorer,+ string expression,+ string message,+ string tag,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);- var tagBuilder = new TagBuilder("textarea");- NameAndIdProvider.GenerateId(viewContext, tagBuilder, fullName, IdAttributeDotReplacement);- tagBuilder.MergeAttributes(htmlAttributeDictionary, replaceExisting: true);- if (rows > 0)- {- tagBuilder.MergeAttribute("rows", rows.ToString(CultureInfo.InvariantCulture), replaceExisting: true);- }+ var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);+ var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);+ if (!IsFullNameValid(fullName, htmlAttributeDictionary, "data-valmsg-for"))+ throw new ArgumentException("htmlFieldName");- if (columns > 0)- {- tagBuilder.MergeAttribute(- "cols",- columns.ToString(CultureInfo.InvariantCulture),- replaceExisting: true);- }+ var formContext = viewContext.ClientValidationEnabled ? viewContext.FormContext : null;+ if (!viewContext.ViewData.ModelState.ContainsKey(fullName) && formContext == null) return null;- if (!string.IsNullOrEmpty(fullName))- {- tagBuilder.MergeAttribute("name", fullName, replaceExisting: true);- }+ var tryGetModelStateResult = viewContext.ViewData.ModelState.TryGetValue(fullName, out var entry);+ var modelErrors = tryGetModelStateResult ? entry.Errors : null;- AddPlaceholderAttribute(viewContext.ViewData, tagBuilder, modelExplorer, expression);- AddMaxLengthAttribute(viewContext.ViewData, tagBuilder, modelExplorer, expression);- AddValidationAttributes(viewContext, tagBuilder, modelExplorer, expression);+ ModelError modelError = null;+ if (modelErrors != null && modelErrors.Count != 0)+ modelError = modelErrors.FirstOrDefault(m => !string.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0];- // If there are any errors for a named field, we add this CSS attribute.- if (entry is { Errors.Count: > 0 })- {- tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);- }+ if (modelError == null && formContext == null) return null;- // The first newline is always trimmed when a TextArea is rendered, so we add an extra one- // in case the value being rendered is something like "\r\nHello"- tagBuilder.InnerHtml.AppendLine();- tagBuilder.InnerHtml.Append(value);+ // Even if there are no model errors, we generate the span and add the validation message+ // if formContext is not null.+ if (string.IsNullOrEmpty(tag)) tag = viewContext.ValidationMessageElement;- return tagBuilder;- }+ var tagBuilder = new TagBuilder(tag);+ tagBuilder.MergeAttributes(htmlAttributeDictionary);- /// <inheritdoc />- public virtual TagBuilder GenerateTextBox(- ViewContext viewContext,- ModelExplorer modelExplorer,- string expression,- object value,- string format,- object htmlAttributes)- {- ArgumentNullException.ThrowIfNull(viewContext);+ // Only the style of the span is changed according to the errors if message is null or empty.+ // Otherwise the content and style is handled by the client-side validation.+ var className = modelError != null+ ? HtmlHelper.ValidationMessageCssClassName+ : HtmlHelper.ValidationMessageValidCssClassName;+ tagBuilder.AddCssClass(className);- var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);- return GenerateInput(- viewContext,- InputType.Text,- modelExplorer,+ if (!string.IsNullOrEmpty(message))+ {+ tagBuilder.InnerHtml.SetContent(message);+ }+ else if (modelError != null)+ {+ modelExplorer = modelExplorer ?? ExpressionMetadataProvider.FromStringExpression(expression,- value,- useViewData: modelExplorer == null && value == null,- isChecked: false,- setId: true,- isExplicitValue: true,- format: format,- htmlAttributes: htmlAttributeDictionary);+ viewContext.ViewData,+ _metadataProvider);+ tagBuilder.InnerHtml.SetContent(+ ValidationHelpers.GetModelErrorMessageOrDefault(modelError, entry, modelExplorer));}- /// <inheritdoc />- public virtual TagBuilder GenerateValidationMessage(- ViewContext viewContext,- ModelExplorer modelExplorer,- string expression,- string message,- string tag,- object htmlAttributes)+ if (formContext != null){- ArgumentNullException.ThrowIfNull(viewContext);+ if (!string.IsNullOrEmpty(fullName)) tagBuilder.MergeAttribute("data-valmsg-for", fullName);- var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);- var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes);- if (!IsFullNameValid(fullName, htmlAttributeDictionary, fallbackAttributeName: "data-valmsg-for"))- {- throw new ArgumentException("htmlFieldName");- }+ var replaceValidationMessageContents = string.IsNullOrEmpty(message);+ tagBuilder.MergeAttribute("data-valmsg-replace",+ replaceValidationMessageContents.ToString().ToLowerInvariant());+ }- var formContext = viewContext.ClientValidationEnabled ? viewContext.FormContext : null;- if (!viewContext.ViewData.ModelState.ContainsKey(fullName) && formContext == null)- {- return null;- }+ return tagBuilder;+ }- var tryGetModelStateResult = viewContext.ViewData.ModelState.TryGetValue(fullName, out var entry);- var modelErrors = tryGetModelStateResult ? entry.Errors : null;+ /// <inheritdoc />+ public virtual TagBuilder GenerateValidationSummary(+ ViewContext viewContext,+ bool excludePropertyErrors,+ string message,+ string headerTag,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);- ModelError modelError = null;- if (modelErrors != null && modelErrors.Count != 0)- {- modelError = modelErrors.FirstOrDefault(m => !string.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0];- }+ var viewData = viewContext.ViewData;+ if (!viewContext.ClientValidationEnabled && viewData.ModelState.IsValid)+ // Client-side validation is not enabled to add to the generated element and element will be empty.+ return null;- if (modelError == null && formContext == null)- {- return null;- }+ if (excludePropertyErrors &&+ (!viewData.ModelState.TryGetValue(viewData.TemplateInfo.HtmlFieldPrefix, out var entryForModel) ||+ entryForModel.Errors.Count == 0))+ // Client-side validation (if enabled) will not affect the generated element and element will be empty.+ return null;- // Even if there are no model errors, we generate the span and add the validation message- // if formContext is not null.- if (string.IsNullOrEmpty(tag))- {- tag = viewContext.ValidationMessageElement;- }+ TagBuilder messageTag;+ if (string.IsNullOrEmpty(message))+ {+ messageTag = null;+ }+ else+ {+ if (string.IsNullOrEmpty(headerTag)) headerTag = viewContext.ValidationSummaryMessageElement;- var tagBuilder = new TagBuilder(tag);- tagBuilder.MergeAttributes(htmlAttributeDictionary);+ messageTag = new TagBuilder(headerTag);+ messageTag.InnerHtml.SetContent(message);+ }- // Only the style of the span is changed according to the errors if message is null or empty.- // Otherwise the content and style is handled by the client-side validation.- var className = modelError != null ?- HtmlHelper.ValidationMessageCssClassName :- HtmlHelper.ValidationMessageValidCssClassName;- tagBuilder.AddCssClass(className);+ // If excludePropertyErrors is true, describe any validation issue with the current model in a single item.+ // Otherwise, list individual property errors.+ var isHtmlSummaryModified = false;+ var modelStates = ValidationHelpers.GetModelStateList(viewData, excludePropertyErrors);- if (!string.IsNullOrEmpty(message))- {- tagBuilder.InnerHtml.SetContent(message);- }- else if (modelError != null)+ var htmlSummary = new TagBuilder("ul");+ foreach (var modelState in modelStates)+ // Perf: Avoid allocations+ for (var i = 0; i < modelState.Errors.Count; i++){- modelExplorer = modelExplorer ?? ExpressionMetadataProvider.FromStringExpression(- expression,- viewContext.ViewData,- _metadataProvider);- tagBuilder.InnerHtml.SetContent(- ValidationHelpers.GetModelErrorMessageOrDefault(modelError, entry, modelExplorer));- }+ var modelError = modelState.Errors[i];+ var errorText = ValidationHelpers.GetModelErrorMessageOrDefault(modelError);- if (formContext != null)- {- if (!string.IsNullOrEmpty(fullName))+ if (!string.IsNullOrEmpty(errorText)){- tagBuilder.MergeAttribute("data-valmsg-for", fullName);+ var listItem = new TagBuilder("li");+ listItem.InnerHtml.SetContent(errorText);+ htmlSummary.InnerHtml.AppendLine(listItem);+ isHtmlSummaryModified = true;}-- var replaceValidationMessageContents = string.IsNullOrEmpty(message);- tagBuilder.MergeAttribute("data-valmsg-replace",- replaceValidationMessageContents.ToString().ToLowerInvariant());}- return tagBuilder;- }-- /// <inheritdoc />- public virtual TagBuilder GenerateValidationSummary(- ViewContext viewContext,- bool excludePropertyErrors,- string message,- string headerTag,- object htmlAttributes)+ if (!isHtmlSummaryModified){- ArgumentNullException.ThrowIfNull(viewContext);-- var viewData = viewContext.ViewData;- if (!viewContext.ClientValidationEnabled && viewData.ModelState.IsValid)- {- // Client-side validation is not enabled to add to the generated element and element will be empty.- return null;- }-- if (excludePropertyErrors &&- (!viewData.ModelState.TryGetValue(viewData.TemplateInfo.HtmlFieldPrefix, out var entryForModel) ||- entryForModel.Errors.Count == 0))- {- // Client-side validation (if enabled) will not affect the generated element and element will be empty.- return null;- }+ htmlSummary.InnerHtml.AppendHtml(HiddenListItem);+ htmlSummary.InnerHtml.AppendLine();+ }- TagBuilder messageTag;- if (string.IsNullOrEmpty(message))- {- messageTag = null;- }- else- {- if (string.IsNullOrEmpty(headerTag))- {- headerTag = viewContext.ValidationSummaryMessageElement;- }+ var tagBuilder = new TagBuilder("div");+ tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes));- messageTag = new TagBuilder(headerTag);- messageTag.InnerHtml.SetContent(message);- }+ tagBuilder.AddCssClass(viewData.ModelState.IsValid+ ? HtmlHelper.ValidationSummaryValidCssClassName+ : HtmlHelper.ValidationSummaryCssClassName);- // If excludePropertyErrors is true, describe any validation issue with the current model in a single item.- // Otherwise, list individual property errors.- var isHtmlSummaryModified = false;- var modelStates = ValidationHelpers.GetModelStateList(viewData, excludePropertyErrors);+ if (messageTag != null) tagBuilder.InnerHtml.AppendLine(messageTag);- var htmlSummary = new TagBuilder("ul");- foreach (var modelState in modelStates)- {- // Perf: Avoid allocations- for (var i = 0; i < modelState.Errors.Count; i++)- {- var modelError = modelState.Errors[i];- var errorText = ValidationHelpers.GetModelErrorMessageOrDefault(modelError);+ tagBuilder.InnerHtml.AppendHtml(htmlSummary);- if (!string.IsNullOrEmpty(errorText))- {- var listItem = new TagBuilder("li");- listItem.InnerHtml.SetContent(errorText);- htmlSummary.InnerHtml.AppendLine(listItem);- isHtmlSummaryModified = true;- }- }- }+ if (viewContext.ClientValidationEnabled && !excludePropertyErrors)+ // Inform the client where to replace the list of property errors after validation.+ tagBuilder.MergeAttribute("data-valmsg-summary", "true");- if (!isHtmlSummaryModified)- {- htmlSummary.InnerHtml.AppendHtml(HiddenListItem);- htmlSummary.InnerHtml.AppendLine();- }+ return tagBuilder;+ }- var tagBuilder = new TagBuilder("div");- tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes));+ /// <inheritdoc />+ public virtual ICollection<string> GetCurrentValues(+ ViewContext viewContext,+ ModelExplorer modelExplorer,+ string expression,+ bool allowMultiple)+ {+ ArgumentNullException.ThrowIfNull(viewContext);- tagBuilder.AddCssClass(viewData.ModelState.IsValid- ? HtmlHelper.ValidationSummaryValidCssClassName- : HtmlHelper.ValidationSummaryCssClassName);+ var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);+ var type = allowMultiple ? typeof(string[]) : typeof(string);+ var rawValue = GetModelStateValue(viewContext, fullName, type);- if (messageTag != null)+ // If ModelState did not contain a current value, fall back to ViewData- or ModelExplorer-supplied value.+ if (rawValue == null)+ {+ if (modelExplorer == null){- tagBuilder.InnerHtml.AppendLine(messageTag);+ // Html.DropDownList() and Html.ListBox() helper case.+ rawValue = viewContext.ViewData.Eval(expression);+ if (rawValue is IEnumerable<SelectListItem>)+ // This ViewData item contains the fallback selectList collection for GenerateSelect().+ // Do not try to use this collection.+ rawValue = null;}-- tagBuilder.InnerHtml.AppendHtml(htmlSummary);-- if (viewContext.ClientValidationEnabled && !excludePropertyErrors)+ else{- // Inform the client where to replace the list of property errors after validation.- tagBuilder.MergeAttribute("data-valmsg-summary", "true");+ // <select/>, Html.DropDownListFor() and Html.ListBoxFor() helper case. Do not use ViewData.+ rawValue = modelExplorer.Model;}- return tagBuilder;+ if (rawValue == null) return null;}- /// <inheritdoc />- public virtual ICollection<string> GetCurrentValues(- ViewContext viewContext,- ModelExplorer modelExplorer,- string expression,- bool allowMultiple)+ // Convert raw value to a collection.+ IEnumerable rawValues;+ if (allowMultiple){- ArgumentNullException.ThrowIfNull(viewContext);-- var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);- var type = allowMultiple ? typeof(string[]) : typeof(string);- var rawValue = GetModelStateValue(viewContext, fullName, type);-- // If ModelState did not contain a current value, fall back to ViewData- or ModelExplorer-supplied value.- if (rawValue == null)- {- if (modelExplorer == null)- {- // Html.DropDownList() and Html.ListBox() helper case.- rawValue = viewContext.ViewData.Eval(expression);- if (rawValue is IEnumerable<SelectListItem>)- {- // This ViewData item contains the fallback selectList collection for GenerateSelect().- // Do not try to use this collection.- rawValue = null;- }- }- else- {- // <select/>, Html.DropDownListFor() and Html.ListBoxFor() helper case. Do not use ViewData.- rawValue = modelExplorer.Model;- }+ rawValues = rawValue as IEnumerable;+ if (rawValues == null || rawValues is string)+ throw new InvalidOperationException("SelectExpressionNotEnumerable");+ }+ else+ {+ rawValues = new[] { rawValue };+ }- if (rawValue == null)- {- return null;- }- }+ modelExplorer = modelExplorer ??+ ExpressionMetadataProvider.FromStringExpression(expression, viewContext.ViewData,+ _metadataProvider);+ var metadata = modelExplorer.Metadata;+ if (allowMultiple && metadata.IsEnumerableType) metadata = metadata.ElementMetadata;- // Convert raw value to a collection.- IEnumerable rawValues;- if (allowMultiple)- {- rawValues = rawValue as IEnumerable;- if (rawValues == null || rawValues is string)- {- throw new InvalidOperationException("SelectExpressionNotEnumerable");- }- }- else- {- rawValues = new[] { rawValue };- }+ var enumNames = metadata.EnumNamesAndValues;+ var isTargetEnum = metadata.IsEnum;- modelExplorer = modelExplorer ??- ExpressionMetadataProvider.FromStringExpression(expression, viewContext.ViewData, _metadataProvider);- var metadata = modelExplorer.Metadata;- if (allowMultiple && metadata.IsEnumerableType)- {- metadata = metadata.ElementMetadata;- }+ // Logic below assumes isTargetEnum and enumNames are consistent. Confirm that expectation is met.+ Debug.Assert(isTargetEnum ^ (enumNames == null));- var enumNames = metadata.EnumNamesAndValues;- var isTargetEnum = metadata.IsEnum;+ var innerType = metadata.UnderlyingOrModelType;- // Logic below assumes isTargetEnum and enumNames are consistent. Confirm that expectation is met.- Debug.Assert(isTargetEnum ^ enumNames == null);+ // Convert raw value collection to strings.+ var currentValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase);+ foreach (var value in rawValues)+ {+ // Add original or converted string.+ var stringValue = value as string ?? Convert.ToString(value, CultureInfo.CurrentCulture);- var innerType = metadata.UnderlyingOrModelType;+ // Do not add simple names of enum properties here because whitespace isn't relevant for their binding.+ // Will add matching names just below.+ if (enumNames == null || !enumNames.ContainsKey(stringValue.Trim())) currentValues.Add(stringValue);- // Convert raw value collection to strings.- var currentValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase);- foreach (var value in rawValues)+ // Remainder handles isEnum cases. Convert.ToString() returns field names for enum values but select+ // list may (well, should) contain integer values.+ var enumValue = value as Enum;+ if (isTargetEnum && enumValue == null && value != null){- // Add original or converted string.- var stringValue = value as string ?? Convert.ToString(value, CultureInfo.CurrentCulture);-- // Do not add simple names of enum properties here because whitespace isn't relevant for their binding.- // Will add matching names just below.- if (enumNames == null || !enumNames.ContainsKey(stringValue.Trim()))+ var valueType = value.GetType();+ if (typeof(long).IsAssignableFrom(valueType) || typeof(ulong).IsAssignableFrom(valueType)){- currentValues.Add(stringValue);+ // E.g. user added an int to a ViewData entry and called a string-based HTML helper.+ enumValue = ConvertEnumFromInteger(value, innerType);}-- // Remainder handles isEnum cases. Convert.ToString() returns field names for enum values but select- // list may (well, should) contain integer values.- var enumValue = value as Enum;- if (isTargetEnum && enumValue == null && value != null)+ else if (!string.IsNullOrEmpty(stringValue)){- var valueType = value.GetType();- if (typeof(long).IsAssignableFrom(valueType) || typeof(ulong).IsAssignableFrom(valueType))- {- // E.g. user added an int to a ViewData entry and called a string-based HTML helper.- enumValue = ConvertEnumFromInteger(value, innerType);- }- else if (!string.IsNullOrEmpty(stringValue))- {- // E.g. got a string from ModelState.- var methodInfo = ConvertEnumFromStringMethod.MakeGenericMethod(innerType);- enumValue = (Enum)methodInfo.Invoke(obj: null, parameters: [stringValue]);- }+ // E.g. got a string from ModelState.+ var methodInfo = ConvertEnumFromStringMethod.MakeGenericMethod(innerType);+ enumValue = (Enum)methodInfo.Invoke(null, [stringValue]);}+ }- if (enumValue != null)- {- // Add integer value.- var integerString = enumValue.ToString("d");- currentValues.Add(integerString);+ if (enumValue != null)+ {+ // Add integer value.+ var integerString = enumValue.ToString("d");+ currentValues.Add(integerString);- // isTargetEnum may be false when raw value has a different type than the target e.g. ViewData- // contains enum values and property has type int or string.- if (isTargetEnum)- {- // Add all simple names for this value.- var matchingNames = enumNames- .Where(kvp => string.Equals(integerString, kvp.Value, StringComparison.Ordinal))- .Select(kvp => kvp.Key);- foreach (var name in matchingNames)- {- currentValues.Add(name);- }- }+ // isTargetEnum may be false when raw value has a different type than the target e.g. ViewData+ // contains enum values and property has type int or string.+ if (isTargetEnum)+ {+ // Add all simple names for this value.+ var matchingNames = enumNames+ .Where(kvp => string.Equals(integerString, kvp.Value, StringComparison.Ordinal))+ .Select(kvp => kvp.Key);+ foreach (var name in matchingNames) currentValues.Add(name);}}-- return currentValues;}- internal static string EvalString(ViewContext viewContext, string key, string format)- {- return Convert.ToString(viewContext.ViewData.Eval(key, format), CultureInfo.CurrentCulture);- }+ return currentValues;+ }- /// <remarks>- /// Not used directly in HtmlHelper. Exposed for use in DefaultDisplayTemplates.- /// </remarks>- internal static TagBuilder GenerateOption(SelectListItem item, string text)- {- return GenerateOption(item, text, item.Selected);- }+ /// <inheritdoc />+ public IHtmlContent GenerateGroupsAndOptions(string optionLabel, IEnumerable<SelectListItem> selectList)+ {+ return GenerateGroupsAndOptions(optionLabel, selectList, null);+ }- internal static TagBuilder GenerateOption(SelectListItem item, string text, bool selected)- {- var tagBuilder = new TagBuilder("option");- tagBuilder.InnerHtml.SetContent(text);+ internal static string EvalString(ViewContext viewContext, string key, string format)+ {+ return Convert.ToString(viewContext.ViewData.Eval(key, format), CultureInfo.CurrentCulture);+ }- if (item.Value != null)- {- tagBuilder.Attributes["value"] = item.Value;- }+ /// <remarks>+ /// Not used directly in HtmlHelper. Exposed for use in DefaultDisplayTemplates.+ /// </remarks>+ internal static TagBuilder GenerateOption(SelectListItem item, string text)+ {+ return GenerateOption(item, text, item.Selected);+ }- if (selected)- {- tagBuilder.Attributes["selected"] = "selected";- }+ internal static TagBuilder GenerateOption(SelectListItem item, string text, bool selected)+ {+ var tagBuilder = new TagBuilder("option");+ tagBuilder.InnerHtml.SetContent(text);- if (item.Disabled)- {- tagBuilder.Attributes["disabled"] = "disabled";- }+ if (item.Value != null) tagBuilder.Attributes["value"] = item.Value;- return tagBuilder;- }+ if (selected) tagBuilder.Attributes["selected"] = "selected";- internal static object GetModelStateValue(ViewContext viewContext, string key, Type destinationType)- {- //if (viewContext.ViewData.ModelState.TryGetValue(key, out var entry) && entry.RawValue != null)- //{- // return ModelBindingHelper.ConvertTo(entry.RawValue, destinationType, culture: null);- //}+ if (item.Disabled) tagBuilder.Attributes["disabled"] = "disabled";- return null;- }+ return tagBuilder;+ }- /// <summary>- /// Generate a <form> element.- /// </summary>- /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param>- /// <param name="action">The URL where the form-data should be submitted.</param>- /// <param name="method">The HTTP method for processing the form, either GET or POST.</param>- /// <param name="htmlAttributes">- /// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an- /// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes.- /// </param>- /// <returns>- /// A <see cref="TagBuilder"/> instance for the </form> element.- /// </returns>- protected virtual TagBuilder GenerateFormCore(- ViewContext viewContext,- string action,- string method,- object htmlAttributes)- {- ArgumentNullException.ThrowIfNull(viewContext);+ internal static object GetModelStateValue(ViewContext viewContext, string key, Type destinationType)+ {+ //if (viewContext.ViewData.ModelState.TryGetValue(key, out var entry) && entry.RawValue != null)+ //{+ // return ModelBindingHelper.ConvertTo(entry.RawValue, destinationType, culture: null);+ //}- var tagBuilder = new TagBuilder("form");- tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes));+ return null;+ }- // action is implicitly generated from other parameters, so htmlAttributes take precedence.- tagBuilder.MergeAttribute("action", action);+ /// <summary>+ /// Generate a <form> element.+ /// </summary>+ /// <param name="viewContext">A <see cref="ViewContext" /> instance for the current scope.</param>+ /// <param name="action">The URL where the form-data should be submitted.</param>+ /// <param name="method">The HTTP method for processing the form, either GET or POST.</param>+ /// <param name="htmlAttributes">+ /// An <see cref="object" /> that contains the HTML attributes for the element. Alternatively, an+ /// <see cref="IDictionary{String, Object}" /> instance containing the HTML attributes.+ /// </param>+ /// <returns>+ /// A <see cref="TagBuilder" /> instance for the </form> element.+ /// </returns>+ protected virtual TagBuilder GenerateFormCore(+ ViewContext viewContext,+ string action,+ string method,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);- if (string.IsNullOrEmpty(method))- {- // Occurs only when called from a tag helper.- method = "post";- }+ var tagBuilder = new TagBuilder("form");+ tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes));- // For tag helpers, htmlAttributes will be null; replaceExisting value does not matter.- // method is an explicit parameter to HTML helpers, so it takes precedence over the htmlAttributes.- tagBuilder.MergeAttribute("method", method, replaceExisting: true);+ // action is implicitly generated from other parameters, so htmlAttributes take precedence.+ tagBuilder.MergeAttribute("action", action);- return tagBuilder;- }+ if (string.IsNullOrEmpty(method))+ // Occurs only when called from a tag helper.+ method = "post";- protected virtual TagBuilder GenerateInput(- ViewContext viewContext,- InputType inputType,- ModelExplorer modelExplorer,- string expression,- object value,- bool useViewData,- bool isChecked,- bool setId,- bool isExplicitValue,- string format,- IDictionary<string, object> htmlAttributes)- {- ArgumentNullException.ThrowIfNull(viewContext);+ // For tag helpers, htmlAttributes will be null; replaceExisting value does not matter.+ // method is an explicit parameter to HTML helpers, so it takes precedence over the htmlAttributes.+ tagBuilder.MergeAttribute("method", method, true);- // Not valid to use TextBoxForModel() and so on in a top-level view; would end up with an unnamed input- // elements. But we support the *ForModel() methods in any lower-level template, once HtmlFieldPrefix is- // non-empty.- var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);- if (!IsFullNameValid(fullName, htmlAttributes))- {- throw new ArgumentException($"htmlFieldName {nameof(expression)}");- }+ return tagBuilder;+ }- var inputTypeString = GetInputTypeString(inputType);- var tagBuilder = new TagBuilder("input") {- TagRenderMode = TagRenderMode.SelfClosing- };+ protected virtual TagBuilder GenerateInput(+ ViewContext viewContext,+ InputType inputType,+ ModelExplorer modelExplorer,+ string expression,+ object value,+ bool useViewData,+ bool isChecked,+ bool setId,+ bool isExplicitValue,+ string format,+ IDictionary<string, object> htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(viewContext);++ // Not valid to use TextBoxForModel() and so on in a top-level view; would end up with an unnamed input+ // elements. But we support the *ForModel() methods in any lower-level template, once HtmlFieldPrefix is+ // non-empty.+ var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);+ if (!IsFullNameValid(fullName, htmlAttributes))+ throw new ArgumentException($"htmlFieldName {nameof(expression)}");++ var inputTypeString = GetInputTypeString(inputType);+ var tagBuilder = new TagBuilder("input") {+ TagRenderMode = TagRenderMode.SelfClosing+ };++ tagBuilder.MergeAttributes(htmlAttributes);+ tagBuilder.MergeAttribute("type", inputTypeString);+ if (!string.IsNullOrEmpty(fullName)) tagBuilder.MergeAttribute("name", fullName, true);++ var suppliedTypeString = tagBuilder.Attributes["type"];+ if (_placeholderInputTypes.Contains(suppliedTypeString))+ AddPlaceholderAttribute(viewContext.ViewData, tagBuilder, modelExplorer, expression);- tagBuilder.MergeAttributes(htmlAttributes);- tagBuilder.MergeAttribute("type", inputTypeString);- if (!string.IsNullOrEmpty(fullName))- {- tagBuilder.MergeAttribute("name", fullName, replaceExisting: true);- }+ if (_maxLengthInputTypes.Contains(suppliedTypeString))+ AddMaxLengthAttribute(viewContext.ViewData, tagBuilder, modelExplorer, expression);- var suppliedTypeString = tagBuilder.Attributes["type"];- if (_placeholderInputTypes.Contains(suppliedTypeString))- {- AddPlaceholderAttribute(viewContext.ViewData, tagBuilder, modelExplorer, expression);- }+ var valueParameter = FormatValue(value, format);+ var usedModelState = false;+ switch (inputType)+ {+ case InputType.CheckBox:+ var modelStateWasChecked = GetModelStateValue(viewContext, fullName, typeof(bool)) as bool?;+ if (modelStateWasChecked.HasValue)+ {+ isChecked = modelStateWasChecked.Value;+ usedModelState = true;+ }- if (_maxLengthInputTypes.Contains(suppliedTypeString))- {- AddMaxLengthAttribute(viewContext.ViewData, tagBuilder, modelExplorer, expression);- }+ goto case InputType.Radio;- var valueParameter = FormatValue(value, format);- var usedModelState = false;- switch (inputType)- {- case InputType.CheckBox:- var modelStateWasChecked = GetModelStateValue(viewContext, fullName, typeof(bool)) as bool?;- if (modelStateWasChecked.HasValue)+ case InputType.Radio:+ if (!usedModelState)+ if (GetModelStateValue(viewContext, fullName, typeof(string)) is string modelStateValue){- isChecked = modelStateWasChecked.Value;+ isChecked = string.Equals(modelStateValue, valueParameter, StringComparison.Ordinal);usedModelState = true;}- goto case InputType.Radio;-- case InputType.Radio:- if (!usedModelState)- {- if (GetModelStateValue(viewContext, fullName, typeof(string)) is string modelStateValue)- {- isChecked = string.Equals(modelStateValue, valueParameter, StringComparison.Ordinal);- usedModelState = true;- }- }-- if (!usedModelState && useViewData)- {- isChecked = EvalBoolean(viewContext, expression);- }-- if (isChecked)- {- tagBuilder.MergeAttribute("checked", "checked");- }+ if (!usedModelState && useViewData) isChecked = EvalBoolean(viewContext, expression);- tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue);- break;+ if (isChecked) tagBuilder.MergeAttribute("checked", "checked");- case InputType.Password:- if (value != null)- {- tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue);- }+ tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue);+ break;- break;+ case InputType.Password:+ if (value != null) tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue);- case InputType.Text:- default:- var attributeValue = (string)GetModelStateValue(viewContext, fullName, typeof(string)) ?? (useViewData ? EvalString(viewContext, expression, format) : valueParameter);+ break;- var addValue = true;- object typeAttributeValue;- if (htmlAttributes != null && htmlAttributes.TryGetValue("type", out typeAttributeValue))- {- var typeAttributeString = typeAttributeValue.ToString();- if (string.Equals(typeAttributeString, "file", StringComparison.OrdinalIgnoreCase) ||- string.Equals(typeAttributeString, "image", StringComparison.OrdinalIgnoreCase))- {- // 'value' attribute is not needed for 'file' and 'image' input types.- addValue = false;- }- }+ case InputType.Text:+ default:+ var attributeValue = (string)GetModelStateValue(viewContext, fullName, typeof(string)) ??+ (useViewData ? EvalString(viewContext, expression, format) : valueParameter);- if (addValue)- {- tagBuilder.MergeAttribute("value", attributeValue, replaceExisting: isExplicitValue);- }+ var addValue = true;+ object typeAttributeValue;+ if (htmlAttributes != null && htmlAttributes.TryGetValue("type", out typeAttributeValue))+ {+ var typeAttributeString = typeAttributeValue.ToString();+ if (string.Equals(typeAttributeString, "file", StringComparison.OrdinalIgnoreCase) ||+ string.Equals(typeAttributeString, "image", StringComparison.OrdinalIgnoreCase))+ // 'value' attribute is not needed for 'file' and 'image' input types.+ addValue = false;+ }- break;- }+ if (addValue) tagBuilder.MergeAttribute("value", attributeValue, isExplicitValue);- if (setId)- {- NameAndIdProvider.GenerateId(viewContext, tagBuilder, fullName, IdAttributeDotReplacement);- }+ break;+ }- // If there are any errors for a named field, we add the CSS attribute.- if (viewContext.ViewData.ModelState.TryGetValue(fullName, out var entry) && entry.Errors.Count > 0)- {- tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);- }+ if (setId) NameAndIdProvider.GenerateId(viewContext, tagBuilder, fullName, IdAttributeDotReplacement);- AddValidationAttributes(viewContext, tagBuilder, modelExplorer, expression);+ // If there are any errors for a named field, we add the CSS attribute.+ if (viewContext.ViewData.ModelState.TryGetValue(fullName, out var entry) && entry.Errors.Count > 0)+ tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);- return tagBuilder;- }+ AddValidationAttributes(viewContext, tagBuilder, modelExplorer, expression);- protected virtual TagBuilder GenerateLink(- string linkText,- string url,- object htmlAttributes)- {- ArgumentNullException.ThrowIfNull(linkText);+ return tagBuilder;+ }- var tagBuilder = new TagBuilder("a");- tagBuilder.InnerHtml.SetContent(linkText);+ protected virtual TagBuilder GenerateLink(+ string linkText,+ string url,+ object htmlAttributes)+ {+ ArgumentNullException.ThrowIfNull(linkText);- tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes));- tagBuilder.MergeAttribute("href", url);+ var tagBuilder = new TagBuilder("a");+ tagBuilder.InnerHtml.SetContent(linkText);- return tagBuilder;- }+ tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes));+ tagBuilder.MergeAttribute("href", url);- /// <summary>- /// Adds a placeholder attribute to the <paramref name="tagBuilder" />.- /// </summary>- /// <param name="viewData">A <see cref="ViewDataDictionary"/> instance for the current scope.</param>- /// <param name="tagBuilder">A <see cref="TagBuilder"/> instance.</param>- /// <param name="modelExplorer">The <see cref="ModelExplorer"/> for the <paramref name="expression"/>.</param>- /// <param name="expression">Expression name, relative to the current model.</param>- protected virtual void AddPlaceholderAttribute(- ViewDataDictionary viewData,- TagBuilder tagBuilder,- ModelExplorer modelExplorer,- string expression)- {- modelExplorer = modelExplorer ?? ExpressionMetadataProvider.FromStringExpression(- expression,- viewData,- _metadataProvider);+ return tagBuilder;+ }- var placeholder = modelExplorer.Metadata.Placeholder;- if (!string.IsNullOrEmpty(placeholder))- {- tagBuilder.MergeAttribute("placeholder", placeholder);- }- }+ /// <summary>+ /// Adds a placeholder attribute to the <paramref name="tagBuilder" />.+ /// </summary>+ /// <param name="viewData">A <see cref="ViewDataDictionary" /> instance for the current scope.</param>+ /// <param name="tagBuilder">A <see cref="TagBuilder" /> instance.</param>+ /// <param name="modelExplorer">The <see cref="ModelExplorer" /> for the <paramref name="expression" />.</param>+ /// <param name="expression">Expression name, relative to the current model.</param>+ protected virtual void AddPlaceholderAttribute(+ ViewDataDictionary viewData,+ TagBuilder tagBuilder,+ ModelExplorer modelExplorer,+ string expression)+ {+ modelExplorer = modelExplorer ?? ExpressionMetadataProvider.FromStringExpression(+ expression,+ viewData,+ _metadataProvider);- /// <summary>- /// Adds a <c>maxlength</c> attribute to the <paramref name="tagBuilder" />.- /// </summary>- /// <param name="viewData">A <see cref="ViewDataDictionary"/> instance for the current scope.</param>- /// <param name="tagBuilder">A <see cref="TagBuilder"/> instance.</param>- /// <param name="modelExplorer">The <see cref="ModelExplorer"/> for the <paramref name="expression"/>.</param>- /// <param name="expression">Expression name, relative to the current model.</param>- protected virtual void AddMaxLengthAttribute(- ViewDataDictionary viewData,- TagBuilder tagBuilder,- ModelExplorer modelExplorer,- string expression)- {- modelExplorer = modelExplorer ?? ExpressionMetadataProvider.FromStringExpression(- expression,- viewData,- _metadataProvider);+ var placeholder = modelExplorer.Metadata.Placeholder;+ if (!string.IsNullOrEmpty(placeholder)) tagBuilder.MergeAttribute("placeholder", placeholder);+ }- int? maxLengthValue = null;- foreach (var attribute in modelExplorer.Metadata.ValidatorMetadata)- {- if (attribute is MaxLengthAttribute maxLengthAttribute && (!maxLengthValue.HasValue || maxLengthValue.Value > maxLengthAttribute.Length))- {- maxLengthValue = maxLengthAttribute.Length;- }- else if (attribute is StringLengthAttribute stringLengthAttribute && (!maxLengthValue.HasValue || maxLengthValue.Value > stringLengthAttribute.MaximumLength))- {- maxLengthValue = stringLengthAttribute.MaximumLength;- }- }+ /// <summary>+ /// Adds a <c>maxlength</c> attribute to the <paramref name="tagBuilder" />.+ /// </summary>+ /// <param name="viewData">A <see cref="ViewDataDictionary" /> instance for the current scope.</param>+ /// <param name="tagBuilder">A <see cref="TagBuilder" /> instance.</param>+ /// <param name="modelExplorer">The <see cref="ModelExplorer" /> for the <paramref name="expression" />.</param>+ /// <param name="expression">Expression name, relative to the current model.</param>+ protected virtual void AddMaxLengthAttribute(+ ViewDataDictionary viewData,+ TagBuilder tagBuilder,+ ModelExplorer modelExplorer,+ string expression)+ {+ modelExplorer = modelExplorer ?? ExpressionMetadataProvider.FromStringExpression(+ expression,+ viewData,+ _metadataProvider);++ int? maxLengthValue = null;+ foreach (var attribute in modelExplorer.Metadata.ValidatorMetadata)+ if (attribute is MaxLengthAttribute maxLengthAttribute &&+ (!maxLengthValue.HasValue || maxLengthValue.Value > maxLengthAttribute.Length))+ maxLengthValue = maxLengthAttribute.Length;+ else if (attribute is StringLengthAttribute stringLengthAttribute && (!maxLengthValue.HasValue ||+ maxLengthValue.Value > stringLengthAttribute.MaximumLength))+ maxLengthValue = stringLengthAttribute.MaximumLength;++ if (maxLengthValue.HasValue) tagBuilder.MergeAttribute("maxlength", maxLengthValue.Value.ToString());+ }- if (maxLengthValue.HasValue)- {- tagBuilder.MergeAttribute("maxlength", maxLengthValue.Value.ToString());- }- }+ /// <summary>+ /// Adds validation attributes to the <paramref name="tagBuilder" /> if client validation+ /// is enabled.+ /// </summary>+ /// <param name="viewContext">A <see cref="ViewContext" /> instance for the current scope.</param>+ /// <param name="tagBuilder">A <see cref="TagBuilder" /> instance.</param>+ /// <param name="modelExplorer">The <see cref="ModelExplorer" /> for the <paramref name="expression" />.</param>+ /// <param name="expression">Expression name, relative to the current model.</param>+ protected virtual void AddValidationAttributes(+ ViewContext viewContext,+ TagBuilder tagBuilder,+ ModelExplorer modelExplorer,+ string expression)+ {+ modelExplorer = modelExplorer ?? ExpressionMetadataProvider.FromStringExpression(+ expression,+ viewContext.ViewData,+ _metadataProvider);++ _validationAttributeProvider.AddAndTrackValidationAttributes(+ viewContext,+ modelExplorer,+ expression,+ tagBuilder.Attributes);+ }- /// <summary>- /// Adds validation attributes to the <paramref name="tagBuilder" /> if client validation- /// is enabled.- /// </summary>- /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param>- /// <param name="tagBuilder">A <see cref="TagBuilder"/> instance.</param>- /// <param name="modelExplorer">The <see cref="ModelExplorer"/> for the <paramref name="expression"/>.</param>- /// <param name="expression">Expression name, relative to the current model.</param>- protected virtual void AddValidationAttributes(- ViewContext viewContext,- TagBuilder tagBuilder,- ModelExplorer modelExplorer,- string expression)+ private static Enum ConvertEnumFromInteger(object value, Type targetType)+ {+ try{- modelExplorer = modelExplorer ?? ExpressionMetadataProvider.FromStringExpression(- expression,- viewContext.ViewData,- _metadataProvider);-- _validationAttributeProvider.AddAndTrackValidationAttributes(- viewContext,- modelExplorer,- expression,- tagBuilder.Attributes);+ return (Enum)Enum.ToObject(targetType, value);}-- private static Enum ConvertEnumFromInteger(object value, Type targetType)- {- try- {- return (Enum)Enum.ToObject(targetType, value);- }- catch (Exception exception)+ catch (Exception exception)when (exception is FormatException || exception.InnerException is FormatException)- {- // The integer was too large for this enum type.- return null;- }- }-- private static object ConvertEnumFromString<TEnum>(string value) where TEnum : struct{- if (Enum.TryParse(value, out TEnum enumValue))- {- return enumValue;- }-- // Do not return default(TEnum) when parse was unsuccessful.+ // The integer was too large for this enum type.return null;}+ }- private static bool EvalBoolean(ViewContext viewContext, string key)- {- return Convert.ToBoolean(viewContext.ViewData.Eval(key), CultureInfo.InvariantCulture);- }-- private static string EvalString(ViewContext viewContext, string key)- {- return Convert.ToString(viewContext.ViewData.Eval(key), CultureInfo.CurrentCulture);- }+ private static object ConvertEnumFromString<TEnum>(string value) where TEnum : struct+ {+ if (Enum.TryParse(value, out TEnum enumValue)) return enumValue;- // Only need a dictionary if htmlAttributes is non-null. TagBuilder.MergeAttributes() is fine with null.- private static IDictionary<string, object> GetHtmlAttributeDictionaryOrNull(object htmlAttributes)- {- IDictionary<string, object> htmlAttributeDictionary = null;- if (htmlAttributes != null)- {- htmlAttributeDictionary = htmlAttributes as IDictionary<string, object> ?? HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);- }+ // Do not return default(TEnum) when parse was unsuccessful.+ return null;+ }- return htmlAttributeDictionary;- }+ private static bool EvalBoolean(ViewContext viewContext, string key)+ {+ return Convert.ToBoolean(viewContext.ViewData.Eval(key), CultureInfo.InvariantCulture);+ }- private static string GetInputTypeString(InputType inputType)- {- switch (inputType)- {- case InputType.CheckBox:- return "checkbox";- case InputType.Hidden:- return "hidden";- case InputType.Password:- return "password";- case InputType.Radio:- return "radio";- case InputType.Text:- return "text";- default:- return "text";- }- }+ private static string EvalString(ViewContext viewContext, string key)+ {+ return Convert.ToString(viewContext.ViewData.Eval(key), CultureInfo.CurrentCulture);+ }- private static IEnumerable<SelectListItem> GetSelectListItems(- ViewContext viewContext,- string expression)- {- ArgumentNullException.ThrowIfNull(viewContext);+ // Only need a dictionary if htmlAttributes is non-null. TagBuilder.MergeAttributes() is fine with null.+ private static IDictionary<string, object> GetHtmlAttributeDictionaryOrNull(object htmlAttributes)+ {+ IDictionary<string, object> htmlAttributeDictionary = null;+ if (htmlAttributes != null)+ htmlAttributeDictionary = htmlAttributes as IDictionary<string, object> ??+ HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);- // Method is called only if user did not pass a select list in. They must provide select list items in the- // ViewData dictionary and definitely not as the Model. (Even if the Model datatype were correct, a- // <select> element generated for a collection of SelectListItems would be useless.)- var value = viewContext.ViewData.Eval(expression);+ return htmlAttributeDictionary;+ }- // First check whether above evaluation was successful and did not match ViewData.Model.- if (value == null || value == viewContext.ViewData.Model)- {- throw new InvalidOperationException($"IEnumerable<{nameof(SelectListItem)}>");- }+ private static string GetInputTypeString(InputType inputType)+ {+ switch (inputType)+ {+ case InputType.CheckBox:+ return "checkbox";+ case InputType.Hidden:+ return "hidden";+ case InputType.Password:+ return "password";+ case InputType.Radio:+ return "radio";+ case InputType.Text:+ return "text";+ default:+ return "text";+ }+ }- // Second check the Eval() call returned a collection of SelectListItems.- if (!(value is IEnumerable<SelectListItem> selectList))- {- throw new InvalidOperationException($"{value.GetType().FullName}");- }+ private static IEnumerable<SelectListItem> GetSelectListItems(+ ViewContext viewContext,+ string expression)+ {+ ArgumentNullException.ThrowIfNull(viewContext);- return selectList;- }+ // Method is called only if user did not pass a select list in. They must provide select list items in the+ // ViewData dictionary and definitely not as the Model. (Even if the Model datatype were correct, a+ // <select> element generated for a collection of SelectListItems would be useless.)+ var value = viewContext.ViewData.Eval(expression);- private static bool IsFullNameValid(string fullName, IDictionary<string, object> htmlAttributeDictionary)- {- return IsFullNameValid(fullName, htmlAttributeDictionary, fallbackAttributeName: "name");- }+ // First check whether above evaluation was successful and did not match ViewData.Model.+ if (value == null || value == viewContext.ViewData.Model)+ throw new InvalidOperationException($"IEnumerable<{nameof(SelectListItem)}>");- private static bool IsFullNameValid(- string fullName,- IDictionary<string, object> htmlAttributeDictionary,- string fallbackAttributeName)- {- if (string.IsNullOrEmpty(fullName))- {- // fullName==null is normally an error because name="" is not valid in HTML 5.- if (htmlAttributeDictionary == null)- {- return false;- }+ // Second check the Eval() call returned a collection of SelectListItems.+ if (!(value is IEnumerable<SelectListItem> selectList))+ throw new InvalidOperationException($"{value.GetType().FullName}");- // Check if user has provided an explicit name attribute.- // Generalized a bit because other attributes e.g. data-valmsg-for refer to element names.- htmlAttributeDictionary.TryGetValue(fallbackAttributeName, out var attributeObject);- var attributeString = Convert.ToString(attributeObject, CultureInfo.InvariantCulture);- if (string.IsNullOrEmpty(attributeString))- {- return false;- }- }+ return selectList;+ }- return true;- }+ private static bool IsFullNameValid(string fullName, IDictionary<string, object> htmlAttributeDictionary)+ {+ return IsFullNameValid(fullName, htmlAttributeDictionary, "name");+ }- /// <inheritdoc />- public IHtmlContent GenerateGroupsAndOptions(string optionLabel, IEnumerable<SelectListItem> selectList)+ private static bool IsFullNameValid(+ string fullName,+ IDictionary<string, object> htmlAttributeDictionary,+ string fallbackAttributeName)+ {+ if (string.IsNullOrEmpty(fullName)){- return GenerateGroupsAndOptions(optionLabel, selectList, currentValues: null);+ // fullName==null is normally an error because name="" is not valid in HTML 5.+ if (htmlAttributeDictionary == null) return false;++ // Check if user has provided an explicit name attribute.+ // Generalized a bit because other attributes e.g. data-valmsg-for refer to element names.+ htmlAttributeDictionary.TryGetValue(fallbackAttributeName, out var attributeObject);+ var attributeString = Convert.ToString(attributeObject, CultureInfo.InvariantCulture);+ if (string.IsNullOrEmpty(attributeString)) return false;}- private IHtmlContent GenerateGroupsAndOptions(- string optionLabel,- IEnumerable<SelectListItem> selectList,- ICollection<string> currentValues)- {- if (!(selectList is IList<SelectListItem> itemsList))- {- itemsList = selectList.ToList();- }-- var count = itemsList.Count;- if (optionLabel != null)- {- count++;- }+ return true;+ }- // Short-circuit work below if there's nothing to add.- if (count == 0)- {- return HtmlString.Empty;- }+ private IHtmlContent GenerateGroupsAndOptions(+ string optionLabel,+ IEnumerable<SelectListItem> selectList,+ ICollection<string> currentValues)+ {+ if (!(selectList is IList<SelectListItem> itemsList)) itemsList = selectList.ToList();++ var count = itemsList.Count;+ if (optionLabel != null) count++;++ // Short-circuit work below if there's nothing to add.+ if (count == 0) return HtmlString.Empty;++ var listItemBuilder = new HtmlContentBuilder(count);++ // Make optionLabel the first item that gets rendered.+ if (optionLabel != null)+ listItemBuilder.AppendLine(GenerateOption(+ new SelectListItem {+ Text = optionLabel,+ Value = string.Empty,+ Selected = false+ },+ currentValues: null));++ // Group items in the SelectList if requested.+ // The worst case complexity of this algorithm is O(number of groups*n).+ // If there aren't any groups, it is O(n) where n is number of items in the list.+ var optionGenerated = new bool[itemsList.Count];+ for (var i = 0; i < itemsList.Count; i++)+ if (!optionGenerated[i])+ {+ var item = itemsList[i];+ var optGroup = item.Group;+ if (optGroup != null)+ {+ var groupBuilder = new TagBuilder("optgroup");+ if (optGroup.Name != null) groupBuilder.MergeAttribute("label", optGroup.Name);- var listItemBuilder = new HtmlContentBuilder(count);+ if (optGroup.Disabled) groupBuilder.MergeAttribute("disabled", "disabled");- // Make optionLabel the first item that gets rendered.- if (optionLabel != null)- {- listItemBuilder.AppendLine(GenerateOption(- new SelectListItem {- Text = optionLabel,- Value = string.Empty,- Selected = false- },- currentValues: null));- }+ groupBuilder.InnerHtml.AppendLine();- // Group items in the SelectList if requested.- // The worst case complexity of this algorithm is O(number of groups*n).- // If there aren't any groups, it is O(n) where n is number of items in the list.- var optionGenerated = new bool[itemsList.Count];- for (var i = 0; i < itemsList.Count; i++)- {- if (!optionGenerated[i])- {- var item = itemsList[i];- var optGroup = item.Group;- if (optGroup != null)+ for (var j = i; j < itemsList.Count; j++){- var groupBuilder = new TagBuilder("optgroup");- if (optGroup.Name != null)- {- groupBuilder.MergeAttribute("label", optGroup.Name);- }-- if (optGroup.Disabled)- {- groupBuilder.MergeAttribute("disabled", "disabled");- }+ var groupItem = itemsList[j];- groupBuilder.InnerHtml.AppendLine();-- for (var j = i; j < itemsList.Count; j++)+ if (!optionGenerated[j] &&+ ReferenceEquals(optGroup, groupItem.Group)){- var groupItem = itemsList[j];-- if (!optionGenerated[j] &&- object.ReferenceEquals(optGroup, groupItem.Group))- {- groupBuilder.InnerHtml.AppendLine(GenerateOption(groupItem, currentValues));- optionGenerated[j] = true;- }+ groupBuilder.InnerHtml.AppendLine(GenerateOption(groupItem, currentValues));+ optionGenerated[j] = true;}-- listItemBuilder.AppendLine(groupBuilder);- }- else- {- listItemBuilder.AppendLine(GenerateOption(item, currentValues));- optionGenerated[i] = true;}++ listItemBuilder.AppendLine(groupBuilder);+ }+ else+ {+ listItemBuilder.AppendLine(GenerateOption(item, currentValues));+ optionGenerated[i] = true;}}- return listItemBuilder;- }+ return listItemBuilder;+ }- private IHtmlContent GenerateOption(SelectListItem item, ICollection<string> currentValues)+ private IHtmlContent GenerateOption(SelectListItem item, ICollection<string> currentValues)+ {+ var selected = item.Selected;+ if (currentValues != null){- var selected = item.Selected;- if (currentValues != null)- {- var value = item.Value ?? item.Text;- selected = currentValues.Contains(value);- }-- var tagBuilder = GenerateOption(item, item.Text, selected);- return tagBuilder;+ var value = item.Value ?? item.Text;+ selected = currentValues.Contains(value);}++ var tagBuilder = GenerateOption(item, item.Text, selected);+ return tagBuilder;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ExpressionHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ExpressionHelper.csindex 2e70214b3..6707fdd7b 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ExpressionHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ExpressionHelper.cs@@ -6,4 +6,5 @@// internal class ExpressionHelper// {// }-//}\ No newline at end of file+//}+diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ExpressionMetadataProvider.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ExpressionMetadataProvider.csindex a6ef536a5..aa92799a2 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ExpressionMetadataProvider.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ExpressionMetadataProvider.cs@@ -5,96 +5,88 @@ using Microsoft.AspNetCore.Mvc.ModelBinding;using Microsoft.AspNetCore.Mvc.ViewFeatures;using System.Globalization;-namespace Grand.Web.Common.TagHelpers.Admin.Extend+namespace Grand.Web.Common.TagHelpers.Admin.Extend;++internal static class ExpressionMetadataProvider{- internal static class ExpressionMetadataProvider+ /// <summary>+ /// Gets <see cref="ModelExplorer" /> for named <paramref name="expression" /> in given+ /// <paramref name="viewData" />.+ /// </summary>+ /// <param name="expression">Expression name, relative to <c>viewData.Model</c>.</param>+ /// <param name="viewData">+ /// The <see cref="ViewDataDictionary" /> that may contain the <paramref name="expression" /> value.+ /// </param>+ /// <param name="metadataProvider">The <see cref="IModelMetadataProvider" />.</param>+ /// <returns>+ /// <see cref="ModelExplorer" /> for named <paramref name="expression" /> in given <paramref name="viewData" />.+ /// </returns>+ public static ModelExplorer FromStringExpression(+ string expression,+ ViewDataDictionary viewData,+ IModelMetadataProvider metadataProvider){- /// <summary>- /// Gets <see cref="ModelExplorer"/> for named <paramref name="expression"/> in given- /// <paramref name="viewData"/>.- /// </summary>- /// <param name="expression">Expression name, relative to <c>viewData.Model</c>.</param>- /// <param name="viewData">- /// The <see cref="ViewDataDictionary"/> that may contain the <paramref name="expression"/> value.- /// </param>- /// <param name="metadataProvider">The <see cref="IModelMetadataProvider"/>.</param>- /// <returns>- /// <see cref="ModelExplorer"/> for named <paramref name="expression"/> in given <paramref name="viewData"/>.- /// </returns>- public static ModelExplorer FromStringExpression(- string expression,- ViewDataDictionary viewData,- IModelMetadataProvider metadataProvider)- {- ArgumentNullException.ThrowIfNull(viewData);-- var viewDataInfo = ViewDataEvaluator.Eval(viewData, expression);- if (viewDataInfo == null)- {- // Try getting a property from ModelMetadata if we couldn't find an answer in ViewData- var propertyExplorer = viewData.ModelExplorer.GetExplorerForProperty(expression);- if (propertyExplorer != null)- {- return propertyExplorer;- }- }+ ArgumentNullException.ThrowIfNull(viewData);- if (viewDataInfo != null)- {- if (viewDataInfo.Container == viewData &&- viewDataInfo.Value == viewData.Model &&- string.IsNullOrEmpty(expression))- {- // Nothing for empty expression in ViewData and ViewDataEvaluator just returned the model. Handle- // using FromModel() for its object special case.- return FromModel(viewData, metadataProvider);- }+ var viewDataInfo = ViewDataEvaluator.Eval(viewData, expression);+ if (viewDataInfo == null)+ {+ // Try getting a property from ModelMetadata if we couldn't find an answer in ViewData+ var propertyExplorer = viewData.ModelExplorer.GetExplorerForProperty(expression);+ if (propertyExplorer != null) return propertyExplorer;+ }- ModelExplorer containerExplorer = viewData.ModelExplorer;- if (viewDataInfo.Container != null)- {- containerExplorer = metadataProvider.GetModelExplorerForType(- viewDataInfo.Container.GetType(),- viewDataInfo.Container);- }+ if (viewDataInfo != null)+ {+ if (viewDataInfo.Container == viewData &&+ viewDataInfo.Value == viewData.Model &&+ string.IsNullOrEmpty(expression))+ // Nothing for empty expression in ViewData and ViewDataEvaluator just returned the model. Handle+ // using FromModel() for its object special case.+ return FromModel(viewData, metadataProvider);- if (viewDataInfo.PropertyInfo != null)- {- // We've identified a property access, which provides us with accurate metadata.- var containerMetadata = metadataProvider.GetMetadataForType(viewDataInfo.Container.GetType());- var propertyMetadata = containerMetadata.Properties[viewDataInfo.PropertyInfo.Name];+ var containerExplorer = viewData.ModelExplorer;+ if (viewDataInfo.Container != null)+ containerExplorer = metadataProvider.GetModelExplorerForType(+ viewDataInfo.Container.GetType(),+ viewDataInfo.Container);- Func<object, object> modelAccessor = (ignore) => viewDataInfo.Value;- return containerExplorer.GetExplorerForExpression(propertyMetadata, modelAccessor);- }+ if (viewDataInfo.PropertyInfo != null)+ {+ // We've identified a property access, which provides us with accurate metadata.+ var containerMetadata = metadataProvider.GetMetadataForType(viewDataInfo.Container.GetType());+ var propertyMetadata = containerMetadata.Properties[viewDataInfo.PropertyInfo.Name];- if (viewDataInfo.Value != null)- {- // We have a value, even though we may not know where it came from.- var valueMetadata = metadataProvider.GetMetadataForType(viewDataInfo.Value.GetType());- return containerExplorer.GetExplorerForExpression(valueMetadata, viewDataInfo.Value);- }+ Func<object, object> modelAccessor = ignore => viewDataInfo.Value;+ return containerExplorer.GetExplorerForExpression(propertyMetadata, modelAccessor);}- // Treat the expression as string if we don't find anything better.- var stringMetadata = metadataProvider.GetMetadataForType(typeof(string));- return viewData.ModelExplorer.GetExplorerForExpression(stringMetadata, modelAccessor: null);+ if (viewDataInfo.Value != null)+ {+ // We have a value, even though we may not know where it came from.+ var valueMetadata = metadataProvider.GetMetadataForType(viewDataInfo.Value.GetType());+ return containerExplorer.GetExplorerForExpression(valueMetadata, viewDataInfo.Value);+ }}- private static ModelExplorer FromModel(- ViewDataDictionary viewData,- IModelMetadataProvider metadataProvider)- {- ArgumentNullException.ThrowIfNull(viewData);+ // Treat the expression as string if we don't find anything better.+ var stringMetadata = metadataProvider.GetMetadataForType(typeof(string));+ return viewData.ModelExplorer.GetExplorerForExpression(stringMetadata, null);+ }- if (viewData.ModelMetadata.ModelType == typeof(object))- {- // Use common simple type rather than object so e.g. Editor() at least generates a TextBox.- var model = viewData.Model == null ? null : Convert.ToString(viewData.Model, CultureInfo.CurrentCulture);- return metadataProvider.GetModelExplorerForType(typeof(string), model);- }+ private static ModelExplorer FromModel(+ ViewDataDictionary viewData,+ IModelMetadataProvider metadataProvider)+ {+ ArgumentNullException.ThrowIfNull(viewData);- return viewData.ModelExplorer;+ if (viewData.ModelMetadata.ModelType == typeof(object))+ {+ // Use common simple type rather than object so e.g. Editor() at least generates a TextBox.+ var model = viewData.Model == null ? null : Convert.ToString(viewData.Model, CultureInfo.CurrentCulture);+ return metadataProvider.GetModelExplorerForType(typeof(string), model);}++ return viewData.ModelExplorer;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/FormatWeekHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/FormatWeekHelper.csindex e4e5d6a93..e2e73b759 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/FormatWeekHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/FormatWeekHelper.cs@@ -55,3 +55,4 @@// }// }//}+diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/NameAndIdProvider.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/NameAndIdProvider.csindex fec08f4c3..51f750732 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/NameAndIdProvider.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/NameAndIdProvider.cs@@ -3,190 +3,163 @@using Microsoft.AspNetCore.Mvc.Rendering;-namespace Grand.Web.Common.TagHelpers.Admin.Extend+namespace Grand.Web.Common.TagHelpers.Admin.Extend;++internal static class NameAndIdProvider{- internal static class NameAndIdProvider+ private static readonly object PreviousNameAndIdKey = typeof(PreviousNameAndId);++ /// <summary>+ /// Returns a valid HTML 4.01 "id" attribute value for an element with the given <paramref name="fullName" />.+ /// </summary>+ /// <param name="viewContext">A <see cref="ViewContext" /> instance for the current scope.</param>+ /// <param name="fullName">+ /// The fully-qualified expression name, ignoring the current model. Also the original HTML element name.+ /// </param>+ /// <param name="invalidCharReplacement">+ /// The <see cref="string" /> (normally a single <see cref="char" />) to substitute for invalid characters in+ /// <paramref name="fullName" />.+ /// </param>+ /// <returns>+ /// Valid HTML 4.01 "id" attribute value for an element with the given <paramref name="fullName" />.+ /// </returns>+ /// <remarks>+ /// Similar to <see cref="TagBuilder.CreateSanitizedId" /> but caches value for repeated invocations.+ /// </remarks>+ public static string CreateSanitizedId(ViewContext viewContext, string fullName, string invalidCharReplacement){- private static readonly object PreviousNameAndIdKey = typeof(PreviousNameAndId);-- /// <summary>- /// Returns a valid HTML 4.01 "id" attribute value for an element with the given <paramref name="fullName"/>.- /// </summary>- /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param>- /// <param name="fullName">- /// The fully-qualified expression name, ignoring the current model. Also the original HTML element name.- /// </param>- /// <param name="invalidCharReplacement">- /// The <see cref="string"/> (normally a single <see cref="char"/>) to substitute for invalid characters in- /// <paramref name="fullName"/>.- /// </param>- /// <returns>- /// Valid HTML 4.01 "id" attribute value for an element with the given <paramref name="fullName"/>.- /// </returns>- /// <remarks>- /// Similar to <see cref="TagBuilder.CreateSanitizedId"/> but caches value for repeated invocations.- /// </remarks>- public static string CreateSanitizedId(ViewContext viewContext, string fullName, string invalidCharReplacement)- {- ArgumentNullException.ThrowIfNull(viewContext);- ArgumentNullException.ThrowIfNull(invalidCharReplacement);-- if (string.IsNullOrEmpty(fullName))- {- return string.Empty;- }-- // Check cache to avoid whatever TagBuilder.CreateSanitizedId() may do.- var items = viewContext.HttpContext.Items;- object previousNameAndIdObject;- PreviousNameAndId previousNameAndId = null;- if (items.TryGetValue(PreviousNameAndIdKey, out previousNameAndIdObject) &&- (previousNameAndId = (PreviousNameAndId)previousNameAndIdObject) != null &&- string.Equals(previousNameAndId.FullName, fullName, StringComparison.Ordinal))- {- return previousNameAndId.SanitizedId;- }-- var sanitizedId = TagBuilder.CreateSanitizedId(fullName, invalidCharReplacement);-- if (previousNameAndId == null)- {- // Do not create a PreviousNameAndId when TagBuilder.CreateSanitizedId() only examined fullName.- if (string.Equals(fullName, sanitizedId, StringComparison.Ordinal))- {- return sanitizedId;- }-- previousNameAndId = new PreviousNameAndId();- items[PreviousNameAndIdKey] = previousNameAndId;- }-- previousNameAndId.FullName = fullName;- previousNameAndId.SanitizedId = sanitizedId;-+ ArgumentNullException.ThrowIfNull(viewContext);+ ArgumentNullException.ThrowIfNull(invalidCharReplacement);++ if (string.IsNullOrEmpty(fullName)) return string.Empty;++ // Check cache to avoid whatever TagBuilder.CreateSanitizedId() may do.+ var items = viewContext.HttpContext.Items;+ object previousNameAndIdObject;+ PreviousNameAndId previousNameAndId = null;+ if (items.TryGetValue(PreviousNameAndIdKey, out previousNameAndIdObject) &&+ (previousNameAndId = (PreviousNameAndId)previousNameAndIdObject) != null &&+ string.Equals(previousNameAndId.FullName, fullName, StringComparison.Ordinal))return previousNameAndId.SanitizedId;- }- /// <summary>- /// Adds a valid HTML 4.01 "id" attribute for an element with the given <paramref name="fullName"/>. Does- /// nothing if <see cref="TagBuilder.Attributes"/> already contains an "id" attribute or the- /// <paramref name="fullName"/> is <c>null</c> or empty.- /// </summary>- /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param>- /// <param name="tagBuilder">A <see cref="TagBuilder"/> instance that will contain the "id" attribute.</param>- /// <param name="fullName">- /// The fully-qualified expression name, ignoring the current model. Also the original HTML element name.- /// </param>- /// <param name="invalidCharReplacement">- /// The <see cref="string"/> (normally a single <see cref="char"/>) to substitute for invalid characters in- /// <paramref name="fullName"/>.- /// </param>- /// <remarks>- /// Similar to <see cref="TagBuilder.GenerateId"/> but caches value for repeated invocations.- /// </remarks>- /// <seealso cref="CreateSanitizedId"/>- public static void GenerateId(- ViewContext viewContext,- TagBuilder tagBuilder,- string fullName,- string invalidCharReplacement)+ var sanitizedId = TagBuilder.CreateSanitizedId(fullName, invalidCharReplacement);++ if (previousNameAndId == null){- ArgumentNullException.ThrowIfNull(viewContext);- ArgumentNullException.ThrowIfNull(tagBuilder);- ArgumentNullException.ThrowIfNull(invalidCharReplacement);-- if (string.IsNullOrEmpty(fullName))- {- return;- }-- if (!tagBuilder.Attributes.ContainsKey("id"))- {- var sanitizedId = CreateSanitizedId(viewContext, fullName, invalidCharReplacement);-- // Duplicate check for null or empty to cover the corner case where fullName contains only invalid- // characters and invalidCharReplacement is empty.- if (!string.IsNullOrEmpty(sanitizedId))- {- tagBuilder.Attributes["id"] = sanitizedId;- }- }+ // Do not create a PreviousNameAndId when TagBuilder.CreateSanitizedId() only examined fullName.+ if (string.Equals(fullName, sanitizedId, StringComparison.Ordinal)) return sanitizedId;++ previousNameAndId = new PreviousNameAndId();+ items[PreviousNameAndIdKey] = previousNameAndId;}- /// <summary>- /// Returns the full HTML element name for the specified <paramref name="expression"/>.- /// </summary>- /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param>- /// <param name="expression">Expression name, relative to the current model.</param>- /// <returns>Fully-qualified expression name for <paramref name="expression"/>.</returns>- /// <remarks>- /// Similar to <see cref="TemplateInfo.GetFullHtmlFieldName"/> but caches value for repeated invocations.- /// </remarks>- public static string GetFullHtmlFieldName(ViewContext viewContext, string expression)+ previousNameAndId.FullName = fullName;+ previousNameAndId.SanitizedId = sanitizedId;++ return previousNameAndId.SanitizedId;+ }++ /// <summary>+ /// Adds a valid HTML 4.01 "id" attribute for an element with the given <paramref name="fullName" />. Does+ /// nothing if <see cref="TagBuilder.Attributes" /> already contains an "id" attribute or the+ /// <paramref name="fullName" /> is <c>null</c> or empty.+ /// </summary>+ /// <param name="viewContext">A <see cref="ViewContext" /> instance for the current scope.</param>+ /// <param name="tagBuilder">A <see cref="TagBuilder" /> instance that will contain the "id" attribute.</param>+ /// <param name="fullName">+ /// The fully-qualified expression name, ignoring the current model. Also the original HTML element name.+ /// </param>+ /// <param name="invalidCharReplacement">+ /// The <see cref="string" /> (normally a single <see cref="char" />) to substitute for invalid characters in+ /// <paramref name="fullName" />.+ /// </param>+ /// <remarks>+ /// Similar to <see cref="TagBuilder.GenerateId" /> but caches value for repeated invocations.+ /// </remarks>+ /// <seealso cref="CreateSanitizedId" />+ public static void GenerateId(+ ViewContext viewContext,+ TagBuilder tagBuilder,+ string fullName,+ string invalidCharReplacement)+ {+ ArgumentNullException.ThrowIfNull(viewContext);+ ArgumentNullException.ThrowIfNull(tagBuilder);+ ArgumentNullException.ThrowIfNull(invalidCharReplacement);++ if (string.IsNullOrEmpty(fullName)) return;++ if (!tagBuilder.Attributes.ContainsKey("id")){- var htmlFieldPrefix = viewContext.ViewData.TemplateInfo.HtmlFieldPrefix;- if (string.IsNullOrEmpty(expression))- {- return htmlFieldPrefix;- }-- if (string.IsNullOrEmpty(htmlFieldPrefix))- {- return expression;- }-- // Need to concatenate. See if we've already done that.- var items = viewContext.HttpContext.Items;- object previousNameAndIdObject;- PreviousNameAndId previousNameAndId = null;- if (items.TryGetValue(PreviousNameAndIdKey, out previousNameAndIdObject) &&- (previousNameAndId = (PreviousNameAndId)previousNameAndIdObject) != null &&- string.Equals(previousNameAndId.HtmlFieldPrefix, htmlFieldPrefix, StringComparison.Ordinal) &&- string.Equals(previousNameAndId.Expression, expression, StringComparison.Ordinal))- {- return previousNameAndId.OutputFullName;- }-- if (previousNameAndId == null)- {- previousNameAndId = new PreviousNameAndId();- items[PreviousNameAndIdKey] = previousNameAndId;- }-- previousNameAndId.HtmlFieldPrefix = htmlFieldPrefix;- previousNameAndId.Expression = expression;- if (expression.StartsWith("[", StringComparison.Ordinal))- {- // The expression might represent an indexer access, in which case with a 'dot' would be invalid.- previousNameAndId.OutputFullName = htmlFieldPrefix + expression;- }- else- {- previousNameAndId.OutputFullName = htmlFieldPrefix + "." + expression;- }+ var sanitizedId = CreateSanitizedId(viewContext, fullName, invalidCharReplacement);- return previousNameAndId.OutputFullName;+ // Duplicate check for null or empty to cover the corner case where fullName contains only invalid+ // characters and invalidCharReplacement is empty.+ if (!string.IsNullOrEmpty(sanitizedId)) tagBuilder.Attributes["id"] = sanitizedId;}+ }++ /// <summary>+ /// Returns the full HTML element name for the specified <paramref name="expression" />.+ /// </summary>+ /// <param name="viewContext">A <see cref="ViewContext" /> instance for the current scope.</param>+ /// <param name="expression">Expression name, relative to the current model.</param>+ /// <returns>Fully-qualified expression name for <paramref name="expression" />.</returns>+ /// <remarks>+ /// Similar to <see cref="TemplateInfo.GetFullHtmlFieldName" /> but caches value for repeated invocations.+ /// </remarks>+ public static string GetFullHtmlFieldName(ViewContext viewContext, string expression)+ {+ var htmlFieldPrefix = viewContext.ViewData.TemplateInfo.HtmlFieldPrefix;+ if (string.IsNullOrEmpty(expression)) return htmlFieldPrefix;++ if (string.IsNullOrEmpty(htmlFieldPrefix)) return expression;++ // Need to concatenate. See if we've already done that.+ var items = viewContext.HttpContext.Items;+ object previousNameAndIdObject;+ PreviousNameAndId previousNameAndId = null;+ if (items.TryGetValue(PreviousNameAndIdKey, out previousNameAndIdObject) &&+ (previousNameAndId = (PreviousNameAndId)previousNameAndIdObject) != null &&+ string.Equals(previousNameAndId.HtmlFieldPrefix, htmlFieldPrefix, StringComparison.Ordinal) &&+ string.Equals(previousNameAndId.Expression, expression, StringComparison.Ordinal))+ return previousNameAndId.OutputFullName;- private class PreviousNameAndId+ if (previousNameAndId == null){- // Cached ambient input for NameAndIdProvider.GetFullHtmlFieldName(). TemplateInfo.HtmlFieldPrefix may- // change during the lifetime of a ViewContext.- public string HtmlFieldPrefix { get; set; }+ previousNameAndId = new PreviousNameAndId();+ items[PreviousNameAndIdKey] = previousNameAndId;+ }- // Cached input for NameAndIdProvider.GetFullHtmlFieldName().- public string Expression { get; set; }+ previousNameAndId.HtmlFieldPrefix = htmlFieldPrefix;+ previousNameAndId.Expression = expression;+ if (expression.StartsWith("[", StringComparison.Ordinal))+ // The expression might represent an indexer access, in which case with a 'dot' would be invalid.+ previousNameAndId.OutputFullName = htmlFieldPrefix + expression;+ else+ previousNameAndId.OutputFullName = htmlFieldPrefix + "." + expression;- // Cached return value for NameAndIdProvider.GetFullHtmlFieldName().- public string OutputFullName { get; set; }+ return previousNameAndId.OutputFullName;+ }- // Cached input for NameAndIdProvider.CreateSanitizedId(). Since IHtmlHelper.GenerateIdFromName() is- // available to all, there is no guarantee this is equal to OutputFullName when CreateSanitizedId() is- // called.- public string FullName { get; set; }+ private class PreviousNameAndId+ {+ // Cached ambient input for NameAndIdProvider.GetFullHtmlFieldName(). TemplateInfo.HtmlFieldPrefix may+ // change during the lifetime of a ViewContext.+ public string HtmlFieldPrefix { get; set; }- // Cached return value for NameAndIdProvider.CreateSanitizedId().- public string SanitizedId { get; set; }- }+ // Cached input for NameAndIdProvider.GetFullHtmlFieldName().+ public string Expression { get; set; }++ // Cached return value for NameAndIdProvider.GetFullHtmlFieldName().+ public string OutputFullName { get; set; }++ // Cached input for NameAndIdProvider.CreateSanitizedId(). Since IHtmlHelper.GenerateIdFromName() is+ // available to all, there is no guarantee this is equal to OutputFullName when CreateSanitizedId() is+ // called.+ public string FullName { get; set; }++ // Cached return value for NameAndIdProvider.CreateSanitizedId().+ public string SanitizedId { get; set; }}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/TemplateBuilder.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/TemplateBuilder.csindex 9c2463efc..9171935c9 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/TemplateBuilder.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/TemplateBuilder.cs@@ -10,130 +10,113 @@ using Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers;using System.Diagnostics;using System.Globalization;-namespace Grand.Web.Common.TagHelpers.Admin.Extend+namespace Grand.Web.Common.TagHelpers.Admin.Extend;++internal class TemplateBuilder{- internal class TemplateBuilder+ private readonly object _additionalViewData;+ private readonly IViewBufferScope _bufferScope;+ private readonly string _htmlFieldName;+ private readonly ModelMetadata _metadata;+ private readonly ModelExplorer _modelExplorer;+ private readonly bool _readOnly;+ private readonly string _templateName;+ private readonly ViewContext _viewContext;+ private readonly ViewDataDictionary _viewData;+ private readonly IViewEngine _viewEngine;+ private object _model;++ public TemplateBuilder(+ IViewEngine viewEngine,+ IViewBufferScope bufferScope,+ ViewContext viewContext,+ ViewDataDictionary viewData,+ ModelExplorer modelExplorer,+ string htmlFieldName,+ string templateName,+ bool readOnly,+ object additionalViewData)+ {+ ArgumentNullException.ThrowIfNull(viewEngine);+ ArgumentNullException.ThrowIfNull(bufferScope);+ ArgumentNullException.ThrowIfNull(viewContext);+ ArgumentNullException.ThrowIfNull(viewData);+ ArgumentNullException.ThrowIfNull(modelExplorer);++ _viewEngine = viewEngine;+ _bufferScope = bufferScope;+ _viewContext = viewContext;+ _viewData = viewData;+ _modelExplorer = modelExplorer;+ _htmlFieldName = htmlFieldName;+ _templateName = templateName;+ _readOnly = readOnly;+ _additionalViewData = additionalViewData;++ _model = modelExplorer.Model;+ _metadata = modelExplorer.Metadata;+ }++ public async Task<IHtmlContent> Build(){- private readonly IViewEngine _viewEngine;- private readonly IViewBufferScope _bufferScope;- private readonly ViewContext _viewContext;- private readonly ViewDataDictionary _viewData;- private readonly ModelExplorer _modelExplorer;- private object _model;- private readonly ModelMetadata _metadata;- private readonly string _htmlFieldName;- private readonly string _templateName;- private readonly bool _readOnly;- private readonly object _additionalViewData;-- public TemplateBuilder(- IViewEngine viewEngine,- IViewBufferScope bufferScope,- ViewContext viewContext,- ViewDataDictionary viewData,- ModelExplorer modelExplorer,- string htmlFieldName,- string templateName,- bool readOnly,- object additionalViewData)+ if (_metadata.ConvertEmptyStringToNull && string.Empty.Equals(_model)) _model = null;++ // Normally this shouldn't happen, unless someone writes their own custom Object templates which+ // don't check to make sure that the object hasn't already been displayed+ if (_viewData.TemplateInfo.Visited(_modelExplorer)) return HtmlString.Empty;++ // Create VDD of type object so any model type is allowed.+ var viewData = new ViewDataDictionary<object>(_viewData) {+ // Create a new ModelExplorer in order to preserve the model metadata of the original _viewData even+ // though _model may have been reset to null. Otherwise we might lose track of the model type /property.+ ModelExplorer = _modelExplorer.GetExplorerForModel(_model)+ };++ var formatString =+ _readOnly ? viewData.ModelMetadata.DisplayFormatString : viewData.ModelMetadata.EditFormatString;++ var formattedModelValue = _model;+ if (_model == null){- ArgumentNullException.ThrowIfNull(viewEngine);- ArgumentNullException.ThrowIfNull(bufferScope);- ArgumentNullException.ThrowIfNull(viewContext);- ArgumentNullException.ThrowIfNull(viewData);- ArgumentNullException.ThrowIfNull(modelExplorer);-- _viewEngine = viewEngine;- _bufferScope = bufferScope;- _viewContext = viewContext;- _viewData = viewData;- _modelExplorer = modelExplorer;- _htmlFieldName = htmlFieldName;- _templateName = templateName;- _readOnly = readOnly;- _additionalViewData = additionalViewData;-- _model = modelExplorer.Model;- _metadata = modelExplorer.Metadata;+ if (_readOnly) formattedModelValue = _metadata.NullDisplayText;}-- public async Task<IHtmlContent> Build()+ else if (!string.IsNullOrEmpty(formatString)){- if (_metadata.ConvertEmptyStringToNull && string.Empty.Equals(_model))- {- _model = null;- }-- // Normally this shouldn't happen, unless someone writes their own custom Object templates which- // don't check to make sure that the object hasn't already been displayed- if (_viewData.TemplateInfo.Visited(_modelExplorer))- {- return HtmlString.Empty;- }-- // Create VDD of type object so any model type is allowed.- var viewData = new ViewDataDictionary<object>(_viewData) {- // Create a new ModelExplorer in order to preserve the model metadata of the original _viewData even- // though _model may have been reset to null. Otherwise we might lose track of the model type /property.- ModelExplorer = _modelExplorer.GetExplorerForModel(_model)- };-- var formatString = _readOnly ?- viewData.ModelMetadata.DisplayFormatString :- viewData.ModelMetadata.EditFormatString;-- var formattedModelValue = _model;- if (_model == null)- {- if (_readOnly)- {- formattedModelValue = _metadata.NullDisplayText;- }- }- else if (!string.IsNullOrEmpty(formatString))- {- formattedModelValue = string.Format(CultureInfo.CurrentCulture, formatString, _model);- }- else if (viewData.ModelMetadata.IsEnum && _model is Enum modelEnum)- {- // Cover the case where the model is an enum and we want the string value of it- var value = modelEnum.ToString("d");- var enumGrouped = viewData.ModelMetadata.EnumGroupedDisplayNamesAndValues;- Debug.Assert(enumGrouped != null);- foreach (var kvp in enumGrouped)+ formattedModelValue = string.Format(CultureInfo.CurrentCulture, formatString, _model);+ }+ else if (viewData.ModelMetadata.IsEnum && _model is Enum modelEnum)+ {+ // Cover the case where the model is an enum and we want the string value of it+ var value = modelEnum.ToString("d");+ var enumGrouped = viewData.ModelMetadata.EnumGroupedDisplayNamesAndValues;+ Debug.Assert(enumGrouped != null);+ foreach (var kvp in enumGrouped)+ if (kvp.Value == value){- if (kvp.Value == value)- {- // Creates a ModelExplorer with the same Metadata except that the Model is a string instead of an Enum- formattedModelValue = kvp.Key.Name;- break;- }+ // Creates a ModelExplorer with the same Metadata except that the Model is a string instead of an Enum+ formattedModelValue = kvp.Key.Name;+ break;}- }+ }- viewData.TemplateInfo.FormattedModelValue = formattedModelValue;- viewData.TemplateInfo.HtmlFieldPrefix = _viewData.TemplateInfo.GetFullHtmlFieldName(_htmlFieldName);+ viewData.TemplateInfo.FormattedModelValue = formattedModelValue;+ viewData.TemplateInfo.HtmlFieldPrefix = _viewData.TemplateInfo.GetFullHtmlFieldName(_htmlFieldName);- if (_additionalViewData != null)- {- foreach (var kvp in HtmlHelper.ObjectToDictionary(_additionalViewData))- {- viewData[kvp.Key] = kvp.Value;- }- }+ if (_additionalViewData != null)+ foreach (var kvp in HtmlHelper.ObjectToDictionary(_additionalViewData))+ viewData[kvp.Key] = kvp.Value;- var visitedObjectsKey = _model ?? _modelExplorer.ModelType;- viewData.TemplateInfo.AddVisited(visitedObjectsKey);+ var visitedObjectsKey = _model ?? _modelExplorer.ModelType;+ viewData.TemplateInfo.AddVisited(visitedObjectsKey);- var templateRenderer = new TemplateRenderer(- _viewEngine,- _bufferScope,- _viewContext,- viewData,- _templateName,- _readOnly);+ var templateRenderer = new TemplateRenderer(+ _viewEngine,+ _bufferScope,+ _viewContext,+ viewData,+ _templateName,+ _readOnly);- return await templateRenderer.Render();- }+ return await templateRenderer.Render();}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/TemplateRenderer.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/TemplateRenderer.csindex 334315ff2..d04645c72 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/TemplateRenderer.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/TemplateRenderer.cs@@ -12,240 +12,215 @@ using Microsoft.Extensions.DependencyInjection;using System.Collections;using System.Reflection;-namespace Grand.Web.Common.TagHelpers.Admin.Extend+namespace Grand.Web.Common.TagHelpers.Admin.Extend;++internal class TemplateRenderer{- internal class TemplateRenderer+ private const string DisplayTemplateViewPath = "DisplayTemplates";+ private const string EditorTemplateViewPath = "EditorTemplates";+ public const string IEnumerableOfIFormFileName = "IEnumerable`" + nameof(IFormFile);++ private static readonly Dictionary<string, Func<IHtmlHelper, Task<IHtmlContent>>> _defaultDisplayActions =+ new(StringComparer.OrdinalIgnoreCase) {+ { "Collection", DefaultDisplayTemplates.CollectionTemplate },+ { "EmailAddress", DefaultDisplayTemplates.EmailAddressTemplate },+ { "HiddenInput", DefaultDisplayTemplates.HiddenInputTemplate },+ { "Html", DefaultDisplayTemplates.HtmlTemplate },+ { "Text", DefaultDisplayTemplates.StringTemplate },+ { "Url", DefaultDisplayTemplates.UrlTemplate },+ { typeof(bool).Name, DefaultDisplayTemplates.BooleanTemplate },+ { typeof(double).Name, DefaultDisplayTemplates.DecimalTemplate },+ { typeof(string).Name, DefaultDisplayTemplates.StringTemplate },+ { typeof(object).Name, DefaultDisplayTemplates.ObjectTemplate }+ };++ private static readonly Dictionary<string, Func<IHtmlHelper, Task<IHtmlContent>>> _defaultEditorActions =+ new(StringComparer.OrdinalIgnoreCase) {+ { "Collection", DefaultEditorTemplates.CollectionTemplate },+ { "EmailAddress", DefaultEditorTemplates.EmailAddressInputTemplate },+ { "HiddenInput", DefaultEditorTemplates.HiddenInputTemplate },+ { "MultilineText", DefaultEditorTemplates.MultilineTemplate },+ { "Password", DefaultEditorTemplates.PasswordTemplate },+ { "PhoneNumber", DefaultEditorTemplates.PhoneNumberInputTemplate },+ { "Text", DefaultEditorTemplates.StringTemplate },+ { "Url", DefaultEditorTemplates.UrlInputTemplate },+ { "Date", DefaultEditorTemplates.DateInputTemplate },+ { "DateTime", DefaultEditorTemplates.DateTimeLocalInputTemplate },+ { "DateTime-local", DefaultEditorTemplates.DateTimeLocalInputTemplate },+ { nameof(DateTimeOffset), DefaultEditorTemplates.DateTimeOffsetTemplate },+ { "Time", DefaultEditorTemplates.TimeInputTemplate },+ { "Month", DefaultEditorTemplates.MonthInputTemplate },+ { "Week", DefaultEditorTemplates.WeekInputTemplate },+ { typeof(byte).Name, DefaultEditorTemplates.NumberInputTemplate },+ { typeof(sbyte).Name, DefaultEditorTemplates.NumberInputTemplate },+ { typeof(short).Name, DefaultEditorTemplates.NumberInputTemplate },+ { typeof(ushort).Name, DefaultEditorTemplates.NumberInputTemplate },+ { typeof(int).Name, DefaultEditorTemplates.NumberInputTemplate },+ { typeof(uint).Name, DefaultEditorTemplates.NumberInputTemplate },+ { typeof(long).Name, DefaultEditorTemplates.NumberInputTemplate },+ { typeof(ulong).Name, DefaultEditorTemplates.NumberInputTemplate },+ { typeof(bool).Name, DefaultEditorTemplates.BooleanTemplate },+ { typeof(double).Name, DefaultEditorTemplates.DecimalTemplate },+ { typeof(string).Name, DefaultEditorTemplates.StringTemplate },+ { typeof(object).Name, DefaultEditorTemplates.ObjectTemplate },+ { typeof(IFormFile).Name, DefaultEditorTemplates.FileInputTemplate },+ { IEnumerableOfIFormFileName, DefaultEditorTemplates.FileCollectionInputTemplate }+ };++ private readonly IViewBufferScope _bufferScope;+ private readonly bool _readOnly;+ private readonly string _templateName;+ private readonly ViewContext _viewContext;+ private readonly ViewDataDictionary _viewData;++ private readonly IViewEngine _viewEngine;++ public TemplateRenderer(+ IViewEngine viewEngine,+ IViewBufferScope bufferScope,+ ViewContext viewContext,+ ViewDataDictionary viewData,+ string templateName,+ bool readOnly){- private const string DisplayTemplateViewPath = "DisplayTemplates";- private const string EditorTemplateViewPath = "EditorTemplates";- public const string IEnumerableOfIFormFileName = "IEnumerable`" + nameof(IFormFile);+ ArgumentNullException.ThrowIfNull(viewEngine);+ ArgumentNullException.ThrowIfNull(bufferScope);+ ArgumentNullException.ThrowIfNull(viewContext);+ ArgumentNullException.ThrowIfNull(viewData);++ _viewEngine = viewEngine;+ _bufferScope = bufferScope;+ _viewContext = viewContext;+ _viewData = viewData;+ _templateName = templateName;+ _readOnly = readOnly;+ }- private static readonly Dictionary<string, Func<IHtmlHelper, Task<IHtmlContent>>> _defaultDisplayActions =- new Dictionary<string, Func<IHtmlHelper, Task<IHtmlContent>>>(StringComparer.OrdinalIgnoreCase)- {- { "Collection", DefaultDisplayTemplates.CollectionTemplate },- { "EmailAddress", DefaultDisplayTemplates.EmailAddressTemplate },- { "HiddenInput", DefaultDisplayTemplates.HiddenInputTemplate },- { "Html", DefaultDisplayTemplates.HtmlTemplate },- { "Text", DefaultDisplayTemplates.StringTemplate },- { "Url", DefaultDisplayTemplates.UrlTemplate },- { typeof(bool).Name, DefaultDisplayTemplates.BooleanTemplate },- { typeof(double).Name, DefaultDisplayTemplates.DecimalTemplate },- { typeof(string).Name, DefaultDisplayTemplates.StringTemplate },- { typeof(object).Name, DefaultDisplayTemplates.ObjectTemplate },- };-- private static readonly Dictionary<string, Func<IHtmlHelper, Task<IHtmlContent>>> _defaultEditorActions =- new Dictionary<string, Func<IHtmlHelper, Task<IHtmlContent>>>(StringComparer.OrdinalIgnoreCase)- {- { "Collection", DefaultEditorTemplates.CollectionTemplate },- { "EmailAddress", DefaultEditorTemplates.EmailAddressInputTemplate },- { "HiddenInput", DefaultEditorTemplates.HiddenInputTemplate },- { "MultilineText", DefaultEditorTemplates.MultilineTemplate },- { "Password", DefaultEditorTemplates.PasswordTemplate },- { "PhoneNumber", DefaultEditorTemplates.PhoneNumberInputTemplate },- { "Text", DefaultEditorTemplates.StringTemplate },- { "Url", DefaultEditorTemplates.UrlInputTemplate },- { "Date", DefaultEditorTemplates.DateInputTemplate },- { "DateTime", DefaultEditorTemplates.DateTimeLocalInputTemplate },- { "DateTime-local", DefaultEditorTemplates.DateTimeLocalInputTemplate },- { nameof(DateTimeOffset), DefaultEditorTemplates.DateTimeOffsetTemplate },- { "Time", DefaultEditorTemplates.TimeInputTemplate },- { "Month", DefaultEditorTemplates.MonthInputTemplate },- { "Week", DefaultEditorTemplates.WeekInputTemplate },- { typeof(byte).Name, DefaultEditorTemplates.NumberInputTemplate },- { typeof(sbyte).Name, DefaultEditorTemplates.NumberInputTemplate },- { typeof(short).Name, DefaultEditorTemplates.NumberInputTemplate },- { typeof(ushort).Name, DefaultEditorTemplates.NumberInputTemplate },- { typeof(int).Name, DefaultEditorTemplates.NumberInputTemplate },- { typeof(uint).Name, DefaultEditorTemplates.NumberInputTemplate },- { typeof(long).Name, DefaultEditorTemplates.NumberInputTemplate },- { typeof(ulong).Name, DefaultEditorTemplates.NumberInputTemplate },- { typeof(bool).Name, DefaultEditorTemplates.BooleanTemplate },- { typeof(double).Name, DefaultEditorTemplates.DecimalTemplate },- { typeof(string).Name, DefaultEditorTemplates.StringTemplate },- { typeof(object).Name, DefaultEditorTemplates.ObjectTemplate },- { typeof(IFormFile).Name, DefaultEditorTemplates.FileInputTemplate },- { IEnumerableOfIFormFileName, DefaultEditorTemplates.FileCollectionInputTemplate },- };-- private readonly IViewEngine _viewEngine;- private readonly IViewBufferScope _bufferScope;- private readonly ViewContext _viewContext;- private readonly ViewDataDictionary _viewData;- private readonly string _templateName;- private readonly bool _readOnly;-- public TemplateRenderer(- IViewEngine viewEngine,- IViewBufferScope bufferScope,- ViewContext viewContext,- ViewDataDictionary viewData,- string templateName,- bool readOnly)- {- ArgumentNullException.ThrowIfNull(viewEngine);- ArgumentNullException.ThrowIfNull(bufferScope);- ArgumentNullException.ThrowIfNull(viewContext);- ArgumentNullException.ThrowIfNull(viewData);-- _viewEngine = viewEngine;- _bufferScope = bufferScope;- _viewContext = viewContext;- _viewData = viewData;- _templateName = templateName;- _readOnly = readOnly;- }+ public async Task<IHtmlContent> Render()+ {+ var defaultActions = GetDefaultActions();+ var modeViewPath = _readOnly ? DisplayTemplateViewPath : EditorTemplateViewPath;- public async Task<IHtmlContent> Render()+ foreach (var viewName in GetViewNames()){- var defaultActions = GetDefaultActions();- var modeViewPath = _readOnly ? DisplayTemplateViewPath : EditorTemplateViewPath;-- foreach (var viewName in GetViewNames())+ var viewEngineResult = _viewEngine.GetView(_viewContext.ExecutingFilePath, viewName, false);+ if (!viewEngineResult.Success){- var viewEngineResult = _viewEngine.GetView(_viewContext.ExecutingFilePath, viewName, isMainPage: false);- if (!viewEngineResult.Success)- {- var fullViewName = modeViewPath + "/" + viewName;- viewEngineResult = _viewEngine.FindView(_viewContext, fullViewName, isMainPage: false);- }+ var fullViewName = modeViewPath + "/" + viewName;+ viewEngineResult = _viewEngine.FindView(_viewContext, fullViewName, false);+ }- if (viewEngineResult.Success)+ if (viewEngineResult.Success)+ {+ var viewBuffer = new ViewBuffer(_bufferScope, viewName, ViewBuffer.PartialViewPageSize);+ using (var writer = new ViewBufferTextWriter(viewBuffer, _viewContext.Writer.Encoding)){- var viewBuffer = new ViewBuffer(_bufferScope, viewName, ViewBuffer.PartialViewPageSize);- using (var writer = new ViewBufferTextWriter(viewBuffer, _viewContext.Writer.Encoding))+ // Forcing synchronous behavior so users don't have to await templates.+ var view = viewEngineResult.View;+ using (view as IDisposable){- // Forcing synchronous behavior so users don't have to await templates.- var view = viewEngineResult.View;- using (view as IDisposable)- {- var viewContext = new ViewContext(_viewContext, viewEngineResult.View, _viewData, writer);- await viewEngineResult.View.RenderAsync(viewContext);- return viewBuffer;- }+ var viewContext = new ViewContext(_viewContext, viewEngineResult.View, _viewData, writer);+ await viewEngineResult.View.RenderAsync(viewContext);+ return viewBuffer;}}-- if (defaultActions.TryGetValue(viewName, out var defaultAction))- {- return await defaultAction(MakeHtmlHelper(_viewContext, _viewData));- }}- throw new InvalidOperationException(_viewData.ModelExplorer.ModelType.FullName);- }- private Dictionary<string, Func<IHtmlHelper, Task<IHtmlContent>>> GetDefaultActions()- {- return _readOnly ? _defaultDisplayActions : _defaultEditorActions;+ if (defaultActions.TryGetValue(viewName, out var defaultAction))+ return await defaultAction(MakeHtmlHelper(_viewContext, _viewData));}- private IEnumerable<string> GetViewNames()- {- var metadata = _viewData.ModelMetadata;- var templateHints = new[]- {- _templateName,- metadata.TemplateHint,- metadata.DataTypeName- };+ throw new InvalidOperationException(_viewData.ModelExplorer.ModelType.FullName);+ }- foreach (var templateHint in templateHints.Where(s => !string.IsNullOrEmpty(s)))- {- yield return templateHint;- }+ private Dictionary<string, Func<IHtmlHelper, Task<IHtmlContent>>> GetDefaultActions()+ {+ return _readOnly ? _defaultDisplayActions : _defaultEditorActions;+ }- // We don't want to search for Nullable<T>, we want to search for T (which should handle both T and- // Nullable<T>).- var fieldType = metadata.UnderlyingOrModelType;- foreach (var typeName in GetTypeNames(metadata, fieldType))- {- yield return typeName;- }- }+ private IEnumerable<string> GetViewNames()+ {+ var metadata = _viewData.ModelMetadata;+ var templateHints = new[] {+ _templateName,+ metadata.TemplateHint,+ metadata.DataTypeName+ };++ foreach (var templateHint in templateHints.Where(s => !string.IsNullOrEmpty(s))) yield return templateHint;++ // We don't want to search for Nullable<T>, we want to search for T (which should handle both T and+ // Nullable<T>).+ var fieldType = metadata.UnderlyingOrModelType;+ foreach (var typeName in GetTypeNames(metadata, fieldType)) yield return typeName;+ }- public static IEnumerable<string> GetTypeNames(ModelMetadata modelMetadata, Type fieldType)- {- // Not returning type name here for IEnumerable<IFormFile> since we will be returning- // a more specific name, IEnumerableOfIFormFileName.- var fieldTypeInfo = fieldType.GetTypeInfo();+ public static IEnumerable<string> GetTypeNames(ModelMetadata modelMetadata, Type fieldType)+ {+ // Not returning type name here for IEnumerable<IFormFile> since we will be returning+ // a more specific name, IEnumerableOfIFormFileName.+ var fieldTypeInfo = fieldType.GetTypeInfo();- if (typeof(IEnumerable<IFormFile>) != fieldType)- {- yield return fieldType.Name;- }+ if (typeof(IEnumerable<IFormFile>) != fieldType) yield return fieldType.Name;- if (fieldType == typeof(string))- {- // Nothing more to provide- yield break;- }+ if (fieldType == typeof(string))+ // Nothing more to provide+ yield break;- if (!modelMetadata.IsComplexType)- {- // IsEnum is false for the Enum class itself- if (fieldTypeInfo.IsEnum)- {- // Same as fieldType.BaseType.Name in this case- yield return "Enum";- }- else if (fieldType == typeof(DateTimeOffset))- {- yield return "DateTime";- }+ if (!modelMetadata.IsComplexType)+ {+ // IsEnum is false for the Enum class itself+ if (fieldTypeInfo.IsEnum)+ // Same as fieldType.BaseType.Name in this case+ yield return "Enum";+ else if (fieldType == typeof(DateTimeOffset)) yield return "DateTime";++ yield return "String";+ yield break;+ }- yield return "String";- yield break;- }- if (!fieldTypeInfo.IsInterface)+ if (!fieldTypeInfo.IsInterface)+ {+ var type = fieldType;+ while (true){- var type = fieldType;- while (true)- {- type = type.GetTypeInfo().BaseType;- if (type == null || type == typeof(object))- {- break;- }+ type = type.GetTypeInfo().BaseType;+ if (type == null || type == typeof(object)) break;- yield return type.Name;- }+ yield return type.Name;}+ }- if (typeof(IEnumerable).IsAssignableFrom(fieldType))+ if (typeof(IEnumerable).IsAssignableFrom(fieldType))+ {+ if (typeof(IEnumerable<IFormFile>).IsAssignableFrom(fieldType)){- if (typeof(IEnumerable<IFormFile>).IsAssignableFrom(fieldType))- {- yield return IEnumerableOfIFormFileName;-- // Specific name has already been returned, now return the generic name.- if (typeof(IEnumerable<IFormFile>) == fieldType)- {- yield return fieldType.Name;- }- }+ yield return IEnumerableOfIFormFileName;- yield return "Collection";- }- else if (typeof(IFormFile) != fieldType && typeof(IFormFile).IsAssignableFrom(fieldType))- {- yield return nameof(IFormFile);+ // Specific name has already been returned, now return the generic name.+ if (typeof(IEnumerable<IFormFile>) == fieldType) yield return fieldType.Name;}- yield return "Object";+ yield return "Collection";}-- private static IHtmlHelper MakeHtmlHelper(ViewContext viewContext, ViewDataDictionary viewData)+ else if (typeof(IFormFile) != fieldType && typeof(IFormFile).IsAssignableFrom(fieldType)){- var newHelper = viewContext.HttpContext.RequestServices.GetRequiredService<IHtmlHelper>();+ yield return nameof(IFormFile);+ }- if (newHelper is IViewContextAware contextable)- {- var newViewContext = new ViewContext(viewContext, viewContext.View, viewData, viewContext.Writer);- contextable.Contextualize(newViewContext);- }+ yield return "Object";+ }- return newHelper;+ private static IHtmlHelper MakeHtmlHelper(ViewContext viewContext, ViewDataDictionary viewData)+ {+ var newHelper = viewContext.HttpContext.RequestServices.GetRequiredService<IHtmlHelper>();++ if (newHelper is IViewContextAware contextable)+ {+ var newViewContext = new ViewContext(viewContext, viewContext.View, viewData, viewContext.Writer);+ contextable.Contextualize(newViewContext);}++ return newHelper;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ValidationHelpers.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ValidationHelpers.csindex 7d8b48786..e4e494ac9 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ValidationHelpers.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ValidationHelpers.cs@@ -5,110 +5,83 @@ using Microsoft.AspNetCore.Mvc.ModelBinding;using Microsoft.AspNetCore.Mvc.ViewFeatures;using System.Diagnostics;-namespace Grand.Web.Common.TagHelpers.Admin.Extend+namespace Grand.Web.Common.TagHelpers.Admin.Extend;++internal static class ValidationHelpers{- internal static class ValidationHelpers+ public static string GetModelErrorMessageOrDefault(ModelError modelError){- public static string GetModelErrorMessageOrDefault(ModelError modelError)- {- Debug.Assert(modelError != null);+ Debug.Assert(modelError != null);- if (!string.IsNullOrEmpty(modelError.ErrorMessage))- {- return modelError.ErrorMessage;- }+ if (!string.IsNullOrEmpty(modelError.ErrorMessage)) return modelError.ErrorMessage;- // Default in the ValidationSummary case is no error message.- return string.Empty;- }+ // Default in the ValidationSummary case is no error message.+ return string.Empty;+ }- public static string GetModelErrorMessageOrDefault(- ModelError modelError,- ModelStateEntry containingEntry,- ModelExplorer modelExplorer)- {- Debug.Assert(modelError != null);- Debug.Assert(containingEntry != null);- Debug.Assert(modelExplorer != null);+ public static string GetModelErrorMessageOrDefault(+ ModelError modelError,+ ModelStateEntry containingEntry,+ ModelExplorer modelExplorer)+ {+ Debug.Assert(modelError != null);+ Debug.Assert(containingEntry != null);+ Debug.Assert(modelExplorer != null);- if (!string.IsNullOrEmpty(modelError.ErrorMessage))- {- return modelError.ErrorMessage;- }+ if (!string.IsNullOrEmpty(modelError.ErrorMessage)) return modelError.ErrorMessage;- // Default in the ValidationMessage case is a fallback error message.- var attemptedValue = containingEntry.AttemptedValue ?? "null";- return modelExplorer.Metadata.ModelBindingMessageProvider.ValueIsInvalidAccessor(attemptedValue);- }+ // Default in the ValidationMessage case is a fallback error message.+ var attemptedValue = containingEntry.AttemptedValue ?? "null";+ return modelExplorer.Metadata.ModelBindingMessageProvider.ValueIsInvalidAccessor(attemptedValue);+ }- // Returns non-null list of model states, which caller will render in order provided.- public static IList<ModelStateEntry> GetModelStateList(- ViewDataDictionary viewData,- bool excludePropertyErrors)+ // Returns non-null list of model states, which caller will render in order provided.+ public static IList<ModelStateEntry> GetModelStateList(+ ViewDataDictionary viewData,+ bool excludePropertyErrors)+ {+ if (excludePropertyErrors){- if (excludePropertyErrors)- {- viewData.ModelState.TryGetValue(viewData.TemplateInfo.HtmlFieldPrefix, out var ms);+ viewData.ModelState.TryGetValue(viewData.TemplateInfo.HtmlFieldPrefix, out var ms);- if (ms != null)- {- return new[] { ms };- }- }- else if (viewData.ModelState.Count > 0)- {- var metadata = viewData.ModelMetadata;- var modelStateDictionary = viewData.ModelState;- var entries = new List<ModelStateEntry>();- Visit(modelStateDictionary.Root, metadata, entries);+ if (ms != null) return new[] { ms };+ }+ else if (viewData.ModelState.Count > 0)+ {+ var metadata = viewData.ModelMetadata;+ var modelStateDictionary = viewData.ModelState;+ var entries = new List<ModelStateEntry>();+ Visit(modelStateDictionary.Root, metadata, entries);- if (entries.Count < modelStateDictionary.Count)- {- // Account for entries in the ModelStateDictionary that do not have corresponding ModelMetadata values.- foreach (var entry in modelStateDictionary)- {- if (!entries.Contains(entry.Value))- {- entries.Add(entry.Value);- }- }- }+ if (entries.Count < modelStateDictionary.Count)+ // Account for entries in the ModelStateDictionary that do not have corresponding ModelMetadata values.+ foreach (var entry in modelStateDictionary)+ if (!entries.Contains(entry.Value))+ entries.Add(entry.Value);- return entries;- }-- return Array.Empty<ModelStateEntry>();+ return entries;}- private static void Visit(- ModelStateEntry modelStateEntry,- ModelMetadata metadata,- List<ModelStateEntry> orderedModelStateEntries)- {- if (metadata.ElementMetadata != null && modelStateEntry.Children != null)- {- foreach (var indexEntry in modelStateEntry.Children)- {- Visit(indexEntry, metadata.ElementMetadata, orderedModelStateEntries);- }- }- else- {- for (var i = 0; i < metadata.Properties.Count; i++)- {- var propertyMetadata = metadata.Properties[i];- var propertyModelStateEntry = modelStateEntry.GetModelStateForProperty(propertyMetadata.PropertyName);- if (propertyModelStateEntry != null)- {- Visit(propertyModelStateEntry, propertyMetadata, orderedModelStateEntries);- }- }- }+ return Array.Empty<ModelStateEntry>();+ }- if (!modelStateEntry.IsContainerNode)+ private static void Visit(+ ModelStateEntry modelStateEntry,+ ModelMetadata metadata,+ List<ModelStateEntry> orderedModelStateEntries)+ {+ if (metadata.ElementMetadata != null && modelStateEntry.Children != null)+ foreach (var indexEntry in modelStateEntry.Children)+ Visit(indexEntry, metadata.ElementMetadata, orderedModelStateEntries);+ else+ for (var i = 0; i < metadata.Properties.Count; i++){- orderedModelStateEntries.Add(modelStateEntry);+ var propertyMetadata = metadata.Properties[i];+ var propertyModelStateEntry = modelStateEntry.GetModelStateForProperty(propertyMetadata.PropertyName);+ if (propertyModelStateEntry != null)+ Visit(propertyModelStateEntry, propertyMetadata, orderedModelStateEntries);}- }++ if (!modelStateEntry.IsContainerNode) orderedModelStateEntries.Add(modelStateEntry);}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ViewBuffer.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ViewBuffer.csindex 48c6c5fd3..6d71a72cb 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ViewBuffer.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ViewBuffer.cs@@ -6,366 +6,320 @@ using Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers;using System.Runtime.CompilerServices;using System.Text.Encodings.Web;-namespace Grand.Web.Common.TagHelpers.Admin.Extend+namespace Grand.Web.Common.TagHelpers.Admin.Extend;++internal class ViewBuffer : IHtmlContentBuilder{- internal class ViewBuffer : IHtmlContentBuilder+ public static readonly int PartialViewPageSize = 32;+ public static readonly int TagHelperPageSize = 32;+ public static readonly int ViewComponentPageSize = 32;+ public static readonly int ViewPageSize = 256;++ private readonly IViewBufferScope _bufferScope;+ private readonly string _name;+ private readonly int _pageSize;+ private ViewBufferPage _currentPage; // Limits allocation if the ViewBuffer has only one page (frequent case).+ private List<ViewBufferPage> _multiplePages; // Allocated only if necessary++ /// <summary>+ /// Initializes a new instance of <see cref="ViewBuffer" />.+ /// </summary>+ /// <param name="bufferScope">The <see cref="IViewBufferScope" />.</param>+ /// <param name="name">A name to identify this instance.</param>+ /// <param name="pageSize">The size of buffer pages.</param>+ public ViewBuffer(IViewBufferScope bufferScope, string name, int pageSize){- public static readonly int PartialViewPageSize = 32;- public static readonly int TagHelperPageSize = 32;- public static readonly int ViewComponentPageSize = 32;- public static readonly int ViewPageSize = 256;-- private readonly IViewBufferScope _bufferScope;- private readonly string _name;- private readonly int _pageSize;- private ViewBufferPage _currentPage; // Limits allocation if the ViewBuffer has only one page (frequent case).- private List<ViewBufferPage> _multiplePages; // Allocated only if necessary-- /// <summary>- /// Initializes a new instance of <see cref="ViewBuffer"/>.- /// </summary>- /// <param name="bufferScope">The <see cref="IViewBufferScope"/>.</param>- /// <param name="name">A name to identify this instance.</param>- /// <param name="pageSize">The size of buffer pages.</param>- public ViewBuffer(IViewBufferScope bufferScope, string name, int pageSize)- {- ArgumentNullException.ThrowIfNull(bufferScope);- ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pageSize);+ ArgumentNullException.ThrowIfNull(bufferScope);+ ArgumentOutOfRangeException.ThrowIfNegativeOrZero(pageSize);- _bufferScope = bufferScope;- _name = name;- _pageSize = pageSize;- }+ _bufferScope = bufferScope;+ _name = name;+ _pageSize = pageSize;+ }- /// <summary>- /// Get the <see cref="ViewBufferPage"/> count.- /// </summary>- public int Count {- get {- if (_multiplePages != null)- {- return _multiplePages.Count;- }- if (_currentPage != null)- {- return 1;- }- return 0;- }+ /// <summary>+ /// Get the <see cref="ViewBufferPage" /> count.+ /// </summary>+ public int Count {+ get {+ if (_multiplePages != null) return _multiplePages.Count;+ if (_currentPage != null) return 1;+ return 0;}+ }- /// <summary>- /// Gets a <see cref="ViewBufferPage"/>.- /// </summary>- public ViewBufferPage this[int index] {- get {- if (_multiplePages != null)- {- return _multiplePages[index];- }- if (index == 0 && _currentPage != null)- {- return _currentPage;- }- throw new IndexOutOfRangeException();- }+ /// <summary>+ /// Gets a <see cref="ViewBufferPage" />.+ /// </summary>+ public ViewBufferPage this[int index] {+ get {+ if (_multiplePages != null) return _multiplePages[index];+ if (index == 0 && _currentPage != null) return _currentPage;+ throw new IndexOutOfRangeException();}+ }- /// <inheritdoc />- // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339- [MethodImpl(MethodImplOptions.AggressiveInlining)]- public IHtmlContentBuilder Append(string unencoded)- {- if (unencoded != null)- {- // Text that needs encoding is the uncommon case in views, which is why it- // creates a wrapper and pre-encoded text does not.- AppendValue(new ViewBufferValue(new EncodingWrapper(unencoded)));- }+ /// <inheritdoc />+ // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339+ [MethodImpl(MethodImplOptions.AggressiveInlining)]+ public IHtmlContentBuilder Append(string unencoded)+ {+ if (unencoded != null)+ // Text that needs encoding is the uncommon case in views, which is why it+ // creates a wrapper and pre-encoded text does not.+ AppendValue(new ViewBufferValue(new EncodingWrapper(unencoded)));- return this;- }+ return this;+ }- /// <inheritdoc />- // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339- [MethodImpl(MethodImplOptions.AggressiveInlining)]- public IHtmlContentBuilder AppendHtml(IHtmlContent content)- {- if (content != null)- {- AppendValue(new ViewBufferValue(content));- }+ /// <inheritdoc />+ // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339+ [MethodImpl(MethodImplOptions.AggressiveInlining)]+ public IHtmlContentBuilder AppendHtml(IHtmlContent content)+ {+ if (content != null) AppendValue(new ViewBufferValue(content));- return this;- }+ return this;+ }- /// <inheritdoc />- // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339- [MethodImpl(MethodImplOptions.AggressiveInlining)]- public IHtmlContentBuilder AppendHtml(string encoded)- {- if (encoded != null)- {- AppendValue(new ViewBufferValue(encoded));- }+ /// <inheritdoc />+ // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339+ [MethodImpl(MethodImplOptions.AggressiveInlining)]+ public IHtmlContentBuilder AppendHtml(string encoded)+ {+ if (encoded != null) AppendValue(new ViewBufferValue(encoded));- return this;- }+ return this;+ }- // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339- [MethodImpl(MethodImplOptions.AggressiveInlining)]- private void AppendValue(ViewBufferValue value)- {- var page = GetCurrentPage();- page.Append(value);- }+ /// <inheritdoc />+ public IHtmlContentBuilder Clear()+ {+ _multiplePages = null;+ _currentPage = null;+ return this;+ }++ /// <inheritdoc />+ public void WriteTo(TextWriter writer, HtmlEncoder encoder)+ {+ ArgumentNullException.ThrowIfNull(writer);+ ArgumentNullException.ThrowIfNull(encoder);- // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339- [MethodImpl(MethodImplOptions.AggressiveInlining)]- private ViewBufferPage GetCurrentPage()+ for (var i = 0; i < Count; i++){- var currentPage = _currentPage;- if (currentPage == null || currentPage.IsFull)+ var page = this[i];+ for (var j = 0; j < page.Count; j++){- // Uncommon slow-path- return AppendNewPage();- }+ var value = page.Buffer[j];- return currentPage;- }+ if (value.Value is string valueAsString)+ {+ writer.Write(valueAsString);+ continue;+ }- // Slow path for above, don't inline- [MethodImpl(MethodImplOptions.NoInlining)]- private ViewBufferPage AppendNewPage()- {- AddPage(new ViewBufferPage(_bufferScope.GetPage(_pageSize)));- return _currentPage;+ if (value.Value is IHtmlContent valueAsHtmlContent) valueAsHtmlContent.WriteTo(writer, encoder);+ }}+ }- private void AddPage(ViewBufferPage page)+ public void CopyTo(IHtmlContentBuilder destination)+ {+ ArgumentNullException.ThrowIfNull(destination);++ for (var i = 0; i < Count; i++){- if (_multiplePages != null)- {- _multiplePages.Add(page);- }- else if (_currentPage != null)+ var page = this[i];+ for (var j = 0; j < page.Count; j++){- _multiplePages = [- _currentPage,- page- ];+ var value = page.Buffer[j];++ string valueAsString;+ IHtmlContentContainer valueAsContainer;+ if ((valueAsString = value.Value as string) != null)+ destination.AppendHtml(valueAsString);+ else if ((valueAsContainer = value.Value as IHtmlContentContainer) != null)+ valueAsContainer.CopyTo(destination);+ else+ destination.AppendHtml((IHtmlContent)value.Value);}-- _currentPage = page;}+ }- /// <inheritdoc />- public IHtmlContentBuilder Clear()- {- _multiplePages = null;- _currentPage = null;- return this;- }+ public void MoveTo(IHtmlContentBuilder destination)+ {+ ArgumentNullException.ThrowIfNull(destination);- /// <inheritdoc />- public void WriteTo(TextWriter writer, HtmlEncoder encoder)+ // Perf: We have an efficient implementation when the destination is another view buffer,+ // we can just insert our pages as-is.+ if (destination is ViewBuffer other){- ArgumentNullException.ThrowIfNull(writer);- ArgumentNullException.ThrowIfNull(encoder);-- for (var i = 0; i < Count; i++)- {- var page = this[i];- for (var j = 0; j < page.Count; j++)- {- var value = page.Buffer[j];-- if (value.Value is string valueAsString)- {- writer.Write(valueAsString);- continue;- }-- if (value.Value is IHtmlContent valueAsHtmlContent)- {- valueAsHtmlContent.WriteTo(writer, encoder);- continue;- }- }- }+ MoveTo(other);+ return;}- /// <summary>- /// Writes the buffered content to <paramref name="writer"/>.- /// </summary>- /// <param name="writer">The <see cref="TextWriter"/>.</param>- /// <param name="encoder">The <see cref="HtmlEncoder"/>.</param>- /// <returns>A <see cref="Task"/> which will complete once content has been written.</returns>- public async Task WriteToAsync(TextWriter writer, HtmlEncoder encoder)+ for (var i = 0; i < Count; i++){- ArgumentNullException.ThrowIfNull(writer);- ArgumentNullException.ThrowIfNull(encoder);-- for (var i = 0; i < Count; i++)+ var page = this[i];+ for (var j = 0; j < page.Count; j++){- var page = this[i];- for (var j = 0; j < page.Count; j++)- {- var value = page.Buffer[j];-- if (value.Value is string valueAsString)- {- await writer.WriteAsync(valueAsString);- continue;- }-- if (value.Value is ViewBuffer valueAsViewBuffer)- {- await valueAsViewBuffer.WriteToAsync(writer, encoder);- continue;- }-- if (value.Value is IHtmlContent valueAsHtmlContent)- {- valueAsHtmlContent.WriteTo(writer, encoder);- await writer.FlushAsync();- continue;- }- }+ var value = page.Buffer[j];++ string valueAsString;+ IHtmlContentContainer valueAsContainer;+ if ((valueAsString = value.Value as string) != null)+ destination.AppendHtml(valueAsString);+ else if ((valueAsContainer = value.Value as IHtmlContentContainer) != null)+ valueAsContainer.MoveTo(destination);+ else+ destination.AppendHtml((IHtmlContent)value.Value);}}- private string DebuggerToString()+ for (var i = 0; i < Count; i++){- return _name;+ var page = this[i];+ Array.Clear(page.Buffer, 0, page.Count);+ _bufferScope.ReturnSegment(page.Buffer);}- public void CopyTo(IHtmlContentBuilder destination)- {- ArgumentNullException.ThrowIfNull(destination);+ Clear();+ }- for (var i = 0; i < Count; i++)- {- var page = this[i];- for (var j = 0; j < page.Count; j++)- {- var value = page.Buffer[j];-- string valueAsString;- IHtmlContentContainer valueAsContainer;- if ((valueAsString = value.Value as string) != null)- {- destination.AppendHtml(valueAsString);- }- else if ((valueAsContainer = value.Value as IHtmlContentContainer) != null)- {- valueAsContainer.CopyTo(destination);- }- else- {- destination.AppendHtml((IHtmlContent)value.Value);- }- }- }- }+ // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339+ [MethodImpl(MethodImplOptions.AggressiveInlining)]+ private void AppendValue(ViewBufferValue value)+ {+ var page = GetCurrentPage();+ page.Append(value);+ }- public void MoveTo(IHtmlContentBuilder destination)- {- ArgumentNullException.ThrowIfNull(destination);+ // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339+ [MethodImpl(MethodImplOptions.AggressiveInlining)]+ private ViewBufferPage GetCurrentPage()+ {+ var currentPage = _currentPage;+ if (currentPage == null || currentPage.IsFull)+ // Uncommon slow-path+ return AppendNewPage();- // Perf: We have an efficient implementation when the destination is another view buffer,- // we can just insert our pages as-is.- if (destination is ViewBuffer other)- {- MoveTo(other);- return;- }+ return currentPage;+ }- for (var i = 0; i < Count; i++)- {- var page = this[i];- for (var j = 0; j < page.Count; j++)- {- var value = page.Buffer[j];-- string valueAsString;- IHtmlContentContainer valueAsContainer;- if ((valueAsString = value.Value as string) != null)- {- destination.AppendHtml(valueAsString);- }- else if ((valueAsContainer = value.Value as IHtmlContentContainer) != null)- {- valueAsContainer.MoveTo(destination);- }- else- {- destination.AppendHtml((IHtmlContent)value.Value);- }- }- }+ // Slow path for above, don't inline+ [MethodImpl(MethodImplOptions.NoInlining)]+ private ViewBufferPage AppendNewPage()+ {+ AddPage(new ViewBufferPage(_bufferScope.GetPage(_pageSize)));+ return _currentPage;+ }- for (var i = 0; i < Count; i++)- {- var page = this[i];- Array.Clear(page.Buffer, 0, page.Count);- _bufferScope.ReturnSegment(page.Buffer);- }+ private void AddPage(ViewBufferPage page)+ {+ if (_multiplePages != null)+ _multiplePages.Add(page);+ else if (_currentPage != null)+ _multiplePages = [+ _currentPage,+ page+ ];++ _currentPage = page;+ }- Clear();- }+ /// <summary>+ /// Writes the buffered content to <paramref name="writer" />.+ /// </summary>+ /// <param name="writer">The <see cref="TextWriter" />.</param>+ /// <param name="encoder">The <see cref="HtmlEncoder" />.</param>+ /// <returns>A <see cref="Task" /> which will complete once content has been written.</returns>+ public async Task WriteToAsync(TextWriter writer, HtmlEncoder encoder)+ {+ ArgumentNullException.ThrowIfNull(writer);+ ArgumentNullException.ThrowIfNull(encoder);- private void MoveTo(ViewBuffer destination)+ for (var i = 0; i < Count; i++){- for (var i = 0; i < Count; i++)+ var page = this[i];+ for (var j = 0; j < page.Count; j++){- var page = this[i];+ var value = page.Buffer[j];- var destinationPage = destination.Count == 0 ? null : destination[destination.Count - 1];-- var isLessThanHalfFull = 2 * page.Count <= page.Capacity;- if (isLessThanHalfFull &&- destinationPage != null &&- destinationPage.Capacity - destinationPage.Count >= page.Count)+ if (value.Value is string valueAsString){- Array.Copy(- sourceArray: page.Buffer,- sourceIndex: 0,- destinationArray: destinationPage.Buffer,- destinationIndex: destinationPage.Count,- length: page.Count);-- destinationPage.Count += page.Count;-- // Now we can return the source page, and it can be reused in the scope of this request.- Array.Clear(page.Buffer, 0, page.Count);- _bufferScope.ReturnSegment(page.Buffer);-+ await writer.WriteAsync(valueAsString);+ continue;}- else++ if (value.Value is ViewBuffer valueAsViewBuffer){- // Otherwise, let's just add the source page to the other buffer.- destination.AddPage(page);+ await valueAsViewBuffer.WriteToAsync(writer, encoder);+ continue;}+ if (value.Value is IHtmlContent valueAsHtmlContent)+ {+ valueAsHtmlContent.WriteTo(writer, encoder);+ await writer.FlushAsync();+ }}-- Clear();}+ }++ private string DebuggerToString()+ {+ return _name;+ }- private class EncodingWrapper : IHtmlContent+ private void MoveTo(ViewBuffer destination)+ {+ for (var i = 0; i < Count; i++){- private readonly string _unencoded;+ var page = this[i];- public EncodingWrapper(string unencoded)+ var destinationPage = destination.Count == 0 ? null : destination[destination.Count - 1];++ var isLessThanHalfFull = 2 * page.Count <= page.Capacity;+ if (isLessThanHalfFull &&+ destinationPage != null &&+ destinationPage.Capacity - destinationPage.Count >= page.Count){- _unencoded = unencoded;- }+ Array.Copy(+ page.Buffer,+ 0,+ destinationPage.Buffer,+ destinationPage.Count,+ page.Count);- public void WriteTo(TextWriter writer, HtmlEncoder encoder)+ destinationPage.Count += page.Count;++ // Now we can return the source page, and it can be reused in the scope of this request.+ Array.Clear(page.Buffer, 0, page.Count);+ _bufferScope.ReturnSegment(page.Buffer);+ }+ else{- encoder.Encode(writer, _unencoded);+ // Otherwise, let's just add the source page to the other buffer.+ destination.AddPage(page);}}++ Clear();+ }++ private class EncodingWrapper : IHtmlContent+ {+ private readonly string _unencoded;++ public EncodingWrapper(string unencoded)+ {+ _unencoded = unencoded;+ }++ public void WriteTo(TextWriter writer, HtmlEncoder encoder)+ {+ encoder.Encode(writer, _unencoded);+ }}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ViewBufferPage.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ViewBufferPage.csindex f789e22bb..cdbf3e9dc 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ViewBufferPage.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ViewBufferPage.cs@@ -4,28 +4,27 @@using Microsoft.AspNetCore.Mvc.ViewFeatures.Buffers;using System.Runtime.CompilerServices;-namespace Grand.Web.Common.TagHelpers.Admin.Extend+namespace Grand.Web.Common.TagHelpers.Admin.Extend;++internal class ViewBufferPage{- internal class ViewBufferPage+ public ViewBufferPage(ViewBufferValue[] buffer){- public ViewBufferPage(ViewBufferValue[] buffer)- {- Buffer = buffer;- }+ Buffer = buffer;+ }- public ViewBufferValue[] Buffer { get; }+ public ViewBufferValue[] Buffer { get; }- public int Capacity => Buffer.Length;+ public int Capacity => Buffer.Length;- public int Count { get; set; }+ public int Count { get; set; }- public bool IsFull => Count == Capacity;+ public bool IsFull => Count == Capacity;- // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339- [MethodImpl(MethodImplOptions.AggressiveInlining)]- public void Append(ViewBufferValue value)- {- Buffer[Count++] = value;- }+ // Very common trivial method; nudge it to inline https://github.com/aspnet/Mvc/pull/8339+ [MethodImpl(MethodImplOptions.AggressiveInlining)]+ public void Append(ViewBufferValue value)+ {+ Buffer[Count++] = value;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ViewBufferTextWriter.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ViewBufferTextWriter.csindex a0209e532..b10105940 100644--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ViewBufferTextWriter.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/Extend/ViewBufferTextWriter.cs@@ -4,370 +4,309 @@using Microsoft.AspNetCore.Html;using System.Text.Encodings.Web;-namespace Grand.Web.Common.TagHelpers.Admin.Extend+namespace Grand.Web.Common.TagHelpers.Admin.Extend;++internal class ViewBufferTextWriter : TextWriter{- internal class ViewBufferTextWriter : TextWriter+ private readonly HtmlEncoder _htmlEncoder;+ private readonly TextWriter _inner;++ /// <summary>+ /// Creates a new instance of <see cref="ViewBufferTextWriter" />.+ /// </summary>+ /// <param name="buffer">The <see cref="ViewBuffer" /> for buffered output.</param>+ /// <param name="encoding">The <see cref="System.Text.Encoding" />.</param>+ public ViewBufferTextWriter(ViewBuffer buffer, Encoding encoding){- private readonly TextWriter _inner;- private readonly HtmlEncoder _htmlEncoder;-- /// <summary>- /// Creates a new instance of <see cref="ViewBufferTextWriter"/>.- /// </summary>- /// <param name="buffer">The <see cref="ViewBuffer"/> for buffered output.</param>- /// <param name="encoding">The <see cref="System.Text.Encoding"/>.</param>- public ViewBufferTextWriter(ViewBuffer buffer, Encoding encoding)- {- ArgumentNullException.ThrowIfNull(buffer);- ArgumentNullException.ThrowIfNull(encoding);+ ArgumentNullException.ThrowIfNull(buffer);+ ArgumentNullException.ThrowIfNull(encoding);- Buffer = buffer;- Encoding = encoding;- }+ Buffer = buffer;+ Encoding = encoding;+ }- /// <summary>- /// Creates a new instance of <see cref="ViewBufferTextWriter"/>.- /// </summary>- /// <param name="buffer">The <see cref="ViewBuffer"/> for buffered output.</param>- /// <param name="encoding">The <see cref="System.Text.Encoding"/>.</param>- /// <param name="htmlEncoder">The HTML encoder.</param>- /// <param name="inner">- /// The inner <see cref="TextWriter"/> to write output to when this instance is no longer buffering.- /// </param>- public ViewBufferTextWriter(ViewBuffer buffer, Encoding encoding, HtmlEncoder htmlEncoder, TextWriter inner)- {- ArgumentNullException.ThrowIfNull(buffer);- ArgumentNullException.ThrowIfNull(encoding);- ArgumentNullException.ThrowIfNull(htmlEncoder);- ArgumentNullException.ThrowIfNull(inner);-- Buffer = buffer;- Encoding = encoding;- _htmlEncoder = htmlEncoder;- _inner = inner;- }+ /// <summary>+ /// Creates a new instance of <see cref="ViewBufferTextWriter" />.+ /// </summary>+ /// <param name="buffer">The <see cref="ViewBuffer" /> for buffered output.</param>+ /// <param name="encoding">The <see cref="System.Text.Encoding" />.</param>+ /// <param name="htmlEncoder">The HTML encoder.</param>+ /// <param name="inner">+ /// The inner <see cref="TextWriter" /> to write output to when this instance is no longer buffering.+ /// </param>+ public ViewBufferTextWriter(ViewBuffer buffer, Encoding encoding, HtmlEncoder htmlEncoder, TextWriter inner)+ {+ ArgumentNullException.ThrowIfNull(buffer);+ ArgumentNullException.ThrowIfNull(encoding);+ ArgumentNullException.ThrowIfNull(htmlEncoder);+ ArgumentNullException.ThrowIfNull(inner);++ Buffer = buffer;+ Encoding = encoding;+ _htmlEncoder = htmlEncoder;+ _inner = inner;+ }- /// <inheritdoc />- public override Encoding Encoding { get; }+ /// <inheritdoc />+ public override Encoding Encoding { get; }- /// <inheritdoc />- public bool IsBuffering { get; private set; } = true;+ /// <inheritdoc />+ public bool IsBuffering { get; private set; } = true;- /// <summary>- /// Gets the <see cref="ViewBuffer"/>.- /// </summary>- public ViewBuffer Buffer { get; }+ /// <summary>+ /// Gets the <see cref="ViewBuffer" />.+ /// </summary>+ public ViewBuffer Buffer { get; }- /// <inheritdoc />- public override void Write(char value)- {- if (IsBuffering)- {- Buffer.AppendHtml(value.ToString());- }- else- {- _inner.Write(value);- }- }+ /// <inheritdoc />+ public override void Write(char value)+ {+ if (IsBuffering)+ Buffer.AppendHtml(value.ToString());+ else+ _inner.Write(value);+ }++ /// <inheritdoc />+ public override void Write(char[] buffer, int index, int count)+ {+ ArgumentNullException.ThrowIfNull(buffer);++ if (index < 0 || index >= buffer.Length) throw new ArgumentOutOfRangeException(nameof(index));++ if (count < 0 || buffer.Length - index < count) throw new ArgumentOutOfRangeException(nameof(count));++ if (IsBuffering)+ Buffer.AppendHtml(new string(buffer, index, count));+ else+ _inner.Write(buffer, index, count);+ }++ /// <inheritdoc />+ public override void Write(string value)+ {+ if (string.IsNullOrEmpty(value)) return;++ if (IsBuffering)+ Buffer.AppendHtml(value);+ else+ _inner.Write(value);+ }++ /// <inheritdoc />+ public override void Write(object value)+ {+ if (value == null) return;++ if (value is IHtmlContentContainer container)+ Write(container);+ else if (value is IHtmlContent htmlContent)+ Write(htmlContent);+ else+ Write(value.ToString());+ }++ /// <summary>+ /// Writes an <see cref="IHtmlContent" /> value.+ /// </summary>+ /// <param name="value">The <see cref="IHtmlContent" /> value.</param>+ public void Write(IHtmlContent value)+ {+ if (value == null) return;++ if (IsBuffering)+ Buffer.AppendHtml(value);+ else+ value.WriteTo(_inner, _htmlEncoder);+ }- /// <inheritdoc />- public override void Write(char[] buffer, int index, int count)+ /// <summary>+ /// Writes an <see cref="IHtmlContentContainer" /> value.+ /// </summary>+ /// <param name="value">The <see cref="IHtmlContentContainer" /> value.</param>+ public void Write(IHtmlContentContainer value)+ {+ if (value == null) return;++ if (IsBuffering)+ value.MoveTo(Buffer);+ else+ value.WriteTo(_inner, _htmlEncoder);+ }++ /// <inheritdoc />+ public override void WriteLine(object value)+ {+ if (value == null) return;++ if (value is IHtmlContentContainer container){- ArgumentNullException.ThrowIfNull(buffer);-- if (index < 0 || index >= buffer.Length)- {- throw new ArgumentOutOfRangeException(nameof(index));- }-- if (count < 0 || buffer.Length - index < count)- {- throw new ArgumentOutOfRangeException(nameof(count));- }-- if (IsBuffering)- {- Buffer.AppendHtml(new string(buffer, index, count));- }- else- {- _inner.Write(buffer, index, count);- }+ Write(container);+ Write(NewLine);}-- /// <inheritdoc />- public override void Write(string value)+ else if (value is IHtmlContent htmlContent){- if (string.IsNullOrEmpty(value))- {- return;- }-- if (IsBuffering)- {- Buffer.AppendHtml(value);- }- else- {- _inner.Write(value);- }+ Write(htmlContent);+ Write(NewLine);}-- /// <inheritdoc />- public override void Write(object value)+ else{- if (value == null)- {- return;- }-- if (value is IHtmlContentContainer container)- {- Write(container);- }- else if (value is IHtmlContent htmlContent)- {- Write(htmlContent);- }- else- {- Write(value.ToString());- }+ Write(value.ToString());+ Write(NewLine);}+ }- /// <summary>- /// Writes an <see cref="IHtmlContent"/> value.- /// </summary>- /// <param name="value">The <see cref="IHtmlContent"/> value.</param>- public void Write(IHtmlContent value)+ /// <inheritdoc />+ public override Task WriteAsync(char value)+ {+ if (IsBuffering){- if (value == null)- {- return;- }-- if (IsBuffering)- {- Buffer.AppendHtml(value);- }- else- {- value.WriteTo(_inner, _htmlEncoder);- }+ Buffer.AppendHtml(value.ToString());+ return Task.CompletedTask;}- /// <summary>- /// Writes an <see cref="IHtmlContentContainer"/> value.- /// </summary>- /// <param name="value">The <see cref="IHtmlContentContainer"/> value.</param>- public void Write(IHtmlContentContainer value)+ return _inner.WriteAsync(value);+ }++ /// <inheritdoc />+ public override Task WriteAsync(char[] buffer, int index, int count)+ {+ ArgumentNullException.ThrowIfNull(buffer);+ ArgumentOutOfRangeException.ThrowIfNegative(index);++ if (count < 0 || buffer.Length - index < count) throw new ArgumentOutOfRangeException(nameof(count));++ if (IsBuffering){- if (value == null)- {- return;- }-- if (IsBuffering)- {- value.MoveTo(Buffer);- }- else- {- value.WriteTo(_inner, _htmlEncoder);- }+ Buffer.AppendHtml(new string(buffer, index, count));+ return Task.CompletedTask;}- /// <inheritdoc />- public override void WriteLine(object value)+ return _inner.WriteAsync(buffer, index, count);+ }++ /// <inheritdoc />+ public override Task WriteAsync(string value)+ {+ if (IsBuffering){- if (value == null)- {- return;- }-- if (value is IHtmlContentContainer container)- {- Write(container);- Write(NewLine);- }- else if (value is IHtmlContent htmlContent)- {- Write(htmlContent);- Write(NewLine);- }- else- {- Write(value.ToString());- Write(NewLine);- }+ Buffer.AppendHtml(value);+ return Task.CompletedTask;}- /// <inheritdoc />- public override Task WriteAsync(char value)- {- if (IsBuffering)- {- Buffer.AppendHtml(value.ToString());- return Task.CompletedTask;- }+ return _inner.WriteAsync(value);+ }- return _inner.WriteAsync(value);- }+ /// <inheritdoc />+ public override void WriteLine()+ {+ if (IsBuffering)+ Buffer.AppendHtml(NewLine);+ else+ _inner.WriteLine();+ }- /// <inheritdoc />- public override Task WriteAsync(char[] buffer, int index, int count)+ /// <inheritdoc />+ public override void WriteLine(string value)+ {+ if (IsBuffering){- ArgumentNullException.ThrowIfNull(buffer);- ArgumentOutOfRangeException.ThrowIfNegative(index);-- if (count < 0 || buffer.Length - index < count)- {- throw new ArgumentOutOfRangeException(nameof(count));- }-- if (IsBuffering)- {- Buffer.AppendHtml(new string(buffer, index, count));- return Task.CompletedTask;- }-- return _inner.WriteAsync(buffer, index, count);+ Buffer.AppendHtml(value);+ Buffer.AppendHtml(NewLine);}-- /// <inheritdoc />- public override Task WriteAsync(string value)+ else{- if (IsBuffering)- {- Buffer.AppendHtml(value);- return Task.CompletedTask;- }-- return _inner.WriteAsync(value);+ _inner.WriteLine(value);}+ }- /// <inheritdoc />- public override void WriteLine()+ /// <inheritdoc />+ public override Task WriteLineAsync(char value)+ {+ if (IsBuffering){- if (IsBuffering)- {- Buffer.AppendHtml(NewLine);- }- else- {- _inner.WriteLine();- }+ Buffer.AppendHtml(value.ToString());+ Buffer.AppendHtml(NewLine);+ return Task.CompletedTask;}- /// <inheritdoc />- public override void WriteLine(string value)- {- if (IsBuffering)- {- Buffer.AppendHtml(value);- Buffer.AppendHtml(NewLine);- }- else- {- _inner.WriteLine(value);- }- }+ return _inner.WriteLineAsync(value);+ }- /// <inheritdoc />- public override Task WriteLineAsync(char value)+ /// <inheritdoc />+ public override Task WriteLineAsync(char[] value, int start, int offset)+ {+ if (IsBuffering){- if (IsBuffering)- {- Buffer.AppendHtml(value.ToString());- Buffer.AppendHtml(NewLine);- return Task.CompletedTask;- }-- return _inner.WriteLineAsync(value);+ Buffer.AppendHtml(new string(value, start, offset));+ Buffer.AppendHtml(NewLine);+ return Task.CompletedTask;}- /// <inheritdoc />- public override Task WriteLineAsync(char[] value, int start, int offset)+ return _inner.WriteLineAsync(value, start, offset);+ }++ /// <inheritdoc />+ public override Task WriteLineAsync(string value)+ {+ if (IsBuffering){- if (IsBuffering)- {- Buffer.AppendHtml(new string(value, start, offset));- Buffer.AppendHtml(NewLine);- return Task.CompletedTask;- }-- return _inner.WriteLineAsync(value, start, offset);+ Buffer.AppendHtml(value);+ Buffer.AppendHtml(NewLine);+ return Task.CompletedTask;}- /// <inheritdoc />- public override Task WriteLineAsync(string value)+ return _inner.WriteLineAsync(value);+ }++ /// <inheritdoc />+ public override Task WriteLineAsync()+ {+ if (IsBuffering){- if (IsBuffering)- {- Buffer.AppendHtml(value);- Buffer.AppendHtml(NewLine);- return Task.CompletedTask;- }-- return _inner.WriteLineAsync(value);+ Buffer.AppendHtml(NewLine);+ return Task.CompletedTask;}- /// <inheritdoc />- public override Task WriteLineAsync()- {- if (IsBuffering)- {- Buffer.AppendHtml(NewLine);- return Task.CompletedTask;- }+ return _inner.WriteLineAsync();+ }- return _inner.WriteLineAsync();- }+ /// <summary>+ /// Copies the buffered content to the unbuffered writer and invokes flush on it.+ /// Additionally causes this instance to no longer buffer and direct all write operations+ /// to the unbuffered writer.+ /// </summary>+ public override void Flush()+ {+ if (_inner == null || _inner is ViewBufferTextWriter) return;- /// <summary>- /// Copies the buffered content to the unbuffered writer and invokes flush on it.- /// Additionally causes this instance to no longer buffer and direct all write operations- /// to the unbuffered writer.- /// </summary>- public override void Flush()+ if (IsBuffering){- if (_inner == null || _inner is ViewBufferTextWriter)- {- return;- }-- if (IsBuffering)- {- IsBuffering = false;- Buffer.WriteTo(_inner, _htmlEncoder);- Buffer.Clear();- }-- _inner.Flush();+ IsBuffering = false;+ Buffer.WriteTo(_inner, _htmlEncoder);+ Buffer.Clear();}- /// <summary>- /// Copies the buffered content to the unbuffered writer and invokes flush on it.- /// Additionally causes this instance to no longer buffer and direct all write operations- /// to the unbuffered writer.- /// </summary>- /// <returns>A <see cref="Task"/> that represents the asynchronous copy and flush operations.</returns>- public override async Task FlushAsync()+ _inner.Flush();+ }++ /// <summary>+ /// Copies the buffered content to the unbuffered writer and invokes flush on it.+ /// Additionally causes this instance to no longer buffer and direct all write operations+ /// to the unbuffered writer.+ /// </summary>+ /// <returns>A <see cref="Task" /> that represents the asynchronous copy and flush operations.</returns>+ public override async Task FlushAsync()+ {+ if (_inner == null || _inner is ViewBufferTextWriter) return;++ if (IsBuffering){- if (_inner == null || _inner is ViewBufferTextWriter)- {- return;- }-- if (IsBuffering)- {- IsBuffering = false;- await Buffer.WriteToAsync(_inner, _htmlEncoder);- Buffer.Clear();- }-- await _inner.FlushAsync();+ IsBuffering = false;+ await Buffer.WriteToAsync(_inner, _htmlEncoder);+ Buffer.Clear();}++ await _inner.FlushAsync();}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/CanonicalUrlsTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/CanonicalUrlsTagHelper.csindex 2be6c8385..fabaf1235 100644--- a/src/Web/Grand.Web.Common/TagHelpers/CanonicalUrlsTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/CanonicalUrlsTagHelper.cs@@ -1,24 +1,22 @@using Grand.Web.Common.Page;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers-{- [HtmlTargetElement("canonical-urls", TagStructure = TagStructure.WithoutEndTag)]- public class CanonicalUrlsTagHelper : TagHelper- {+namespace Grand.Web.Common.TagHelpers;- private readonly IPageHeadBuilder _pageHeadBuilder;+[HtmlTargetElement("canonical-urls", TagStructure = TagStructure.WithoutEndTag)]+public class CanonicalUrlsTagHelper : TagHelper+{+ private readonly IPageHeadBuilder _pageHeadBuilder;- public CanonicalUrlsTagHelper(IPageHeadBuilder pageHeadBuilder)- {- _pageHeadBuilder = pageHeadBuilder;- }+ public CanonicalUrlsTagHelper(IPageHeadBuilder pageHeadBuilder)+ {+ _pageHeadBuilder = pageHeadBuilder;+ }- public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)- {- output.SuppressOutput();- output.Content.SetHtmlContent(_pageHeadBuilder.GenerateCanonicalUrls());- return Task.CompletedTask;- }+ public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ output.SuppressOutput();+ output.Content.SetHtmlContent(_pageHeadBuilder.GenerateCanonicalUrls());+ return Task.CompletedTask;}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/DatePickerDropDownsTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/DatePickerDropDownsTagHelper.csindex cd7bd980f..fcee79d69 100644--- a/src/Web/Grand.Web.Common/TagHelpers/DatePickerDropDownsTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/DatePickerDropDownsTagHelper.cs@@ -6,103 +6,91 @@ using Microsoft.AspNetCore.Mvc.ViewFeatures;using Microsoft.AspNetCore.Razor.TagHelpers;using System.Globalization;-namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++[HtmlTargetElement("date-picker-dropdown")]+public class DatePickerDropDownsTagHelper : TagHelper{- [HtmlTargetElement("date-picker-dropdown")]- public class DatePickerDropDownsTagHelper : TagHelper+ private readonly IHtmlHelper _htmlHelper;+ private readonly ITranslationService _translationService;++ public DatePickerDropDownsTagHelper(IHtmlHelper htmlHelper, ITranslationService translationService)+ {+ _htmlHelper = htmlHelper;+ _translationService = translationService;+ }++ [ViewContext] public ViewContext ViewContext { get; set; }++ [HtmlAttributeName("PartialViewName")] public string PartialViewName { get; set; }++ [HtmlAttributeName("Attribute")] public string Attribute { get; set; }++ [HtmlAttributeName("control-day")] public string ControlId_Day { get; set; }++ [HtmlAttributeName("control-month")] public string ControlId_Month { get; set; }++ [HtmlAttributeName("control-year")] public string ControlId_Year { get; set; }++ [HtmlAttributeName("begin-year")] public int Begin_Year { get; set; }++ [HtmlAttributeName("end-year")] public int End_Year { get; set; }++ [HtmlAttributeName("selected-day")] public int SelectedDay { get; set; }++ [HtmlAttributeName("selected-month")] public int SelectedMonth { get; set; }++ [HtmlAttributeName("selected-year")] public int SelectedYear { get; set; }++ public override async Task ProcessAsync(TagHelperContext tagHelperContext, TagHelperOutput output){- private readonly IHtmlHelper _htmlHelper;- private readonly ITranslationService _translationService;-- [ViewContext]- public ViewContext ViewContext { get; set; }-- [HtmlAttributeName("PartialViewName")]- public string PartialViewName { get; set; }-- [HtmlAttributeName("Attribute")]- public string Attribute { get; set; }-- [HtmlAttributeName("control-day")]- public string ControlId_Day { get; set; }-- [HtmlAttributeName("control-month")]- public string ControlId_Month { get; set; }-- [HtmlAttributeName("control-year")]- public string ControlId_Year { get; set; }-- [HtmlAttributeName("begin-year")]- public int Begin_Year { get; set; }-- [HtmlAttributeName("end-year")]- public int End_Year { get; set; }-- [HtmlAttributeName("selected-day")]- public int SelectedDay { get; set; }-- [HtmlAttributeName("selected-month")]- public int SelectedMonth { get; set; }-- [HtmlAttributeName("selected-year")]- public int SelectedYear { get; set; }-- public DatePickerDropDownsTagHelper(IHtmlHelper htmlHelper, ITranslationService translationService)- {- _htmlHelper = htmlHelper;- _translationService = translationService;- }-- public override async Task ProcessAsync(TagHelperContext tagHelperContext, TagHelperOutput output)- {- (_htmlHelper as IViewContextAware).Contextualize(ViewContext);-- output.TagName = "div";- output.TagMode = TagMode.StartTagAndEndTag;-- var model = new DatePickerDropDownsModel {- Attribute = Attribute,- Begin_Year = Begin_Year,- Day = ControlId_Day,- Month = ControlId_Month,- Year = ControlId_Year,- End_Year = End_Year,- SelectedDay = SelectedDay,- SelectedMonth = SelectedMonth,- SelectedYear = SelectedYear- };-- model.SelectListDay.Add(new SelectListItem { Value = "0", Text = _translationService.GetResource("Common.Day") });- for (var i = 1; i <= 31; i++)- {- model.SelectListDay.Add(new SelectListItem { Value = i.ToString(), Text = i.ToString(), Selected = SelectedDay == i });- }-- model.SelectListMonth.Add(new SelectListItem { Value = "0", Text = _translationService.GetResource("Common.Month") });- for (var i = 1; i <= 12; i++)- {- model.SelectListMonth.Add(new SelectListItem { Value = i.ToString(), Text = CultureInfo.CurrentUICulture.DateTimeFormat.GetMonthName(i), Selected = SelectedMonth == i });- }-- model.SelectListYear.Add(new SelectListItem { Value = "0", Text = _translationService.GetResource("Common.Year") });-- if (Begin_Year == 0)- Begin_Year = DateTime.UtcNow.Year - 100;- if (End_Year == 0)- End_Year = DateTime.UtcNow.Year;-- if (End_Year > Begin_Year)- {- for (var i = Begin_Year; i <= End_Year; i++)- model.SelectListYear.Add(new SelectListItem { Value = i.ToString(), Text = i.ToString(), Selected = SelectedYear == i });- }- else- {- for (var i = Begin_Year; i >= End_Year; i--)- model.SelectListYear.Add(new SelectListItem { Value = i.ToString(), Text = i.ToString(), Selected = SelectedYear == i });- }- output.Content.SetHtmlContent((await _htmlHelper.PartialAsync(PartialViewName, model)).ToHtmlString());-- }+ (_htmlHelper as IViewContextAware).Contextualize(ViewContext);++ output.TagName = "div";+ output.TagMode = TagMode.StartTagAndEndTag;++ var model = new DatePickerDropDownsModel {+ Attribute = Attribute,+ Begin_Year = Begin_Year,+ Day = ControlId_Day,+ Month = ControlId_Month,+ Year = ControlId_Year,+ End_Year = End_Year,+ SelectedDay = SelectedDay,+ SelectedMonth = SelectedMonth,+ SelectedYear = SelectedYear+ };++ model.SelectListDay.Add(+ new SelectListItem { Value = "0", Text = _translationService.GetResource("Common.Day") });+ for (var i = 1; i <= 31; i++)+ model.SelectListDay.Add(new SelectListItem+ { Value = i.ToString(), Text = i.ToString(), Selected = SelectedDay == i });++ model.SelectListMonth.Add(new SelectListItem+ { Value = "0", Text = _translationService.GetResource("Common.Month") });+ for (var i = 1; i <= 12; i++)+ model.SelectListMonth.Add(new SelectListItem {+ Value = i.ToString(), Text = CultureInfo.CurrentUICulture.DateTimeFormat.GetMonthName(i),+ Selected = SelectedMonth == i+ });++ model.SelectListYear.Add(new SelectListItem+ { Value = "0", Text = _translationService.GetResource("Common.Year") });++ if (Begin_Year == 0)+ Begin_Year = DateTime.UtcNow.Year - 100;+ if (End_Year == 0)+ End_Year = DateTime.UtcNow.Year;++ if (End_Year > Begin_Year)+ for (var i = Begin_Year; i <= End_Year; i++)+ model.SelectListYear.Add(new SelectListItem+ { Value = i.ToString(), Text = i.ToString(), Selected = SelectedYear == i });+ else+ for (var i = Begin_Year; i >= End_Year; i--)+ model.SelectListYear.Add(new SelectListItem+ { Value = i.ToString(), Text = i.ToString(), Selected = SelectedYear == i });+ output.Content.SetHtmlContent((await _htmlHelper.PartialAsync(PartialViewName, model)).ToHtmlString());}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/GenerateCaptchaTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/GenerateCaptchaTagHelper.csindex a7765a5e7..9e5b187ab 100644--- a/src/Web/Grand.Web.Common/TagHelpers/GenerateCaptchaTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/GenerateCaptchaTagHelper.cs@@ -3,50 +3,48 @@ using Microsoft.AspNetCore.Mvc.Rendering;using Microsoft.AspNetCore.Mvc.ViewFeatures;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++[HtmlTargetElement("captcha", TagStructure = TagStructure.WithoutEndTag)]+public class GenerateCaptchaTagHelper : TagHelper{- [HtmlTargetElement("captcha", TagStructure = TagStructure.WithoutEndTag)]- public class GenerateCaptchaTagHelper : TagHelper+ private readonly CaptchaSettings _captchaSettings;+ private readonly IHtmlHelper _htmlHelper;++ public GenerateCaptchaTagHelper(IHtmlHelper htmlHelper, CaptchaSettings captchaSettings){- private readonly IHtmlHelper _htmlHelper;- private readonly CaptchaSettings _captchaSettings;-- /// <summary>- /// ViewContext- /// </summary>- [HtmlAttributeNotBound]- [ViewContext]- public ViewContext ViewContext { get; set; }-- public GenerateCaptchaTagHelper(IHtmlHelper htmlHelper, CaptchaSettings captchaSettings)- {- _htmlHelper = htmlHelper;- _captchaSettings = captchaSettings;- }-- public override void Process(TagHelperContext context, TagHelperOutput output)- {- ArgumentNullException.ThrowIfNull(context);- ArgumentNullException.ThrowIfNull(output);-- //contextualize IHtmlHelper- var viewContextAware = _htmlHelper as IViewContextAware;- viewContextAware?.Contextualize(ViewContext);-- //generate captcha control- var captchaControl = new GoogleRecaptchaControl(_captchaSettings.ReCaptchaVersion)- {- Theme = _captchaSettings.ReCaptchaTheme,- Id = "g-recaptcha-response-value",- PublicKey = _captchaSettings.ReCaptchaPublicKey,- Language = _captchaSettings.ReCaptchaLanguage- };- var captchaControlHtml = captchaControl.RenderControl();-- //tag details- output.TagName = "div";- output.TagMode = TagMode.StartTagAndEndTag;- output.Content.SetHtmlContent(captchaControlHtml);- }+ _htmlHelper = htmlHelper;+ _captchaSettings = captchaSettings;+ }++ /// <summary>+ /// ViewContext+ /// </summary>+ [HtmlAttributeNotBound]+ [ViewContext]+ public ViewContext ViewContext { get; set; }++ public override void Process(TagHelperContext context, TagHelperOutput output)+ {+ ArgumentNullException.ThrowIfNull(context);+ ArgumentNullException.ThrowIfNull(output);++ //contextualize IHtmlHelper+ var viewContextAware = _htmlHelper as IViewContextAware;+ viewContextAware?.Contextualize(ViewContext);++ //generate captcha control+ var captchaControl = new GoogleRecaptchaControl(_captchaSettings.ReCaptchaVersion) {+ Theme = _captchaSettings.ReCaptchaTheme,+ Id = "g-recaptcha-response-value",+ PublicKey = _captchaSettings.ReCaptchaPublicKey,+ Language = _captchaSettings.ReCaptchaLanguage+ };+ var captchaControlHtml = captchaControl.RenderControl();++ //tag details+ output.TagName = "div";+ output.TagMode = TagMode.StartTagAndEndTag;+ output.Content.SetHtmlContent(captchaControlHtml);}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/GrandTextAreaTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/GrandTextAreaTagHelper.csindex 136fc1523..286b84837 100644--- a/src/Web/Grand.Web.Common/TagHelpers/GrandTextAreaTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/GrandTextAreaTagHelper.cs@@ -2,30 +2,28 @@using Microsoft.AspNetCore.Mvc.ViewFeatures;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++[HtmlTargetElement("textarea", Attributes = ForAttributeName)]+public class GrandTextAreaTagHelper : TextAreaTagHelper{- [HtmlTargetElement("textarea", Attributes = ForAttributeName)]- public class GrandTextAreaTagHelper : TextAreaTagHelper+ private const string ForAttributeName = "asp-for";++ public GrandTextAreaTagHelper(IHtmlGenerator generator) : base(generator){- private const string ForAttributeName = "asp-for";+ }- [HtmlAttributeName("asp-disabled")]- public string IsDisabled { set; get; }+ [HtmlAttributeName("asp-disabled")] public string IsDisabled { set; get; }- public GrandTextAreaTagHelper(IHtmlGenerator generator) : base(generator)+ public override void Process(TagHelperContext context, TagHelperOutput output)+ {+ bool.TryParse(IsDisabled, out var disabled);+ if (disabled){+ var d = new TagHelperAttribute("disabled", "disabled");+ output.Attributes.Add(d);}- public override void Process(TagHelperContext context, TagHelperOutput output)- {- bool.TryParse(IsDisabled, out var disabled);- if (disabled)- {- var d = new TagHelperAttribute("disabled", "disabled");- output.Attributes.Add(d);- }-- base.Process(context, output);- }+ base.Process(context, output);}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/HeadCustomTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/HeadCustomTagHelper.csindex 2bdef5661..2bc6cef88 100644--- a/src/Web/Grand.Web.Common/TagHelpers/HeadCustomTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/HeadCustomTagHelper.cs@@ -1,24 +1,22 @@using Grand.Web.Common.Page;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers-{- [HtmlTargetElement("head-custom", TagStructure = TagStructure.WithoutEndTag)]- public class HeadCustomTagHelper : TagHelper- {+namespace Grand.Web.Common.TagHelpers;- private readonly IPageHeadBuilder _pageHeadBuilder;+[HtmlTargetElement("head-custom", TagStructure = TagStructure.WithoutEndTag)]+public class HeadCustomTagHelper : TagHelper+{+ private readonly IPageHeadBuilder _pageHeadBuilder;- public HeadCustomTagHelper(IPageHeadBuilder pageHeadBuilder)- {- _pageHeadBuilder = pageHeadBuilder;- }+ public HeadCustomTagHelper(IPageHeadBuilder pageHeadBuilder)+ {+ _pageHeadBuilder = pageHeadBuilder;+ }- public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)- {- output.SuppressOutput();- output.Content.SetHtmlContent(_pageHeadBuilder.GenerateHeadCustom());- return Task.CompletedTask;- }+ public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ output.SuppressOutput();+ output.Content.SetHtmlContent(_pageHeadBuilder.GenerateHeadCustom());+ return Task.CompletedTask;}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/HtmlClassTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/HtmlClassTagHelper.csindex 80e370c16..4ea4779e6 100644--- a/src/Web/Grand.Web.Common/TagHelpers/HtmlClassTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/HtmlClassTagHelper.cs@@ -1,32 +1,27 @@using Grand.Web.Common.Page;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++[HtmlTargetElement("html-class", TagStructure = TagStructure.WithoutEndTag)]+[HtmlTargetElement("html-class", Attributes = ForAttributeName)]+public class HtmlClassTagHelper : TagHelper{- [HtmlTargetElement("html-class", TagStructure = TagStructure.WithoutEndTag)]- [HtmlTargetElement("html-class", Attributes = ForAttributeName)]- public class HtmlClassTagHelper : TagHelper- {- private const string ForAttributeName = "asp-name";+ private const string ForAttributeName = "asp-name";- [HtmlAttributeName(ForAttributeName)]- public string Part { set; get; }+ private readonly IPageHeadBuilder _pageHeadBuilder;- private readonly IPageHeadBuilder _pageHeadBuilder;+ public HtmlClassTagHelper(IPageHeadBuilder pageHeadBuilder)+ {+ _pageHeadBuilder = pageHeadBuilder;+ }- public HtmlClassTagHelper(IPageHeadBuilder pageHeadBuilder)- {- _pageHeadBuilder = pageHeadBuilder;- }+ [HtmlAttributeName(ForAttributeName)] public string Part { set; get; }- public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)- {- output.SuppressOutput();- if (!string.IsNullOrEmpty(Part))- {- _pageHeadBuilder.AddPageCssClassParts(Part);- }- return Task.CompletedTask;- }+ public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ output.SuppressOutput();+ if (!string.IsNullOrEmpty(Part)) _pageHeadBuilder.AddPageCssClassParts(Part);+ return Task.CompletedTask;}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/HtmlTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/HtmlTagHelper.csindex 0d9fc30c4..26842f3ea 100644--- a/src/Web/Grand.Web.Common/TagHelpers/HtmlTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/HtmlTagHelper.cs@@ -2,47 +2,47 @@using Grand.Web.Common.Page;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++[HtmlTargetElement("html", Attributes = ForAttributeName)]+public class HtmlTagHelper : TagHelper{- [HtmlTargetElement("html", Attributes = ForAttributeName)]- public class HtmlTagHelper : TagHelper- {- private const string ForAttributeName = "use-lang";+ private const string ForAttributeName = "use-lang";++ private readonly IPageHeadBuilder _pageHeadBuilder;+ private readonly IWorkContext _workContext;- [HtmlAttributeName(ForAttributeName)]- public bool UseLanguage { set; get; }+ public HtmlTagHelper(IWorkContext workContext, IPageHeadBuilder pageHeadBuilder)+ {+ _workContext = workContext;+ _pageHeadBuilder = pageHeadBuilder;+ }- private readonly IPageHeadBuilder _pageHeadBuilder;- private readonly IWorkContext _workContext;+ [HtmlAttributeName(ForAttributeName)] public bool UseLanguage { set; get; }- public HtmlTagHelper(IWorkContext workContext, IPageHeadBuilder pageHeadBuilder)+ public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ if (UseLanguage){- _workContext = workContext;- _pageHeadBuilder = pageHeadBuilder;+ output.Attributes.Add("lang", _workContext.WorkingLanguage.UniqueSeoCode);+ if (_workContext.WorkingLanguage.Rtl)+ output.Attributes.Add("dir", "rtl");}- public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ var classes = _pageHeadBuilder.GeneratePageCssClasses();+ if (string.IsNullOrEmpty(classes)) return Task.CompletedTask;+ if (output.Attributes.ContainsName("class"))+ {+ var attribute = output.Attributes["class"];+ output.Attributes.Remove(attribute);+ output.Attributes.Add("class", $"{attribute.Value} {classes}");+ }+ else{- if (UseLanguage)- {- output.Attributes.Add("lang", _workContext.WorkingLanguage.UniqueSeoCode);- if(_workContext.WorkingLanguage.Rtl)- output.Attributes.Add("dir", "rtl");- }-- var classes = _pageHeadBuilder.GeneratePageCssClasses();- if (string.IsNullOrEmpty(classes)) return Task.CompletedTask;- if (output.Attributes.ContainsName("class"))- {- var attribute = output.Attributes["class"];- output.Attributes.Remove(attribute);- output.Attributes.Add("class", $"{attribute.Value} {classes}");- }- else- output.Attributes.Add("class", classes);--- return Task.CompletedTask;+ output.Attributes.Add("class", classes);}+++ return Task.CompletedTask;}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/IResourceManager.cs b/src/Web/Grand.Web.Common/TagHelpers/IResourceManager.csindex adeb99561..dfb2b9b85 100644--- a/src/Web/Grand.Web.Common/TagHelpers/IResourceManager.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/IResourceManager.cs@@ -1,79 +1,79 @@//Contribution: Orchard project (https://github.com/OrchardCMS/OrchardCore)+using Microsoft.AspNetCore.Html;-namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++public interface IResourceManager{- public interface IResourceManager- {- /// <summary>- /// Registers a script tag on the head- /// </summary>- /// <param name="script"></param>- /// <param name="order"></param>- void RegisterHeadScript(IHtmlContent script, int order);+ /// <summary>+ /// Registers a script tag on the head+ /// </summary>+ /// <param name="script"></param>+ /// <param name="order"></param>+ void RegisterHeadScript(IHtmlContent script, int order);- /// <summary>- /// Registers a custom script tag on at the header.- /// </summary>- void RegisterHeaderScript(IHtmlContent script, int order);+ /// <summary>+ /// Registers a custom script tag on at the header.+ /// </summary>+ void RegisterHeaderScript(IHtmlContent script, int order);- /// <summary>- /// Registers a custom script tag on at the foot.- /// </summary>- /// <param name="script"></param>- /// <param name="order"></param>- void RegisterFootScript(IHtmlContent script, int order);+ /// <summary>+ /// Registers a custom script tag on at the foot.+ /// </summary>+ /// <param name="script"></param>+ /// <param name="order"></param>+ void RegisterFootScript(IHtmlContent script, int order);- /// <summary>- /// Registers a custom template tag in the head/footer.- /// </summary>- /// <param name="script"></param>- /// <param name="head"></param>- void RegisterTemplate(IHtmlContent script, bool head);+ /// <summary>+ /// Registers a custom template tag in the head/footer.+ /// </summary>+ /// <param name="script"></param>+ /// <param name="head"></param>+ void RegisterTemplate(IHtmlContent script, bool head);- /// <summary>- /// Returns the registered head script resources.- /// </summary>- IEnumerable<IHtmlContent> GetRegisteredHeadScripts();+ /// <summary>+ /// Returns the registered head script resources.+ /// </summary>+ IEnumerable<IHtmlContent> GetRegisteredHeadScripts();- /// <summary>- /// Returns the registered header script resources.- /// </summary>- IEnumerable<IHtmlContent> GetRegisteredHeaderScripts();+ /// <summary>+ /// Returns the registered header script resources.+ /// </summary>+ IEnumerable<IHtmlContent> GetRegisteredHeaderScripts();- /// <summary>- /// Returns the registered footer script resources.- /// </summary>- IEnumerable<IHtmlContent> GetRegisteredFootScripts();+ /// <summary>+ /// Returns the registered footer script resources.+ /// </summary>+ IEnumerable<IHtmlContent> GetRegisteredFootScripts();- /// <summary>- /// Renders the registered header script tags.- /// </summary>- void RenderHeadScript(IHtmlContentBuilder builder);+ /// <summary>+ /// Renders the registered header script tags.+ /// </summary>+ void RenderHeadScript(IHtmlContentBuilder builder);- /// <summary>- /// Renders the registered header script tags.- /// </summary>- void RenderHeaderScript(IHtmlContentBuilder builder);+ /// <summary>+ /// Renders the registered header script tags.+ /// </summary>+ void RenderHeaderScript(IHtmlContentBuilder builder);- /// <summary>- /// Renders the registered footer script tags.- /// </summary>- void RenderFootScript(IHtmlContentBuilder builder);+ /// <summary>+ /// Renders the registered footer script tags.+ /// </summary>+ void RenderFootScript(IHtmlContentBuilder builder);- /// <summary>- /// Renders the registered header link tags.- /// </summary>- void RenderHeadLink(IHtmlContentBuilder builder);+ /// <summary>+ /// Renders the registered header link tags.+ /// </summary>+ void RenderHeadLink(IHtmlContentBuilder builder);- /// <summary>- /// Renders the registered template tags.- /// </summary>- void RenderTemplate(IHtmlContentBuilder builder, bool head);+ /// <summary>+ /// Renders the registered template tags.+ /// </summary>+ void RenderTemplate(IHtmlContentBuilder builder, bool head);- /// <summary>- /// Registers a link tag.- /// </summary>- void RegisterLink(LinkEntry link);- }-}+ /// <summary>+ /// Registers a link tag.+ /// </summary>+ void RegisterLink(LinkEntry link);+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/InputTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/InputTagHelper.csindex ed3a435b4..3e9e3eb91 100644--- a/src/Web/Grand.Web.Common/TagHelpers/InputTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/InputTagHelper.cs@@ -1,38 +1,36 @@--using Microsoft.AspNetCore.Mvc.ViewFeatures;+using Microsoft.AspNetCore.Mvc.ViewFeatures;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++[HtmlTargetElement("input", Attributes = ForAttributeName)]+public class InputTagHelper : Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper{- [HtmlTargetElement("input", Attributes = ForAttributeName)]- public class InputTagHelper : Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper+ private const string ForAttributeName = "asp-for";++ public InputTagHelper(IHtmlGenerator generator) : base(generator){- private const string ForAttributeName = "asp-for";+ }- [HtmlAttributeName("asp-disabled")]- public string IsDisabled { set; get; }+ [HtmlAttributeName("asp-disabled")] public string IsDisabled { set; get; }- [HtmlAttributeName("asp-readonly")]- public bool IsReadonly { set; get; }+ [HtmlAttributeName("asp-readonly")] public bool IsReadonly { set; get; }- public InputTagHelper(IHtmlGenerator generator) : base(generator)+ public override void Process(TagHelperContext context, TagHelperOutput output)+ {+ bool.TryParse(IsDisabled, out var disabled);+ if (disabled){+ var d = new TagHelperAttribute("disabled", "disabled");+ output.Attributes.Add(d);}- public override void Process(TagHelperContext context, TagHelperOutput output)+ if (IsReadonly){- bool.TryParse(IsDisabled, out var disabled);- if (disabled)- {- var d = new TagHelperAttribute("disabled", "disabled");- output.Attributes.Add(d);- }- if (IsReadonly)- {- var d = new TagHelperAttribute("readonly");- output.Attributes.Add(d);- }- base.Process(context, output);+ var d = new TagHelperAttribute("readonly");+ output.Attributes.Add(d);}++ base.Process(context, output);}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/LinkEntry.cs b/src/Web/Grand.Web.Common/TagHelpers/LinkEntry.csindex 0cc931089..3512e2d1d 100644--- a/src/Web/Grand.Web.Common/TagHelpers/LinkEntry.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/LinkEntry.cs@@ -1,97 +1,87 @@using Microsoft.AspNetCore.Html;using Microsoft.AspNetCore.Mvc.Rendering;-namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++public class LinkEntry{- public class LinkEntry+ private readonly TagBuilder _builder = new("link");++ public LinkEntry(){- private readonly TagBuilder _builder = new TagBuilder("link");+ _builder.TagRenderMode = TagRenderMode.SelfClosing;+ }- public string Condition { get; set; }+ public string Condition { get; set; }- private int _priority { get; set; }+ private int _priority { get; set; }- public LinkEntry()- {- _builder.TagRenderMode = TagRenderMode.SelfClosing;- }-- public string Rel- {- get- {- string value;- _builder.Attributes.TryGetValue("rel", out value);- return value;- }- set => SetAttribute("rel", value);+ public string Rel {+ get {+ string value;+ _builder.Attributes.TryGetValue("rel", out value);+ return value;}+ set => SetAttribute("rel", value);+ }- public string Type- {- get- {- string value;- _builder.Attributes.TryGetValue("type", out value);- return value;- }- set => SetAttribute("type", value);+ public string Type {+ get {+ string value;+ _builder.Attributes.TryGetValue("type", out value);+ return value;}+ set => SetAttribute("type", value);+ }- public string Title- {- get- {- string value;- _builder.Attributes.TryGetValue("title", out value);- return value;- }- set => SetAttribute("title", value);+ public string Title {+ get {+ string value;+ _builder.Attributes.TryGetValue("title", out value);+ return value;}+ set => SetAttribute("title", value);+ }- public string Href- {- get- {- string value;- _builder.Attributes.TryGetValue("href", out value);- return value;- }- set => SetAttribute("href", value);+ public string Href {+ get {+ string value;+ _builder.Attributes.TryGetValue("href", out value);+ return value;}+ set => SetAttribute("href", value);+ }- public int Priority- {- get => _priority;- set => _priority = value;- }+ public int Priority {+ get => _priority;+ set => _priority = value;+ }- public IHtmlContent GetTag()+ public IHtmlContent GetTag()+ {+ if (!string.IsNullOrEmpty(Condition)){- if (!string.IsNullOrEmpty(Condition))- {- var htmlBuilder = new HtmlContentBuilder();- htmlBuilder.AppendHtml("<!--[if " + Condition + "]>");- htmlBuilder.AppendHtml(_builder);- htmlBuilder.AppendHtml("<![endif]-->");+ var htmlBuilder = new HtmlContentBuilder();+ htmlBuilder.AppendHtml("<!--[if " + Condition + "]>");+ htmlBuilder.AppendHtml(_builder);+ htmlBuilder.AppendHtml("<![endif]-->");- return htmlBuilder;- }-- return _builder;+ return htmlBuilder;}- public LinkEntry AddAttribute(string name, string value)- {- _builder.MergeAttribute(name, value);- return this;- }+ return _builder;+ }- public LinkEntry SetAttribute(string name, string value)- {- _builder.MergeAttribute(name, value, true);- return this;- }+ public LinkEntry AddAttribute(string name, string value)+ {+ _builder.MergeAttribute(name, value);+ return this;+ }++ public LinkEntry SetAttribute(string name, string value)+ {+ _builder.MergeAttribute(name, value, true);+ return this;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/LinkTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/LinkTagHelper.csindex 8468a553f..3021d4d04 100644--- a/src/Web/Grand.Web.Common/TagHelpers/LinkTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/LinkTagHelper.cs@@ -1,79 +1,58 @@using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++[HtmlTargetElement("link", TagStructure = TagStructure.WithoutEndTag, Attributes = SrcAttributeName)]+[HtmlTargetElement("link", TagStructure = TagStructure.WithoutEndTag, Attributes = SrcPriority)]+public class LinkTagHelper : TagHelper{- [HtmlTargetElement("link", TagStructure = TagStructure.WithoutEndTag, Attributes = SrcAttributeName)]- [HtmlTargetElement("link", TagStructure = TagStructure.WithoutEndTag, Attributes = SrcPriority)]- public class LinkTagHelper : TagHelper+ private const string SrcAttributeName = "asp-src";+ private const string SrcPriority = "asp-priority";++ private readonly IResourceManager _resourceManager;++ public LinkTagHelper(IResourceManager resourceManager){- private const string SrcAttributeName = "asp-src";- private const string SrcPriority = "asp-priority";+ _resourceManager = resourceManager;+ }- [HtmlAttributeName(SrcPriority)]- public int Priority { get; set; }+ [HtmlAttributeName(SrcPriority)] public int Priority { get; set; }- public string Rel { get; set; }+ public string Rel { get; set; }- [HtmlAttributeName(SrcAttributeName)]- public string Src { get; set; }+ [HtmlAttributeName(SrcAttributeName)] public string Src { get; set; }- public string Title { get; set; }+ public string Title { get; set; }- public string Type { get; set; }+ public string Type { get; set; }- public string Condition { get; set; }+ public string Condition { get; set; }- private readonly IResourceManager _resourceManager;+ public override void Process(TagHelperContext context, TagHelperOutput output)+ {+ var linkEntry = new LinkEntry {+ Priority = Priority+ };- public LinkTagHelper(IResourceManager resourceManager)- {- _resourceManager = resourceManager;- }+ if (!string.IsNullOrEmpty(Src)) linkEntry.Href = Src;- public override void Process(TagHelperContext context, TagHelperOutput output)+ if (!string.IsNullOrEmpty(Rel)) linkEntry.Rel = Rel;++ if (!string.IsNullOrEmpty(Condition)) linkEntry.Condition = Condition;++ if (!string.IsNullOrEmpty(Title)) linkEntry.Title = Title;++ if (!string.IsNullOrEmpty(Type)) linkEntry.Type = Type;++ foreach (var attribute in output.Attributes){- var linkEntry = new LinkEntry {- Priority = Priority- };-- if (!string.IsNullOrEmpty(Src))- {- linkEntry.Href = Src;- }-- if (!string.IsNullOrEmpty(Rel))- {- linkEntry.Rel = Rel;- }-- if (!string.IsNullOrEmpty(Condition))- {- linkEntry.Condition = Condition;- }-- if (!string.IsNullOrEmpty(Title))- {- linkEntry.Title = Title;- }-- if (!string.IsNullOrEmpty(Type))- {- linkEntry.Type = Type;- }-- foreach (var attribute in output.Attributes)- {- if (string.Equals(attribute.Name, "href", StringComparison.OrdinalIgnoreCase))- {- continue;- }-- linkEntry.SetAttribute(attribute.Name, attribute.Value.ToString());- }-- _resourceManager.RegisterLink(linkEntry);-- output.TagName = null;+ if (string.Equals(attribute.Name, "href", StringComparison.OrdinalIgnoreCase)) continue;++ linkEntry.SetAttribute(attribute.Name, attribute.Value.ToString());}++ _resourceManager.RegisterLink(linkEntry);++ output.TagName = null;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/LocalizedEditorTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/LocalizedEditorTagHelper.csindex a2a9b6a43..c93b6c97e 100644--- a/src/Web/Grand.Web.Common/TagHelpers/LocalizedEditorTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/LocalizedEditorTagHelper.cs@@ -9,97 +9,93 @@ using Microsoft.AspNetCore.Razor.TagHelpers;using Microsoft.Extensions.DependencyInjection;using System.Net;-namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++public class LocalizedEditorTagHelper : TagHelper{- public class LocalizedEditorTagHelper : TagHelper- {- [HtmlAttributeName("name")]- public string Name { get; set; }- [HtmlAttributeName("ignore-if-severa-stores")]- public bool IgnoreIfSeveralStores { get; set; } = false;- [ViewContext]- [HtmlAttributeNotBound]- public ViewContext ViewContext { get; set; }- [HtmlAttributeName("localized-template")]- public Func<int, HelperResult> LocalizedTemplate { get; set; }- [HtmlAttributeName("language-ids")]- public List<string> LanguagesIds { get; set; }-- public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)- {- var localizationSupported = LanguagesIds.Count > 1;- var standardContent = (await output.GetChildContentAsync()).GetContent();- if (IgnoreIfSeveralStores)- {- var storeService = ViewContext.HttpContext.RequestServices.GetRequiredService<IStoreService>();- if ((await storeService.GetAllStores()).Count >= 2)- {- localizationSupported = false;- }- }+ [HtmlAttributeName("name")] public string Name { get; set; }- if (localizationSupported)- {- var tabStrip = new StringBuilder();- tabStrip.AppendLine($"<div id='{Name}'>");- tabStrip.AppendLine("<ul>");+ [HtmlAttributeName("ignore-if-severa-stores")]+ public bool IgnoreIfSeveralStores { get; set; } = false;- //default tab- tabStrip.AppendLine("<li class='k-state-active'>");- tabStrip.AppendLine("Standard");- tabStrip.AppendLine("</li>");+ [ViewContext] [HtmlAttributeNotBound] public ViewContext ViewContext { get; set; }- var languageService = ViewContext.HttpContext.RequestServices.GetRequiredService<ILanguageService>();+ [HtmlAttributeName("localized-template")]+ public Func<int, HelperResult> LocalizedTemplate { get; set; }- foreach (var locale in LanguagesIds)- {- //languages- var language = await languageService.GetLanguageById(locale);+ [HtmlAttributeName("language-ids")] public List<string> LanguagesIds { get; set; }- tabStrip.AppendLine("<li>");- var urlHelper = new UrlHelper(ViewContext);- var iconUrl = urlHelper.Content("~/assets/images/flags/" + language.FlagImageFileName);- tabStrip.AppendLine($"<img class='k-image' alt='' src='{iconUrl}'>");- tabStrip.AppendLine(WebUtility.HtmlEncode(language.Name));- tabStrip.AppendLine("</li>");- }+ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ var localizationSupported = LanguagesIds.Count > 1;+ var standardContent = (await output.GetChildContentAsync()).GetContent();+ if (IgnoreIfSeveralStores)+ {+ var storeService = ViewContext.HttpContext.RequestServices.GetRequiredService<IStoreService>();+ if ((await storeService.GetAllStores()).Count >= 2) localizationSupported = false;+ }- tabStrip.AppendLine("</ul>");+ if (localizationSupported)+ {+ var tabStrip = new StringBuilder();+ tabStrip.AppendLine($"<div id='{Name}'>");+ tabStrip.AppendLine("<ul>");- //default tab- tabStrip.AppendLine("<div>");- tabStrip.AppendLine(standardContent);- tabStrip.AppendLine("</div>");+ //default tab+ tabStrip.AppendLine("<li class='k-state-active'>");+ tabStrip.AppendLine("Standard");+ tabStrip.AppendLine("</li>");- for (var i = 0; i < LanguagesIds.Count; i++)- {- //languages- tabStrip.AppendLine("<div>");- tabStrip.AppendLine(LocalizedTemplate(i).ToHtmlString());- tabStrip.AppendLine("</div>");- }+ var languageService = ViewContext.HttpContext.RequestServices.GetRequiredService<ILanguageService>();- tabStrip.AppendLine("</div>");- tabStrip.AppendLine("<script>");- tabStrip.AppendLine("$(document).ready(function() {");- tabStrip.AppendLine($"$('#{Name}').kendoTabStrip(");- tabStrip.AppendLine("{");- tabStrip.AppendLine("animation: {");- tabStrip.AppendLine("open: {");- tabStrip.AppendLine("effects: \"fadeIn\"");- tabStrip.AppendLine("}");- tabStrip.AppendLine("}");- tabStrip.AppendLine("});");- tabStrip.AppendLine("});");- tabStrip.AppendLine("</script>");- output.TagName = null;- output.Content.SetHtmlContent(tabStrip.ToString());+ foreach (var locale in LanguagesIds)+ {+ //languages+ var language = await languageService.GetLanguageById(locale);++ tabStrip.AppendLine("<li>");+ var urlHelper = new UrlHelper(ViewContext);+ var iconUrl = urlHelper.Content("~/assets/images/flags/" + language.FlagImageFileName);+ tabStrip.AppendLine($"<img class='k-image' alt='' src='{iconUrl}'>");+ tabStrip.AppendLine(WebUtility.HtmlEncode(language.Name));+ tabStrip.AppendLine("</li>");}- else++ tabStrip.AppendLine("</ul>");++ //default tab+ tabStrip.AppendLine("<div>");+ tabStrip.AppendLine(standardContent);+ tabStrip.AppendLine("</div>");++ for (var i = 0; i < LanguagesIds.Count; i++){- output.TagName = null;- output.Content.SetHtmlContent(standardContent);+ //languages+ tabStrip.AppendLine("<div>");+ tabStrip.AppendLine(LocalizedTemplate(i).ToHtmlString());+ tabStrip.AppendLine("</div>");}++ tabStrip.AppendLine("</div>");+ tabStrip.AppendLine("<script>");+ tabStrip.AppendLine("$(document).ready(function() {");+ tabStrip.AppendLine($"$('#{Name}').kendoTabStrip(");+ tabStrip.AppendLine("{");+ tabStrip.AppendLine("animation: {");+ tabStrip.AppendLine("open: {");+ tabStrip.AppendLine("effects: \"fadeIn\"");+ tabStrip.AppendLine("}");+ tabStrip.AppendLine("}");+ tabStrip.AppendLine("});");+ tabStrip.AppendLine("});");+ tabStrip.AppendLine("</script>");+ output.TagName = null;+ output.Content.SetHtmlContent(tabStrip.ToString());+ }+ else+ {+ output.TagName = null;+ output.Content.SetHtmlContent(standardContent);}}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/MetaDescriptionTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/MetaDescriptionTagHelper.csindex 995dfb8b0..02598832c 100644--- a/src/Web/Grand.Web.Common/TagHelpers/MetaDescriptionTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/MetaDescriptionTagHelper.cs@@ -1,26 +1,23 @@using Grand.Web.Common.Page;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers-{- [HtmlTargetElement("meta-description", TagStructure = TagStructure.WithoutEndTag)]- public class MetaDescriptionTagHelper : TagHelper- {+namespace Grand.Web.Common.TagHelpers;- private readonly IPageHeadBuilder _pageHeadBuilder;-- public MetaDescriptionTagHelper(IPageHeadBuilder pageHeadBuilder)- {- _pageHeadBuilder = pageHeadBuilder;- }+[HtmlTargetElement("meta-description", TagStructure = TagStructure.WithoutEndTag)]+public class MetaDescriptionTagHelper : TagHelper+{+ private readonly IPageHeadBuilder _pageHeadBuilder;- public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)- {- output.TagName = "meta";- output.Attributes.Add("name", "description");- output.Attributes.Add("content", _pageHeadBuilder.GenerateMetaDescription());- return Task.CompletedTask;- }+ public MetaDescriptionTagHelper(IPageHeadBuilder pageHeadBuilder)+ {+ _pageHeadBuilder = pageHeadBuilder;+ }+ public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ output.TagName = "meta";+ output.Attributes.Add("name", "description");+ output.Attributes.Add("content", _pageHeadBuilder.GenerateMetaDescription());+ return Task.CompletedTask;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/MetaKeywordsTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/MetaKeywordsTagHelper.csindex 91a317622..fa75c91ed 100644--- a/src/Web/Grand.Web.Common/TagHelpers/MetaKeywordsTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/MetaKeywordsTagHelper.cs@@ -1,34 +1,29 @@using Grand.Web.Common.Page;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++[HtmlTargetElement("meta-keywords", TagStructure = TagStructure.WithoutEndTag)]+[HtmlTargetElement("meta-keywords", Attributes = PartAttributeName)]+public class MetaKeywordsTagHelper : TagHelper{- [HtmlTargetElement("meta-keywords", TagStructure = TagStructure.WithoutEndTag)]- [HtmlTargetElement("meta-keywords", Attributes = PartAttributeName)]- public class MetaKeywordsTagHelper : TagHelper- {- private const string PartAttributeName = "asp-part";- [HtmlAttributeName(PartAttributeName)]- public string Attribute { get; set; }+ private const string PartAttributeName = "asp-part";- private readonly IPageHeadBuilder _pageHeadBuilder;+ private readonly IPageHeadBuilder _pageHeadBuilder;- public MetaKeywordsTagHelper(IPageHeadBuilder pageHeadBuilder)- {- _pageHeadBuilder = pageHeadBuilder;- }+ public MetaKeywordsTagHelper(IPageHeadBuilder pageHeadBuilder)+ {+ _pageHeadBuilder = pageHeadBuilder;+ }- public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)- {- if (!string.IsNullOrEmpty(Attribute))- {- _pageHeadBuilder.AppendMetaKeywordParts(Attribute);- }- output.TagName = "meta";- output.Attributes.Add("name", "keywords");- output.Attributes.Add("content", _pageHeadBuilder.GenerateMetaKeywords());- return Task.CompletedTask;- }+ [HtmlAttributeName(PartAttributeName)] public string Attribute { get; set; }+ public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ if (!string.IsNullOrEmpty(Attribute)) _pageHeadBuilder.AppendMetaKeywordParts(Attribute);+ output.TagName = "meta";+ output.Attributes.Add("name", "keywords");+ output.Attributes.Add("content", _pageHeadBuilder.GenerateMetaKeywords());+ return Task.CompletedTask;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/PageNavigationTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/PageNavigationTagHelper.csindex 7e94a8387..2eae7072b 100644--- a/src/Web/Grand.Web.Common/TagHelpers/PageNavigationTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/PageNavigationTagHelper.cs@@ -5,303 +5,262 @@ using Microsoft.AspNetCore.Mvc.Rendering;using Microsoft.AspNetCore.Mvc.ViewFeatures;using Microsoft.AspNetCore.Razor.TagHelpers;using Microsoft.AspNetCore.Routing;--namespace Grand.Web.Common.TagHelpers+using CommonExtensions = Grand.Infrastructure.Extensions.CommonExtensions;++namespace Grand.Web.Common.TagHelpers;++[HtmlTargetElement("page-navigation", TagStructure = TagStructure.WithoutEndTag)]+[HtmlTargetElement("page-navigation", Attributes = QueryParamAttributeName)]+[HtmlTargetElement("page-navigation", Attributes = PaginationParamAttributeName)]+[HtmlTargetElement("page-navigation", Attributes = ShowTotalSummaryParamAttributeName)]+[HtmlTargetElement("page-navigation", Attributes = ShowPagerItemsParamAttributeName)]+[HtmlTargetElement("page-navigation", Attributes = ShowFirstParamAttributeName)]+[HtmlTargetElement("page-navigation", Attributes = ShowPreviousParamAttributeName)]+[HtmlTargetElement("page-navigation", Attributes = ShowNextParamAttributeName)]+[HtmlTargetElement("page-navigation", Attributes = ShowLastParamAttributeName)]+[HtmlTargetElement("page-navigation", Attributes = ShowIndividualPagesParamAttributeName)]+[HtmlTargetElement("page-navigation", Attributes = RenderEmptyParametersParamAttributeName)]+[HtmlTargetElement("page-navigation", Attributes = IndividualPagesDisplayedCountParamAttributeName)]+[HtmlTargetElement("page-navigation", Attributes = BooleanParamAttributeName)]+public class PageNavigationTagHelper : TagHelper{- [HtmlTargetElement("page-navigation", TagStructure = TagStructure.WithoutEndTag)]- [HtmlTargetElement("page-navigation", Attributes = QueryParamAttributeName)]- [HtmlTargetElement("page-navigation", Attributes = PaginationParamAttributeName)]- [HtmlTargetElement("page-navigation", Attributes = ShowTotalSummaryParamAttributeName)]- [HtmlTargetElement("page-navigation", Attributes = ShowPagerItemsParamAttributeName)]- [HtmlTargetElement("page-navigation", Attributes = ShowFirstParamAttributeName)]- [HtmlTargetElement("page-navigation", Attributes = ShowPreviousParamAttributeName)]- [HtmlTargetElement("page-navigation", Attributes = ShowNextParamAttributeName)]- [HtmlTargetElement("page-navigation", Attributes = ShowLastParamAttributeName)]- [HtmlTargetElement("page-navigation", Attributes = ShowIndividualPagesParamAttributeName)]- [HtmlTargetElement("page-navigation", Attributes = RenderEmptyParametersParamAttributeName)]- [HtmlTargetElement("page-navigation", Attributes = IndividualPagesDisplayedCountParamAttributeName)]- [HtmlTargetElement("page-navigation", Attributes = BooleanParamAttributeName)]- public class PageNavigationTagHelper : TagHelper- {- [ViewContext] public ViewContext ViewContext { get; set; }+ private const string QueryParamAttributeName = "asp-query-param";- private const string QueryParamAttributeName = "asp-query-param";+ private const string PaginationParamAttributeName = "asp-pagination";- [HtmlAttributeName(QueryParamAttributeName)]- public string QueryParam { get; set; } = "page";+ private const string ShowTotalSummaryParamAttributeName = "asp-show-total-summary";- private const string PaginationParamAttributeName = "asp-pagination";+ private const string ShowPagerItemsParamAttributeName = "asp-show-pager-items";- [HtmlAttributeName(PaginationParamAttributeName)]- public IPageableModel Pagination { get; set; }+ private const string ShowFirstParamAttributeName = "asp-show-first";- private readonly ITranslationService _translationService;- private readonly IHtmlHelper _htmlHelper;+ private const string ShowPreviousParamAttributeName = "asp-show-previous";- private const string ShowTotalSummaryParamAttributeName = "asp-show-total-summary";+ private const string ShowNextParamAttributeName = "asp-show-next";- [HtmlAttributeName(ShowTotalSummaryParamAttributeName)]- public bool ShowTotalSummary { get; set; }+ private const string ShowLastParamAttributeName = "asp-show-last";- private const string ShowPagerItemsParamAttributeName = "asp-show-pager-items";+ private const string ShowIndividualPagesParamAttributeName = "asp-show-individual-pages";- [HtmlAttributeName(ShowPagerItemsParamAttributeName)]- public bool ShowPagerItems { get; set; } = true;- private const string ShowFirstParamAttributeName = "asp-show-first";+ private const string RenderEmptyParametersParamAttributeName = "asp-render-empty-parameters";- [HtmlAttributeName(ShowFirstParamAttributeName)]- public bool ShowFirst { get; set; } = true;+ private const string IndividualPagesDisplayedCountParamAttributeName = "asp-individual-pages-displayed-count";- private const string ShowPreviousParamAttributeName = "asp-show-previous";+ private const string BooleanParamAttributeName = "asp-boolean-params";+ private readonly IHtmlHelper _htmlHelper;- [HtmlAttributeName(ShowPreviousParamAttributeName)]- public bool ShowPrevious { get; set; } = true;+ private readonly ITranslationService _translationService;- private const string ShowNextParamAttributeName = "asp-show-next";+ public PageNavigationTagHelper(ITranslationService translationService, IHtmlHelper htmlHelper)+ {+ _translationService = translationService;+ _htmlHelper = htmlHelper;+ }- [HtmlAttributeName(ShowNextParamAttributeName)]- public bool ShowNext { get; set; } = true;+ [ViewContext] public ViewContext ViewContext { get; set; }- private const string ShowLastParamAttributeName = "asp-show-last";+ [HtmlAttributeName(QueryParamAttributeName)]+ public string QueryParam { get; set; } = "page";- [HtmlAttributeName(ShowLastParamAttributeName)]- public bool ShowLast { get; set; } = true;+ [HtmlAttributeName(PaginationParamAttributeName)]+ public IPageableModel Pagination { get; set; }- private const string ShowIndividualPagesParamAttributeName = "asp-show-individual-pages";+ [HtmlAttributeName(ShowTotalSummaryParamAttributeName)]+ public bool ShowTotalSummary { get; set; }- [HtmlAttributeName(ShowIndividualPagesParamAttributeName)]- public bool ShowIndividualPages { get; set; } = true;+ [HtmlAttributeName(ShowPagerItemsParamAttributeName)]+ public bool ShowPagerItems { get; set; } = true;+ [HtmlAttributeName(ShowFirstParamAttributeName)]+ public bool ShowFirst { get; set; } = true;- private const string RenderEmptyParametersParamAttributeName = "asp-render-empty-parameters";+ [HtmlAttributeName(ShowPreviousParamAttributeName)]+ public bool ShowPrevious { get; set; } = true;- [HtmlAttributeName(RenderEmptyParametersParamAttributeName)]- public bool RenderEmptyParameters { get; set; } = true;+ [HtmlAttributeName(ShowNextParamAttributeName)]+ public bool ShowNext { get; set; } = true;- private const string IndividualPagesDisplayedCountParamAttributeName = "asp-individual-pages-displayed-count";+ [HtmlAttributeName(ShowLastParamAttributeName)]+ public bool ShowLast { get; set; } = true;- [HtmlAttributeName(IndividualPagesDisplayedCountParamAttributeName)]- public int IndividualPagesDisplayedCount { get; set; } = 5;+ [HtmlAttributeName(ShowIndividualPagesParamAttributeName)]+ public bool ShowIndividualPages { get; set; } = true;- private const string BooleanParamAttributeName = "asp-boolean-params";+ [HtmlAttributeName(RenderEmptyParametersParamAttributeName)]+ public bool RenderEmptyParameters { get; set; } = true;- [HtmlAttributeName(BooleanParamAttributeName)]- public IList<string> BooleanParameterNames { get; set; } = new List<string>();+ [HtmlAttributeName(IndividualPagesDisplayedCountParamAttributeName)]+ public int IndividualPagesDisplayedCount { get; set; } = 5;- public PageNavigationTagHelper(ITranslationService translationService, IHtmlHelper htmlHelper)- {- _translationService = translationService;- _htmlHelper = htmlHelper;- }+ [HtmlAttributeName(BooleanParamAttributeName)]+ public IList<string> BooleanParameterNames { get; set; } = new List<string>();++ public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ output.SuppressOutput();++ (_htmlHelper as IViewContextAware)?.Contextualize(ViewContext);++ var links = GenerateHtmlString();++ if (string.IsNullOrEmpty(links)) return Task.CompletedTask;+ var sb = new StringBuilder();+ sb.AppendFormat("<nav aria-label=\"Page navigation\">");+ sb.Append(Environment.NewLine);+ sb.AppendFormat(links);+ sb.Append(Environment.NewLine);+ sb.AppendFormat("</nav>");+ sb.Append(Environment.NewLine);+ output.Content.SetHtmlContent(sb.ToString());+ return Task.CompletedTask;+ }++ public virtual string GenerateHtmlString()+ {+ if (Pagination.TotalItems == 0)+ return null;- public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ var links = new StringBuilder();+ if (ShowTotalSummary && Pagination.TotalPages > 0){- output.SuppressOutput();-- (_htmlHelper as IViewContextAware)?.Contextualize(ViewContext);-- var links = GenerateHtmlString();-- if (string.IsNullOrEmpty(links)) return Task.CompletedTask;- var sb = new StringBuilder();- sb.AppendFormat("<nav aria-label=\"Page navigation\">");- sb.Append(Environment.NewLine);- sb.AppendFormat(links);- sb.Append(Environment.NewLine);- sb.AppendFormat("</nav>");- sb.Append(Environment.NewLine);- output.Content.SetHtmlContent(sb.ToString());- return Task.CompletedTask;+ links.Append("<li class=\"total-summary\">");+ links.Append(string.Format(_translationService.GetResource("Pager.CurrentPage"),+ Pagination.PageIndex + 1, Pagination.TotalPages, Pagination.TotalItems));+ links.Append("</li>");}- public virtual string GenerateHtmlString()+ if (ShowPagerItems && Pagination.TotalPages > 1){- if (Pagination.TotalItems == 0)- return null;-- var links = new StringBuilder();- if (ShowTotalSummary && Pagination.TotalPages > 0)- {- links.Append("<li class=\"total-summary\">");- links.Append(string.Format(_translationService.GetResource("Pager.CurrentPage"),- Pagination.PageIndex + 1, Pagination.TotalPages, Pagination.TotalItems));- links.Append("</li>");- }-- if (ShowPagerItems && Pagination.TotalPages > 1)- {- if (ShowFirst)- {- //first page- if (Pagination.PageIndex >= 3 && Pagination.TotalPages > IndividualPagesDisplayedCount)- {- links.Append(CreatePageLink(1, _translationService.GetResource("Pager.First"),- "first-page page-item"));- }- }-- if (ShowPrevious)- {- //previous page- if (Pagination.PageIndex > 0)- {- links.Append(CreatePageLink(Pagination.PageIndex,- _translationService.GetResource("Pager.Previous"), "previous-page page-item"));- }- }-- if (ShowIndividualPages)- {- //individual pages- var firstIndividualPageIndex = GetFirstIndividualPageIndex();- var lastIndividualPageIndex = GetLastIndividualPageIndex();- for (var i = firstIndividualPageIndex; i <= lastIndividualPageIndex; i++)- {- if (Pagination.PageIndex == i)- {- links.Append(- $"<li class=\"current-page page-item\"><a class=\"page-link\">{i + 1}</a></li>");- }- else- {- links.Append(CreatePageLink(i + 1, (i + 1).ToString(), "individual-page page-item"));- }- }- }-- if (ShowNext)- {- //next page- if (Pagination.PageIndex + 1 < Pagination.TotalPages)- {- links.Append(CreatePageLink(Pagination.PageIndex + 2,- _translationService.GetResource("Pager.Next"), "next-page page-item"));- }- }-- if (ShowLast)- {- //last page- if (Pagination.PageIndex + 3 < Pagination.TotalPages &&- Pagination.TotalPages > IndividualPagesDisplayedCount)- {- links.Append(CreatePageLink(Pagination.TotalPages,- _translationService.GetResource("Pager.Last"), "last-page page-item"));- }- }- }-- var result = links.ToString();- if (!string.IsNullOrEmpty(result))+ if (ShowFirst)+ //first page+ if (Pagination.PageIndex >= 3 && Pagination.TotalPages > IndividualPagesDisplayedCount)+ links.Append(CreatePageLink(1, _translationService.GetResource("Pager.First"),+ "first-page page-item"));++ if (ShowPrevious)+ //previous page+ if (Pagination.PageIndex > 0)+ links.Append(CreatePageLink(Pagination.PageIndex,+ _translationService.GetResource("Pager.Previous"), "previous-page page-item"));++ if (ShowIndividualPages){- result = "<ul class=\"pagination\">" + result + "</ul>";+ //individual pages+ var firstIndividualPageIndex = GetFirstIndividualPageIndex();+ var lastIndividualPageIndex = GetLastIndividualPageIndex();+ for (var i = firstIndividualPageIndex; i <= lastIndividualPageIndex; i++)+ if (Pagination.PageIndex == i)+ links.Append(+ $"<li class=\"current-page page-item\"><a class=\"page-link\">{i + 1}</a></li>");+ else+ links.Append(CreatePageLink(i + 1, (i + 1).ToString(), "individual-page page-item"));}- return result;+ if (ShowNext)+ //next page+ if (Pagination.PageIndex + 1 < Pagination.TotalPages)+ links.Append(CreatePageLink(Pagination.PageIndex + 2,+ _translationService.GetResource("Pager.Next"), "next-page page-item"));++ if (ShowLast)+ //last page+ if (Pagination.PageIndex + 3 < Pagination.TotalPages &&+ Pagination.TotalPages > IndividualPagesDisplayedCount)+ links.Append(CreatePageLink(Pagination.TotalPages,+ _translationService.GetResource("Pager.Last"), "last-page page-item"));}- protected virtual string CreatePageLink(int pageNumber, string text, string cssClass)- {- var liBuilder = new TagBuilder("li");- if (!string.IsNullOrWhiteSpace(cssClass))- liBuilder.AddCssClass(cssClass);+ var result = links.ToString();+ if (!string.IsNullOrEmpty(result)) result = "<ul class=\"pagination\">" + result + "</ul>";- var aBuilder = new TagBuilder("a");- aBuilder.InnerHtml.AppendHtml(text);- aBuilder.AddCssClass("page-link");- aBuilder.MergeAttribute("href", CreateDefaultUrl(pageNumber));+ return result;+ }- liBuilder.InnerHtml.AppendHtml(aBuilder);- return liBuilder.RenderHtmlContent();- }+ protected virtual string CreatePageLink(int pageNumber, string text, string cssClass)+ {+ var liBuilder = new TagBuilder("li");+ if (!string.IsNullOrWhiteSpace(cssClass))+ liBuilder.AddCssClass(cssClass);- protected virtual string CreateDefaultUrl(int pageNumber)- {- var routeValues = new RouteValueDictionary();+ var aBuilder = new TagBuilder("a");+ aBuilder.InnerHtml.AppendHtml(text);+ aBuilder.AddCssClass("page-link");+ aBuilder.MergeAttribute("href", CreateDefaultUrl(pageNumber));- var parametersWithEmptyValues = new List<string>();- foreach (var key in _htmlHelper.ViewContext.HttpContext.Request.Query.Keys)- {- var value = _htmlHelper.ViewContext.HttpContext.Request.Query[key].ToString();- if (RenderEmptyParameters && string.IsNullOrEmpty(value))- {- parametersWithEmptyValues.Add(key);- }- else- {- if (BooleanParameterNames.Contains(key, StringComparer.OrdinalIgnoreCase))- {- //find more info here: http://www.mindstorminteractive.com/pages/jquery-fix-asp-net-mvc-checkbox-truefalse-value/- if (!string.IsNullOrEmpty(value) &&- value.Equals("true,false", StringComparison.OrdinalIgnoreCase))- {- value = "true";- }- }-- routeValues[key] = value;- }- }+ liBuilder.InnerHtml.AppendHtml(aBuilder);+ return liBuilder.RenderHtmlContent();+ }++ protected virtual string CreateDefaultUrl(int pageNumber)+ {+ var routeValues = new RouteValueDictionary();- if (pageNumber > 1)+ var parametersWithEmptyValues = new List<string>();+ foreach (var key in _htmlHelper.ViewContext.HttpContext.Request.Query.Keys)+ {+ var value = _htmlHelper.ViewContext.HttpContext.Request.Query[key].ToString();+ if (RenderEmptyParameters && string.IsNullOrEmpty(value)){- routeValues[QueryParam] = pageNumber;+ parametersWithEmptyValues.Add(key);}else{- //SEO. we do not render pageindex query string parameter for the first page- if (routeValues.ContainsKey(QueryParam))- {- routeValues.Remove(QueryParam);- }+ if (BooleanParameterNames.Contains(key, StringComparer.OrdinalIgnoreCase))+ //find more info here: http://www.mindstorminteractive.com/pages/jquery-fix-asp-net-mvc-checkbox-truefalse-value/+ if (!string.IsNullOrEmpty(value) &&+ value.Equals("true,false", StringComparison.OrdinalIgnoreCase))+ value = "true";++ routeValues[key] = value;}+ }- var url =- $"{ViewContext.HttpContext.Request.Scheme}://{ViewContext.HttpContext.Request.Host}{ViewContext.HttpContext.Request.Path}";- url = routeValues.Aggregate(url, (current, routeValue) => Grand.Infrastructure.Extensions.CommonExtensions.ModifyQueryString(current, routeValue.Key, routeValue.Value?.ToString()));+ if (pageNumber > 1)+ {+ routeValues[QueryParam] = pageNumber;+ }+ else+ {+ //SEO. we do not render pageindex query string parameter for the first page+ if (routeValues.ContainsKey(QueryParam)) routeValues.Remove(QueryParam);+ }- if (!RenderEmptyParameters || !parametersWithEmptyValues.Any()) return url;+ var url =+ $"{ViewContext.HttpContext.Request.Scheme}://{ViewContext.HttpContext.Request.Host}{ViewContext.HttpContext.Request.Path}";+ url = routeValues.Aggregate(url,+ (current, routeValue) =>+ CommonExtensions.ModifyQueryString(current, routeValue.Key, routeValue.Value?.ToString()));- return parametersWithEmptyValues.Aggregate(url, (current, key) => Grand.Infrastructure.Extensions.CommonExtensions.ModifyQueryString(current, key, null));- }+ if (!RenderEmptyParameters || !parametersWithEmptyValues.Any()) return url;- protected virtual int GetFirstIndividualPageIndex()- {- if (Pagination.TotalPages < IndividualPagesDisplayedCount ||- Pagination.PageIndex - IndividualPagesDisplayedCount / 2 < 0)- {- return 0;- }+ return parametersWithEmptyValues.Aggregate(url,+ (current, key) => CommonExtensions.ModifyQueryString(current, key, null));+ }- if (Pagination.PageIndex + IndividualPagesDisplayedCount / 2 >= Pagination.TotalPages)- {- return Pagination.TotalPages - IndividualPagesDisplayedCount;- }+ protected virtual int GetFirstIndividualPageIndex()+ {+ if (Pagination.TotalPages < IndividualPagesDisplayedCount ||+ Pagination.PageIndex - IndividualPagesDisplayedCount / 2 < 0)+ return 0;- return Pagination.PageIndex - IndividualPagesDisplayedCount / 2;- }+ if (Pagination.PageIndex + IndividualPagesDisplayedCount / 2 >= Pagination.TotalPages)+ return Pagination.TotalPages - IndividualPagesDisplayedCount;- protected virtual int GetLastIndividualPageIndex()- {- var num = IndividualPagesDisplayedCount / 2;- if (IndividualPagesDisplayedCount % 2 == 0)- {- num--;- }+ return Pagination.PageIndex - IndividualPagesDisplayedCount / 2;+ }- if (Pagination.TotalPages < IndividualPagesDisplayedCount ||- Pagination.PageIndex + num >= Pagination.TotalPages)- {- return Pagination.TotalPages - 1;- }+ protected virtual int GetLastIndividualPageIndex()+ {+ var num = IndividualPagesDisplayedCount / 2;+ if (IndividualPagesDisplayedCount % 2 == 0) num--;- if (Pagination.PageIndex - IndividualPagesDisplayedCount / 2 < 0)- {- return IndividualPagesDisplayedCount - 1;- }+ if (Pagination.TotalPages < IndividualPagesDisplayedCount ||+ Pagination.PageIndex + num >= Pagination.TotalPages)+ return Pagination.TotalPages - 1;- return Pagination.PageIndex + num;- }+ if (Pagination.PageIndex - IndividualPagesDisplayedCount / 2 < 0) return IndividualPagesDisplayedCount - 1;++ return Pagination.PageIndex + num;}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/PictureSourceTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/PictureSourceTagHelper.csindex 33acb1ffd..6832edb4e 100644--- a/src/Web/Grand.Web.Common/TagHelpers/PictureSourceTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/PictureSourceTagHelper.cs@@ -1,33 +1,31 @@using Grand.Business.Core.Interfaces.Storage;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++[HtmlTargetElement("source", ParentTag = "picture")]+public class PictureSourceTagHelper : TagHelper{- [HtmlTargetElement("source", ParentTag = "picture")]- public class PictureSourceTagHelper : TagHelper+ private readonly IPictureService _pictureService;++ public PictureSourceTagHelper(IPictureService pictureService){- [HtmlAttributeName("picture-id")]- public string PictureId { set; get; }+ _pictureService = pictureService;+ }- [HtmlAttributeName("picture-size")]- public int PictureSize { set; get; }+ [HtmlAttributeName("picture-id")] public string PictureId { set; get; }- private readonly IPictureService _pictureService;+ [HtmlAttributeName("picture-size")] public int PictureSize { set; get; }- public PictureSourceTagHelper(IPictureService pictureService)+ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ if (!string.IsNullOrEmpty(PictureId)){- _pictureService = pictureService;+ var pictureUrl = await _pictureService.GetPictureUrl(PictureId, PictureSize, false);+ var srcset = new TagHelperAttribute("srcset", pictureUrl);+ output.Attributes.Add(srcset);}- public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)- {- if (!string.IsNullOrEmpty(PictureId))- {- var pictureUrl = await _pictureService.GetPictureUrl(PictureId, PictureSize, showDefaultPicture: false);- var srcset = new TagHelperAttribute("srcset", pictureUrl);- output.Attributes.Add(srcset);- }- await base.ProcessAsync(context, output);- }+ await base.ProcessAsync(context, output);}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/RequiredTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/RequiredTagHelper.csindex a735b07cc..a37e78129 100644--- a/src/Web/Grand.Web.Common/TagHelpers/RequiredTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/RequiredTagHelper.cs@@ -1,16 +1,15 @@using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++[HtmlTargetElement("grand-required")]+public class RequiredTagHelper : TagHelper{- [HtmlTargetElement("grand-required")]- public class RequiredTagHelper : TagHelper+ public override void Process(TagHelperContext context, TagHelperOutput output){- public override void Process(TagHelperContext context, TagHelperOutput output)- {- output.TagName = "span";- output.TagMode = TagMode.StartTagAndEndTag;- output.Attributes.SetAttribute("class", "required");- output.Content.SetContent("*");- }+ output.TagName = "span";+ output.TagMode = TagMode.StartTagAndEndTag;+ output.Attributes.SetAttribute("class", "required");+ output.Content.SetContent("*");}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/ResourceManager.cs b/src/Web/Grand.Web.Common/TagHelpers/ResourceManager.csindex 2d81aba67..dd48a16ee 100644--- a/src/Web/Grand.Web.Common/TagHelpers/ResourceManager.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/ResourceManager.cs@@ -1,154 +1,146 @@//Contribution: Orchard project (https://github.com/OrchardCMS/OrchardCore)+using Microsoft.AspNetCore.Html;-namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++public class ResourceManager : IResourceManager{- public class ResourceManager : IResourceManager+ private readonly List<(IHtmlContent content, int order)> _footScripts = new();+ private readonly List<(IHtmlContent content, int order)> _headerScripts = new();+ private readonly List<(IHtmlContent content, int order)> _headScripts = new();+ private readonly List<LinkEntry> _links = new();+ private List<IHtmlContent> _templatesFooter;+ private List<IHtmlContent> _templatesHeader;++ public IEnumerable<IHtmlContent> GetRegisteredHeadScripts(){- private readonly List<(IHtmlContent content, int order)> _headScripts = new();- private readonly List<(IHtmlContent content, int order)> _headerScripts = new();- private readonly List<(IHtmlContent content, int order)> _footScripts = new();- private List<IHtmlContent> _templatesHeader;- private List<IHtmlContent> _templatesFooter;- private readonly List<LinkEntry> _links = new();-- public IEnumerable<IHtmlContent> GetRegisteredHeadScripts()- {- return _headScripts.OrderBy(x => x.order).Select(x => x.content);- }- public IEnumerable<IHtmlContent> GetRegisteredHeaderScripts()- {- return _headerScripts.OrderBy(x => x.order).Select(x => x.content);- }+ return _headScripts.OrderBy(x => x.order).Select(x => x.content);+ }- public IEnumerable<IHtmlContent> GetRegisteredFootScripts()- {- return _footScripts.OrderBy(x => x.order).Select(x => x.content);- }- public IEnumerable<IHtmlContent> GetRegisteredTemplatesHeader()- {- return _templatesHeader ?? Enumerable.Empty<IHtmlContent>();- }- public IEnumerable<IHtmlContent> GetRegisteredTemplatesFooter()- {- return _templatesFooter ?? Enumerable.Empty<IHtmlContent>();- }+ public IEnumerable<IHtmlContent> GetRegisteredHeaderScripts()+ {+ return _headerScripts.OrderBy(x => x.order).Select(x => x.content);+ }++ public IEnumerable<IHtmlContent> GetRegisteredFootScripts()+ {+ return _footScripts.OrderBy(x => x.order).Select(x => x.content);+ }++ public void RegisterHeadScript(IHtmlContent script, int order)+ {+ _headScripts.Add((script, order));+ }++ public void RegisterHeaderScript(IHtmlContent script, int order)+ {+ _headerScripts.Add((script, order));+ }- public void RegisterHeadScript(IHtmlContent script, int order)+ public void RegisterFootScript(IHtmlContent script, int order)+ {+ _footScripts.Add((script, order));+ }++ public void RegisterTemplate(IHtmlContent script, bool head)+ {+ if (head){- _headScripts.Add((script, order));+ _templatesHeader ??= new List<IHtmlContent>();+ _templatesHeader.Add(script);}- public void RegisterHeaderScript(IHtmlContent script, int order)+ else{- _headerScripts.Add((script, order));+ _templatesFooter ??= new List<IHtmlContent>();+ _templatesFooter.Add(script);}+ }- public void RegisterFootScript(IHtmlContent script, int order)+ /// <summary>+ /// Renders the registered head script tags.+ /// </summary>+ public void RenderHeadScript(IHtmlContentBuilder builder)+ {+ var first = true;+ foreach (var context in GetRegisteredHeadScripts()){- _footScripts.Add((script, order));- }+ if (!first) builder.AppendHtml(Environment.NewLine);- public void RegisterTemplate(IHtmlContent script, bool head)- {- if (head)- {- _templatesHeader ??= new List<IHtmlContent>();- _templatesHeader.Add(script);- }- else- {- _templatesFooter ??= new List<IHtmlContent>();- _templatesFooter.Add(script);- }- }- /// <summary>- /// Renders the registered head script tags.- /// </summary>- public void RenderHeadScript(IHtmlContentBuilder builder)- {- var first = true;- foreach (var context in GetRegisteredHeadScripts())- {- if (!first)- {- builder.AppendHtml(Environment.NewLine);- }-- first = false;-- builder.AppendHtml(context);- }+ first = false;++ builder.AppendHtml(context);}+ }- public void RenderFootScript(IHtmlContentBuilder builder)+ public void RenderFootScript(IHtmlContentBuilder builder)+ {+ var first = true;+ foreach (var context in GetRegisteredFootScripts()){- var first = true;- foreach (var context in GetRegisteredFootScripts())- {- if (!first)- {- builder.AppendHtml(Environment.NewLine);- }-- first = false;-- builder.AppendHtml(context);- }+ if (!first) builder.AppendHtml(Environment.NewLine);++ first = false;++ builder.AppendHtml(context);}- public void RenderHeaderScript(IHtmlContentBuilder builder)- {- var first = true;- foreach (var context in GetRegisteredHeaderScripts())- {- if (!first)- {- builder.AppendHtml(Environment.NewLine);- }+ }- first = false;+ public void RenderHeaderScript(IHtmlContentBuilder builder)+ {+ var first = true;+ foreach (var context in GetRegisteredHeaderScripts())+ {+ if (!first) builder.AppendHtml(Environment.NewLine);- builder.AppendHtml(context);- }+ first = false;+ builder.AppendHtml(context);}+ }- public void RenderHeadLink(IHtmlContentBuilder builder)- {- var first = true;+ public void RenderHeadLink(IHtmlContentBuilder builder)+ {+ var first = true;- var registeredLinks = _links.OrderBy(x => x.Priority).ToList();- foreach (var link in registeredLinks)- {- if (!first)- {- builder.AppendHtml(Environment.NewLine);- }+ var registeredLinks = _links.OrderBy(x => x.Priority).ToList();+ foreach (var link in registeredLinks)+ {+ if (!first) builder.AppendHtml(Environment.NewLine);- first = false;+ first = false;- builder.AppendHtml(link.GetTag());- }+ builder.AppendHtml(link.GetTag());}- public void RenderTemplate(IHtmlContentBuilder builder, bool head)- {- var first = true;- var templates = head ? GetRegisteredTemplatesHeader() : GetRegisteredTemplatesFooter();- foreach (var context in templates)- {- if (!first)- {- builder.AppendHtml(Environment.NewLine);- }-- first = false;-- builder.AppendHtml(context);- }- }- public void RegisterLink(LinkEntry link)+ }++ public void RenderTemplate(IHtmlContentBuilder builder, bool head)+ {+ var first = true;+ var templates = head ? GetRegisteredTemplatesHeader() : GetRegisteredTemplatesFooter();+ foreach (var context in templates){- _links.Add(link);+ if (!first) builder.AppendHtml(Environment.NewLine);++ first = false;++ builder.AppendHtml(context);}}-}++ public void RegisterLink(LinkEntry link)+ {+ _links.Add(link);+ }++ public IEnumerable<IHtmlContent> GetRegisteredTemplatesHeader()+ {+ return _templatesHeader ?? Enumerable.Empty<IHtmlContent>();+ }++ public IEnumerable<IHtmlContent> GetRegisteredTemplatesFooter()+ {+ return _templatesFooter ?? Enumerable.Empty<IHtmlContent>();+ }+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/ResourceType.cs b/src/Web/Grand.Web.Common/TagHelpers/ResourceType.csindex 390493244..792beaf54 100644--- a/src/Web/Grand.Web.Common/TagHelpers/ResourceType.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/ResourceType.cs@@ -1,13 +1,11 @@--namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++public enum ResourceType{- public enum ResourceType- {- HeadLink,- HeadScript,- ScriptHeader,- ScriptFooter,- TemplateHeader,- TemplateFooter- }-}+ HeadLink,+ HeadScript,+ ScriptHeader,+ ScriptFooter,+ TemplateHeader,+ TemplateFooter+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/ResourcesTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/ResourcesTagHelper.csindex c633ba430..dfb51f875 100644--- a/src/Web/Grand.Web.Common/TagHelpers/ResourcesTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/ResourcesTagHelper.cs@@ -1,52 +1,50 @@using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++[HtmlTargetElement("resources", Attributes = AttributeType)]+public class ResourcesTagHelper : TagHelper{- [HtmlTargetElement("resources", Attributes = AttributeType)]- public class ResourcesTagHelper : TagHelper- {- private const string AttributeType = "asp-type";+ private const string AttributeType = "asp-type";- [HtmlAttributeName(AttributeType)]- public ResourceType Type { get; set; }+ private readonly IResourceManager _resourceManager;- private readonly IResourceManager _resourceManager;+ public ResourcesTagHelper(IResourceManager resourceManager)+ {+ _resourceManager = resourceManager;+ }- public ResourcesTagHelper(IResourceManager resourceManager)- {- _resourceManager = resourceManager;- }+ [HtmlAttributeName(AttributeType)] public ResourceType Type { get; set; }- public override void Process(TagHelperContext tagHelperContext, TagHelperOutput output)+ public override void Process(TagHelperContext tagHelperContext, TagHelperOutput output)+ {+ switch (Type){- switch (Type)- {- case ResourceType.ScriptHeader:- _resourceManager.RenderHeaderScript(output.Content);- break;-- case ResourceType.ScriptFooter:- _resourceManager.RenderFootScript(output.Content);- break;-- case ResourceType.HeadLink:- _resourceManager.RenderHeadLink(output.Content);- break;-- case ResourceType.HeadScript:- _resourceManager.RenderHeadScript(output.Content);- break;-- case ResourceType.TemplateHeader:- _resourceManager.RenderTemplate(output.Content, true);- break;-- case ResourceType.TemplateFooter:- _resourceManager.RenderTemplate(output.Content, false);- break;- }-- output.TagName = null;+ case ResourceType.ScriptHeader:+ _resourceManager.RenderHeaderScript(output.Content);+ break;++ case ResourceType.ScriptFooter:+ _resourceManager.RenderFootScript(output.Content);+ break;++ case ResourceType.HeadLink:+ _resourceManager.RenderHeadLink(output.Content);+ break;++ case ResourceType.HeadScript:+ _resourceManager.RenderHeadScript(output.Content);+ break;++ case ResourceType.TemplateHeader:+ _resourceManager.RenderTemplate(output.Content, true);+ break;++ case ResourceType.TemplateFooter:+ _resourceManager.RenderTemplate(output.Content, false);+ break;}++ output.TagName = null;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/ScriptLocation.cs b/src/Web/Grand.Web.Common/TagHelpers/ScriptLocation.csindex 6c4613913..e7f6b1aa8 100644--- a/src/Web/Grand.Web.Common/TagHelpers/ScriptLocation.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/ScriptLocation.cs@@ -1,10 +1,8 @@--namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++public enum ScriptLocation{- public enum ScriptLocation- {- Head,- Header,- Footer- }-}+ Head,+ Header,+ Footer+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/ScriptTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/ScriptTagHelper.csindex ceaf53654..fa0a55fde 100644--- a/src/Web/Grand.Web.Common/TagHelpers/ScriptTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/ScriptTagHelper.cs@@ -2,73 +2,65 @@using Microsoft.AspNetCore.Mvc.Rendering;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers-{+namespace Grand.Web.Common.TagHelpers;- [HtmlTargetElement("script", Attributes = LocationAttributeName)]- [HtmlTargetElement("script", Attributes = SrcAttributeName)]- [HtmlTargetElement("script", Attributes = OrderAttributeName)]- public class ScriptTagHelper : TagHelper- {+[HtmlTargetElement("script", Attributes = LocationAttributeName)]+[HtmlTargetElement("script", Attributes = SrcAttributeName)]+[HtmlTargetElement("script", Attributes = OrderAttributeName)]+public class ScriptTagHelper : TagHelper+{+ private const string LocationAttributeName = "asp-location";+ private const string SrcAttributeName = "asp-src";+ private const string OrderAttributeName = "asp-order";+ private readonly IHttpContextAccessor _httpContextAccessor;- private const string LocationAttributeName = "asp-location";- private const string SrcAttributeName = "asp-src";- private const string OrderAttributeName = "asp-order";+ private readonly IResourceManager _resourceManager;- [HtmlAttributeName(LocationAttributeName)]- public ScriptLocation Location { get; set; }+ public ScriptTagHelper(IResourceManager resourceManager, IHttpContextAccessor httpContextAccessor)+ {+ _resourceManager = resourceManager;+ _httpContextAccessor = httpContextAccessor;+ }- [HtmlAttributeName(SrcAttributeName)]- public string Src { get; set; }+ [HtmlAttributeName(LocationAttributeName)]+ public ScriptLocation Location { get; set; }- [HtmlAttributeName(OrderAttributeName)]- public int DisplayOrder { get; set; }+ [HtmlAttributeName(SrcAttributeName)] public string Src { get; set; }- private readonly IResourceManager _resourceManager;- private readonly IHttpContextAccessor _httpContextAccessor;+ [HtmlAttributeName(OrderAttributeName)]+ public int DisplayOrder { get; set; }- public ScriptTagHelper(IResourceManager resourceManager, IHttpContextAccessor httpContextAccessor)- {- _resourceManager = resourceManager;- _httpContextAccessor = httpContextAccessor;- }- public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ var isAjaxCall = _httpContextAccessor.HttpContext != null &&+ _httpContextAccessor.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";+ if (!isAjaxCall){- var isAjaxCall = _httpContextAccessor.HttpContext != null && _httpContextAccessor.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";- if (!isAjaxCall)- {- output.SuppressOutput();-- var childContent = await output.GetChildContentAsync();+ output.SuppressOutput();- var builder = new TagBuilder("script");- builder.InnerHtml.AppendHtml(childContent);- builder.TagRenderMode = TagRenderMode.Normal;- if(!string.IsNullOrEmpty(Src))- {- builder.Attributes.Add("src", Src);- }- foreach (var attribute in output.Attributes)- {- builder.Attributes.Add(attribute.Name, attribute.Value.ToString());- }+ var childContent = await output.GetChildContentAsync();- switch (Location)- {- case ScriptLocation.Head:- _resourceManager.RegisterHeadScript(builder, DisplayOrder);- break;+ var builder = new TagBuilder("script");+ builder.InnerHtml.AppendHtml(childContent);+ builder.TagRenderMode = TagRenderMode.Normal;+ if (!string.IsNullOrEmpty(Src)) builder.Attributes.Add("src", Src);+ foreach (var attribute in output.Attributes)+ builder.Attributes.Add(attribute.Name, attribute.Value.ToString());++ switch (Location)+ {+ case ScriptLocation.Head:+ _resourceManager.RegisterHeadScript(builder, DisplayOrder);+ break;- case ScriptLocation.Header:- _resourceManager.RegisterHeaderScript(builder, DisplayOrder);- break;+ case ScriptLocation.Header:+ _resourceManager.RegisterHeaderScript(builder, DisplayOrder);+ break;- case ScriptLocation.Footer:- _resourceManager.RegisterFootScript(builder, DisplayOrder);- break;- }+ case ScriptLocation.Footer:+ _resourceManager.RegisterFootScript(builder, DisplayOrder);+ break;}}-}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/TemplateTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/TemplateTagHelper.csindex 0a1c7c2ba..ea32a5ef4 100644--- a/src/Web/Grand.Web.Common/TagHelpers/TemplateTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/TemplateTagHelper.cs@@ -2,59 +2,56 @@using Microsoft.AspNetCore.Mvc.Rendering;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers+namespace Grand.Web.Common.TagHelpers;++[HtmlTargetElement("template", Attributes = AttributeNameHeader)]+[HtmlTargetElement("template", Attributes = AttributeNameFooter)]+public class TemplateTagHelper : TagHelper{+ private const string AttributeNameHeader = "asp-header";- [HtmlTargetElement("template", Attributes = AttributeNameHeader)]- [HtmlTargetElement("template", Attributes = AttributeNameFooter)]- public class TemplateTagHelper : TagHelper- {- private const string AttributeNameHeader = "asp-header";+ private const string AttributeNameFooter = "asp-footer";+ private readonly IHttpContextAccessor _httpContextAccessor;- private const string AttributeNameFooter = "asp-footer";+ private readonly IResourceManager _resourceManager;- [HtmlAttributeName(AttributeNameHeader)]- public bool Header { get; set; }+ public TemplateTagHelper(IResourceManager resourceManager, IHttpContextAccessor httpContextAccessor)+ {+ _resourceManager = resourceManager;+ _httpContextAccessor = httpContextAccessor;+ }- [HtmlAttributeName(AttributeNameFooter)]- public bool Footer { get; set; }+ [HtmlAttributeName(AttributeNameHeader)]+ public bool Header { get; set; }- private readonly IResourceManager _resourceManager;- private readonly IHttpContextAccessor _httpContextAccessor;+ [HtmlAttributeName(AttributeNameFooter)]+ public bool Footer { get; set; }- public TemplateTagHelper(IResourceManager resourceManager, IHttpContextAccessor httpContextAccessor)- {- _resourceManager = resourceManager;- _httpContextAccessor = httpContextAccessor;- }- public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ var isAjaxCall = _httpContextAccessor.HttpContext != null &&+ _httpContextAccessor.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";+ if (!isAjaxCall){- var isAjaxCall = _httpContextAccessor.HttpContext != null && _httpContextAccessor.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";- if (!isAjaxCall)+ output.SuppressOutput();++ var childContent = await output.GetChildContentAsync();++ var builder = new TagBuilder("template");+ builder.InnerHtml.AppendHtml(childContent);+ builder.TagRenderMode = TagRenderMode.Normal;+ foreach (var attribute in output.Attributes)+ builder.Attributes.Add(attribute.Name, attribute.Value.ToString());++ switch (Header){- output.SuppressOutput();-- var childContent = await output.GetChildContentAsync();-- var builder = new TagBuilder("template");- builder.InnerHtml.AppendHtml(childContent);- builder.TagRenderMode = TagRenderMode.Normal;- foreach (var attribute in output.Attributes)- {- builder.Attributes.Add(attribute.Name, attribute.Value.ToString());- }-- switch (Header)- {- case true when !Footer:- _resourceManager.RegisterTemplate(builder, true);- break;- case false when Footer:- _resourceManager.RegisterTemplate(builder, false);- break;- }+ case true when !Footer:+ _resourceManager.RegisterTemplate(builder, true);+ break;+ case false when Footer:+ _resourceManager.RegisterTemplate(builder, false);+ break;}}-}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/TagHelpers/TitleTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/TitleTagHelper.csindex 3e6a528b4..1b723623f 100644--- a/src/Web/Grand.Web.Common/TagHelpers/TitleTagHelper.cs+++ b/src/Web/Grand.Web.Common/TagHelpers/TitleTagHelper.cs@@ -1,38 +1,32 @@using Grand.Web.Common.Page;using Microsoft.AspNetCore.Razor.TagHelpers;-namespace Grand.Web.Common.TagHelpers-{- [HtmlTargetElement("title", Attributes = PartAttributeName)]- [HtmlTargetElement("title", Attributes = DefaultAttributeName)]- public class TitleTagHelper : TagHelper- {- private const string PartAttributeName = "asp-part";- private const string DefaultAttributeName = "asp-default-title";+namespace Grand.Web.Common.TagHelpers;- [HtmlAttributeName(PartAttributeName)]- public string Attribute { get; set; }+[HtmlTargetElement("title", Attributes = PartAttributeName)]+[HtmlTargetElement("title", Attributes = DefaultAttributeName)]+public class TitleTagHelper : TagHelper+{+ private const string PartAttributeName = "asp-part";+ private const string DefaultAttributeName = "asp-default-title";- [HtmlAttributeName(DefaultAttributeName)]- public bool DefaultTitle { get; set; } = true;+ private readonly IPageHeadBuilder _pageHeadBuilder;- private readonly IPageHeadBuilder _pageHeadBuilder;+ public TitleTagHelper(IPageHeadBuilder pageHeadBuilder)+ {+ _pageHeadBuilder = pageHeadBuilder;+ }- public TitleTagHelper(IPageHeadBuilder pageHeadBuilder)- {- _pageHeadBuilder = pageHeadBuilder;- }+ [HtmlAttributeName(PartAttributeName)] public string Attribute { get; set; }- public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)- {- if (!string.IsNullOrEmpty(Attribute))- {- _pageHeadBuilder.AddTitleParts(Attribute);- }- var content = _pageHeadBuilder.GenerateTitle(DefaultTitle);- output.Content.Append(content);- return Task.CompletedTask;- }+ [HtmlAttributeName(DefaultAttributeName)]+ public bool DefaultTitle { get; set; } = true;+ public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)+ {+ if (!string.IsNullOrEmpty(Attribute)) _pageHeadBuilder.AddTitleParts(Attribute);+ var content = _pageHeadBuilder.GenerateTitle(DefaultTitle);+ output.Content.Append(content);+ return Task.CompletedTask;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Themes/DefaultThemeView.cs b/src/Web/Grand.Web.Common/Themes/DefaultThemeView.csindex 700bef9e7..c58fdd840 100644--- a/src/Web/Grand.Web.Common/Themes/DefaultThemeView.cs+++ b/src/Web/Grand.Web.Common/Themes/DefaultThemeView.cs@@ -4,8 +4,9 @@ public class DefaultThemeView : IThemeView{public string AreaName => "";public string ThemeName => "Default";-- public ThemeInfo ThemeInfo => new ("Default theme", "~/assets/samples/default-theme.jpg", "Default GrandNode theme", true);++ public ThemeInfo ThemeInfo =>+ new("Default theme", "~/assets/samples/default-theme.jpg", "Default GrandNode theme", true);public IEnumerable<string> GetViewLocations(){diff --git a/src/Web/Grand.Web.Common/Themes/IThemeContext.cs b/src/Web/Grand.Web.Common/Themes/IThemeContext.csindex 9dcdb5ed3..4f6d47040 100644--- a/src/Web/Grand.Web.Common/Themes/IThemeContext.cs+++ b/src/Web/Grand.Web.Common/Themes/IThemeContext.cs@@ -1,22 +1,22 @@namespace Grand.Web.Common.Themes;/// <summary>-/// Work context+/// Work context/// </summary>public interface IThemeContext{/// <summary>- /// Get area name+ /// Get area name/// </summary>string AreaName { get; }/// <summary>- /// Get current theme system name+ /// Get current theme system name/// </summary>string GetCurrentTheme();/// <summary>- /// Set current theme system name+ /// Set current theme system name/// </summary>Task SetTheme(string themeName);}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Themes/IThemeView.cs b/src/Web/Grand.Web.Common/Themes/IThemeView.csindex bcf4665c5..788646d67 100644--- a/src/Web/Grand.Web.Common/Themes/IThemeView.cs+++ b/src/Web/Grand.Web.Common/Themes/IThemeView.cs@@ -8,4 +8,4 @@ public interface IThemeViewIEnumerable<string> GetViewLocations();}-public record ThemeInfo(string Title, string PreviewImageUrl, string PreviewText, bool SupportRtl);+public record ThemeInfo(string Title, string PreviewImageUrl, string PreviewText, bool SupportRtl);\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Themes/ThemeContext.cs b/src/Web/Grand.Web.Common/Themes/ThemeContext.csindex bc211c011..6c0914841 100644--- a/src/Web/Grand.Web.Common/Themes/ThemeContext.cs+++ b/src/Web/Grand.Web.Common/Themes/ThemeContext.cs@@ -6,13 +6,13 @@ namespace Grand.Web.Common.Themes;public class ThemeContext : ThemeContextBase{- private readonly StoreInformationSettings _storeInformationSettings;private readonly IHttpContextAccessor _contextAccessor;+ private readonly StoreInformationSettings _storeInformationSettings;private string _themeName;public ThemeContext(- IHttpContextAccessor contextAccessor,- SecurityConfig securityConfig,+ IHttpContextAccessor contextAccessor,+ SecurityConfig securityConfig,StoreInformationSettings storeInformationSettings) :base(contextAccessor, securityConfig){@@ -29,9 +29,7 @@ public class ThemeContext : ThemeContextBasevar theme = "";if (_storeInformationSettings.AllowCustomerToSelectTheme)- {- theme = _contextAccessor.HttpContext?.Request.Cookies[this.CookiesName];- }+ theme = _contextAccessor.HttpContext?.Request.Cookies[CookiesName];//default store themeif (string.IsNullOrEmpty(theme))diff --git a/src/Web/Grand.Web.Common/Themes/ThemeContextBase.cs b/src/Web/Grand.Web.Common/Themes/ThemeContextBase.csindex ce83f31c9..3d32b6c87 100644--- a/src/Web/Grand.Web.Common/Themes/ThemeContextBase.cs+++ b/src/Web/Grand.Web.Common/Themes/ThemeContextBase.cs@@ -6,23 +6,24 @@ namespace Grand.Web.Common.Themes;public abstract class ThemeContextBase : IThemeContext{private readonly IHttpContextAccessor _contextAccessor;- private readonly SecurityConfig _securityConfig;+ private readonly SecurityConfig _securityConfig;+protected ThemeContextBase(IHttpContextAccessor contextAccessor, SecurityConfig securityConfig){_contextAccessor = contextAccessor;_securityConfig = securityConfig;}- public abstract string AreaName { get; }-public string CookiesName => $"{_securityConfig.CookiePrefix}.{AreaName}.Theme";++ public abstract string AreaName { get; }public abstract string GetCurrentTheme();public Task SetTheme(string themeName){_contextAccessor.HttpContext?.Response.Cookies.Delete(CookiesName);_contextAccessor.HttpContext?.Response.Cookies.Append(CookiesName, themeName,- new CookieOptions { HttpOnly = false, Expires = DateTimeOffset.Now.AddYears(1)});+ new CookieOptions { HttpOnly = false, Expires = DateTimeOffset.Now.AddYears(1) });return Task.CompletedTask;}}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Themes/ThemeContextFactory.cs b/src/Web/Grand.Web.Common/Themes/ThemeContextFactory.csindex 99ea8b2f7..e731ac799 100644--- a/src/Web/Grand.Web.Common/Themes/ThemeContextFactory.cs+++ b/src/Web/Grand.Web.Common/Themes/ThemeContextFactory.cs@@ -7,7 +7,6 @@ public class ThemeContextFactory : IThemeContextFactorypublic ThemeContextFactory(IEnumerable<IThemeContext> themeContexts){_themeContexts = themeContexts.ToDictionary(f => f.AreaName, f => f);-}public IThemeContext GetThemeContext(string areaName)diff --git a/src/Web/Grand.Web.Common/Validators/CaptchaValidator.cs b/src/Web/Grand.Web.Common/Validators/CaptchaValidator.csindex 505c667c1..c69020eec 100644--- a/src/Web/Grand.Web.Common/Validators/CaptchaValidator.cs+++ b/src/Web/Grand.Web.Common/Validators/CaptchaValidator.cs@@ -11,29 +11,18 @@ public class CaptchaValidator : BaseGrandValidator<ICaptchaValidModel>{private readonly IHttpContextAccessor _contextAccessor;private readonly GoogleReCaptchaValidator _googleReCaptchaValidator;-- #region Constants- private const string ChallengeFieldKey = "recaptcha_challenge_field";- private const string ResponseFieldKey = "recaptcha_response_field";- private const string GResponseFieldKeyV3 = "g-recaptcha-response-value";- private const string GResponseFieldKeyV2 = "g-recaptcha-response";-- #endregionpublic CaptchaValidator(IEnumerable<IValidatorConsumer<ICaptchaValidModel>> validators,IHttpContextAccessor contextAccessor, GoogleReCaptchaValidator googleReCaptchaValidator) : base(validators){_contextAccessor = contextAccessor;_googleReCaptchaValidator = googleReCaptchaValidator;-+RuleFor(x => x).CustomAsync(async (x, context, _) =>{var result = await ValidateCaptcha(x);- if (!result.isValid)- {- context.AddFailure(result.error);- }+ if (!result.isValid) context.AddFailure(result.error);});}@@ -58,10 +47,8 @@ public class CaptchaValidator : BaseGrandValidator<ICaptchaValidModel>captchaResponseValue = form[ResponseFieldKey];gCaptchaResponseValue = string.Empty;foreach (var item in form.Keys)- {if (item.Contains(GResponseFieldKeyV3))gCaptchaResponseValue = form[item];- }if (string.IsNullOrEmpty(gCaptchaResponseValue))gCaptchaResponseValue = form[GResponseFieldKeyV2];@@ -76,7 +63,16 @@ public class CaptchaValidator : BaseGrandValidator<ICaptchaValidModel>? captchaResponseValue: gCaptchaResponseValue);isValid = recaptchaResponse.Success;-+return isValid ? (true, string.Empty) : (false, string.Join(',', recaptchaResponse.ErrorCodes));}++ #region Constants++ private const string ChallengeFieldKey = "recaptcha_challenge_field";+ private const string ResponseFieldKey = "recaptcha_response_field";+ private const string GResponseFieldKeyV3 = "g-recaptcha-response-value";+ private const string GResponseFieldKeyV2 = "g-recaptcha-response";++ #endregion}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Validators/NoScriptsAttribute.cs b/src/Web/Grand.Web.Common/Validators/NoScriptsAttribute.csindex 00a7f2b27..8ba74e4fe 100644--- a/src/Web/Grand.Web.Common/Validators/NoScriptsAttribute.cs+++ b/src/Web/Grand.Web.Common/Validators/NoScriptsAttribute.cs@@ -2,22 +2,26 @@using System.Text.RegularExpressions;namespace Grand.Web.Common.Validators;+public class NoScriptsAttribute : ValidationAttribute{// Simple regular expression to detect potential scripts- private const string Pattern = "<script.*?>.*?</script>|javascript:[^\\s]*|onload=|onerror=|onmouseover=|onclick=|onchange=|onsubmit=";-+ private const string Pattern =+ "<script.*?>.*?</script>|javascript:[^\\s]*|onload=|onerror=|onmouseover=|onclick=|onchange=|onsubmit=";+protected override ValidationResult IsValid(object value, ValidationContext validationContext){if (value == null) return ValidationResult.Success;var valueAsString = value.ToString();// Check if the value contains a script- return ContainsScript(valueAsString) ? new ValidationResult("JavaScript scripts are not allowed.") : ValidationResult.Success;+ return ContainsScript(valueAsString)+ ? new ValidationResult("JavaScript scripts are not allowed.")+ : ValidationResult.Success;}private static bool ContainsScript(string input){- Regex scriptRegex = new Regex(Pattern, RegexOptions.IgnoreCase);+ var scriptRegex = new Regex(Pattern, RegexOptions.IgnoreCase);return scriptRegex.IsMatch(input);}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/Validators/ValidatorFactory.cs b/src/Web/Grand.Web.Common/Validators/ValidatorFactory.csindex 4d0078b4e..2024bb500 100644--- a/src/Web/Grand.Web.Common/Validators/ValidatorFactory.cs+++ b/src/Web/Grand.Web.Common/Validators/ValidatorFactory.cs@@ -16,10 +16,7 @@ public class ValidatorFactory : IValidatorFactorypublic IValidator<T> GetValidator<T>(){var validator = _serviceProvider.GetService<IValidator<T>>();- if (validator != null)- {- return validator;- }+ if (validator != null) return validator;throw new InvalidOperationException($"No validator found for type {typeof(T).Name}.");}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/View/DefaultAreaViewFactory.cs b/src/Web/Grand.Web.Common/View/DefaultAreaViewFactory.csindex cf9968c80..01879771b 100644--- a/src/Web/Grand.Web.Common/View/DefaultAreaViewFactory.cs+++ b/src/Web/Grand.Web.Common/View/DefaultAreaViewFactory.cs@@ -4,28 +4,31 @@ namespace Grand.Web.Common.View;public class DefaultAreaViewFactory : IAreaViewFactory{- public string AreaName => "";-- private readonly IEnumerable<IThemeView> _themeFactories;private readonly IThemeContext _themeContext;-++ private readonly IEnumerable<IThemeView> _themeFactories;+public DefaultAreaViewFactory(IEnumerable<IThemeView> themeFactories, IThemeContextFactory themeContextFactory){_themeContext = themeContextFactory.GetThemeContext(AreaName);- _themeFactories = themeFactories.Where(x=>x.AreaName == AreaName);+ _themeFactories = themeFactories.Where(x => x.AreaName == AreaName);}+ public string AreaName => "";+public IEnumerable<string> GetViewLocations(IEnumerable<string> viewLocations){var themeName = _themeContext?.GetCurrentTheme();-- if(string.IsNullOrEmpty(themeName)) return GetDefaultViewLocations();-++ if (string.IsNullOrEmpty(themeName)) return GetDefaultViewLocations();+var themeViewLocations = _themeFactories- .Where(x=>x.ThemeName == themeName)- .SelectMany(x=>x.GetViewLocations())+ .Where(x => x.ThemeName == themeName)+ .SelectMany(x => x.GetViewLocations()).ToList();- return themeViewLocations.Any() ? themeViewLocations.Concat(GetDefaultViewLocations()) : GetDefaultViewLocations();+ return themeViewLocations.Any()+ ? themeViewLocations.Concat(GetDefaultViewLocations())+ : GetDefaultViewLocations();}private IEnumerable<string> GetDefaultViewLocations()diff --git a/src/Web/Grand.Web.Common/View/ViewFactory.cs b/src/Web/Grand.Web.Common/View/ViewFactory.csindex 246d6a243..17ab3e1f9 100644--- a/src/Web/Grand.Web.Common/View/ViewFactory.cs+++ b/src/Web/Grand.Web.Common/View/ViewFactory.cs@@ -4,7 +4,7 @@ namespace Grand.Web.Common.View;public class ViewFactory : IViewFactory{private readonly IDictionary<string, IAreaViewFactory> _areaFactories;-+public ViewFactory(IEnumerable<IAreaViewFactory> areaFactories){_areaFactories = areaFactories.ToDictionary(f => f.AreaName, f => f);@@ -17,9 +17,8 @@ public class ViewFactory : IViewFactoryviewLocations = areaFactory.GetViewLocations(viewLocations);return;}-- viewLocations = new List<string>- {++ viewLocations = new List<string> {"/Views/{1}/{0}.cshtml","/Views/Shared/{0}.cshtml"};diff --git a/src/Web/Grand.Web.Common/View/ViewLocationExpander.cs b/src/Web/Grand.Web.Common/View/ViewLocationExpander.csindex f41937868..581dc2fe1 100644--- a/src/Web/Grand.Web.Common/View/ViewLocationExpander.cs+++ b/src/Web/Grand.Web.Common/View/ViewLocationExpander.cs@@ -2,28 +2,30 @@using Microsoft.AspNetCore.Mvc.Razor;using Microsoft.Extensions.DependencyInjection;-namespace Grand.Web.Common.View+namespace Grand.Web.Common.View;++public class ViewLocationExpander : IViewLocationExpander{- public class ViewLocationExpander : IViewLocationExpander+ private const string ThemeKey = "Theme";++ public void PopulateValues(ViewLocationExpanderContext context)+ {+ var themeContextFactory =+ context.ActionContext.HttpContext.RequestServices.GetRequiredService<IThemeContextFactory>();+ var themeContext = themeContextFactory.GetThemeContext(context.AreaName ?? "");+ var themeName = themeContext?.GetCurrentTheme();+ if (!string.IsNullOrEmpty(themeName))+ context.Values[ThemeKey] = themeContext?.GetCurrentTheme();+ }++ public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context,+ IEnumerable<string> viewLocations){- private const string ThemeKey = "Theme";- public void PopulateValues(ViewLocationExpanderContext context)- {- var themeContextFactory = context.ActionContext.HttpContext.RequestServices.GetRequiredService<IThemeContextFactory>();- var themeContext = themeContextFactory.GetThemeContext(context.AreaName ?? "");- var themeName = themeContext?.GetCurrentTheme();- if(!string.IsNullOrEmpty(themeName))- context.Values[ThemeKey] = themeContext?.GetCurrentTheme();- }+ if (!context.Values.TryGetValue(ThemeKey, out var _)) return viewLocations;- public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)- {- if (!context.Values.TryGetValue(ThemeKey, out var _)) return viewLocations;-- var viewFactory = context.ActionContext.HttpContext.RequestServices.GetRequiredService<IViewFactory>();- viewFactory.GetViewPath(context.AreaName ?? "", ref viewLocations);+ var viewFactory = context.ActionContext.HttpContext.RequestServices.GetRequiredService<IViewFactory>();+ viewFactory.GetViewPath(context.AreaName ?? "", ref viewLocations);- return viewLocations;- }+ return viewLocations;}-}+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/ViewRender/ViewRenderService.cs b/src/Web/Grand.Web.Common/ViewRender/ViewRenderService.csindex 9b394f6ab..3ad936589 100644--- a/src/Web/Grand.Web.Common/ViewRender/ViewRenderService.cs+++ b/src/Web/Grand.Web.Common/ViewRender/ViewRenderService.cs@@ -8,57 +8,52 @@ using Microsoft.AspNetCore.Mvc.Rendering;using Microsoft.AspNetCore.Mvc.ViewFeatures;using Microsoft.AspNetCore.Routing;-namespace Grand.Web.Common.ViewRender+namespace Grand.Web.Common.ViewRender;++/// <summary>+/// Allow to get Razor page content as string+/// </summary>+public class ViewRenderService : IViewRenderService{- /// <summary>- /// Allow to get Razor page content as string- /// </summary>- public class ViewRenderService : IViewRenderService- {- private readonly IRazorViewEngine _razorViewEngine;- private readonly ITempDataProvider _tempDataProvider;- private readonly IServiceProvider _serviceProvider;+ private readonly IRazorViewEngine _razorViewEngine;+ private readonly IServiceProvider _serviceProvider;+ private readonly ITempDataProvider _tempDataProvider;- public ViewRenderService(IRazorViewEngine razorViewEngine,- ITempDataProvider tempDataProvider,- IServiceProvider serviceProvider)- {- _razorViewEngine = razorViewEngine;- _tempDataProvider = tempDataProvider;- _serviceProvider = serviceProvider;- }+ public ViewRenderService(IRazorViewEngine razorViewEngine,+ ITempDataProvider tempDataProvider,+ IServiceProvider serviceProvider)+ {+ _razorViewEngine = razorViewEngine;+ _tempDataProvider = tempDataProvider;+ _serviceProvider = serviceProvider;+ }- public async Task<string> RenderToStringAsync<TModel>(string viewPath, TModel model)- {- var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };- var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());+ public async Task<string> RenderToStringAsync<TModel>(string viewPath, TModel model)+ {+ var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };+ var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());- await using var sw = new StringWriter();- var viewResult = _razorViewEngine.GetView(viewPath, viewPath, false);+ await using var sw = new StringWriter();+ var viewResult = _razorViewEngine.GetView(viewPath, viewPath, false);- if (viewResult.View == null)- {- throw new ArgumentNullException($"{viewPath} does not match any available view");- }+ if (viewResult.View == null) throw new ArgumentNullException($"{viewPath} does not match any available view");- var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) {- Model = model- };+ var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) {+ Model = model+ };- var viewContext = new ViewContext(- actionContext,- viewResult.View,- viewDictionary,- new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),- sw,- new HtmlHelperOptions()- );+ var viewContext = new ViewContext(+ actionContext,+ viewResult.View,+ viewDictionary,+ new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),+ sw,+ new HtmlHelperOptions()+ );- await viewResult.View.RenderAsync(viewContext);- return sw.ToString();- }+ await viewResult.View.RenderAsync(viewContext);+ return sw.ToString();}-}-+}\ No newline at end of filediff --git a/src/Web/Grand.Web.Common/WorkContext.cs b/src/Web/Grand.Web.Common/WorkContext.csindex edfafa2d4..688f08d63 100644--- a/src/Web/Grand.Web.Common/WorkContext.cs+++ b/src/Web/Grand.Web.Common/WorkContext.cs@@ -18,429 +18,438 @@ using Microsoft.AspNetCore.Localization;using Microsoft.Extensions.DependencyInjection;using Wangkanai.Detection.Services;-namespace Grand.Web.Common+namespace Grand.Web.Common;++/// <summary>+/// Represents work context for web application / current customer / store / language / currency+/// </summary>+public class WorkContext : IWorkContext, IWorkContextSetter{+ #region Ctor++ public WorkContext(+ IHttpContextAccessor httpContextAccessor,+ IGrandAuthenticationService authenticationService,+ ICurrencyService currencyService,+ ICustomerService customerService,+ IGroupService groupService,+ ILanguageService languageService,+ IStoreHelper storeHelper,+ IAclService aclService,+ IVendorService vendorService,+ LanguageSettings languageSettings,+ TaxSettings taxSettings,+ AppConfig config)+ {+ _httpContextAccessor = httpContextAccessor;+ _authenticationService = authenticationService;+ _currencyService = currencyService;+ _customerService = customerService;+ _groupService = groupService;+ _languageService = languageService;+ _storeHelper = storeHelper;+ _aclService = aclService;+ _vendorService = vendorService;+ _languageSettings = languageSettings;+ _taxSettings = taxSettings;+ _config = config;+ }++ #endregion++ #region Fields++ private readonly IHttpContextAccessor _httpContextAccessor;+ private readonly IGrandAuthenticationService _authenticationService;+ private readonly ICurrencyService _currencyService;+ private readonly ICustomerService _customerService;+ private readonly IGroupService _groupService;+ private readonly ILanguageService _languageService;+ private readonly IStoreHelper _storeHelper;+ private readonly IAclService _aclService;+ private readonly IVendorService _vendorService;++ private readonly LanguageSettings _languageSettings;+ private readonly TaxSettings _taxSettings;+ private readonly AppConfig _config;++ private Customer _cachedCustomer;+ private Customer _originalCustomerIfImpersonated;+ private Vendor _cachedVendor;+ private Language _cachedLanguage;+ private Currency _cachedCurrency;++ private TaxDisplayType _cachedTaxDisplayType;++ #endregion++ #region Utilities+/// <summary>- /// Represents work context for web application / current customer / store / language / currency+ /// Get language from the requested page URL/// </summary>- public class WorkContext : IWorkContext, IWorkContextSetter+ /// <returns>The found language</returns>+ protected virtual async Task<Language> GetLanguageFromUrl(IList<Language> languages){- #region Fields-- private readonly IHttpContextAccessor _httpContextAccessor;- private readonly IGrandAuthenticationService _authenticationService;- private readonly ICurrencyService _currencyService;- private readonly ICustomerService _customerService;- private readonly IGroupService _groupService;- private readonly ILanguageService _languageService;- private readonly IStoreHelper _storeHelper;- private readonly IAclService _aclService;- private readonly IVendorService _vendorService;-- private readonly LanguageSettings _languageSettings;- private readonly TaxSettings _taxSettings;- private readonly AppConfig _config;-- private Customer _cachedCustomer;- private Customer _originalCustomerIfImpersonated;- private Vendor _cachedVendor;- private Language _cachedLanguage;- private Currency _cachedCurrency;-- private TaxDisplayType _cachedTaxDisplayType;-- #endregion-- #region Ctor-- public WorkContext(- IHttpContextAccessor httpContextAccessor,- IGrandAuthenticationService authenticationService,- ICurrencyService currencyService,- ICustomerService customerService,- IGroupService groupService,- ILanguageService languageService,- IStoreHelper storeHelper,- IAclService aclService,- IVendorService vendorService,- LanguageSettings languageSettings,- TaxSettings taxSettings,- AppConfig config)- {- _httpContextAccessor = httpContextAccessor;- _authenticationService = authenticationService;- _currencyService = currencyService;- _customerService = customerService;- _groupService = groupService;- _languageService = languageService;- _storeHelper = storeHelper;- _aclService = aclService;- _vendorService = vendorService;- _languageSettings = languageSettings;- _taxSettings = taxSettings;- _config = config;- }+ if (_httpContextAccessor.HttpContext?.Request == null)+ return await Task.FromResult<Language>(null);- #endregion+ var path = _httpContextAccessor.HttpContext.Request.Path.Value;+ if (string.IsNullOrEmpty(path))+ return await Task.FromResult<Language>(null);- #region Utilities+ var firstSegment = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ??+ string.Empty;+ if (string.IsNullOrEmpty(firstSegment))+ return await Task.FromResult<Language>(null);- /// <summary>- /// Get language from the requested page URL- /// </summary>- /// <returns>The found language</returns>- protected virtual async Task<Language> GetLanguageFromUrl(IList<Language> languages)- {- if (_httpContextAccessor.HttpContext?.Request == null)- return await Task.FromResult<Language>(null);+ var language = languages.FirstOrDefault(urlLanguage =>+ urlLanguage.UniqueSeoCode.Equals(firstSegment, StringComparison.OrdinalIgnoreCase));- var path = _httpContextAccessor.HttpContext.Request.Path.Value;- if (string.IsNullOrEmpty(path))- return await Task.FromResult<Language>(null);+ if (language is not { Published: true } || !_aclService.Authorize(language, CurrentStore.Id))+ return await Task.FromResult<Language>(null);- var firstSegment = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ??- string.Empty;- if (string.IsNullOrEmpty(firstSegment))- return await Task.FromResult<Language>(null);+ return language;+ }- var language = languages.FirstOrDefault(urlLanguage =>- urlLanguage.UniqueSeoCode.Equals(firstSegment, StringComparison.OrdinalIgnoreCase));+ /// <summary>+ /// Get language from the request+ /// </summary>+ /// <returns>The found language</returns>+ protected virtual async Task<Language> GetLanguageFromRequest(IList<Language> languages)+ {+ if (_httpContextAccessor.HttpContext?.Request == null)+ return await Task.FromResult<Language>(null);- if (language is not { Published: true } || !_aclService.Authorize(language, CurrentStore.Id))- return await Task.FromResult<Language>(null);+ //get request culture+ var requestCulture =+ _httpContextAccessor.HttpContext.Features.Get<IRequestCultureFeature>()?.RequestCulture;+ if (requestCulture == null)+ return await Task.FromResult<Language>(null);- return language;- }+ //try to get language by culture name+ var requestLanguage = languages.FirstOrDefault(language =>+ language.LanguageCulture.Equals(requestCulture.Culture.Name, StringComparison.OrdinalIgnoreCase));- /// <summary>- /// Get language from the request- /// </summary>- /// <returns>The found language</returns>- protected virtual async Task<Language> GetLanguageFromRequest(IList<Language> languages)- {- if (_httpContextAccessor.HttpContext?.Request == null)- return await Task.FromResult<Language>(null);+ //check language availability+ if (requestLanguage is not { Published: true } ||+ !_aclService.Authorize(requestLanguage, CurrentStore.Id))+ return await Task.FromResult<Language>(null);- //get request culture- var requestCulture =- _httpContextAccessor.HttpContext.Features.Get<IRequestCultureFeature>()?.RequestCulture;- if (requestCulture == null)- return await Task.FromResult<Language>(null);+ return requestLanguage;+ }- //try to get language by culture name- var requestLanguage = languages.FirstOrDefault(language =>- language.LanguageCulture.Equals(requestCulture.Culture.Name, StringComparison.OrdinalIgnoreCase));+ protected virtual async Task<Customer> SetImpersonatedCustomer(Customer customer)+ {+ //get impersonate user if required+ var impersonatedCustomerId =+ customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.ImpersonatedCustomerId);+ if (string.IsNullOrEmpty(impersonatedCustomerId)) return null;+ var impersonatedCustomer = await _customerService.GetCustomerById(impersonatedCustomerId);+ if (impersonatedCustomer is not { Deleted: false, Active: true }) return null;+ //set impersonated customer+ _originalCustomerIfImpersonated = customer;+ return impersonatedCustomer;+ }- //check language availability- if (requestLanguage is not { Published: true } ||- !_aclService.Authorize(requestLanguage, CurrentStore.Id))- return await Task.FromResult<Language>(null);+ #endregion- return requestLanguage;- }+ #region Properties- protected virtual async Task<Customer> SetImpersonatedCustomer(Customer customer)- {- //get impersonate user if required- var impersonatedCustomerId =- customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.ImpersonatedCustomerId);- if (string.IsNullOrEmpty(impersonatedCustomerId)) return null;- var impersonatedCustomer = await _customerService.GetCustomerById(impersonatedCustomerId);- if (impersonatedCustomer is not { Deleted: false, Active: true }) return null;- //set impersonated customer- _originalCustomerIfImpersonated = customer;- return impersonatedCustomer;+ /// <summary>+ /// Gets the current customer+ /// </summary>+ public virtual Customer CurrentCustomer => _cachedCustomer;- }+ /// <summary>+ /// Set the current customer by Middleware+ /// </summary>+ /// <returns></returns>+ public virtual async Task<Customer> SetCurrentCustomer()+ {+ var customer = await GetBackgroundTaskCustomer();+ if (customer != null) return _cachedCustomer = customer;- #endregion+ customer = await GetAuthenticatedCustomer();+ if (customer != null) return _cachedCustomer = customer;- #region Properties+ customer = await GetGuestCustomer();+ if (customer != null) return _cachedCustomer = customer;- /// <summary>- /// Gets the current customer- /// </summary>- public virtual Customer CurrentCustomer => _cachedCustomer;+ customer = await GetApiUserCustomer();+ if (customer != null) return _cachedCustomer = customer;- /// <summary>- /// Set the current customer by Middleware- /// </summary>- /// <returns></returns>- public virtual async Task<Customer> SetCurrentCustomer()- {- Customer customer = await GetBackgroundTaskCustomer();- if (customer != null) return _cachedCustomer = customer;-- customer = await GetAuthenticatedCustomer();- if (customer != null) return _cachedCustomer = customer;-- customer = await GetGuestCustomer();- if (customer != null) return _cachedCustomer = customer;-- customer = await GetApiUserCustomer();- if (customer != null) return _cachedCustomer = customer;-- customer = await GetSearchEngineCustomer();- if (customer != null) return _cachedCustomer = customer;-- customer = await GetAllowAnonymousCustomer();- if (customer != null) return _cachedCustomer = customer;-- //create guest if not exists- customer = await CreateCustomerGuest();-- //cache the found customer- return _cachedCustomer = customer;- }- private async Task<Customer> GetBackgroundTaskCustomer()- {- if (_httpContextAccessor.HttpContext != null) return null;-- return await _customerService.GetCustomerBySystemName(SystemCustomerNames.BackgroundTask);- }- private async Task<Customer> GetAllowAnonymousCustomer()- {- var endpoint = _httpContextAccessor.HttpContext?.GetEndpoint();- if (endpoint?.Metadata.GetMetadata<IAllowAnonymous>() == null) return null;-- return await _customerService.GetCustomerBySystemName(SystemCustomerNames.Anonymous);- }-- private async Task<Customer> GetAuthenticatedCustomer()- {- var customer = await _authenticationService.GetAuthenticatedCustomer();- if (customer == null) return null;-- var impersonatedCustomer = await SetImpersonatedCustomer(customer);- if (impersonatedCustomer != null)- customer = impersonatedCustomer;-- return customer;- }-- private async Task<Customer> GetApiUserCustomer()- {- var apiAuthenticationService = _httpContextAccessor.HttpContext.RequestServices.GetService<IApiAuthenticationService>();- return await apiAuthenticationService.GetAuthenticatedCustomer();- }-- private async Task<Customer> GetSearchEngineCustomer()- {- var detectionService = _httpContextAccessor.HttpContext.RequestServices.GetService<IDetectionService>();- var isCrawler = detectionService.Crawler?.IsCrawler;- if (!isCrawler.GetValueOrDefault()) return null;-- return await _customerService.GetCustomerBySystemName(SystemCustomerNames.SearchEngine);- }-- private async Task<Customer> GetGuestCustomer()- {- var guid = await _authenticationService.GetCustomerGuid();- if (string.IsNullOrEmpty(guid) || !Guid.TryParse(guid, out Guid customerGuid)) return null;-- var customerByGuid = await _customerService.GetCustomerByGuid(customerGuid);- if (customerByGuid is { Deleted: false, Active: true } && !await _groupService.IsRegistered(customerByGuid))- return customerByGuid;-- return null;- }-- private async Task<Customer> CreateCustomerGuest()- {- var userFields = new List<UserField>();-- if (_httpContextAccessor?.HttpContext?.Request.GetTypedHeaders().Referer?.ToString() is { } referer)- userFields.Add(new UserField() { Key = SystemCustomerFieldNames.UrlReferrer, Value = referer, StoreId = ""});-- if (!string.IsNullOrEmpty(CurrentStore.DefaultCurrencyId))- userFields.Add(new UserField() { Key = SystemCustomerFieldNames.CurrencyId, Value = CurrentStore.DefaultCurrencyId, StoreId = CurrentStore.Id});-- if (!string.IsNullOrEmpty(CurrentStore.DefaultLanguageId))- userFields.Add(new UserField() { Key = SystemCustomerFieldNames.LanguageId, Value = CurrentStore.DefaultLanguageId, StoreId = CurrentStore.Id});-- var customer = new Customer {- CustomerGuid = Guid.NewGuid(),- Active = true,- StoreId = CurrentStore.Id,- LastActivityDateUtc = DateTime.UtcNow,- LastIpAddress = _httpContextAccessor?.HttpContext?.Connection?.RemoteIpAddress?.ToString(),- UserFields = userFields- };-- customer = await _customerService.InsertGuestCustomer(customer);-- //set customer cookie- await _authenticationService.SetCustomerGuid(customer.CustomerGuid);- return customer;- }+ customer = await GetSearchEngineCustomer();+ if (customer != null) return _cachedCustomer = customer;- /// <summary>- /// Set the current customer- /// </summary>- /// <returns></returns>- public virtual async Task<Customer> SetCurrentCustomer(Customer customer)- {- if (customer == null || customer.Deleted || !customer.Active)- {- //if the current customer is null/not active then set background task customer- customer = await _customerService.GetCustomerBySystemName(SystemCustomerNames.BackgroundTask);- }+ customer = await GetAllowAnonymousCustomer();+ if (customer != null) return _cachedCustomer = customer;- return _cachedCustomer = customer ?? throw new Exception("No customer could be loaded");- }+ //create guest if not exists+ customer = await CreateCustomerGuest();- /// <summary>- /// Gets the original customer- /// </summary>- public virtual Customer OriginalCustomerIfImpersonated => _originalCustomerIfImpersonated;+ //cache the found customer+ return _cachedCustomer = customer;+ }- /// <summary>- /// Gets the current vendor- /// </summary>- public virtual Vendor CurrentVendor => _cachedVendor;+ private async Task<Customer> GetBackgroundTaskCustomer()+ {+ if (_httpContextAccessor.HttpContext != null) return null;- /// <summary>- /// Set the current vendor (logged-in manager)- /// </summary>- public virtual async Task<Vendor> SetCurrentVendor(Customer customer)- {- if (customer == null)- return await Task.FromResult<Vendor>(null);+ return await _customerService.GetCustomerBySystemName(SystemCustomerNames.BackgroundTask);+ }- if (string.IsNullOrEmpty(customer.VendorId))- return await Task.FromResult<Vendor>(null);+ private async Task<Customer> GetAllowAnonymousCustomer()+ {+ var endpoint = _httpContextAccessor.HttpContext?.GetEndpoint();+ if (endpoint?.Metadata.GetMetadata<IAllowAnonymous>() == null) return null;- //try to get vendor- var vendor = await _vendorService.GetVendorById(customer.VendorId);+ return await _customerService.GetCustomerBySystemName(SystemCustomerNames.Anonymous);+ }- //check vendor availability- if (vendor == null || vendor.Deleted || !vendor.Active)- return await Task.FromResult<Vendor>(null);+ private async Task<Customer> GetAuthenticatedCustomer()+ {+ var customer = await _authenticationService.GetAuthenticatedCustomer();+ if (customer == null) return null;- //cache the found vendor- return _cachedVendor = vendor;- }+ var impersonatedCustomer = await SetImpersonatedCustomer(customer);+ if (impersonatedCustomer != null)+ customer = impersonatedCustomer;- /// <summary>- /// Gets or sets current user working language- /// </summary>- public virtual Language WorkingLanguage => _cachedLanguage;-- /// <summary>- /// Set current user working language by Middleware- /// </summary>- /// <param name="customer"></param>- /// <returns></returns>- public virtual async Task<Language> SetWorkingLanguage(Customer customer)- {- Language language = null;+ return customer;+ }- var adminAreaUrl =- _httpContextAccessor.HttpContext?.Request.Path.StartsWithSegments(new PathString("/Admin"));- var allStoreLanguages = await _languageService.GetAllLanguages(showHidden: adminAreaUrl ?? false);+ private async Task<Customer> GetApiUserCustomer()+ {+ var apiAuthenticationService =+ _httpContextAccessor.HttpContext.RequestServices.GetService<IApiAuthenticationService>();+ return await apiAuthenticationService.GetAuthenticatedCustomer();+ }- if (allStoreLanguages.Count == 1)- return _cachedLanguage = allStoreLanguages.FirstOrDefault();+ private async Task<Customer> GetSearchEngineCustomer()+ {+ var detectionService = _httpContextAccessor.HttpContext.RequestServices.GetService<IDetectionService>();+ var isCrawler = detectionService.Crawler?.IsCrawler;+ if (!isCrawler.GetValueOrDefault()) return null;- if (_config.SeoFriendlyUrlsForLanguagesEnabled)- language = await GetLanguageFromUrl(allStoreLanguages);+ return await _customerService.GetCustomerBySystemName(SystemCustomerNames.SearchEngine);+ }- //get current lang identifier- var customerLanguageId =- customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId, CurrentStore.Id);+ private async Task<Customer> GetGuestCustomer()+ {+ var guid = await _authenticationService.GetCustomerGuid();+ if (string.IsNullOrEmpty(guid) || !Guid.TryParse(guid, out var customerGuid)) return null;- if (_languageSettings.AutomaticallyDetectLanguage &&- language == null && string.IsNullOrEmpty(customerLanguageId))- {- language = await GetLanguageFromRequest(allStoreLanguages);- }+ var customerByGuid = await _customerService.GetCustomerByGuid(customerGuid);+ if (customerByGuid is { Deleted: false, Active: true } && !await _groupService.IsRegistered(customerByGuid))+ return customerByGuid;- //check customer language- var customerLanguage = (language ??- (!string.IsNullOrEmpty(customerLanguageId)- ? allStoreLanguages.FirstOrDefault(lang => lang.Id == customerLanguageId)- : allStoreLanguages.FirstOrDefault(lang =>- //if the language for the current store not exist, then use the first- lang.Id == CurrentStore.DefaultLanguageId))) ?? allStoreLanguages.FirstOrDefault();-- return _cachedLanguage = customerLanguage ?? throw new Exception("No language could be loaded");- }+ return null;+ }- /// <summary>- /// Get current user working currency- /// </summary>- public virtual Currency WorkingCurrency => _cachedCurrency;+ private async Task<Customer> CreateCustomerGuest()+ {+ var userFields = new List<UserField>();++ if (_httpContextAccessor?.HttpContext?.Request.GetTypedHeaders().Referer?.ToString() is { } referer)+ userFields.Add(new UserField { Key = SystemCustomerFieldNames.UrlReferrer, Value = referer, StoreId = "" });++ if (!string.IsNullOrEmpty(CurrentStore.DefaultCurrencyId))+ userFields.Add(new UserField {+ Key = SystemCustomerFieldNames.CurrencyId, Value = CurrentStore.DefaultCurrencyId,+ StoreId = CurrentStore.Id+ });++ if (!string.IsNullOrEmpty(CurrentStore.DefaultLanguageId))+ userFields.Add(new UserField {+ Key = SystemCustomerFieldNames.LanguageId, Value = CurrentStore.DefaultLanguageId,+ StoreId = CurrentStore.Id+ });++ var customer = new Customer {+ CustomerGuid = Guid.NewGuid(),+ Active = true,+ StoreId = CurrentStore.Id,+ LastActivityDateUtc = DateTime.UtcNow,+ LastIpAddress = _httpContextAccessor?.HttpContext?.Connection?.RemoteIpAddress?.ToString(),+ UserFields = userFields+ };++ customer = await _customerService.InsertGuestCustomer(customer);++ //set customer cookie+ await _authenticationService.SetCustomerGuid(customer.CustomerGuid);+ return customer;+ }- /// <summary>- /// Set current user working currency by Middleware- /// </summary>- public virtual async Task<Currency> SetWorkingCurrency(Customer customer)- {- //return store currency when we're you are in admin panel- var adminAreaUrl =- _httpContextAccessor.HttpContext?.Request.Path.StartsWithSegments(new PathString("/Admin"));- if (adminAreaUrl.HasValue && adminAreaUrl.Value)- {- var primaryStoreCurrency = await _currencyService.GetPrimaryStoreCurrency();- if (primaryStoreCurrency != null)- {- _cachedCurrency = primaryStoreCurrency;- return primaryStoreCurrency;- }- }+ /// <summary>+ /// Set the current customer+ /// </summary>+ /// <returns></returns>+ public virtual async Task<Customer> SetCurrentCustomer(Customer customer)+ {+ if (customer == null || customer.Deleted || !customer.Active)+ //if the current customer is null/not active then set background task customer+ customer = await _customerService.GetCustomerBySystemName(SystemCustomerNames.BackgroundTask);++ return _cachedCustomer = customer ?? throw new Exception("No customer could be loaded");+ }++ /// <summary>+ /// Gets the original customer+ /// </summary>+ public virtual Customer OriginalCustomerIfImpersonated => _originalCustomerIfImpersonated;++ /// <summary>+ /// Gets the current vendor+ /// </summary>+ public virtual Vendor CurrentVendor => _cachedVendor;- var allStoreCurrencies = await _currencyService.GetAllCurrencies(storeId: CurrentStore?.Id);+ /// <summary>+ /// Set the current vendor (logged-in manager)+ /// </summary>+ public virtual async Task<Vendor> SetCurrentVendor(Customer customer)+ {+ if (customer == null)+ return await Task.FromResult<Vendor>(null);- if (allStoreCurrencies.Count == 1)- return _cachedCurrency = allStoreCurrencies.FirstOrDefault();+ if (string.IsNullOrEmpty(customer.VendorId))+ return await Task.FromResult<Vendor>(null);- var customerCurrencyId =- customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CurrencyId, CurrentStore?.Id);+ //try to get vendor+ var vendor = await _vendorService.GetVendorById(customer.VendorId);- var customerCurrency = (allStoreCurrencies.FirstOrDefault(currency => currency.Id == customerCurrencyId) ?? (!string.IsNullOrEmpty(CurrentStore?.DefaultCurrencyId) ? allStoreCurrencies.FirstOrDefault(currency => currency.Id == CurrentStore.DefaultCurrencyId) : allStoreCurrencies.FirstOrDefault(currency => currency.Id == WorkingLanguage.DefaultCurrencyId))) ??- allStoreCurrencies.FirstOrDefault();+ //check vendor availability+ if (vendor == null || vendor.Deleted || !vendor.Active)+ return await Task.FromResult<Vendor>(null);+ //cache the found vendor+ return _cachedVendor = vendor;+ }- return _cachedCurrency = customerCurrency ?? throw new Exception("No currency could be loaded");- }+ /// <summary>+ /// Gets or sets current user working language+ /// </summary>+ public virtual Language WorkingLanguage => _cachedLanguage;- /// <summary>- /// Gets or sets current tax display type- /// </summary>- public virtual TaxDisplayType TaxDisplayType => _cachedTaxDisplayType;+ /// <summary>+ /// Set current user working language by Middleware+ /// </summary>+ /// <param name="customer"></param>+ /// <returns></returns>+ public virtual async Task<Language> SetWorkingLanguage(Customer customer)+ {+ Language language = null;- public virtual async Task<TaxDisplayType> SetTaxDisplayType(Customer customer)- {- TaxDisplayType taxDisplayType;+ var adminAreaUrl =+ _httpContextAccessor.HttpContext?.Request.Path.StartsWithSegments(new PathString("/Admin"));+ var allStoreLanguages = await _languageService.GetAllLanguages(adminAreaUrl ?? false);- if (_taxSettings.AllowCustomersToSelectTaxDisplayType && customer != null)- {- var taxDisplayTypeId =- customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.TaxDisplayTypeId, CurrentStore.Id);- taxDisplayType = (TaxDisplayType)taxDisplayTypeId;- }- else+ if (allStoreLanguages.Count == 1)+ return _cachedLanguage = allStoreLanguages.FirstOrDefault();++ if (_config.SeoFriendlyUrlsForLanguagesEnabled)+ language = await GetLanguageFromUrl(allStoreLanguages);++ //get current lang identifier+ var customerLanguageId =+ customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId, CurrentStore.Id);++ if (_languageSettings.AutomaticallyDetectLanguage &&+ language == null && string.IsNullOrEmpty(customerLanguageId))+ language = await GetLanguageFromRequest(allStoreLanguages);++ //check customer language+ var customerLanguage = (language ??+ (!string.IsNullOrEmpty(customerLanguageId)+ ? allStoreLanguages.FirstOrDefault(lang => lang.Id == customerLanguageId)+ : allStoreLanguages.FirstOrDefault(lang =>+ //if the language for the current store not exist, then use the first+ lang.Id == CurrentStore.DefaultLanguageId))) ??+ allStoreLanguages.FirstOrDefault();++ return _cachedLanguage = customerLanguage ?? throw new Exception("No language could be loaded");+ }++ /// <summary>+ /// Get current user working currency+ /// </summary>+ public virtual Currency WorkingCurrency => _cachedCurrency;++ /// <summary>+ /// Set current user working currency by Middleware+ /// </summary>+ public virtual async Task<Currency> SetWorkingCurrency(Customer customer)+ {+ //return store currency when we're you are in admin panel+ var adminAreaUrl =+ _httpContextAccessor.HttpContext?.Request.Path.StartsWithSegments(new PathString("/Admin"));+ if (adminAreaUrl.HasValue && adminAreaUrl.Value)+ {+ var primaryStoreCurrency = await _currencyService.GetPrimaryStoreCurrency();+ if (primaryStoreCurrency != null){- //or get the default tax display type- taxDisplayType = _taxSettings.TaxDisplayType;+ _cachedCurrency = primaryStoreCurrency;+ return primaryStoreCurrency;}+ }- //cache the value- _cachedTaxDisplayType = taxDisplayType;+ var allStoreCurrencies = await _currencyService.GetAllCurrencies(storeId: CurrentStore?.Id);- return await Task.FromResult(_cachedTaxDisplayType);- }+ if (allStoreCurrencies.Count == 1)+ return _cachedCurrency = allStoreCurrencies.FirstOrDefault();++ var customerCurrencyId =+ customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CurrencyId, CurrentStore?.Id);++ var customerCurrency = (allStoreCurrencies.FirstOrDefault(currency => currency.Id == customerCurrencyId) ??+ (!string.IsNullOrEmpty(CurrentStore?.DefaultCurrencyId)+ ? allStoreCurrencies.FirstOrDefault(currency =>+ currency.Id == CurrentStore.DefaultCurrencyId)+ : allStoreCurrencies.FirstOrDefault(currency =>+ currency.Id == WorkingLanguage.DefaultCurrencyId))) ??+ allStoreCurrencies.FirstOrDefault();+++ return _cachedCurrency = customerCurrency ?? throw new Exception("No currency could be loaded");+ }- /// <summary>- /// Gets the current store- /// </summary>- public virtual Store CurrentStore => _storeHelper.StoreHost;+ /// <summary>+ /// Gets or sets current tax display type+ /// </summary>+ public virtual TaxDisplayType TaxDisplayType => _cachedTaxDisplayType;++ public virtual async Task<TaxDisplayType> SetTaxDisplayType(Customer customer)+ {+ TaxDisplayType taxDisplayType;- /// <summary>- /// Gets the current domain host- /// </summary>- public virtual DomainHost CurrentHost => _storeHelper.DomainHost;+ if (_taxSettings.AllowCustomersToSelectTaxDisplayType && customer != null)+ {+ var taxDisplayTypeId =+ customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.TaxDisplayTypeId, CurrentStore.Id);+ taxDisplayType = (TaxDisplayType)taxDisplayTypeId;+ }+ else+ {+ //or get the default tax display type+ taxDisplayType = _taxSettings.TaxDisplayType;+ }- #endregion+ //cache the value+ _cachedTaxDisplayType = taxDisplayType;++ return await Task.FromResult(_cachedTaxDisplayType);}++ /// <summary>+ /// Gets the current store+ /// </summary>+ public virtual Store CurrentStore => _storeHelper.StoreHost;++ /// <summary>+ /// Gets the current domain host+ /// </summary>+ public virtual DomainHost CurrentHost => _storeHelper.DomainHost;++ #endregion}\ No newline at end of file