Skip to content

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

Grand.Web.Common - Code refactoring (#345)

Krzysztof Pajak9b7098992c8f
diff --git a/src/Web/Grand.Web.Common/Components/BaseViewComponent.cs b/src/Web/Grand.Web.Common/Components/BaseViewComponent.cs
index 78097a39d..99756eb1b 100644
--- a/src/Web/Grand.Web.Common/Components/BaseViewComponent.cs
+++ b/src/Web/Grand.Web.Common/Components/BaseViewComponent.cs
@@ -14,7 +14,7 @@ namespace Grand.Web.Common.Components
public new IViewComponentResult View<TModel>(TModel model)
{
var viewJson = Request?.Headers["X-Response-View"];
- if (viewJson?.Equals("Json") ?? false)
+ if ((bool)viewJson?.Equals("Json"))
{
return new JsonContentViewComponentResult(JsonConvert.SerializeObject(model));
}
diff --git a/src/Web/Grand.Web.Common/Components/JsonContentViewComponentResult.cs b/src/Web/Grand.Web.Common/Components/JsonContentViewComponentResult.cs
index 6a3e1b1d4..2b75bf704 100644
--- a/src/Web/Grand.Web.Common/Components/JsonContentViewComponentResult.cs
+++ b/src/Web/Grand.Web.Common/Components/JsonContentViewComponentResult.cs
@@ -30,10 +30,10 @@ namespace Grand.Web.Common.Components
public string EncodedContent { get; }
/// <summary>
- /// Set content type for reponse
+ /// Set content type for response
/// </summary>
/// <param name="context"></param>
- protected void ContentType(ViewComponentContext context)
+ private static void ContentType(ViewComponentContext context)
{
context.ViewContext.HttpContext.Response.ContentType = "application/json";
}
diff --git a/src/Web/Grand.Web.Common/Components/ViewComponentExtensions.cs b/src/Web/Grand.Web.Common/Components/ViewComponentExtensions.cs
index 0859dbf2d..9cdefdf9a 100644
--- a/src/Web/Grand.Web.Common/Components/ViewComponentExtensions.cs
+++ b/src/Web/Grand.Web.Common/Components/ViewComponentExtensions.cs
@@ -16,12 +16,7 @@ namespace Grand.Web.Common.Components
var themeViewPath = $"/Themes/{theme}/{viewPath}";
var viewEngine = viewComponent.ViewContext.HttpContext.RequestServices.GetRequiredService<ICompositeViewEngine>();
var result = viewEngine.GetView("", themeViewPath, isMainPage: false);
- if (result.Success)
- {
- return themeViewPath;
- }
-
- return viewName;
+ return result.Success ? themeViewPath : viewName;
}
}
}
diff --git a/src/Web/Grand.Web.Common/Controllers/BaseController.cs b/src/Web/Grand.Web.Common/Controllers/BaseController.cs
index 4b9157f72..d0bb9b31b 100644
--- a/src/Web/Grand.Web.Common/Controllers/BaseController.cs
+++ b/src/Web/Grand.Web.Common/Controllers/BaseController.cs
@@ -32,7 +32,7 @@ namespace Grand.Web.Common.Controllers
/// </summary>
/// <param name="message">Message</param>
/// <param name="persistNextRequest">A value indicating whether a message should be persisted for the next request</param>
- protected virtual void Success(string message, bool persistNextRequest = true)
+ protected void Success(string message, bool persistNextRequest = true)
{
Notification(NotifyType.Success, message, persistNextRequest);
}
@@ -42,7 +42,7 @@ namespace Grand.Web.Common.Controllers
/// </summary>
/// <param name="message">Message</param>
/// <param name="persistNextRequest">A value indicating whether a message should be persisted for the next request</param>
- protected virtual void Warning(string message, bool persistNextRequest = true)
+ protected void Warning(string message, bool persistNextRequest = true)
{
Notification(NotifyType.Warning, message, persistNextRequest);
}
@@ -52,7 +52,7 @@ namespace Grand.Web.Common.Controllers
/// </summary>
/// <param name="message">Message</param>
/// <param name="persistNextRequest">A value indicating whether a message should be persisted for the next request</param>
- protected virtual void Error(string message, bool persistNextRequest = true)
+ protected void Error(string message, bool persistNextRequest = true)
{
Notification(NotifyType.Error, message, persistNextRequest);
}
@@ -60,16 +60,14 @@ namespace Grand.Web.Common.Controllers
/// <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 virtual void Error(ModelStateDictionary ModelState, bool persistNextRequest = true)
+ protected void Error(ModelStateDictionary modelState, bool persistNextRequest = true)
{
var modelErrors = new List<string>();
- foreach (var modelState in ModelState.Values)
+ foreach (var value in modelState.Values)
{
- foreach (var modelError in modelState.Errors)
- {
- modelErrors.Add(modelError.ErrorMessage);
- }
+ modelErrors.AddRange(value.Errors.Select(modelError => modelError.ErrorMessage));
}
Notification(NotifyType.Error, string.Join(',', modelErrors), persistNextRequest);
}
@@ -80,7 +78,7 @@ namespace Grand.Web.Common.Controllers
/// <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 virtual void Error(Exception exception, bool persistNextRequest = true, bool logException = true)
+ protected void Error(Exception exception, bool persistNextRequest = true, bool logException = true)
{
if (logException)
LogException(exception);
@@ -92,12 +90,12 @@ namespace Grand.Web.Common.Controllers
/// Log exception
/// </summary>
/// <param name="exception">Exception</param>
- protected void LogException(Exception exception)
+ private void LogException(Exception exception)
{
var workContext = HttpContext.RequestServices.GetRequiredService<IWorkContext>();
var logger = HttpContext.RequestServices.GetRequiredService<ILogger>();
- _ = logger.InsertLog(Domain.Logging.LogLevel.Error, exception?.Message, exception?.ToString(), workContext.CurrentCustomer, HttpContext.Connection?.RemoteIpAddress?.ToString(),
- HttpContext.Request?.GetDisplayUrl(), HttpContext.Request?.GetTypedHeaders().Referer?.ToString());
+ _ = logger.InsertLog(Domain.Logging.LogLevel.Error, exception?.Message, exception?.ToString(), workContext.CurrentCustomer, HttpContext.Connection.RemoteIpAddress?.ToString(),
+ HttpContext.Request.GetDisplayUrl(), HttpContext.Request.GetTypedHeaders().Referer?.ToString());
}
/// <summary>
@@ -106,13 +104,13 @@ namespace Grand.Web.Common.Controllers
/// <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 virtual void Notification(NotifyType type, string message, bool persistNextRequest)
+ protected void Notification(NotifyType type, string message, bool persistNextRequest)
{
- var dataKey = string.Format("grand.notifications.{0}", type);
+ var dataKey = $"grand.notifications.{type}";
if (persistNextRequest)
{
- if (TempData[dataKey] == null || !(TempData[dataKey] is List<string>))
+ if (TempData[dataKey] == null || TempData[dataKey] is not List<string>)
TempData[dataKey] = new List<string>();
((List<string>)TempData[dataKey]).Add(message);
}
@@ -120,7 +118,7 @@ namespace Grand.Web.Common.Controllers
{
//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 List<string>))
+ if (ViewData[dataKey] == null || ViewData[dataKey] is not List<string>)
ViewData[dataKey] = new List<string>();
((List<string>)ViewData[dataKey]).Add(message);
}
@@ -209,9 +207,9 @@ namespace Grand.Web.Common.Controllers
/// Access denied view
/// </summary>
/// <returns>Access denied view</returns>
- protected virtual IActionResult AccessDeniedView()
+ protected IActionResult AccessDeniedView()
{
- return RedirectToAction("AccessDenied", "Home", new { pageUrl = HttpContext?.Request?.GetEncodedPathAndQuery() });
+ return RedirectToAction("AccessDenied", "Home", new { pageUrl = HttpContext.Request.GetEncodedPathAndQuery() });
}
/// <summary>
diff --git a/src/Web/Grand.Web.Common/Controllers/ControllerExtensions.cs b/src/Web/Grand.Web.Common/Controllers/ControllerExtensions.cs
index baa19e80e..dc004cdc7 100644
--- a/src/Web/Grand.Web.Common/Controllers/ControllerExtensions.cs
+++ b/src/Web/Grand.Web.Common/Controllers/ControllerExtensions.cs
@@ -16,8 +16,9 @@ namespace Grand.Web.Common.Controllers
controller.ViewData.Model = model;
- using var writer = new StringWriter();
+ 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)
diff --git a/src/Web/Grand.Web.Common/Extensions/CommonExtensions.cs b/src/Web/Grand.Web.Common/Extensions/CommonExtensions.cs
index 24e9b9301..b94b4b3dd 100644
--- a/src/Web/Grand.Web.Common/Extensions/CommonExtensions.cs
+++ b/src/Web/Grand.Web.Common/Extensions/CommonExtensions.cs
@@ -44,7 +44,7 @@ namespace Grand.Web.Common.Extensions
select new
{
ID = Convert.ToInt32(enumValue),
- Name = ((translationService != null && workContext != null) ? enumValue.GetTranslationEnum(translationService, workContext) : enumValue.ToString())
+ Name = translationService != null && workContext != null ? enumValue.GetTranslationEnum(translationService, workContext) : enumValue.ToString()
};
object selectedValue = null;
if (markCurrentAsSelected)
diff --git a/src/Web/Grand.Web.Common/Extensions/HtmlExtensions.cs b/src/Web/Grand.Web.Common/Extensions/HtmlExtensions.cs
index 1d9a71734..0bf22a601 100644
--- a/src/Web/Grand.Web.Common/Extensions/HtmlExtensions.cs
+++ b/src/Web/Grand.Web.Common/Extensions/HtmlExtensions.cs
@@ -9,12 +9,10 @@ namespace Grand.Web.Common.Extensions
public static string RenderHtmlContent(this IHtmlContent htmlContent)
{
- using (var writer = new StringWriter())
- {
- htmlContent.WriteTo(writer, HtmlEncoder.Default);
- var htmlOutput = writer.ToString();
- return htmlOutput;
- }
+ using var writer = new StringWriter();
+ htmlContent.WriteTo(writer, HtmlEncoder.Default);
+ var htmlOutput = writer.ToString();
+ return htmlOutput;
}
#endregion
@@ -22,11 +20,9 @@ namespace Grand.Web.Common.Extensions
public static string ToHtmlString(this IHtmlContent tag)
{
- using (var writer = new StringWriter())
- {
- tag.WriteTo(writer, HtmlEncoder.Default);
- return writer.ToString();
- }
+ using var writer = new StringWriter();
+ tag.WriteTo(writer, HtmlEncoder.Default);
+ return writer.ToString();
}
#endregion
diff --git a/src/Web/Grand.Web.Common/Extensions/ModelStateExtensions.cs b/src/Web/Grand.Web.Common/Extensions/ModelStateExtensions.cs
index c9cc02782..20a4cbc90 100644
--- a/src/Web/Grand.Web.Common/Extensions/ModelStateExtensions.cs
+++ b/src/Web/Grand.Web.Common/Extensions/ModelStateExtensions.cs
@@ -6,36 +6,21 @@ namespace Grand.Web.Common.Extensions
{
public static object SerializeErrors(this ModelStateDictionary modelStateDictionary)
{
- return modelStateDictionary.Where(entry => entry.Value.Errors.Any())
+ 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 errors = new List<string>();
- for (var i = 0; i < modelState.Errors.Count; i++)
- {
- var modelError = modelState.Errors[i];
- var errorText = modelError.ErrorMessage;
-
- if (!string.IsNullOrEmpty(errorText))
- {
- errors.Add(errorText);
- }
- }
-
- var dictionary = new Dictionary<string, object>();
- dictionary["errors"] = errors.ToArray();
+ 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)
{
- if (!modelState.IsValid)
- {
- return modelState.SerializeErrors();
- }
- return null;
+ return !modelState.IsValid ? modelState.SerializeErrors() : null;
}
}
}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs b/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs
index ca5138ac3..17a8c4dad 100644
--- a/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs
+++ b/src/Web/Grand.Web.Common/Extensions/SessionExtensions.cs
@@ -30,10 +30,7 @@ namespace Grand.Web.Common.Extensions
public static T Get<T>(this ISession session, string key)
{
var value = session.GetString(key);
- if (value == null)
- return default(T);
-
- return JsonConvert.DeserializeObject<T>(value);
+ return value == null ? default : JsonConvert.DeserializeObject<T>(value);
}
}
}
diff --git a/src/Web/Grand.Web.Common/Extensions/StorageExtensions.cs b/src/Web/Grand.Web.Common/Extensions/StorageExtensions.cs
index ea5e80657..c211f8f73 100644
--- a/src/Web/Grand.Web.Common/Extensions/StorageExtensions.cs
+++ b/src/Web/Grand.Web.Common/Extensions/StorageExtensions.cs
@@ -14,13 +14,11 @@ namespace Grand.Web.Common.Extensions
/// <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;
- }
+ using var fileStream = file.OpenReadStream();
+ using var ms = new MemoryStream();
+ fileStream.CopyTo(ms);
+ var fileBytes = ms.ToArray();
+ return fileBytes;
}
/// <summary>
diff --git a/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs b/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs
index 6668ff71f..ab484e211 100644
--- a/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/AffiliateAttribute.cs
@@ -28,8 +28,8 @@ namespace Grand.Web.Common.Filters
{
#region Constants
- private const string ID_QUERY_PARAMETER_NAME = "affiliateid";
- private const string FRIENDLYURLNAME_QUERY_PARAMETER_NAME = "affiliate";
+ private const string IdQueryParameterName = "affiliateid";
+ private const string FriendlyUrlNameQueryParameterName = "affiliate";
#endregion
@@ -60,9 +60,9 @@ namespace Grand.Web.Common.Filters
/// Set the affiliate identifier of current customer
/// </summary>
/// <param name="affiliate">Affiliate</param>
- protected async Task SetCustomerAffiliateId(Affiliate affiliate)
+ private async Task SetCustomerAffiliateId(Affiliate affiliate)
{
- if (affiliate == null || !affiliate.Active)
+ if (affiliate is not { Active: true })
return;
if (affiliate.Id == _workContext.CurrentCustomer.AffiliateId)
@@ -81,33 +81,34 @@ namespace Grand.Web.Common.Filters
/// 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 (context == null || context.HttpContext == null || context.HttpContext.Request == null)
+ if (context?.HttpContext.Request == null)
return;
//check request query parameters
var request = context.HttpContext.Request;
- if (request?.Query == null || !request.Query.Any())
+ if (!request.Query.Any())
return;
if (!DataSettingsManager.DatabaseIsInstalled())
return;
//try to find by ID
- var affiliateIds = request.Query[ID_QUERY_PARAMETER_NAME];
+ var affiliateIds = request.Query[IdQueryParameterName];
if (affiliateIds.Any())
{
- string affiliateId = affiliateIds.FirstOrDefault();
+ 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[FRIENDLYURLNAME_QUERY_PARAMETER_NAME];
+ var affiliateNames = request.Query[FriendlyUrlNameQueryParameterName];
if (affiliateNames.Any())
{
var affiliateName = affiliateNames.FirstOrDefault();
diff --git a/src/Web/Grand.Web.Common/Filters/ArgumentNameFilterAttribute.cs b/src/Web/Grand.Web.Common/Filters/ArgumentNameFilterAttribute.cs
index 84a3b7006..7442c9196 100644
--- a/src/Web/Grand.Web.Common/Filters/ArgumentNameFilterAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/ArgumentNameFilterAttribute.cs
@@ -9,7 +9,7 @@ namespace Grand.Web.Common.Filters
public override void OnActionExecuting(ActionExecutingContext context)
{
- if (context == null || context.HttpContext == null || context.HttpContext.Request == null)
+ if (context?.HttpContext.Request == null)
return;
context.ActionArguments[Argument] = context.HttpContext.Request.Form.Keys.Any(key => key.Equals(KeyName));
diff --git a/src/Web/Grand.Web.Common/Filters/AuthorizeAdminAttribute.cs b/src/Web/Grand.Web.Common/Filters/AuthorizeAdminAttribute.cs
index a442c91e1..11139febd 100644
--- a/src/Web/Grand.Web.Common/Filters/AuthorizeAdminAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/AuthorizeAdminAttribute.cs
@@ -92,7 +92,7 @@ namespace Grand.Web.Common.Filters
return;
//whether current IP is allowed
- var currentIp = filterContext.HttpContext?.Connection?.RemoteIpAddress?.ToString();
+ var currentIp = filterContext.HttpContext.Connection.RemoteIpAddress?.ToString();
if (!ipAddresses.Any(ip => ip.Equals(currentIp, StringComparison.OrdinalIgnoreCase)))
filterContext.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());
diff --git a/src/Web/Grand.Web.Common/Filters/AuthorizeVendorAttribute.cs b/src/Web/Grand.Web.Common/Filters/AuthorizeVendorAttribute.cs
index b0c77a8f8..1b8cdbfeb 100644
--- a/src/Web/Grand.Web.Common/Filters/AuthorizeVendorAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/AuthorizeVendorAttribute.cs
@@ -55,7 +55,7 @@ namespace Grand.Web.Common.Filters
/// <summary>
/// Called early in the filter pipeline to confirm request is authorized
/// </summary>
- /// <param name="filterContext">Authorization filter context</param>
+ /// <param name="context">Authorization filter context</param>
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
//ignore filter actions
diff --git a/src/Web/Grand.Web.Common/Filters/ClosedStoreAttribute.cs b/src/Web/Grand.Web.Common/Filters/ClosedStoreAttribute.cs
index fac78aacc..f05003833 100644
--- a/src/Web/Grand.Web.Common/Filters/ClosedStoreAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/ClosedStoreAttribute.cs
@@ -69,10 +69,11 @@ namespace Grand.Web.Common.Filters
/// 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 (context == null || context.HttpContext == null || context.HttpContext.Request == null)
+ if (context?.HttpContext?.Request == null)
{
await next();
return;
@@ -106,7 +107,7 @@ namespace Grand.Web.Common.Filters
var actionName = actionDescriptor?.ActionName;
var controllerName = actionDescriptor?.ControllerName;
- if ((string.IsNullOrEmpty(actionName) || string.IsNullOrEmpty(controllerName)) ||
+ if (string.IsNullOrEmpty(actionName) || string.IsNullOrEmpty(controllerName) ||
(controllerName.Equals("Common", StringComparison.OrdinalIgnoreCase) &&
actionName.Equals("StoreClosed", StringComparison.OrdinalIgnoreCase)))
{
diff --git a/src/Web/Grand.Web.Common/Filters/CustomerActivityAttribute.cs b/src/Web/Grand.Web.Common/Filters/CustomerActivityAttribute.cs
index 116e087b6..a17a1c653 100644
--- a/src/Web/Grand.Web.Common/Filters/CustomerActivityAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/CustomerActivityAttribute.cs
@@ -69,7 +69,7 @@ namespace Grand.Web.Common.Filters
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
await next();
- if (context == null || context.HttpContext == null || context.HttpContext.Request == null)
+ if (context?.HttpContext?.Request == null)
return;
if (!DataSettingsManager.DatabaseIsInstalled())
diff --git a/src/Web/Grand.Web.Common/Filters/DenySystemAccountAttribute.cs b/src/Web/Grand.Web.Common/Filters/DenySystemAccountAttribute.cs
index 41546d27e..9a682119a 100644
--- a/src/Web/Grand.Web.Common/Filters/DenySystemAccountAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/DenySystemAccountAttribute.cs
@@ -55,7 +55,7 @@ namespace Grand.Web.Common.Filters
/// <summary>
/// Called early in the filter pipeline to confirm request is authorized
/// </summary>
- /// <param name="filterContext">Authorization filter context</param>
+ /// <param name="context">Authorization filter context</param>
public Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
//ignore filter (the action available even when navigation is not allowed)
diff --git a/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs b/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs
index 1ca62ac4d..f8fac02da 100644
--- a/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/LanguageAttribute.cs
@@ -57,9 +57,10 @@ namespace Grand.Web.Common.Filters
/// 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 (context == null || context.HttpContext == null || context.HttpContext.Request == null)
+ if (context?.HttpContext?.Request == null)
{
await next();
return;
@@ -117,10 +118,10 @@ namespace Grand.Web.Common.Filters
var language = (await _languageService.GetAllLanguages())
.FirstOrDefault(urlLanguage => urlLanguage.UniqueSeoCode.Equals(firstSegment, StringComparison.OrdinalIgnoreCase));
- return language != null ? language.Published : false;
+ return language?.Published ?? false;
}
- private string AddLanguageSeo(string url, Language language)
+ private static string AddLanguageSeo(string url, Language language)
{
if (language == null)
throw new ArgumentNullException(nameof(language));
diff --git a/src/Web/Grand.Web.Common/Filters/PasswordExpiredAttribute.cs b/src/Web/Grand.Web.Common/Filters/PasswordExpiredAttribute.cs
index be3cbd09b..a15dc5cac 100644
--- a/src/Web/Grand.Web.Common/Filters/PasswordExpiredAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/PasswordExpiredAttribute.cs
@@ -53,7 +53,7 @@ namespace Grand.Web.Common.Filters
/// <param name="context">A context for action filters</param>
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
- if (context == null || context.HttpContext == null || context.HttpContext.Request == null)
+ if (context?.HttpContext.Request == null)
return;
if (!DataSettingsManager.DatabaseIsInstalled())
@@ -68,15 +68,15 @@ namespace Grand.Web.Common.Filters
return;
//don't validate on ChangePassword page and store closed
- if ((!(controllerName.Equals("Customer", StringComparison.OrdinalIgnoreCase) &&
- actionName.Equals("ChangePassword", StringComparison.OrdinalIgnoreCase)))
+ if (!(controllerName.Equals("Customer", 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 });
+ var passwordIsExpired = await _mediator.Send(new GetPasswordIsExpiredQuery { Customer = _workContext.CurrentCustomer });
if (passwordIsExpired)
{
//redirect to ChangePassword page if expires
diff --git a/src/Web/Grand.Web.Common/Filters/PublicStoreAttribute.cs b/src/Web/Grand.Web.Common/Filters/PublicStoreAttribute.cs
index 6f17fd049..8c886d9fb 100644
--- a/src/Web/Grand.Web.Common/Filters/PublicStoreAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/PublicStoreAttribute.cs
@@ -81,13 +81,9 @@ namespace Grand.Web.Common.Filters
if (await _permissionService.Authorize(StandardPermission.PublicStoreAllowNavigation))
return;
- if (_storeInformationSettings.StoreClosed)
- {
- filterContext.Result = new RedirectToRouteResult("StoreClosed", new RouteValueDictionary());
- }
- else
+ filterContext.Result = _storeInformationSettings.StoreClosed ? new RedirectToRouteResult("StoreClosed", new RouteValueDictionary()) :
//customer has not access to a public store
- filterContext.Result = new RedirectToRouteResult("Login", new RouteValueDictionary());
+ new RedirectToRouteResult("Login", new RouteValueDictionary());
}
diff --git a/src/Web/Grand.Web.Common/Filters/ValidateCaptchaAttribute.cs b/src/Web/Grand.Web.Common/Filters/ValidateCaptchaAttribute.cs
index f117f41a4..ebdf5dfda 100644
--- a/src/Web/Grand.Web.Common/Filters/ValidateCaptchaAttribute.cs
+++ b/src/Web/Grand.Web.Common/Filters/ValidateCaptchaAttribute.cs
@@ -28,10 +28,10 @@ namespace Grand.Web.Common.Filters
{
#region Constants
- private const string CHALLENGE_FIELD_KEY = "recaptcha_challenge_field";
- private const string RESPONSE_FIELD_KEY = "recaptcha_response_field";
- private const string G_RESPONSE_FIELD_KEY_V3 = "g-recaptcha-response-value";
- private const string G_RESPONSE_FIELD_KEY_V2 = "g-recaptcha-response";
+ 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
@@ -67,31 +67,31 @@ namespace Grand.Web.Common.Filters
//get form values
var form = await context.HttpContext.Request.ReadFormAsync();
- var captchaChallengeValue = form[CHALLENGE_FIELD_KEY];
- var captchaResponseValue = form[RESPONSE_FIELD_KEY];
+ var captchaChallengeValue = form[ChallengeFieldKey];
+ var captchaResponseValue = form[ResponseFieldKey];
var gCaptchaResponseValue = string.Empty;
foreach (var item in form.Keys)
{
- if (item.Contains(G_RESPONSE_FIELD_KEY_V3))
+ if (item.Contains(GResponseFieldKeyV3))
gCaptchaResponseValue = form[item];
}
if(string.IsNullOrEmpty(gCaptchaResponseValue))
- gCaptchaResponseValue = form[G_RESPONSE_FIELD_KEY_V2];
-
- if ((!StringValues.IsNullOrEmpty(captchaChallengeValue) && !StringValues.IsNullOrEmpty(captchaResponseValue)) || !string.IsNullOrEmpty(gCaptchaResponseValue))
+ gCaptchaResponseValue = form[GResponseFieldKeyV2];
+
+ if ((StringValues.IsNullOrEmpty(captchaChallengeValue) ||
+ StringValues.IsNullOrEmpty(captchaResponseValue)) &&
+ string.IsNullOrEmpty(gCaptchaResponseValue)) return false;
+ //Captcha validate request
+ var recaptchaResponse = await _googleReCaptchaValidator.Validate(!StringValues.IsNullOrEmpty(captchaResponseValue) ? captchaResponseValue.ToString() : gCaptchaResponseValue);
+ isValid = recaptchaResponse.IsValid;
+ if (isValid) return true;
+ foreach (var error in recaptchaResponse.ErrorCodes)
{
- //Captcha validate request
- var recaptchaResponse = await _googleReCaptchaValidator.Validate(!StringValues.IsNullOrEmpty(captchaResponseValue) ? captchaResponseValue.ToString() : gCaptchaResponseValue);
- isValid = recaptchaResponse.IsValid;
- if (!isValid)
- foreach (var error in recaptchaResponse.ErrorCodes)
- {
- context.ModelState.AddModelError("", error);
- }
+ context.ModelState.AddModelError("", error);
}
- return isValid;
+ return false;
}
#endregion
@@ -99,14 +99,14 @@ namespace Grand.Web.Common.Filters
#region Methods
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
- if (context == null || context.HttpContext == null || context.HttpContext.Request == null)
+ if (context?.HttpContext.Request == null)
{
await next();
return;
}
//whether CAPTCHA is enabled
- if (_captchaSettings.Enabled && context.HttpContext != null && context.HttpContext.Request != null)
+ if (_captchaSettings.Enabled)
{
//push the validation result as an action parameter
context.ActionArguments[_actionParameterName] = await ValidateCaptcha(context);
diff --git a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs
index b48e37845..b18962587 100644
--- a/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs
+++ b/src/Web/Grand.Web.Common/Infrastructure/ApplicationBuilderExtensions.cs
@@ -61,8 +61,8 @@ namespace Grand.Web.Common.Infrastructure
return;
string authHeader = context.Request.Headers["Authorization"];
- var apirequest = authHeader != null && authHeader.Split(' ')[0] == "Bearer";
- if (apirequest)
+ var apiRequest = authHeader != null && authHeader.Split(' ')[0] == "Bearer";
+ if (apiRequest)
{
await context.Response.WriteAsync(exception.Message);
return;
@@ -77,9 +77,9 @@ namespace Grand.Web.Common.Infrastructure
var workContext = context.RequestServices.GetRequiredService<IWorkContext>();
_ = logger.InsertLog(Domain.Logging.LogLevel.Error, exception.Message, exception.ToString(),
customer: workContext.CurrentCustomer,
- ipAddress: context.Connection?.RemoteIpAddress?.ToString(),
- pageUrl: context.Request?.GetDisplayUrl(),
- referrerUrl: context.Request?.GetTypedHeaders().Referer?.ToString());
+ ipAddress: context.Connection.RemoteIpAddress?.ToString(),
+ pageUrl: context.Request.GetDisplayUrl(),
+ referrerUrl: context.Request.GetTypedHeaders().Referer?.ToString());
//log error
_ = logger.Error(exception.Message, exception, workContext.CurrentCustomer);
}
@@ -105,14 +105,14 @@ namespace Grand.Web.Common.Infrastructure
if (context.HttpContext.Response.StatusCode == 404)
{
string authHeader = context.HttpContext.Request.Headers[HeaderNames.Authorization];
- var apirequest = authHeader != null && authHeader.Split(' ')[0] == JwtBearerDefaults.AuthenticationScheme;
+ var apiRequest = authHeader != null && authHeader.Split(' ')[0] == JwtBearerDefaults.AuthenticationScheme;
var contentTypeProvider = new FileExtensionContentTypeProvider();
- var staticResource = contentTypeProvider.TryGetContentType(context.HttpContext.Request.Path, out string _);
+ var staticResource = contentTypeProvider.TryGetContentType(context.HttpContext.Request.Path, out _);
- if (!apirequest && !staticResource)
+ if (!apiRequest && !staticResource)
{
- var location = "/page-not-found";
+ const string location = "/page-not-found";
context.HttpContext.Response.Redirect(context.HttpContext.Request.PathBase + location);
}
var commonSettings = context.HttpContext.RequestServices.GetRequiredService<CommonSettings>();
@@ -122,11 +122,11 @@ namespace Grand.Web.Common.Infrastructure
//get current customer
var workContext = context.HttpContext.RequestServices.GetRequiredService<IWorkContext>();
_ = logger.InsertLog(Domain.Logging.LogLevel.Error,
- $"Error 404. The requested page ({context.HttpContext.Request?.GetDisplayUrl()}) was not found",
+ $"Error 404. The requested page ({context.HttpContext.Request.GetDisplayUrl()}) was not found",
customer: workContext.CurrentCustomer,
- ipAddress: context.HttpContext?.Connection?.RemoteIpAddress?.ToString(),
- pageUrl: context.HttpContext?.Request?.GetDisplayUrl(),
- referrerUrl: context.HttpContext?.Request?.GetTypedHeaders().Referer?.ToString());
+ ipAddress: context.HttpContext.Connection.RemoteIpAddress?.ToString(),
+ pageUrl: context.HttpContext.Request.GetDisplayUrl(),
+ referrerUrl: context.HttpContext.Request.GetTypedHeaders().Referer?.ToString());
}
}
await Task.CompletedTask;
@@ -142,27 +142,25 @@ namespace Grand.Web.Common.Infrastructure
application.UseStatusCodePages(context =>
{
//handle 400 (Bad request)
- if (context.HttpContext.Response.StatusCode == StatusCodes.Status400BadRequest)
- {
- string authHeader = context.HttpContext.Request.Headers[HeaderNames.Authorization];
- var apirequest = authHeader != null && authHeader.Split(' ')[0] == JwtBearerDefaults.AuthenticationScheme;
+ 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;
- if (!apirequest)
- {
- var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger>();
- var workContext = context.HttpContext.RequestServices.GetRequiredService<IWorkContext>();
- _ = logger.InsertLog(Domain.Logging.LogLevel.Error, "Error 400. Bad request", null, customer: workContext.CurrentCustomer,
- ipAddress: context.HttpContext?.Connection?.RemoteIpAddress?.ToString(),
- pageUrl: context.HttpContext?.Request?.GetDisplayUrl(),
- referrerUrl: context.HttpContext?.Request?.GetTypedHeaders().Referer?.ToString());
- }
- }
+ if (apiRequest) return Task.CompletedTask;
+ var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger>();
+ var workContext = context.HttpContext.RequestServices.GetRequiredService<IWorkContext>();
+ _ = logger.InsertLog(Domain.Logging.LogLevel.Error, "Error 400. Bad request", null, customer: workContext.CurrentCustomer,
+ ipAddress: context.HttpContext.Connection.RemoteIpAddress?.ToString(),
+ pageUrl: context.HttpContext.Request.GetDisplayUrl(),
+ referrerUrl: context.HttpContext.Request.GetTypedHeaders().Referer?.ToString());
return Task.CompletedTask;
});
}
/// <summary>
- /// Congifure authentication
+ /// Configure authentication
/// </summary>
/// <param name="application">Builder for configuring an application's request pipeline</param>
public static void UseGrandAuthentication(this IApplicationBuilder application)
@@ -182,9 +180,9 @@ namespace Grand.Web.Common.Infrastructure
var typeSearcher = endpoints.ServiceProvider.GetRequiredService<ITypeSearcher>();
var endpointProviders = typeSearcher.ClassesOfType<IEndpointProvider>();
var instances = endpointProviders
- .Where(endpointProvider => PluginExtensions.OnlyInstalledPlugins(endpointProvider))
+ .Where(PluginExtensions.OnlyInstalledPlugins)
.Select(endpointProvider => (IEndpointProvider)Activator.CreateInstance(endpointProvider))
- .OrderByDescending(endpointProvider => endpointProvider.Priority);
+ .OrderByDescending(endpointProvider => endpointProvider!.Priority);
foreach (var endpointProvider in instances)
endpointProvider.RegisterEndpoint(endpoints);
@@ -204,6 +202,7 @@ namespace Grand.Web.Common.Infrastructure
/// 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
@@ -273,7 +272,7 @@ namespace Grand.Web.Common.Infrastructure
var serviceProvider = application.ApplicationServices;
var logger = serviceProvider.GetRequiredService<ILogger>();
- _ = logger.Information("Application started", null, null);
+ _ = logger.Information("Application started");
}
/// <summary>
@@ -306,7 +305,7 @@ namespace Grand.Web.Common.Infrastructure
.AddXssProtectionBlock()
.AddFrameOptionsDeny()
.AddContentTypeOptionsNoSniff()
- .AddStrictTransportSecurityMaxAgeIncludeSubDomains(maxAgeInSeconds: 60 * 60 * 24 * 365) // maxage = one year in seconds
+ .AddStrictTransportSecurityMaxAgeIncludeSubDomains(maxAgeInSeconds: 60 * 60 * 24 * 365) // max-age = one year in seconds
.AddReferrerPolicyStrictOriginWhenCrossOrigin()
.AddContentSecurityPolicy(builder =>
{
@@ -362,7 +361,7 @@ namespace Grand.Web.Common.Infrastructure
}
/// <summary>
- /// Configures wethere use or not the Header X-Powered-By and its value.
+ /// 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)
diff --git a/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs b/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs
index 6ceb21b5a..8c01162e1 100644
--- a/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs
+++ b/src/Web/Grand.Web.Common/Infrastructure/BackgroundServiceTask.cs
@@ -11,23 +11,13 @@ namespace Grand.Web.Common.Infrastructure
public class BackgroundServiceTask : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
- private string _taskType;
- public BackgroundServiceTask(string tasktype, IServiceProvider serviceProvider)
+ private readonly string _taskType;
+ public BackgroundServiceTask(string taskType, IServiceProvider serviceProvider)
{
- _taskType = tasktype;
+ _taskType = taskType;
_serviceProvider = serviceProvider;
}
- public override Task StartAsync(CancellationToken cancellationToken)
- {
- return base.StartAsync(cancellationToken);
- }
-
- public override Task StopAsync(CancellationToken cancellationToken)
- {
- return base.StopAsync(cancellationToken);
- }
-
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
@@ -47,7 +37,7 @@ namespace Grand.Web.Common.Infrastructure
var machineName = Environment.MachineName;
var timeInterval = task.TimeInterval > 0 ? task.TimeInterval : 1;
- if (task.Enabled && (string.IsNullOrEmpty(task.LeasedByMachineName) || (machineName == task.LeasedByMachineName)))
+ if (task.Enabled && (string.IsNullOrEmpty(task.LeasedByMachineName) || machineName == task.LeasedByMachineName))
{
var typeofTask = Type.GetType(_taskType);
if (typeofTask != null)
@@ -58,7 +48,7 @@ namespace Grand.Web.Common.Infrastructure
//assign current customer (background task) / current store (from task)
await WorkContext(serviceProvider, task);
- bool runTask = true;
+ var runTask = true;
if(task.LastStartUtc.HasValue)
{
if (DateTime.UtcNow < task.LastStartUtc.Value.AddMinutes(task.TimeInterval))
@@ -121,7 +111,8 @@ namespace Grand.Web.Common.Infrastructure
}
}
- protected async Task WorkContext(IServiceProvider serviceProvider, ScheduleTask scheduleTask)
+
+ private async Task WorkContext(IServiceProvider serviceProvider, ScheduleTask scheduleTask)
{
var workContext = serviceProvider.GetRequiredService<IWorkContext>();
var storeHelper = serviceProvider.GetRequiredService<IStoreHelper>();
diff --git a/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs b/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs
index a869c87d2..95e77b76f 100644
--- a/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs
+++ b/src/Web/Grand.Web.Common/Infrastructure/ServiceCollectionExtensions.cs
@@ -42,17 +42,17 @@ namespace Grand.Web.Common.Infrastructure
/// </summary>
public static class ServiceCollectionExtensions
{
-
/// <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 =>
{
- options.Cookie = new CookieBuilder() {
+ options.Cookie = new CookieBuilder {
Name = $"{config.CookiePrefix}Antiforgery"
};
if (DataSettingsManager.DatabaseIsInstalled())
@@ -68,13 +68,14 @@ namespace Grand.Web.Common.Infrastructure
/// 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() {
+ options.Cookie = new CookieBuilder {
Name = $"{config.CookiePrefix}Session",
- HttpOnly = true,
+ HttpOnly = true
};
if (DataSettingsManager.DatabaseIsInstalled())
{
@@ -104,38 +105,38 @@ namespace Grand.Web.Common.Infrastructure
/// </summary>
public static void AddGrandDataProtection(this IServiceCollection services, IConfiguration configuration)
{
- var redisconfig = new RedisConfig();
- configuration.GetSection("Redis").Bind(redisconfig);
+ var redisConfig = new RedisConfig();
+ configuration.GetSection("Redis").Bind(redisConfig);
- var azureconfig = new AzureConfig();
- configuration.GetSection("Azure").Bind(azureconfig);
+ var azureConfig = new AzureConfig();
+ configuration.GetSection("Azure").Bind(azureConfig);
- if (redisconfig.PersistKeysToRedis)
+ if (redisConfig.PersistKeysToRedis)
{
services.AddDataProtection(opt => opt.ApplicationDiscriminator = "grandnode")
- .PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(redisconfig.PersistKeysToRedisUrl));
+ .PersistKeysToStackExchangeRedis(ConnectionMultiplexer.Connect(redisConfig.PersistKeysToRedisUrl));
}
- else if (azureconfig.PersistKeysToAzureKeyVault || azureconfig.PersistKeysToAzureBlobStorage)
+ else if (azureConfig.PersistKeysToAzureKeyVault || azureConfig.PersistKeysToAzureBlobStorage)
{
- if (azureconfig.PersistKeysToAzureKeyVault)
+ 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),
+ .PersistKeysToAzureBlobStorage(azureConfig.PersistKeysAzureBlobStorageConnectionString, azureConfig.DataProtectionContainerName, azureConfig.DataProtectionBlobName)
+ .ProtectKeysWithAzureKeyVault(new Uri(azureConfig.KeyIdentifier),
new DefaultAzureCredential());
else
{
services.AddDataProtection()
- .PersistKeysToAzureBlobStorage(azureconfig.PersistKeysAzureBlobStorageConnectionString, azureconfig.DataProtectionContainerName, azureconfig.DataProtectionBlobName);
+ .PersistKeysToAzureBlobStorage(azureConfig.PersistKeysAzureBlobStorageConnectionString, azureConfig.DataProtectionContainerName, azureConfig.DataProtectionBlobName);
}
}
else
{
- var securityconfig = new SecurityConfig();
- configuration.GetSection("Security").Bind(securityconfig);
+ var securityConfig = new SecurityConfig();
+ configuration.GetSection("Security").Bind(securityConfig);
- var dataProtectionKeysPath = string.IsNullOrEmpty(securityconfig.KeyPersistenceLocation) ? CommonPath.DataProtectionKeysPath : securityconfig.KeyPersistenceLocation;
+ var dataProtectionKeysPath = string.IsNullOrEmpty(securityConfig.KeyPersistenceLocation) ? CommonPath.DataProtectionKeysPath : securityConfig.KeyPersistenceLocation;
var dataProtectionKeysFolder = new DirectoryInfo(dataProtectionKeysPath);
//configure the data protection system to persist keys to the specified directory
@@ -147,10 +148,11 @@ namespace Grand.Web.Common.Infrastructure
/// 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);
+ var securityConfig = new SecurityConfig();
+ configuration.GetSection("Security").Bind(securityConfig);
//set default authentication schemes
var authenticationBuilder = services.AddAuthentication(options =>
@@ -162,31 +164,31 @@ namespace Grand.Web.Common.Infrastructure
//add main cookie authentication
authenticationBuilder.AddCookie(GrandCookieAuthenticationDefaults.AuthenticationScheme, options =>
{
- options.Cookie.Name = securityconfig.CookiePrefix + GrandCookieAuthenticationDefaults.AuthenticationScheme;
+ 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.SecurePolicy = securityConfig.CookieSecurePolicyAlways ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest;
});
//add external authentication
authenticationBuilder.AddCookie(GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme, options =>
{
- options.Cookie.Name = securityconfig.CookiePrefix + GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme;
+ 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.SecurePolicy = securityConfig.CookieSecurePolicyAlways ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest;
});
//register external authentication plugins now
var typeSearcher = new AppTypeSearcher();
var externalAuthConfigurations = typeSearcher.ClassesOfType<IAuthenticationBuilder>();
var externalAuthInstances = externalAuthConfigurations
- .Where(x => PluginExtensions.OnlyInstalledPlugins(x))
+ .Where(PluginExtensions.OnlyInstalledPlugins)
.Select(x => (IAuthenticationBuilder)Activator.CreateInstance(x))
- .OrderBy(x => x.Priority);
+ .OrderBy(x => x!.Priority);
//add new Authentication
foreach (var instance in externalAuthInstances)
@@ -198,6 +200,7 @@ namespace Grand.Web.Common.Infrastructure
/// 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)
{
@@ -285,7 +288,7 @@ namespace Grand.Web.Common.Infrastructure
var instances = settings.Select(x => (ISettings)Activator.CreateInstance(x));
foreach (var item in instances)
{
- services.AddScoped(item.GetType(), (x) =>
+ services.AddScoped(item!.GetType(), (x) =>
{
var type = item.GetType();
var storeId = "";
@@ -306,7 +309,7 @@ namespace Grand.Web.Common.Infrastructure
hcBuilder.AddCheck("self", () => HealthCheckResult.Healthy());
hcBuilder.AddMongoDb(connection.ConnectionString,
name: "mongodb-check",
- tags: new string[] { "mongodb" });
+ tags: new[] { "mongodb" });
}
@@ -329,7 +332,7 @@ namespace Grand.Web.Common.Infrastructure
options.ExcludedPages = new List<IUrlMatcher> {
new WildcardUrlMatcher("/swagger/*"),
new WildcardUrlMatcher("/admin/*"),
- new ExactUrlMatcher("/admin"),
+ new ExactUrlMatcher("/admin")
};
options.CssMinifierFactory = new NUglifyCssMinifierFactory();
options.JsMinifierFactory = new NUglifyJsMinifierFactory();
@@ -339,13 +342,13 @@ namespace Grand.Web.Common.Infrastructure
options.ExcludedPages = new List<IUrlMatcher> {
new WildcardUrlMatcher("/swagger/*"),
new WildcardUrlMatcher("/admin/*"),
- new ExactUrlMatcher("/admin"),
+ new ExactUrlMatcher("/admin")
};
})
.AddHttpCompression(options =>
{
options.ExcludedPages = new List<IUrlMatcher> {
- new WildcardUrlMatcher("/swagger/*"),
+ new WildcardUrlMatcher("/swagger/*")
};
options.CompressorFactories = new List<ICompressorFactory>
{
diff --git a/src/Web/Grand.Web.Common/Localization/LocService.cs b/src/Web/Grand.Web.Common/Localization/LocService.cs
index 0e4919398..ccb4541a7 100644
--- a/src/Web/Grand.Web.Common/Localization/LocService.cs
+++ b/src/Web/Grand.Web.Common/Localization/LocService.cs
@@ -32,16 +32,16 @@ namespace Grand.Web.Common.Localization
var resFormat = _translationService.GetResource(name.ToLowerInvariant());
if (string.IsNullOrEmpty(resFormat))
{
- return new LocalizedString(name, resFormat, resFormat == null);
+ return new LocalizedString(name, string.Empty, resFormat == null);
}
try
{
return new LocalizedString(name, string.Format(resFormat, arguments),
- resFormat == null);
+ false);
}
catch
{
- return new LocalizedString(name, resFormat, resFormat == null);
+ return new LocalizedString(name, resFormat, false);
}
}
}
diff --git a/src/Web/Grand.Web.Common/Menu/SiteMap.cs b/src/Web/Grand.Web.Common/Menu/SiteMap.cs
index 389f5f250..7817dcab0 100644
--- a/src/Web/Grand.Web.Common/Menu/SiteMap.cs
+++ b/src/Web/Grand.Web.Common/Menu/SiteMap.cs
@@ -21,12 +21,11 @@ namespace Grand.Web.Common.Menu
public virtual async Task Load()
{
var adminSiteMaps = await _adminSiteMapService.GetSiteMap();
- var sitemap = new SiteMapNode()
- {
+ var sitemap = new SiteMapNode {
SystemName = "Home",
ResourceName = "Admin.Home",
ControllerName = "Home",
- ActionName = "Overview",
+ ActionName = "Overview"
};
await PrepareRootNode(sitemap, adminSiteMaps);
}
@@ -38,9 +37,9 @@ namespace Grand.Web.Common.Menu
{
foreach (var item in adminSiteMaps)
{
- var mainsite = new SiteMapNode();
- siteMap.ChildNodes.Add(mainsite);
- await Iterate(mainsite, item);
+ var mainSite = new SiteMapNode();
+ siteMap.ChildNodes.Add(mainSite);
+ await Iterate(mainSite, item);
}
}
RootNode = siteMap;
@@ -52,9 +51,9 @@ namespace Grand.Web.Common.Menu
foreach (var item in siteMapNode.ChildNodes.OrderBy(x=>x.DisplayOrder))
{
- var mainsite = new SiteMapNode();
- siteMap.ChildNodes.Add(mainsite);
- await Iterate(mainsite, item);
+ var mainSite = new SiteMapNode();
+ siteMap.ChildNodes.Add(mainSite);
+ await Iterate(mainSite, item);
}
}
diff --git a/src/Web/Grand.Web.Common/Middleware/DbVersionCheckMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/DbVersionCheckMiddleware.cs
index 5dd3fe7b6..f3131b3a2 100644
--- a/src/Web/Grand.Web.Common/Middleware/DbVersionCheckMiddleware.cs
+++ b/src/Web/Grand.Web.Common/Middleware/DbVersionCheckMiddleware.cs
@@ -22,22 +22,21 @@ namespace Grand.Web.Common.Middleware
IRepository<GrandNodeVersion> repository)
{
- if (context == null || context.Request == null)
+ if (context?.Request == null)
{
- await _next(context);
return;
}
var version = cacheBase.Get(CacheKey.GRAND_NODE_VERSION, () => repository.Table.FirstOrDefault());
if (version == null)
{
- await context.Response.WriteAsync($"The database does not exist.");
+ 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. " +
+ await context.Response.WriteAsync("The database version is not supported in this software version. " +
$"Supported version: {GrandVersion.SupportedDBVersion} , your version: {version.DataBaseVersion}");
}
else
diff --git a/src/Web/Grand.Web.Common/Middleware/InstallUrlMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/InstallUrlMiddleware.cs
index 0c98fe82e..51a41cc24 100644
--- a/src/Web/Grand.Web.Common/Middleware/InstallUrlMiddleware.cs
+++ b/src/Web/Grand.Web.Common/Middleware/InstallUrlMiddleware.cs
@@ -27,14 +27,13 @@ namespace Grand.Web.Common.Middleware
/// Invoke middleware actions
/// </summary>
/// <param name="context">HTTP context</param>
- /// <param name="webHelper">Web helper</param>
/// <returns>Task</returns>
public async Task InvokeAsync(HttpContext context)
{
//whether database is installed
if (!DataSettingsManager.DatabaseIsInstalled())
{
- var installUrl = $"/install";
+ const string installUrl = $"/install";
if (!context.Request.GetEncodedPathAndQuery().StartsWith(installUrl, StringComparison.OrdinalIgnoreCase))
{
//redirect
diff --git a/src/Web/Grand.Web.Common/Middleware/PoweredByMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/PoweredByMiddleware.cs
index 8bee8b513..ae3cc7e84 100644
--- a/src/Web/Grand.Web.Common/Middleware/PoweredByMiddleware.cs
+++ b/src/Web/Grand.Web.Common/Middleware/PoweredByMiddleware.cs
@@ -35,8 +35,8 @@ namespace Grand.Web.Common.Middleware
public class PoweredByMiddlewareOptions: IPoweredByMiddlewareOptions
{
- const string PoweredByHeaderName = "X-Powered-By";
- const string PoweredByHeaderValue = "GrandNode";
+ private const string PoweredByHeaderName = "X-Powered-By";
+ private const string PoweredByHeaderValue = "GrandNode";
public string HeaderName => PoweredByHeaderName;
public string HeaderValue { get; set; } = PoweredByHeaderValue;
diff --git a/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs b/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs
index 96f45e10a..4362bd991 100644
--- a/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs
+++ b/src/Web/Grand.Web.Common/Middleware/WorkContextMiddleware.cs
@@ -31,24 +31,24 @@ namespace Grand.Web.Common.Middleware
/// Invoke middleware actions
/// </summary>
/// <param name="context">HTTP context</param>
+ /// <param name="workContext">workContext</param>
/// <returns>Task</returns>
public async Task Invoke(HttpContext context, IWorkContext workContext)
{
- if (context == null || context.Request == null)
+ if (context?.Request == null)
{
- await _next(context);
return;
}
//set current context
var customer = await workContext.SetCurrentCustomer();
- var vendor = await workContext.SetCurrentVendor(customer);
+ await workContext.SetCurrentVendor(customer);
var language = await workContext.SetWorkingLanguage(customer);
- var currency = await workContext.SetWorkingCurrency(customer);
- var taxtype = await workContext.SetTaxDisplayType(customer);
+ await workContext.SetWorkingCurrency(customer);
+ await workContext.SetTaxDisplayType(customer);
//set culture in admin area
- if (context.Request.Path.Value.StartsWith("/admin", StringComparison.InvariantCultureIgnoreCase))
+ if (context.Request.Path.Value != null && context.Request.Path.Value.StartsWith("/admin", StringComparison.InvariantCultureIgnoreCase))
{
var culture = new CultureInfo("en-US");
CultureInfo.CurrentCulture = culture;
diff --git a/src/Web/Grand.Web.Common/Models/StoreModel.cs b/src/Web/Grand.Web.Common/Models/StoreModel.cs
index 1f19e52bd..b1bc46d2c 100644
--- a/src/Web/Grand.Web.Common/Models/StoreModel.cs
+++ b/src/Web/Grand.Web.Common/Models/StoreModel.cs
@@ -1,6 +1,6 @@
namespace Grand.Web.Common.Models
{
- public partial class StoreModel
+ public class StoreModel
{
public string Id { get; set; }
public string Name { get; set; }
diff --git a/src/Web/Grand.Web.Common/Page/IPageHeadBuilder.cs b/src/Web/Grand.Web.Common/Page/IPageHeadBuilder.cs
index f9433ef64..393d86a49 100644
--- a/src/Web/Grand.Web.Common/Page/IPageHeadBuilder.cs
+++ b/src/Web/Grand.Web.Common/Page/IPageHeadBuilder.cs
@@ -5,7 +5,7 @@ namespace Grand.Web.Common.Page
/// <summary>
/// Page head builder
/// </summary>
- public partial interface IPageHeadBuilder
+ public interface IPageHeadBuilder
{
void AddTitleParts(string part);
void AppendTitleParts(string part);
diff --git a/src/Web/Grand.Web.Common/Page/PageHeadBuilder.cs b/src/Web/Grand.Web.Common/Page/PageHeadBuilder.cs
index 4cd36771e..4fb119b34 100644
--- a/src/Web/Grand.Web.Common/Page/PageHeadBuilder.cs
+++ b/src/Web/Grand.Web.Common/Page/PageHeadBuilder.cs
@@ -5,7 +5,7 @@ namespace Grand.Web.Common.Page
/// <summary>
/// Page head builder
/// </summary>
- public partial class PageHeadBuilder : IPageHeadBuilder
+ public class PageHeadBuilder : IPageHeadBuilder
{
#region Fields
@@ -26,7 +26,6 @@ namespace Grand.Web.Common.Page
/// Constuctor
/// </summary>
/// <param name="seoSettings">SEO settings</param>
- /// <param name="hostingEnvironment">Hosting environment</param>
public PageHeadBuilder(SeoSettings seoSettings)
{
_title = new List<string>();
@@ -65,14 +64,11 @@ namespace Grand.Web.Common.Page
{
string result;
var titleParts = string.Join(_seoSettings.PageTitleSeparator, _title.AsEnumerable().Reverse().ToList());
- if (!String.IsNullOrEmpty(titleParts))
+ if (!string.IsNullOrEmpty(titleParts))
{
if (addDefaultTitle)
{
- if (_seoSettings.PageTitleSeoAdjustment)
- result = string.Join(_seoSettings.PageTitleSeparator, _seoSettings.DefaultTitle, titleParts);
- else
- result = string.Join(_seoSettings.PageTitleSeparator, titleParts, _seoSettings.DefaultTitle);
+ result = _seoSettings.PageTitleSeoAdjustment ? string.Join(_seoSettings.PageTitleSeparator, _seoSettings.DefaultTitle, titleParts) : string.Join(_seoSettings.PageTitleSeparator, titleParts, _seoSettings.DefaultTitle);
}
else
{
@@ -105,7 +101,7 @@ namespace Grand.Web.Common.Page
public virtual string GenerateMetaDescription()
{
var description = string.Join(", ", _metaDescription.AsEnumerable().Reverse().ToList());
- var result = !String.IsNullOrEmpty(description) ? description : _seoSettings.DefaultMetaDescription;
+ var result = !string.IsNullOrEmpty(description) ? description : _seoSettings.DefaultMetaDescription;
return result;
}
@@ -128,7 +124,7 @@ namespace Grand.Web.Common.Page
public virtual string GenerateMetaKeywords()
{
var keyword = string.Join(", ", _metaKeyword.AsEnumerable().Reverse().ToList());
- var result = !String.IsNullOrEmpty(keyword) ? keyword : _seoSettings.DefaultMetaKeywords;
+ var result = !string.IsNullOrEmpty(keyword) ? keyword : _seoSettings.DefaultMetaKeywords;
return result;
}
@@ -153,7 +149,7 @@ namespace Grand.Web.Common.Page
var result = new StringBuilder();
foreach (var canonicalUrl in _canonicalUrl)
{
- result.AppendFormat("<link rel=\"canonical\" href=\"{0}\" />", canonicalUrl);
+ result.Append($"<link rel=\"canonical\" href=\"{canonicalUrl}\" />");
result.Append(Environment.NewLine);
}
return result.ToString();
@@ -208,7 +204,7 @@ namespace Grand.Web.Common.Page
public virtual string GeneratePageCssClasses()
{
- string result = string.Join(" ", _pageCssClass.AsEnumerable().Reverse().ToArray());
+ var result = string.Join(" ", _pageCssClass.AsEnumerable().Reverse().ToArray());
return result;
}
diff --git a/src/Web/Grand.Web.Common/Page/Paging/BasePageableModel.cs b/src/Web/Grand.Web.Common/Page/Paging/BasePageableModel.cs
index f17c81d4a..bdc3211f5 100644
--- a/src/Web/Grand.Web.Common/Page/Paging/BasePageableModel.cs
+++ b/src/Web/Grand.Web.Common/Page/Paging/BasePageableModel.cs
@@ -8,12 +8,12 @@ namespace Grand.Web.Common.Page.Paging
{
#region Methods
- public virtual void LoadPagedList<T>(IPagedList<T> pagedList)
+ public void LoadPagedList<T>(IPagedList<T> pagedList)
{
- FirstItem = (pagedList.PageIndex * pagedList.PageSize) + 1;
+ FirstItem = pagedList.PageIndex * pagedList.PageSize + 1;
HasNextPage = pagedList.HasNextPage;
HasPreviousPage = pagedList.HasPreviousPage;
- LastItem = Math.Min(pagedList.TotalCount, ((pagedList.PageIndex * pagedList.PageSize) + pagedList.PageSize));
+ LastItem = Math.Min(pagedList.TotalCount, (pagedList.PageIndex * pagedList.PageSize) + pagedList.PageSize);
PageNumber = pagedList.PageIndex + 1;
PageSize = pagedList.PageSize;
TotalItems = pagedList.TotalCount;
diff --git a/src/Web/Grand.Web.Common/Routing/LanguageParameterTransformer.cs b/src/Web/Grand.Web.Common/Routing/LanguageParameterTransformer.cs
index 60ab3fe40..5d7f65e31 100644
--- a/src/Web/Grand.Web.Common/Routing/LanguageParameterTransformer.cs
+++ b/src/Web/Grand.Web.Common/Routing/LanguageParameterTransformer.cs
@@ -15,10 +15,7 @@ namespace Grand.Web.Common.Routing
public string TransformOutbound(object value)
{
var lang = _httpContextAccessor.HttpContext?.Request.RouteValues["language"];
- if (lang != null)
- return lang.ToString();
-
- return value == null ? null : value.ToString();
+ return lang != null ? lang.ToString() : value?.ToString();
}
}
}
diff --git a/src/Web/Grand.Web.Common/Routing/SlugRouteTransformer.cs b/src/Web/Grand.Web.Common/Routing/SlugRouteTransformer.cs
index 9d23c0250..8e44ce9b7 100644
--- a/src/Web/Grand.Web.Common/Routing/SlugRouteTransformer.cs
+++ b/src/Web/Grand.Web.Common/Routing/SlugRouteTransformer.cs
@@ -23,9 +23,9 @@ namespace Grand.Web.Common.Routing
_config = config;
}
- protected async ValueTask<string> GetSeName(string entityId, string entityName, string languageId)
+ private async ValueTask<string> GetSeName(string entityId, string entityName, string languageId)
{
- string result = string.Empty;
+ var result = string.Empty;
if (!string.IsNullOrEmpty(languageId))
{
result = await _slugService.GetActiveSlug(entityId, entityName, languageId);
@@ -73,14 +73,13 @@ namespace Grand.Web.Common.Routing
//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());
- if (language == null)
- language = (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);
+ var slugForCurrentLanguage = await GetSeName(entityUrl.EntityId, entityUrl.EntityName, language?.Id);
if (!string.IsNullOrEmpty(slugForCurrentLanguage) && !slugForCurrentLanguage.Equals(slug.ToString(), StringComparison.OrdinalIgnoreCase))
{
values["controller"] = "Common";
@@ -92,11 +91,8 @@ namespace Grand.Web.Common.Routing
}
}
}
- else
- {
- //TODO - redirect when current lang is not the same as slug lang
- }
+ //TODO - redirect when current lang is not the same as slug lang
switch (entityUrl.EntityName.ToLowerInvariant())
{
case "product":
diff --git a/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeActionAttribute.cs b/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeActionAttribute.cs
index 788f509d0..1cce91bc7 100644
--- a/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeActionAttribute.cs
+++ b/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeActionAttribute.cs
@@ -16,7 +16,7 @@ namespace Grand.Web.Common.Security.Authorization
PermissionAction = actionName;
}
- // Get or set the permision property by manipulating
+ // Get or set the permission property by manipulating
public string PermissionAction { get; set; }
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
@@ -54,7 +54,6 @@ namespace Grand.Web.Common.Security.Authorization
context.Result = new JsonResult(new DataSourceResult { Errors = $"Access denied to the resource {context.HttpContext.Request.Path}" });
}
}
- return;
}
}
}
diff --git a/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeAttribute.cs b/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeAttribute.cs
index 3ed99c3a6..8aca6006e 100644
--- a/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeAttribute.cs
+++ b/src/Web/Grand.Web.Common/Security/Authorization/PermissionAuthorizeAttribute.cs
@@ -15,7 +15,7 @@ namespace Grand.Web.Common.Security.Authorization
Permission = permission;
}
- // Get or set the permision property by manipulating
+ // Get or set the permission property by manipulating
public string Permission { get; set; }
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
@@ -37,8 +37,6 @@ namespace Grand.Web.Common.Security.Authorization
context.Result = new RedirectToRouteResult("AdminLogin", new RouteValueDictionary());
else
context.Result = new RedirectToActionResult("AccessDenied", "Home", new { pageUrl = context.HttpContext.Request.Path });
-
- return;
}
}
}
diff --git a/src/Web/Grand.Web.Common/Security/Captcha/CaptchaSettingsExtension.cs b/src/Web/Grand.Web.Common/Security/Captcha/CaptchaSettingsExtension.cs
index f2551b83c..b646af40c 100644
--- a/src/Web/Grand.Web.Common/Security/Captcha/CaptchaSettingsExtension.cs
+++ b/src/Web/Grand.Web.Common/Security/Captcha/CaptchaSettingsExtension.cs
@@ -7,11 +7,11 @@ namespace Grand.Web.Common.Security.Captcha
public static string GetWrongCaptchaMessage(this CaptchaSettings captchaSettings,
ITranslationService translationService)
{
- if (captchaSettings.ReCaptchaVersion == GoogleReCaptchaVersion.V2)
- return translationService.GetResource("Common.WrongCaptchaV2");
- if (captchaSettings.ReCaptchaVersion == GoogleReCaptchaVersion.V3)
- return translationService.GetResource("Common.WrongCaptchaV3");
- return 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 file
diff --git a/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaValidator.cs b/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaValidator.cs
index 1e3691849..8fb907150 100644
--- a/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaValidator.cs
+++ b/src/Web/Grand.Web.Common/Security/Captcha/GoogleReCaptchaValidator.cs
@@ -6,7 +6,7 @@ namespace Grand.Web.Common.Security.Captcha
{
public class GoogleReCaptchaValidator
{
- private const string RECAPTCHA_VERIFY_URL = "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}&remoteip={2}";
+ private const string RecaptchaVerifyUrl = "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}&remoteip={2}";
private readonly CaptchaSettings _captchaSettings;
private readonly IHttpContextAccessor _httpContextAccessor;
@@ -23,16 +23,17 @@ namespace Grand.Web.Common.Security.Captcha
public async Task<GoogleReCaptchaResponse> Validate(string response)
{
- GoogleReCaptchaResponse result = null;
- var requestUri = string.Format(RECAPTCHA_VERIFY_URL, _captchaSettings.ReCaptchaPrivateKey, response,
- _httpContextAccessor.HttpContext.Connection.RemoteIpAddress?.ToString());
+ 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);
+ var contentResult = await responseMessage.Content.ReadAsStringAsync();
+ result = ParseResponseResult(contentResult);
}
catch (Exception exc)
@@ -40,7 +41,7 @@ namespace Grand.Web.Common.Security.Captcha
result = new GoogleReCaptchaResponse { IsValid = false };
result.ErrorCodes.Add("Unknown error" + exc.Message);
}
-
+
return result;
}
@@ -52,15 +53,15 @@ namespace Grand.Web.Common.Security.Captcha
var success = resultObject.Value<bool>("success");
if(_captchaSettings.ReCaptchaVersion == GoogleReCaptchaVersion.V3)
{
- decimal score = resultObject.Value<decimal>("score");
+ var score = resultObject.Value<decimal>("score");
if (_captchaSettings.ReCaptchaScore > 0)
success = success && score >= _captchaSettings.ReCaptchaScore;
}
result.IsValid = success;
if (resultObject.Value<JToken>("error-codes") != null &&
- resultObject.Value<JToken>("error-codes").Values<string>().Any())
- result.ErrorCodes = resultObject.Value<JToken>("error-codes").Values<string>().ToList();
+ resultObject.Value<JToken>("error-codes")!.Values<string>().Any())
+ result.ErrorCodes = resultObject.Value<JToken>("error-codes")?.Values<string>().ToList();
return result;
}
diff --git a/src/Web/Grand.Web.Common/Security/Captcha/GoogleRecaptchaControl.cs b/src/Web/Grand.Web.Common/Security/Captcha/GoogleRecaptchaControl.cs
index a88735476..608ab6468 100644
--- a/src/Web/Grand.Web.Common/Security/Captcha/GoogleRecaptchaControl.cs
+++ b/src/Web/Grand.Web.Common/Security/Captcha/GoogleRecaptchaControl.cs
@@ -5,7 +5,7 @@ namespace Grand.Web.Common.Security.Captcha
{
public class GoogleRecaptchaControl
{
- private const string RECAPTCHA_API_URL_VERSION = "https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit";
+ private const string RecaptchaApiUrlVersion = "https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit";
public string Id { get; set; }
public string Theme { get; set; }
@@ -23,31 +23,29 @@ namespace Grand.Web.Common.Security.Captcha
{
SetTheme();
- if (_version == GoogleReCaptchaVersion.V2)
- {
- return RenderV2();
- }
- if (_version == GoogleReCaptchaVersion.V3)
- {
- return RenderV3();
- }
-
- throw new NotSupportedException("Specified version is not supported");
+ return _version switch {
+ GoogleReCaptchaVersion.V2 => RenderV2(),
+ GoogleReCaptchaVersion.V3 => RenderV3(),
+ _ => throw new NotSupportedException("Specified version is not supported")
+ };
}
private string RenderV2()
{
- var scriptCallbackTag = new TagBuilder("script");
- scriptCallbackTag.TagRenderMode = TagRenderMode.Normal;
+ 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");
- captchaTag.TagRenderMode = TagRenderMode.Normal;
+ var captchaTag = new TagBuilder("div") {
+ TagRenderMode = TagRenderMode.Normal
+ };
captchaTag.Attributes.Add("id", Id);
- var scriptLoadApiTag = new TagBuilder("script");
- scriptLoadApiTag.TagRenderMode = TagRenderMode.Normal;
- scriptLoadApiTag.Attributes.Add("src", RECAPTCHA_API_URL_VERSION + (string.IsNullOrEmpty(Language) ? "" : string.Format("&hl={0}", Language)));
+ 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);
@@ -56,8 +54,9 @@ namespace Grand.Web.Common.Security.Captcha
private string RenderV3()
{
- var scriptCallbackTag = new TagBuilder("script");
- scriptCallbackTag.TagRenderMode = TagRenderMode.Normal;
+ var scriptCallbackTag = new TagBuilder("script") {
+ TagRenderMode = TagRenderMode.Normal
+ };
var clientId = Guid.NewGuid().ToString();
var script = new StringBuilder();
script.AppendLine("function onloadCallback() {");
@@ -79,8 +78,9 @@ namespace Grand.Web.Common.Security.Captcha
script.AppendLine("})}");
scriptCallbackTag.InnerHtml.AppendHtml(script.ToString());
- var captchaTagInput = new TagBuilder("input");
- captchaTagInput.TagRenderMode = TagRenderMode.Normal;
+ var captchaTagInput = new TagBuilder("input") {
+ TagRenderMode = TagRenderMode.Normal
+ };
captchaTagInput.Attributes.Add("type", "hidden");
captchaTagInput.Attributes.Add("id", Id);
captchaTagInput.Attributes.Add("name", Id);
@@ -88,9 +88,11 @@ namespace Grand.Web.Common.Security.Captcha
var captchaTagDiv = new TagBuilder("div");
captchaTagDiv.Attributes.Add("id", $"{clientId}");
- var scriptLoadApiTag = new TagBuilder("script");
+ var scriptLoadApiTag = new TagBuilder("script") {
+ TagRenderMode = TagRenderMode.Normal
+ };
scriptLoadApiTag.TagRenderMode = TagRenderMode.Normal;
- scriptLoadApiTag.Attributes.Add("src", RECAPTCHA_API_URL_VERSION + (string.IsNullOrEmpty(Language) ? "" : string.Format("&hl={0}", Language)));
+ scriptLoadApiTag.Attributes.Add("src", RecaptchaApiUrlVersion + (string.IsNullOrEmpty(Language) ? "" : $"&hl={Language}"));
return scriptLoadApiTag.RenderHtmlContent() + scriptCallbackTag.RenderHtmlContent() + captchaTagInput.RenderHtmlContent() + captchaTagDiv.RenderHtmlContent();
}
@@ -99,8 +101,7 @@ namespace Grand.Web.Common.Security.Captcha
{
var themes = new[] { "white", "blackglass", "red", "clean", "light", "dark" };
- if (Theme is null)
- Theme = "light";
+ Theme ??= "light";
switch (Theme.ToLower())
{
diff --git a/src/Web/Grand.Web.Common/Startup/AuthenticationStartup.cs b/src/Web/Grand.Web.Common/Startup/AuthenticationStartup.cs
index d4cd15485..a2c01bcfe 100644
--- a/src/Web/Grand.Web.Common/Startup/AuthenticationStartup.cs
+++ b/src/Web/Grand.Web.Common/Startup/AuthenticationStartup.cs
@@ -33,6 +33,7 @@ namespace Grand.Web.Common.Startup
/// 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
@@ -42,7 +43,7 @@ namespace Grand.Web.Common.Startup
//configure authentication
application.UseGrandAuthentication();
- //set workcontext
+ //set work context
application.UseMiddleware<WorkContextMiddleware>();
}
diff --git a/src/Web/Grand.Web.Common/Startup/GrandCommonStartup.cs b/src/Web/Grand.Web.Common/Startup/GrandCommonStartup.cs
index 25cedfc4d..33db963a8 100644
--- a/src/Web/Grand.Web.Common/Startup/GrandCommonStartup.cs
+++ b/src/Web/Grand.Web.Common/Startup/GrandCommonStartup.cs
@@ -24,8 +24,8 @@ namespace Grand.Web.Common.Startup
/// <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();
@@ -36,11 +36,11 @@ namespace Grand.Web.Common.Startup
//add options feature
services.AddOptions();
- //add HTTP sesion state feature
- services.AddHttpSession(securityconfig);
+ //add HTTP session state feature
+ services.AddHttpSession(securityConfig);
//add anti-forgery
- services.AddAntiForgery(securityconfig);
+ services.AddAntiForgery(securityConfig);
//add localization
services.AddLocalization();
@@ -51,7 +51,7 @@ namespace Grand.Web.Common.Startup
//add WebEncoderOptions
services.AddWebEncoder();
- //adddetection device
+ //add detection device
services.AddDetectionDevice();
//add routing
@@ -112,11 +112,7 @@ namespace Grand.Web.Common.Startup
//use request localization
if (appConfig.UseRequestLocalization)
{
- var supportedCultures = new List<CultureInfo>();
- foreach (var culture in appConfig.SupportedCultures)
- {
- supportedCultures.Add(new CultureInfo(culture));
- }
+ var supportedCultures = appConfig.SupportedCultures.Select(culture => new CultureInfo(culture)).ToList();
application.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture(appConfig.DefaultRequestCulture),
@@ -144,7 +140,7 @@ namespace Grand.Web.Common.Startup
// Write streamlined request completion events, instead of the more verbose ones from the framework.
// To use the default framework request logging instead, remove this line and set the "Microsoft"
- // level in appsettings.json to "Information".
+ // level in app settings json to "Information".
if (appConfig.UseSerilogRequestLogging)
application.UseSerilogRequestLogging();
diff --git a/src/Web/Grand.Web.Common/Startup/HostFilteringStartup.cs b/src/Web/Grand.Web.Common/Startup/HostFilteringStartup.cs
index f23f238b4..2d5387d86 100644
--- a/src/Web/Grand.Web.Common/Startup/HostFilteringStartup.cs
+++ b/src/Web/Grand.Web.Common/Startup/HostFilteringStartup.cs
@@ -21,11 +21,11 @@ namespace Grand.Web.Common.Startup
/// <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?
+ var hosts = securityConfig.AllowedHosts?
.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
if (hosts?.Length > 0)
{
@@ -37,6 +37,7 @@ namespace Grand.Web.Common.Startup
/// 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
diff --git a/src/Web/Grand.Web.Common/Startup/MigrationApplicationStartup.cs b/src/Web/Grand.Web.Common/Startup/MigrationApplicationStartup.cs
index 413c105f3..65417396e 100644
--- a/src/Web/Grand.Web.Common/Startup/MigrationApplicationStartup.cs
+++ b/src/Web/Grand.Web.Common/Startup/MigrationApplicationStartup.cs
@@ -35,11 +35,9 @@ namespace Grand.Web.Common.Startup
var serviceProvider = application.ApplicationServices;
var appConfig = serviceProvider.GetRequiredService<AppConfig>();
- if (!appConfig.SkipMigrationProcess)
- {
- var migrationProcess = serviceProvider.GetRequiredService<IMigrationProcess>();
- migrationProcess.RunMigrationProcess();
- }
+ if (appConfig.SkipMigrationProcess) return;
+ var migrationProcess = serviceProvider.GetRequiredService<IMigrationProcess>();
+ migrationProcess.RunMigrationProcess();
}
/// <summary>
diff --git a/src/Web/Grand.Web.Common/Startup/StartupApplication.cs b/src/Web/Grand.Web.Common/Startup/StartupApplication.cs
index f5fe2cab6..ba85cf93c 100644
--- a/src/Web/Grand.Web.Common/Startup/StartupApplication.cs
+++ b/src/Web/Grand.Web.Common/Startup/StartupApplication.cs
@@ -31,9 +31,8 @@ namespace Grand.Web.Common.Startup
/// <summary>
/// Register services and interfaces
/// </summary>
- /// <param name="ServiceCollection">Service Collection</param>
- /// <param name="typeSearcher">Type finder</param>
- /// <param name="config">Config</param>
+ /// <param name="services">Service Collection</param>
+ /// <param name="configuration">Config</param>
public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
RegisterCache(services, configuration);
@@ -60,7 +59,7 @@ namespace Grand.Web.Common.Startup
if (config.RedisPubSubEnabled)
{
var redis = ConnectionMultiplexer.Connect(config.RedisPubSubConnectionString);
- serviceCollection.AddSingleton<ISubscriber>(c => redis.GetSubscriber());
+ serviceCollection.AddSingleton(_ => redis.GetSubscriber());
serviceCollection.AddSingleton<IMessageBus, RedisMessageBus>();
serviceCollection.AddSingleton<ICacheBase, RedisMessageCacheManager>();
return;
@@ -101,8 +100,8 @@ namespace Grand.Web.Common.Startup
else
{
var provider = serviceCollection.BuildServiceProvider();
- var _tmp = provider.GetRequiredService<IStringLocalizerFactory>();
- serviceCollection.AddScoped(c => new LocService(_tmp));
+ var tmp = provider.GetRequiredService<IStringLocalizerFactory>();
+ serviceCollection.AddScoped(_ => new LocService(tmp));
}
//powered by
diff --git a/src/Web/Grand.Web.Common/Startup/TaskHandler.cs b/src/Web/Grand.Web.Common/Startup/TaskHandler.cs
index 382699970..80d536995 100644
--- a/src/Web/Grand.Web.Common/Startup/TaskHandler.cs
+++ b/src/Web/Grand.Web.Common/Startup/TaskHandler.cs
@@ -15,26 +15,19 @@ namespace Grand.Web.Common.Startup
public static void RegisterTasks(this IServiceCollection services)
{
//database is already installed, so start scheduled tasks
- if (DataSettingsManager.DatabaseIsInstalled())
- {
- var appConfig = services.BuildServiceProvider().GetRequiredService<AppConfig>();
- if (!appConfig.DisableHostedService)
- {
- var typeSearcher = new AppTypeSearcher();
- var scheduleTasks = typeSearcher.ClassesOfType<IScheduleTask>();
+ if (!DataSettingsManager.DatabaseIsInstalled()) return;
+ var appConfig = services.BuildServiceProvider().GetRequiredService<AppConfig>();
+ if (appConfig.DisableHostedService) return;
+ var typeSearcher = new AppTypeSearcher();
+ var scheduleTasks = typeSearcher.ClassesOfType<IScheduleTask>();
- var scheduleTasksInstalled = scheduleTasks
- .Where(t => PluginExtensions.OnlyInstalledPlugins(t)); //ignore not installed plugins
+ 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 =>
- {
- return new BackgroundServiceTask($"{task.FullName}, {assemblyName}", sp);
- });
- }
- }
+ foreach (var task in scheduleTasksInstalled)
+ {
+ var assemblyName = task.Assembly.GetName().Name;
+ services.AddSingleton<IHostedService, BackgroundServiceTask>(sp => new BackgroundServiceTask($"{task.FullName}, {assemblyName}", sp));
}
}
}
diff --git a/src/Web/Grand.Web.Common/Startup/UrlRewriteStartup.cs b/src/Web/Grand.Web.Common/Startup/UrlRewriteStartup.cs
index 74c69a11b..9ab6d3ec0 100644
--- a/src/Web/Grand.Web.Common/Startup/UrlRewriteStartup.cs
+++ b/src/Web/Grand.Web.Common/Startup/UrlRewriteStartup.cs
@@ -37,11 +37,9 @@ namespace Grand.Web.Common.Startup
{
if (File.Exists("App_Data/UrlRewrite.xml"))
{
- using (var streamReader = File.OpenText("App_Data/UrlRewrite.xml"))
- {
- rewriteOptions = true;
- urlRewriteOptions.AddIISUrlRewrite(streamReader);
- }
+ using var streamReader = File.OpenText("App_Data/UrlRewrite.xml");
+ rewriteOptions = true;
+ urlRewriteOptions.AddIISUrlRewrite(streamReader);
}
}
if (urlConfig.UrlRewriteHttpsOptions)
diff --git a/src/Web/Grand.Web.Common/StoreHelper.cs b/src/Web/Grand.Web.Common/StoreHelper.cs
index 97c5b01ee..2e2e99bbc 100644
--- a/src/Web/Grand.Web.Common/StoreHelper.cs
+++ b/src/Web/Grand.Web.Common/StoreHelper.cs
@@ -16,7 +16,7 @@ namespace Grand.Web.Common
private Store _cachedStore;
private DomainHost _cachedDomainHost;
- private const string STORE_COOKIE_NAME = ".Grand.Store";
+ private const string StoreCookieName = ".Grand.Store";
#endregion
@@ -37,77 +37,64 @@ namespace Grand.Web.Common
protected virtual string GetStoreCookie()
{
- if (_httpContextAccessor.HttpContext == null || _httpContextAccessor.HttpContext.Request == null)
- return null;
-
- return _httpContextAccessor.HttpContext.Request.Cookies[STORE_COOKIE_NAME];
+ return _httpContextAccessor.HttpContext?.Request.Cookies[StoreCookieName];
}
#endregion
public Store StoreHost {
get {
- if (_cachedStore == null)
- {
- //try to determine the current store by HOST header
- string host = _httpContextAccessor.HttpContext?.Request?.Host.Host;
+ 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));
- if (stores.Count() == 0)
- {
- _cachedStore = allStores.FirstOrDefault();
- }
- else if (stores.Count() == 1)
- {
+ 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();
- }
- else if (stores.Count() > 1)
+ break;
+ case > 1:
{
var cookie = GetStoreCookie();
if (!string.IsNullOrEmpty(cookie))
{
- var storecookie = stores.FirstOrDefault(x => x.Id == cookie);
- if (storecookie != null)
- _cachedStore = storecookie;
- else
- _cachedStore = stores.FirstOrDefault();
+ var storeCookie = stores.FirstOrDefault(x => x.Id == cookie);
+ _cachedStore = storeCookie ?? stores.FirstOrDefault();
}
else
_cachedStore = stores.FirstOrDefault();
- }
- return _cachedStore ?? throw new Exception("No store could be loaded");
-
+ break;
+ }
}
- return _cachedStore;
+ return _cachedStore ?? throw new Exception("No store could be loaded");
}
}
public DomainHost DomainHost {
get {
- if (_cachedDomainHost == null)
+ if (_cachedDomainHost != null) return _cachedDomainHost;
+ //try to determine the current HOST header
+ var host = _httpContextAccessor.HttpContext?.Request.GetTypedHeaders().Host.ToString();
+ if (StoreHost != null)
{
- //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"
- };
- }
- if (_cachedDomainHost == null)
- {
- _cachedDomainHost = new DomainHost() {
- Id = int.MinValue.ToString(),
- Url = host,
- HostName = "temporary"
- };
- }
- return _cachedDomainHost;
+ _cachedDomainHost = StoreHost.HostValue(host) ?? new DomainHost {
+ Id = int.MinValue.ToString(),
+ Url = StoreHost.SslEnabled ? StoreHost.SecureUrl : StoreHost.Url,
+ HostName = "temporary-store"
+ };
}
- return _cachedDomainHost;
+
+ return _cachedDomainHost ??= new DomainHost {
+ Id = int.MinValue.ToString(),
+ Url = host,
+ HostName = "temporary"
+ };
}
}
@@ -123,8 +110,7 @@ namespace Grand.Web.Common
if (store != null)
_cachedStore = store;
}
- if (_cachedStore == null)
- _cachedStore = (await _storeService.GetAllStores()).FirstOrDefault();
+ _cachedStore ??= (await _storeService.GetAllStores()).FirstOrDefault();
return _cachedStore ?? throw new Exception("No store could be loaded by BackgroundService");
@@ -136,7 +122,7 @@ namespace Grand.Web.Common
/// <param name="storeId">Store ident</param>
public virtual async Task SetStoreCookie(string storeId)
{
- if (_httpContextAccessor.HttpContext == null || _httpContextAccessor.HttpContext.Response == null)
+ if (_httpContextAccessor.HttpContext == null)
return;
var store = await _storeService.GetStoreById(storeId);
@@ -144,7 +130,7 @@ namespace Grand.Web.Common
return;
//remove current cookie
- _httpContextAccessor.HttpContext.Response.Cookies.Delete(STORE_COOKIE_NAME);
+ _httpContextAccessor.HttpContext.Response.Cookies.Delete(StoreCookieName);
//get date of cookie expiration
var cookieExpiresDate = DateTime.UtcNow.AddHours(CommonHelper.CookieAuthExpires);
@@ -154,7 +140,7 @@ namespace Grand.Web.Common
HttpOnly = true,
Expires = cookieExpiresDate
};
- _httpContextAccessor.HttpContext.Response.Cookies.Append(STORE_COOKIE_NAME, storeId, options);
+ _httpContextAccessor.HttpContext.Response.Cookies.Append(StoreCookieName, storeId, options);
}
}
diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminDeleteConfirmationTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminDeleteConfirmationTagHelper.cs
index 350cd5f82..699c4e5a5 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminDeleteConfirmationTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminDeleteConfirmationTagHelper.cs
@@ -9,7 +9,7 @@ using Microsoft.AspNetCore.Razor.TagHelpers;
namespace Grand.Web.Common.TagHelpers.Admin
{
[HtmlTargetElement("admin-delete-confirmation")]
- public partial class AdminDeleteConfirmationTagHelper : TagHelper
+ public class AdminDeleteConfirmationTagHelper : TagHelper
{
[ViewContext]
public ViewContext ViewContext { get; set; }
@@ -40,17 +40,17 @@ namespace Grand.Web.Common.TagHelpers.Admin
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 modelId = string.IsNullOrEmpty(ModelId) ? ViewContext.RouteData.Values["Id"]?.ToString() : ModelId;
var deleteConfirmationModel = new DeleteConfirmationModel
{
Id = modelId,
- ControllerName = ViewContext.RouteData.Values["controller"].ToString(),
+ ControllerName = ViewContext.RouteData.Values["controller"]?.ToString(),
ActionName = Action,
WindowId = windowId
};
- (_htmlHelper as IViewContextAware).Contextualize(ViewContext);
+ (_htmlHelper as IViewContextAware)?.Contextualize(ViewContext);
output.TagName = "div";
output.TagMode = TagMode.StartTagAndEndTag;
@@ -62,14 +62,14 @@ namespace Grand.Web.Common.TagHelpers.Admin
var window = new StringBuilder();
window.AppendLine("<script>");
window.AppendLine("$(document).ready(function() {");
- window.AppendLine(string.Format("$('#{0}').click(function (e) ", ButtonId));
+ window.AppendLine($"$('#{ButtonId}').click(function (e) ");
window.AppendLine("{");
window.AppendLine("e.preventDefault();");
- window.AppendLine(string.Format("var window = $('#{0}');", windowId));
+ window.AppendLine($"var window = $('#{windowId}');");
window.AppendLine("if (!window.data('kendoWindow')) {");
window.AppendLine("window.kendoWindow({");
window.AppendLine("modal: true,");
- window.AppendLine(string.Format("title: '{0}',", _translationService.GetResource("Admin.Common.AreYouSure")));
+ window.AppendLine($"title: '{_translationService.GetResource("Admin.Common.AreYouSure")}',");
window.AppendLine("actions: ['Close']");
window.AppendLine("});");
window.AppendLine("}");
diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminInputTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminInputTagHelper.cs
index 117c313fc..fba863ba2 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminInputTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminInputTagHelper.cs
@@ -101,7 +101,7 @@ namespace Grand.Web.Common.TagHelpers.Admin
output.SuppressOutput();
//disabled attribute
- bool.TryParse(IsDisabled, out bool disabled);
+ bool.TryParse(IsDisabled, out var disabled);
if (disabled)
{
var d = new TagHelperAttribute("disabled", "disabled");
@@ -109,7 +109,7 @@ namespace Grand.Web.Common.TagHelpers.Admin
}
//required asterisk
- bool.TryParse(IsRequired, out bool required);
+ bool.TryParse(IsRequired, out var required);
if (required)
{
output.PreElement.SetHtmlContent("<div class='input-group input-group-required'>");
@@ -121,7 +121,7 @@ namespace Grand.Web.Common.TagHelpers.Admin
viewContextAware?.Contextualize(ViewContext);
//add form-control class
- bool.TryParse(RenderFormControlClass, out bool renderFormControlClass);
+ 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" };
@@ -177,7 +177,7 @@ namespace Grand.Web.Common.TagHelpers.Admin
{
if (target == null)
{
- throw new ArgumentNullException("target", "The assignment target cannot be null.");
+ throw new ArgumentNullException(nameof(target), "The assignment target cannot be null.");
}
if (string.IsNullOrEmpty(fieldName))
diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminLabelTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminLabelTagHelper.cs
index c61ea917a..c8cd28736 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminLabelTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminLabelTagHelper.cs
@@ -39,7 +39,7 @@ namespace Grand.Web.Common.TagHelpers.Admin
: "control-label col-md-3 col-sm-3";
if (RequiredAttribute)
{
- classValue = classValue + " required";
+ classValue += " required";
}
output.Attributes.SetAttribute("class", classValue);
@@ -55,7 +55,7 @@ namespace Grand.Web.Common.TagHelpers.Admin
output.Content.SetContent(resource);
}
- if (resourceDisplayName != null && DisplayHint)
+ if (DisplayHint)
{
var hintResource = _translationService.GetResource(
diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminSelectTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminSelectTagHelper.cs
index 879f32f75..39ac074b3 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminSelectTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminSelectTagHelper.cs
@@ -12,13 +12,8 @@ namespace Grand.Web.Common.TagHelpers.Admin
private const string ForAttributeName = "asp-for";
private const string DisplayHintAttributeName = "asp-display-hint";
- private readonly IWorkContext _workContext;
- private readonly ITranslationService _translationService;
-
- public AdminSelectTagHelper(IHtmlGenerator generator, IWorkContext workContext, ITranslationService translationService) : base(generator)
+ public AdminSelectTagHelper(IHtmlGenerator generator) : base(generator)
{
- _workContext = workContext;
- _translationService = translationService;
}
[HtmlAttributeName(DisplayHintAttributeName)]
@@ -30,8 +25,7 @@ namespace Grand.Web.Common.TagHelpers.Admin
output.TagName = "select";
output.TagMode = TagMode.StartTagAndEndTag;
var classValue = "form-control k-input ";
- TagHelperAttribute forAttribute;
- if (context.AllAttributes.TryGetAttribute("class", out forAttribute))
+ if (context.AllAttributes.TryGetAttribute("class", out var forAttribute))
{
classValue += forAttribute.Value.ToString();
}
diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabAppendTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabAppendTagHelper.cs
index dccd56468..285e5c73f 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabAppendTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabAppendTagHelper.cs
@@ -3,7 +3,7 @@
namespace Grand.Web.Common.TagHelpers.Admin
{
[HtmlTargetElement("admin-tab-append", Attributes = "tab-strip-name, tab-name, tab-content")]
- public partial class AdminTabAppendTagHelper : TagHelper
+ public class AdminTabAppendTagHelper : TagHelper
{
private const string TabStripName = "tab-strip-name";
private const string TabName = "tab-name";
diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabContentTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabContentTagHelper.cs
index 1ed2c438d..9b6bdbd60 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabContentTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabContentTagHelper.cs
@@ -5,7 +5,7 @@ using Microsoft.AspNetCore.Razor.TagHelpers;
namespace Grand.Web.Common.TagHelpers.Admin
{
[HtmlTargetElement("content", ParentTag = "tabstrip-item")]
- public partial class AdminTabContentTagHelper : TagHelper
+ public class AdminTabContentTagHelper : TagHelper
{
[ViewContext]
public ViewContext ViewContext { get; set; }
diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemTagHelper.cs
index a04ff2eed..81ec08626 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemTagHelper.cs
@@ -5,7 +5,7 @@ using Microsoft.AspNetCore.Razor.TagHelpers;
namespace Grand.Web.Common.TagHelpers.Admin
{
[HtmlTargetElement("tabstrip-item")]
- public partial class AdminTabStripItemTagHelper : TagHelper
+ public class AdminTabStripItemTagHelper : TagHelper
{
[ViewContext]
public ViewContext ViewContext { get; set; }
@@ -18,8 +18,8 @@ namespace Grand.Web.Common.TagHelpers.Admin
private int GetSelectedTabIndex()
{
- int index = 0;
- string dataKey = "Grand.selected-tab-index";
+ var index = 0;
+ var dataKey = "Grand.selected-tab-index";
if (this.ViewContext.ViewData[dataKey] is int)
{
index = (int)this.ViewContext.ViewData[dataKey];
@@ -37,7 +37,7 @@ namespace Grand.Web.Common.TagHelpers.Admin
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
- var content = await output.GetChildContentAsync();
+ _ = await output.GetChildContentAsync();
output.TagName = "li";
var selectedIndex = GetSelectedTabIndex();
diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemsTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemsTagHelper.cs
index 2f5933929..54035aae5 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemsTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripItemsTagHelper.cs
@@ -3,7 +3,7 @@
namespace Grand.Web.Common.TagHelpers.Admin
{
[HtmlTargetElement("items", ParentTag = "admin-tabstrip")]
- public partial class AdminTabStripItemsTagHelper : TagHelper
+ public class AdminTabStripItemsTagHelper : TagHelper
{
public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripTagHelper.cs
index 4627a3d30..fcf80ceba 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTabStripTagHelper.cs
@@ -9,7 +9,7 @@ using Wangkanai.Detection.Services;
namespace Grand.Web.Common.TagHelpers.Admin
{
[HtmlTargetElement("admin-tabstrip")]
- public partial class AdminTabStripTagHelper : TagHelper
+ public class AdminTabStripTagHelper : TagHelper
{
private readonly IMediator _mediator;
private readonly IDetectionService _detectionService;
@@ -60,10 +60,8 @@ namespace Grand.Web.Common.TagHelpers.Admin
var eventMessage = new AdminTabStripCreated(Name);
await _mediator.Publish(eventMessage);
- int i = 0;
foreach (var eventBlock in eventMessage.BlocksToRender)
{
- i++;
sb.AppendLine($"tab_{rnd}.append({{");
sb.AppendLine($" text: '{eventBlock.tabname}',");
sb.AppendLine($" content: '{eventBlock.content}'");
@@ -93,8 +91,8 @@ namespace Grand.Web.Common.TagHelpers.Admin
private int GetSelectedTabIndex()
{
- int index = 0;
- string dataKey = "Grand.selected-tab-index";
+ var index = 0;
+ var dataKey = "Grand.selected-tab-index";
if (ViewContext.ViewData[dataKey] is int)
{
index = (int)ViewContext.ViewData[dataKey];
diff --git a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTextAreaTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTextAreaTagHelper.cs
index fc79bcc66..7e23f4555 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTextAreaTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/Admin/AdminTextAreaTagHelper.cs
@@ -52,7 +52,7 @@ namespace Grand.Web.Common.TagHelpers.Admin
output.Attributes.SetAttribute("class", classValue);
//add disabled attribute
- bool.TryParse(IsDisabled, out bool disabled);
+ bool.TryParse(IsDisabled, out var disabled);
if (disabled)
{
var d = new TagHelperAttribute("disabled", "disabled");
@@ -66,7 +66,7 @@ namespace Grand.Web.Common.TagHelpers.Admin
output.Attributes.SetAttribute("cols", colsNumber);
//required asterisk
- bool.TryParse(IsRequired, out bool required);
+ bool.TryParse(IsRequired, out var required);
if (required)
{
output.PreElement.SetHtmlContent("<div class='input-group input-group-required'>");
diff --git a/src/Web/Grand.Web.Common/TagHelpers/GrandTextAreaTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/GrandTextAreaTagHelper.cs
index 6aab8fdc9..136fc1523 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/GrandTextAreaTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/GrandTextAreaTagHelper.cs
@@ -18,7 +18,7 @@ namespace Grand.Web.Common.TagHelpers
public override void Process(TagHelperContext context, TagHelperOutput output)
{
- bool.TryParse(IsDisabled, out bool disabled);
+ bool.TryParse(IsDisabled, out var disabled);
if (disabled)
{
var d = new TagHelperAttribute("disabled", "disabled");
diff --git a/src/Web/Grand.Web.Common/TagHelpers/HtmlTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/HtmlTagHelper.cs
index 982afe597..0d9fc30c4 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/HtmlTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/HtmlTagHelper.cs
@@ -31,18 +31,16 @@ namespace Grand.Web.Common.TagHelpers
}
var classes = _pageHeadBuilder.GeneratePageCssClasses();
- if(!string.IsNullOrEmpty(classes))
+ if (string.IsNullOrEmpty(classes)) return Task.CompletedTask;
+ if (output.Attributes.ContainsName("class"))
{
- 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);
+ 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;
}
diff --git a/src/Web/Grand.Web.Common/TagHelpers/IResourceManager.cs b/src/Web/Grand.Web.Common/TagHelpers/IResourceManager.cs
index 0ff0c4418..adeb99561 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/IResourceManager.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/IResourceManager.cs
@@ -9,6 +9,7 @@ namespace Grand.Web.Common.TagHelpers
/// Registers a script tag on the head
/// </summary>
/// <param name="script"></param>
+ /// <param name="order"></param>
void RegisterHeadScript(IHtmlContent script, int order);
/// <summary>
@@ -20,12 +21,14 @@ namespace Grand.Web.Common.TagHelpers
/// 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>
diff --git a/src/Web/Grand.Web.Common/TagHelpers/LinkTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/LinkTagHelper.cs
index 49a21c468..8468a553f 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/LinkTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/LinkTagHelper.cs
@@ -32,8 +32,9 @@ namespace Grand.Web.Common.TagHelpers
public override void Process(TagHelperContext context, TagHelperOutput output)
{
- var linkEntry = new LinkEntry();
- linkEntry.Priority = Priority;
+ var linkEntry = new LinkEntry {
+ Priority = Priority
+ };
if (!string.IsNullOrEmpty(Src))
{
@@ -62,7 +63,7 @@ namespace Grand.Web.Common.TagHelpers
foreach (var attribute in output.Attributes)
{
- if (String.Equals(attribute.Name, "href", StringComparison.OrdinalIgnoreCase))
+ if (string.Equals(attribute.Name, "href", StringComparison.OrdinalIgnoreCase))
{
continue;
}
diff --git a/src/Web/Grand.Web.Common/TagHelpers/LocalizedEditorTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/LocalizedEditorTagHelper.cs
index 0f9151233..a2a9b6a43 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/LocalizedEditorTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/LocalizedEditorTagHelper.cs
@@ -41,7 +41,7 @@ namespace Grand.Web.Common.TagHelpers
if (localizationSupported)
{
var tabStrip = new StringBuilder();
- tabStrip.AppendLine(string.Format("<div id='{0}'>", Name));
+ tabStrip.AppendLine($"<div id='{Name}'>");
tabStrip.AppendLine("<ul>");
//default tab
@@ -59,7 +59,7 @@ namespace Grand.Web.Common.TagHelpers
tabStrip.AppendLine("<li>");
var urlHelper = new UrlHelper(ViewContext);
var iconUrl = urlHelper.Content("~/assets/images/flags/" + language.FlagImageFileName);
- tabStrip.AppendLine(string.Format("<img class='k-image' alt='' src='{0}'>", iconUrl));
+ tabStrip.AppendLine($"<img class='k-image' alt='' src='{iconUrl}'>");
tabStrip.AppendLine(WebUtility.HtmlEncode(language.Name));
tabStrip.AppendLine("</li>");
}
@@ -71,7 +71,7 @@ namespace Grand.Web.Common.TagHelpers
tabStrip.AppendLine(standardContent);
tabStrip.AppendLine("</div>");
- for (int i = 0; i < LanguagesIds.Count; i++)
+ for (var i = 0; i < LanguagesIds.Count; i++)
{
//languages
tabStrip.AppendLine("<div>");
@@ -82,7 +82,7 @@ namespace Grand.Web.Common.TagHelpers
tabStrip.AppendLine("</div>");
tabStrip.AppendLine("<script>");
tabStrip.AppendLine("$(document).ready(function() {");
- tabStrip.AppendLine(string.Format("$('#{0}').kendoTabStrip(", Name));
+ tabStrip.AppendLine($"$('#{Name}').kendoTabStrip(");
tabStrip.AppendLine("{");
tabStrip.AppendLine("animation: {");
tabStrip.AppendLine("open: {");
diff --git a/src/Web/Grand.Web.Common/TagHelpers/PageNavigationTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/PageNavigationTagHelper.cs
index 45ccf7474..af69924ba 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/PageNavigationTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/PageNavigationTagHelper.cs
@@ -23,14 +23,15 @@ namespace Grand.Web.Common.TagHelpers
[HtmlTargetElement("page-navigation", Attributes = BooleanParamAttributeName)]
public class PageNavigationTagHelper : TagHelper
{
- [ViewContext]
- public ViewContext ViewContext { get; set; }
+ [ViewContext] public ViewContext ViewContext { get; set; }
private const string QueryParamAttributeName = "asp-query-param";
+
[HtmlAttributeName(QueryParamAttributeName)]
public string QueryParam { get; set; } = "page";
private const string PaginationParamAttributeName = "asp-pagination";
+
[HtmlAttributeName(PaginationParamAttributeName)]
public IPageableModel Pagination { get; set; }
@@ -38,43 +39,53 @@ namespace Grand.Web.Common.TagHelpers
private readonly IHtmlHelper _htmlHelper;
private const string ShowTotalSummaryParamAttributeName = "asp-show-total-summary";
+
[HtmlAttributeName(ShowTotalSummaryParamAttributeName)]
public bool ShowTotalSummary { get; set; }
private const string ShowPagerItemsParamAttributeName = "asp-show-pager-items";
+
[HtmlAttributeName(ShowPagerItemsParamAttributeName)]
public bool ShowPagerItems { get; set; } = true;
private const string ShowFirstParamAttributeName = "asp-show-first";
+
[HtmlAttributeName(ShowFirstParamAttributeName)]
public bool ShowFirst { get; set; } = true;
private const string ShowPreviousParamAttributeName = "asp-show-previous";
+
[HtmlAttributeName(ShowPreviousParamAttributeName)]
public bool ShowPrevious { get; set; } = true;
private const string ShowNextParamAttributeName = "asp-show-next";
+
[HtmlAttributeName(ShowNextParamAttributeName)]
public bool ShowNext { get; set; } = true;
private const string ShowLastParamAttributeName = "asp-show-last";
+
[HtmlAttributeName(ShowLastParamAttributeName)]
public bool ShowLast { get; set; } = true;
private const string ShowIndividualPagesParamAttributeName = "asp-show-individual-pages";
+
[HtmlAttributeName(ShowIndividualPagesParamAttributeName)]
public bool ShowIndividualPages { get; set; } = true;
private const string RenderEmptyParametersParamAttributeName = "asp-render-empty-parameters";
+
[HtmlAttributeName(RenderEmptyParametersParamAttributeName)]
public bool RenderEmptyParameters { get; set; } = true;
private const string IndividualPagesDisplayedCountParamAttributeName = "asp-individual-pages-displayed-count";
+
[HtmlAttributeName(IndividualPagesDisplayedCountParamAttributeName)]
public int IndividualPagesDisplayedCount { get; set; } = 5;
private const string BooleanParamAttributeName = "asp-boolean-params";
+
[HtmlAttributeName(BooleanParamAttributeName)]
public IList<string> BooleanParameterNames { get; set; } = new List<string>();
@@ -88,21 +99,19 @@ namespace Grand.Web.Common.TagHelpers
{
output.SuppressOutput();
- (_htmlHelper as IViewContextAware).Contextualize(ViewContext);
+ (_htmlHelper as IViewContextAware)?.Contextualize(ViewContext);
var links = GenerateHtmlString();
- if (!string.IsNullOrEmpty(links))
- {
- 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());
- }
+ 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;
}
@@ -115,9 +124,11 @@ namespace Grand.Web.Common.TagHelpers
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(string.Format(_translationService.GetResource("Pager.CurrentPage"),
+ Pagination.PageIndex + 1, Pagination.TotalPages, Pagination.TotalItems));
links.Append("</li>");
}
+
if (ShowPagerItems && (Pagination.TotalPages > 1))
{
if (ShowFirst)
@@ -125,27 +136,32 @@ namespace Grand.Web.Common.TagHelpers
//first page
if ((Pagination.PageIndex >= 3) && (Pagination.TotalPages > IndividualPagesDisplayedCount))
{
- links.Append(CreatePageLink(1, _translationService.GetResource("Pager.First"), "first-page page-item"));
+ 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"));
+ links.Append(CreatePageLink(Pagination.PageIndex,
+ _translationService.GetResource("Pager.Previous"), "previous-page page-item"));
}
}
+
if (ShowIndividualPages)
{
//individual pages
- int firstIndividualPageIndex = GetFirstIndividualPageIndex();
- int lastIndividualPageIndex = GetLastIndividualPageIndex();
- for (int i = firstIndividualPageIndex; i <= lastIndividualPageIndex; i++)
+ var firstIndividualPageIndex = GetFirstIndividualPageIndex();
+ var lastIndividualPageIndex = GetLastIndividualPageIndex();
+ for (var i = firstIndividualPageIndex; i <= lastIndividualPageIndex; i++)
{
if (Pagination.PageIndex == i)
{
- links.AppendFormat("<li class=\"current-page page-item\"><a class=\"page-link\">{0}</a></li>", (i + 1));
+ links.Append(
+ $"<li class=\"current-page page-item\"><a class=\"page-link\">{(i + 1)}</a></li>");
}
else
{
@@ -153,29 +169,35 @@ namespace Grand.Web.Common.TagHelpers
}
}
}
+
if (ShowNext)
{
//next page
- if ((Pagination.PageIndex + 1) < Pagination.TotalPages)
+ if (Pagination.PageIndex + 1 < Pagination.TotalPages)
{
- links.Append(CreatePageLink(Pagination.PageIndex + 2, _translationService.GetResource("Pager.Next"), "next-page page-item"));
+ 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))
+ if (Pagination.PageIndex + 3 < Pagination.TotalPages &&
+ (Pagination.TotalPages > IndividualPagesDisplayedCount))
{
- links.Append(CreatePageLink(Pagination.TotalPages, _translationService.GetResource("Pager.Last"), "last-page page-item"));
+ links.Append(CreatePageLink(Pagination.TotalPages,
+ _translationService.GetResource("Pager.Last"), "last-page page-item"));
}
}
}
var result = links.ToString();
- if (!String.IsNullOrEmpty(result))
+ if (!string.IsNullOrEmpty(result))
{
result = "<ul class=\"pagination\">" + result + "</ul>";
}
+
return result;
}
@@ -193,12 +215,13 @@ namespace Grand.Web.Common.TagHelpers
liBuilder.InnerHtml.AppendHtml(aBuilder);
return liBuilder.RenderHtmlContent();
}
+
protected virtual string CreateDefaultUrl(int pageNumber)
{
var routeValues = new RouteValueDictionary();
var parametersWithEmptyValues = new List<string>();
- foreach (var key in _htmlHelper.ViewContext.HttpContext.Request.Query.Keys.Where(key => key != null))
+ foreach (var key in _htmlHelper.ViewContext.HttpContext.Request.Query.Keys)
{
var value = _htmlHelper.ViewContext.HttpContext.Request.Query[key].ToString();
if (RenderEmptyParameters && string.IsNullOrEmpty(value))
@@ -210,11 +233,13 @@ namespace Grand.Web.Common.TagHelpers
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))
+ if (!string.IsNullOrEmpty(value) &&
+ value.Equals("true,false", StringComparison.OrdinalIgnoreCase))
{
value = "true";
}
}
+
routeValues[key] = value;
}
}
@@ -232,51 +257,51 @@ namespace Grand.Web.Common.TagHelpers
}
}
- var url = $"{ViewContext.HttpContext?.Request?.Scheme}://{ViewContext.HttpContext?.Request?.Host}{ViewContext.HttpContext?.Request?.Path}";
- foreach (var routeValue in routeValues)
- {
- url = Grand.Infrastructure.Extensions.CommonExtensions.ModifyQueryString(url, routeValue.Key, routeValue.Value?.ToString());
- }
- if (RenderEmptyParameters && parametersWithEmptyValues.Any())
- {
- foreach (var key in parametersWithEmptyValues)
- {
- url = Grand.Infrastructure.Extensions.CommonExtensions.ModifyQueryString(url, key, null);
- }
- }
- return url;
+ 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 (!RenderEmptyParameters || !parametersWithEmptyValues.Any()) return url;
+
+ return parametersWithEmptyValues.Aggregate(url, (current, key) => Grand.Infrastructure.Extensions.CommonExtensions.ModifyQueryString(current, key, null));
}
protected virtual int GetFirstIndividualPageIndex()
{
- if ((Pagination.TotalPages < IndividualPagesDisplayedCount) ||
- ((Pagination.PageIndex - (IndividualPagesDisplayedCount / 2)) < 0))
+ if (Pagination.TotalPages < IndividualPagesDisplayedCount ||
+ ((Pagination.PageIndex - IndividualPagesDisplayedCount / 2) < 0))
{
return 0;
}
- if ((Pagination.PageIndex + (IndividualPagesDisplayedCount / 2)) >= Pagination.TotalPages)
+
+ if ((Pagination.PageIndex + IndividualPagesDisplayedCount / 2) >= Pagination.TotalPages)
{
return (Pagination.TotalPages - IndividualPagesDisplayedCount);
}
- return (Pagination.PageIndex - (IndividualPagesDisplayedCount / 2));
+
+ return (Pagination.PageIndex - IndividualPagesDisplayedCount / 2);
}
+
protected virtual int GetLastIndividualPageIndex()
{
- int num = IndividualPagesDisplayedCount / 2;
- if ((IndividualPagesDisplayedCount % 2) == 0)
+ var num = IndividualPagesDisplayedCount / 2;
+ if (IndividualPagesDisplayedCount % 2 == 0)
{
num--;
}
- if ((Pagination.TotalPages < IndividualPagesDisplayedCount) ||
- ((Pagination.PageIndex + num) >= Pagination.TotalPages))
+
+ if (Pagination.TotalPages < IndividualPagesDisplayedCount ||
+ Pagination.PageIndex + num >= Pagination.TotalPages)
{
return (Pagination.TotalPages - 1);
}
+
if ((Pagination.PageIndex - (IndividualPagesDisplayedCount / 2)) < 0)
{
return (IndividualPagesDisplayedCount - 1);
}
+
return (Pagination.PageIndex + num);
}
}
-}
+}
\ No newline at end of file
diff --git a/src/Web/Grand.Web.Common/TagHelpers/PictureSourceTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/PictureSourceTagHelper.cs
index e1e00316d..33acb1ffd 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/PictureSourceTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/PictureSourceTagHelper.cs
@@ -23,8 +23,8 @@ namespace Grand.Web.Common.TagHelpers
{
if (!string.IsNullOrEmpty(PictureId))
{
- var pictureurl = await _pictureService.GetPictureUrl(PictureId, PictureSize, showDefaultPicture: false);
- var srcset = new TagHelperAttribute("srcset", pictureurl);
+ var pictureUrl = await _pictureService.GetPictureUrl(PictureId, PictureSize, showDefaultPicture: false);
+ var srcset = new TagHelperAttribute("srcset", pictureUrl);
output.Attributes.Add(srcset);
}
await base.ProcessAsync(context, output);
diff --git a/src/Web/Grand.Web.Common/TagHelpers/ResourceManager.cs b/src/Web/Grand.Web.Common/TagHelpers/ResourceManager.cs
index a2e2f7ae0..3e4de8bc8 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/ResourceManager.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/ResourceManager.cs
@@ -5,12 +5,12 @@ namespace Grand.Web.Common.TagHelpers
{
public class ResourceManager : IResourceManager
{
- private List<(IHtmlContent content, int order)> _headScripts;
- private List<(IHtmlContent content, int order)> _headerScripts;
- private List<(IHtmlContent content, int order)> _footScripts;
+ private readonly List<(IHtmlContent content, int order)> _headScripts;
+ private readonly List<(IHtmlContent content, int order)> _headerScripts;
+ private readonly List<(IHtmlContent content, int order)> _footScripts;
private List<IHtmlContent> _templatesHeader;
private List<IHtmlContent> _templatesFooter;
- private List<LinkEntry> _links;
+ private readonly List<LinkEntry> _links;
public ResourceManager()
{
@@ -34,11 +34,11 @@ namespace Grand.Web.Common.TagHelpers
}
public IEnumerable<IHtmlContent> GetRegisteredTemplatesHeader()
{
- return _templatesHeader == null ? Enumerable.Empty<IHtmlContent>() : _templatesHeader;
+ return _templatesHeader ?? Enumerable.Empty<IHtmlContent>();
}
public IEnumerable<IHtmlContent> GetRegisteredTemplatesFooter()
{
- return _templatesFooter == null ? Enumerable.Empty<IHtmlContent>() : _templatesFooter;
+ return _templatesFooter ?? Enumerable.Empty<IHtmlContent>();
}
public void RegisterHeadScript(IHtmlContent script, int order)
@@ -59,16 +59,12 @@ namespace Grand.Web.Common.TagHelpers
{
if (head)
{
- if (_templatesHeader == null)
- _templatesHeader = new List<IHtmlContent>();
-
+ _templatesHeader ??= new List<IHtmlContent>();
_templatesHeader.Add(script);
}
else
{
- if (_templatesFooter == null)
- _templatesFooter = new List<IHtmlContent>();
-
+ _templatesFooter ??= new List<IHtmlContent>();
_templatesFooter.Add(script);
}
}
@@ -129,12 +125,11 @@ namespace Grand.Web.Common.TagHelpers
var first = true;
var registeredLinks = _links.OrderBy(x => x.Priority).ToList();
- for (var i = 0; i < registeredLinks.Count; i++)
+ foreach (var link in registeredLinks)
{
- var link = registeredLinks[i];
if (!first)
{
- builder.AppendHtml(System.Environment.NewLine);
+ builder.AppendHtml(Environment.NewLine);
}
first = false;
diff --git a/src/Web/Grand.Web.Common/TagHelpers/ScriptTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/ScriptTagHelper.cs
index b392466d0..1912233ce 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/ScriptTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/ScriptTagHelper.cs
@@ -34,7 +34,7 @@ namespace Grand.Web.Common.TagHelpers
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
- bool isAjaxCall = _httpContextAccessor.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
+ var isAjaxCall = _httpContextAccessor.HttpContext != null && _httpContextAccessor.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
if (!isAjaxCall)
{
output.SuppressOutput();
diff --git a/src/Web/Grand.Web.Common/TagHelpers/TemplateTagHelper.cs b/src/Web/Grand.Web.Common/TagHelpers/TemplateTagHelper.cs
index c6d87dc6a..0a1c7c2ba 100644
--- a/src/Web/Grand.Web.Common/TagHelpers/TemplateTagHelper.cs
+++ b/src/Web/Grand.Web.Common/TagHelpers/TemplateTagHelper.cs
@@ -29,7 +29,7 @@ namespace Grand.Web.Common.TagHelpers
}
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
- bool isAjaxCall = _httpContextAccessor.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
+ var isAjaxCall = _httpContextAccessor.HttpContext != null && _httpContextAccessor.HttpContext.Request.Headers["x-requested-with"] == "XMLHttpRequest";
if (!isAjaxCall)
{
output.SuppressOutput();
@@ -44,15 +44,15 @@ namespace Grand.Web.Common.TagHelpers
builder.Attributes.Add(attribute.Name, attribute.Value.ToString());
}
- if (Header && !Footer)
+ switch (Header)
{
- _resourceManager.RegisterTemplate(builder, true);
+ case true when !Footer:
+ _resourceManager.RegisterTemplate(builder, true);
+ break;
+ case false when Footer:
+ _resourceManager.RegisterTemplate(builder, false);
+ break;
}
- if (!Header && Footer)
- {
- _resourceManager.RegisterTemplate(builder, false);
- }
-
}
}
diff --git a/src/Web/Grand.Web.Common/Themes/IThemeProvider.cs b/src/Web/Grand.Web.Common/Themes/IThemeProvider.cs
index 5bc1f622e..724ba03c6 100644
--- a/src/Web/Grand.Web.Common/Themes/IThemeProvider.cs
+++ b/src/Web/Grand.Web.Common/Themes/IThemeProvider.cs
@@ -2,7 +2,7 @@
namespace Grand.Web.Common.Themes
{
- public partial interface IThemeProvider
+ public interface IThemeProvider
{
bool ThemeConfigurationExists(string themeName);
diff --git a/src/Web/Grand.Web.Common/Themes/ThemeContext.cs b/src/Web/Grand.Web.Common/Themes/ThemeContext.cs
index 91cc01b40..1dd077bcb 100644
--- a/src/Web/Grand.Web.Common/Themes/ThemeContext.cs
+++ b/src/Web/Grand.Web.Common/Themes/ThemeContext.cs
@@ -10,7 +10,7 @@ namespace Grand.Web.Common.Themes
/// <summary>
/// Theme context
/// </summary>
- public partial class ThemeContext : IThemeContext
+ public class ThemeContext : IThemeContext
{
private readonly IWorkContext _workContext;
private readonly IUserFieldService _userFieldService;
@@ -18,7 +18,7 @@ namespace Grand.Web.Common.Themes
private readonly VendorSettings _vendorSettings;
private readonly IThemeProvider _themeProvider;
- private bool _themeIsCached, _adminthemeIsCached;
+ private bool _themeIsCached, _adminThemeIsCached;
private string _cachedThemeName, _cachedAdminThemeName;
public ThemeContext(IWorkContext workContext,
@@ -44,7 +44,7 @@ namespace Grand.Web.Common.Themes
if (_themeIsCached)
return _cachedThemeName;
- string theme = "";
+ var theme = "";
if (_storeInformationSettings.AllowCustomerToSelectTheme)
{
if (_workContext.CurrentCustomer != null)
@@ -67,7 +67,7 @@ namespace Grand.Web.Common.Themes
//cache theme
_cachedThemeName = theme;
- _adminthemeIsCached = true;
+ _adminThemeIsCached = true;
return theme;
}
}
@@ -80,7 +80,7 @@ namespace Grand.Web.Common.Themes
get
{
- if (_adminthemeIsCached)
+ if (_adminThemeIsCached)
return _cachedAdminThemeName;
var theme = "Default";
@@ -92,9 +92,9 @@ namespace Grand.Web.Common.Themes
{
if (_workContext.CurrentCustomer != null)
{
- var customertheme = _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.AdminThemeName, _workContext.CurrentStore.Id);
- if (!string.IsNullOrEmpty(customertheme))
- theme = customertheme;
+ var customerTheme = _workContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.AdminThemeName, _workContext.CurrentStore.Id);
+ if (!string.IsNullOrEmpty(customerTheme))
+ theme = customerTheme;
}
}
diff --git a/src/Web/Grand.Web.Common/Themes/ThemeList.cs b/src/Web/Grand.Web.Common/Themes/ThemeList.cs
index 799f9d0c3..bdd419b1a 100644
--- a/src/Web/Grand.Web.Common/Themes/ThemeList.cs
+++ b/src/Web/Grand.Web.Common/Themes/ThemeList.cs
@@ -3,39 +3,34 @@ using Newtonsoft.Json;
namespace Grand.Web.Common.Themes
{
- public partial class ThemeList : IThemeList
+ public class ThemeList : IThemeList
{
public ThemeList()
{
ThemeConfigurations = new List<ThemeConfiguration>();
- if (Directory.Exists(CommonPath.ThemePath))
- foreach (var themeName in Directory.GetDirectories(CommonPath.ThemePath))
+ if (!Directory.Exists(CommonPath.ThemePath)) return;
+ foreach (var themeName in Directory.GetDirectories(CommonPath.ThemePath))
+ {
+ var configuration = CreateThemeConfiguration(themeName);
+ if (configuration != null)
{
- var configuration = CreateThemeConfiguration(themeName);
- if (configuration != null)
- {
- ThemeConfigurations.Add(configuration);
- }
+ ThemeConfigurations.Add(configuration);
}
+ }
}
public IList<ThemeConfiguration> ThemeConfigurations { get; }
- private ThemeConfiguration CreateThemeConfiguration(string themePath)
+ private static ThemeConfiguration CreateThemeConfiguration(string themePath)
{
var themeDirectory = new DirectoryInfo(themePath);
var themeConfigFile = new FileInfo(Path.Combine(themeDirectory.FullName, "theme.cfg"));
- if (themeConfigFile.Exists)
- {
- var themeConfiguration = JsonConvert.DeserializeObject<ThemeConfiguration>(File.ReadAllText(themeConfigFile.FullName));
- if (themeConfiguration != null)
- {
- themeConfiguration.Name = themeDirectory.Name;
- return themeConfiguration;
- }
- }
- return null;
+ if (!themeConfigFile.Exists) return null;
+ var themeConfiguration = JsonConvert.DeserializeObject<ThemeConfiguration>(File.ReadAllText(themeConfigFile.FullName));
+ if (themeConfiguration == null) return null;
+ themeConfiguration.Name = themeDirectory.Name;
+ return themeConfiguration;
}
}
diff --git a/src/Web/Grand.Web.Common/Themes/ThemeProvider.cs b/src/Web/Grand.Web.Common/Themes/ThemeProvider.cs
index a9296f980..f91fd15d0 100644
--- a/src/Web/Grand.Web.Common/Themes/ThemeProvider.cs
+++ b/src/Web/Grand.Web.Common/Themes/ThemeProvider.cs
@@ -4,7 +4,7 @@ using Newtonsoft.Json;
namespace Grand.Web.Common.Themes
{
- public partial class ThemeProvider : IThemeProvider
+ public class ThemeProvider : IThemeProvider
{
#region Fields
@@ -30,10 +30,7 @@ namespace Grand.Web.Common.Themes
public IList<ThemeConfiguration> GetConfigurations()
{
- if(string.IsNullOrEmpty(CommonPath.Param))
- return _themeList.ThemeConfigurations;
-
- return _themeList.ThemeConfigurations.Where(x => string.IsNullOrEmpty(x.Directory) || x.Directory == CommonPath.Param).ToList();
+ return string.IsNullOrEmpty(CommonPath.Param) ? _themeList.ThemeConfigurations : _themeList.ThemeConfigurations.Where(x => string.IsNullOrEmpty(x.Directory) || x.Directory == CommonPath.Param).ToList();
}
public ThemeInfo GetThemeDescriptorFromText(string text)
@@ -42,9 +39,12 @@ namespace Grand.Web.Common.Themes
try
{
var themeConfiguration = JsonConvert.DeserializeObject<ThemeConfiguration>(text);
- themeDescriptor.FriendlyName = themeConfiguration.Title;
+ themeDescriptor.FriendlyName = themeConfiguration?.Title;
+ }
+ catch
+ {
+ // ignored
}
- catch { }
return themeDescriptor;
}
diff --git a/src/Web/Grand.Web.Common/Themes/ThemeViewLocationExpander.cs b/src/Web/Grand.Web.Common/Themes/ThemeViewLocationExpander.cs
index f3ce61f99..654b55313 100644
--- a/src/Web/Grand.Web.Common/Themes/ThemeViewLocationExpander.cs
+++ b/src/Web/Grand.Web.Common/Themes/ThemeViewLocationExpander.cs
@@ -4,8 +4,8 @@ namespace Grand.Web.Common.Themes
{
public class ThemeViewLocationExpander : IViewLocationExpander
{
- private const string THEME_KEY = "Theme";
- private const string AREA_ADMIN_KEY = "AdminTheme";
+ private const string ThemeKey = "Theme";
+ private const string AreaAdminKey = "AdminTheme";
public void PopulateValues(ViewLocationExpanderContext context)
@@ -13,26 +13,26 @@ namespace Grand.Web.Common.Themes
var themeContext = (IThemeContext)context.ActionContext.HttpContext.RequestServices.GetService(typeof(IThemeContext));
if (context.AreaName?.Equals("Admin") ?? false)
- context.Values[AREA_ADMIN_KEY] = themeContext.AdminAreaThemeName;
+ context.Values[AreaAdminKey] = themeContext?.AdminAreaThemeName;
else
- context.Values[THEME_KEY] = themeContext.WorkingThemeName;
+ context.Values[ThemeKey] = themeContext?.WorkingThemeName;
}
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
- if (context.AreaName == null && context.Values.TryGetValue(THEME_KEY, out var theme))
+ if (context.AreaName == null && context.Values.TryGetValue(ThemeKey, out var theme))
{
viewLocations = new[] {
$"/Themes/{theme}/Views/{{1}}/{{0}}.cshtml",
- $"/Themes/{theme}/Views/Shared/{{0}}.cshtml",
+ $"/Themes/{theme}/Views/Shared/{{0}}.cshtml"
}
.Concat(viewLocations);
}
- if ((context.AreaName?.Equals("Admin") ?? false) && context.Values.TryGetValue(AREA_ADMIN_KEY, out var admintheme))
+ if ((context.AreaName?.Equals("Admin") ?? false) && context.Values.TryGetValue(AreaAdminKey, out var adminTheme))
{
viewLocations = new[] {
- $"/Areas/{{2}}/Themes/{admintheme}/Views/{{1}}/{{0}}.cshtml",
- $"/Areas/{{2}}/Themes/{admintheme}/Views/Shared/{{0}}.cshtml",
+ $"/Areas/{{2}}/Themes/{adminTheme}/Views/{{1}}/{{0}}.cshtml",
+ $"/Areas/{{2}}/Themes/{adminTheme}/Views/Shared/{{0}}.cshtml"
}
.Concat(viewLocations);
}
diff --git a/src/Web/Grand.Web.Common/ViewRender/ViewRenderService.cs b/src/Web/Grand.Web.Common/ViewRender/ViewRenderService.cs
index 773c80c57..9b394f6ab 100644
--- a/src/Web/Grand.Web.Common/ViewRender/ViewRenderService.cs
+++ b/src/Web/Grand.Web.Common/ViewRender/ViewRenderService.cs
@@ -11,7 +11,7 @@ using Microsoft.AspNetCore.Routing;
namespace Grand.Web.Common.ViewRender
{
/// <summary>
- /// Allow to get Rezor page content as string
+ /// Allow to get Razor page content as string
/// </summary>
public class ViewRenderService : IViewRenderService
{
@@ -35,33 +35,29 @@ namespace Grand.Web.Common.ViewRender
var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };
var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
- 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");
- }
-
- var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()) {
- Model = model
- };
+ await using var sw = new StringWriter();
+ var viewResult = _razorViewEngine.GetView(viewPath, viewPath, false);
- var viewContext = new ViewContext(
- actionContext,
- viewResult.View,
- viewDictionary,
- new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
- sw,
- new HtmlHelperOptions()
- );
-
- await viewResult.View.RenderAsync(viewContext);
- return sw.ToString();
+ 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 viewContext = new ViewContext(
+ actionContext,
+ viewResult.View,
+ viewDictionary,
+ new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
+ sw,
+ new HtmlHelperOptions()
+ );
+ await viewResult.View.RenderAsync(viewContext);
+ return sw.ToString();
}
}
}
diff --git a/src/Web/Grand.Web.Common/WorkContext.cs b/src/Web/Grand.Web.Common/WorkContext.cs
index 9be917f3b..25c0d0f53 100644
--- a/src/Web/Grand.Web.Common/WorkContext.cs
+++ b/src/Web/Grand.Web.Common/WorkContext.cs
@@ -22,13 +22,13 @@ namespace Grand.Web.Common
/// <summary>
/// Represents work context for web application / current customer / store / language / currency
/// </summary>
- public partial class WorkContext : IWorkContext
+ public class WorkContext : IWorkContext
{
#region Fields
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IGrandAuthenticationService _authenticationService;
- private readonly IApiAuthenticationService _apiauthenticationService;
+ private readonly IApiAuthenticationService _apiAuthenticationService;
private readonly ICurrencyService _currencyService;
private readonly ICustomerService _customerService;
private readonly IGroupService _groupService;
@@ -58,7 +58,7 @@ namespace Grand.Web.Common
public WorkContext(
IHttpContextAccessor httpContextAccessor,
IGrandAuthenticationService authenticationService,
- IApiAuthenticationService apiauthenticationService,
+ IApiAuthenticationService apiAuthenticationService,
ICurrencyService currencyService,
ICustomerService customerService,
IGroupService groupService,
@@ -74,7 +74,7 @@ namespace Grand.Web.Common
{
_httpContextAccessor = httpContextAccessor;
_authenticationService = authenticationService;
- _apiauthenticationService = apiauthenticationService;
+ _apiAuthenticationService = apiAuthenticationService;
_currencyService = currencyService;
_customerService = customerService;
_groupService = groupService;
@@ -99,20 +99,22 @@ namespace Grand.Web.Common
/// <returns>The found language</returns>
protected virtual async Task<Language> GetLanguageFromUrl(IList<Language> languages)
{
- if (_httpContextAccessor.HttpContext == null || _httpContextAccessor.HttpContext.Request == null)
+ if (_httpContextAccessor.HttpContext?.Request == null)
return await Task.FromResult<Language>(null);
var path = _httpContextAccessor.HttpContext.Request.Path.Value;
if (string.IsNullOrEmpty(path))
return await Task.FromResult<Language>(null);
- var firstSegment = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? string.Empty;
+ var firstSegment = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ??
+ string.Empty;
if (string.IsNullOrEmpty(firstSegment))
return await Task.FromResult<Language>(null);
- var language = languages.FirstOrDefault(urlLanguage => urlLanguage.UniqueSeoCode.Equals(firstSegment, StringComparison.OrdinalIgnoreCase));
+ var language = languages.FirstOrDefault(urlLanguage =>
+ urlLanguage.UniqueSeoCode.Equals(firstSegment, StringComparison.OrdinalIgnoreCase));
- if (language == null || !language.Published || !_aclService.Authorize(language, CurrentStore.Id))
+ if (language is not { Published: true } || !_aclService.Authorize(language, CurrentStore.Id))
return await Task.FromResult<Language>(null);
return language;
@@ -124,11 +126,12 @@ namespace Grand.Web.Common
/// <returns>The found language</returns>
protected virtual async Task<Language> GetLanguageFromRequest(IList<Language> languages)
{
- if (_httpContextAccessor.HttpContext == null || _httpContextAccessor.HttpContext.Request == null)
+ if (_httpContextAccessor.HttpContext?.Request == null)
return await Task.FromResult<Language>(null);
//get request culture
- var requestCulture = _httpContextAccessor.HttpContext.Features.Get<IRequestCultureFeature>()?.RequestCulture;
+ var requestCulture =
+ _httpContextAccessor.HttpContext.Features.Get<IRequestCultureFeature>()?.RequestCulture;
if (requestCulture == null)
return await Task.FromResult<Language>(null);
@@ -137,7 +140,8 @@ namespace Grand.Web.Common
language.LanguageCulture.Equals(requestCulture.Culture.Name, StringComparison.OrdinalIgnoreCase));
//check language availability
- if (requestLanguage == null || !requestLanguage.Published || !_aclService.Authorize(requestLanguage, CurrentStore.Id))
+ if (requestLanguage is not { Published: true } ||
+ !_aclService.Authorize(requestLanguage, CurrentStore.Id))
return await Task.FromResult<Language>(null);
return requestLanguage;
@@ -146,18 +150,15 @@ namespace Grand.Web.Common
protected virtual async Task<Customer> SetImpersonatedCustomer(Customer customer)
{
//get impersonate user if required
- var impersonatedCustomerId = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.ImpersonatedCustomerId);
- if (!string.IsNullOrEmpty(impersonatedCustomerId))
- {
- var impersonatedCustomer = await _customerService.GetCustomerById(impersonatedCustomerId);
- if (impersonatedCustomer != null && !impersonatedCustomer.Deleted && impersonatedCustomer.Active)
- {
- //set impersonated customer
- _originalCustomerIfImpersonated = customer;
- return impersonatedCustomer;
- }
- }
- return null;
+ 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;
+
}
#endregion
@@ -175,7 +176,7 @@ namespace Grand.Web.Common
/// <returns></returns>
public virtual async Task<Customer> SetCurrentCustomer()
{
- Customer customer = null;
+ Customer customer;
//check whether request is made by a background (schedule) task
if (_httpContextAccessor.HttpContext == null)
{
@@ -190,9 +191,9 @@ namespace Grand.Web.Common
}
}
- //set customer as a background task if method setted as AllowAnonymous
+ //set customer as a background task if method settled as AllowAnonymous
var endpoint = _httpContextAccessor.HttpContext?.GetEndpoint();
- if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() is object)
+ if (endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null)
{
customer = await _customerService.GetCustomerBySystemName(SystemCustomerNames.Anonymous);
//if customer comes from Anonymous method, doesn't need to create cookies
@@ -204,85 +205,75 @@ namespace Grand.Web.Common
}
}
- if (customer == null || customer.Deleted || !customer.Active)
+ //try to get registered user
+ customer = await _authenticationService.GetAuthenticatedCustomer();
+ //if customer is authenticated
+ if (customer != null)
{
- //try to get registered user
- customer = await _authenticationService.GetAuthenticatedCustomer();
- //if customer is authenticated
- if (customer != null)
- {
- //remove cookie
- await _authenticationService.SetCustomerGuid(Guid.Empty);
+ //remove cookie
+ await _authenticationService.SetCustomerGuid(Guid.Empty);
- //set if use impersonated session
- var impersonatedCustomer = await SetImpersonatedCustomer(customer);
- if (impersonatedCustomer != null)
- customer = impersonatedCustomer;
+ //set if use impersonated session
+ var impersonatedCustomer = await SetImpersonatedCustomer(customer);
+ if (impersonatedCustomer != null)
+ customer = impersonatedCustomer;
- //cache the found customer
- _cachedCustomer = customer;
+ //cache the found customer
+ _cachedCustomer = customer;
- return customer;
- }
+ return customer;
}
- if (customer == null)
+ //try to get api user
+ customer = await _apiAuthenticationService.GetAuthenticatedCustomer();
+ //if customer comes from api, doesn't need to create cookies
+ if (customer != null)
{
- //try to get api user
- customer = await _apiauthenticationService.GetAuthenticatedCustomer();
- //if customer comes from api, doesn't need to create cookies
- if (customer != null)
- {
- //set if use impersonated session
- var impersonatedCustomer = await SetImpersonatedCustomer(customer);
- if (impersonatedCustomer != null)
- customer = impersonatedCustomer;
-
- //cache the found customer
- _cachedCustomer = customer;
- return customer;
- }
+ //set if use impersonated session
+ var impersonatedCustomer = await SetImpersonatedCustomer(customer);
+ if (impersonatedCustomer != null)
+ customer = impersonatedCustomer;
+
+ //cache the found customer
+ _cachedCustomer = customer;
+ return customer;
}
-
- if (customer == null || customer.Deleted || !customer.Active)
+
+ //get guest customer
+ var guid = await _authenticationService.GetCustomerGuid();
+ if (!string.IsNullOrEmpty(guid))
{
- //get guest customer
- var customerguid = await _authenticationService.GetCustomerGuid();
- if (!string.IsNullOrEmpty(customerguid))
+ if (Guid.TryParse(guid, out Guid customerGuid))
{
- if (Guid.TryParse(customerguid, out Guid customerGuid))
- {
- //get customer from guid (cannot not be registered)
- var customerByguid = await _customerService.GetCustomerByGuid(customerGuid);
- if (customerByguid != null && !await _groupService.IsRegistered(customerByguid))
- customer = customerByguid;
- }
+ //get customer from guid (cannot not be registered)
+ var customerByGuid = await _customerService.GetCustomerByGuid(customerGuid);
+ if (customerByGuid != null && !await _groupService.IsRegistered(customerByGuid))
+ customer = customerByGuid;
}
}
-
+
if (customer == null || customer.Deleted || !customer.Active)
{
var isCrawler = _detectionService.Crawler?.IsCrawler;
//check whether request is made by a search engine, in this case return built-in customer record for search engines
- if (isCrawler.HasValue && isCrawler.Value)
+ if (isCrawler.Value)
customer = await _customerService.GetCustomerBySystemName(SystemCustomerNames.SearchEngine);
}
- if (customer == null || customer.Deleted || !customer.Active)
+ if (customer is { Deleted: false, Active: true })
+ return _cachedCustomer = customer;
+
+ //create guest if not exists
+ customer = await _customerService.InsertGuestCustomer(CurrentStore);
+ if (_httpContextAccessor?.HttpContext?.Request.GetTypedHeaders().Referer?.ToString() is { } referer)
{
- //create guest if not exists
- customer = await _customerService.InsertGuestCustomer(CurrentStore);
- if (_httpContextAccessor?.HttpContext?.Request?.GetTypedHeaders().Referer?.ToString() is { } referer)
- {
- await _userFieldService.SaveField(customer, SystemCustomerFieldNames.UrlReferrer, referer);
- }
- //set customer cookie
- await _authenticationService.SetCustomerGuid(customer.CustomerGuid);
+ await _userFieldService.SaveField(customer, SystemCustomerFieldNames.UrlReferrer, referer);
}
-
+ //set customer cookie
+ await _authenticationService.SetCustomerGuid(customer.CustomerGuid);
//cache the found customer
- return _cachedCustomer = customer ?? throw new Exception("No customer could be loaded");
+ return _cachedCustomer = customer;
}
/// <summary>
@@ -296,6 +287,7 @@ namespace Grand.Web.Common
//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");
}
@@ -342,7 +334,8 @@ namespace Grand.Web.Common
public virtual async Task<Language> SetWorkingLanguage(Language language)
{
if (language != null)
- await _userFieldService.SaveField(CurrentCustomer, SystemCustomerFieldNames.LanguageId, language.Id, CurrentStore.Id);
+ await _userFieldService.SaveField(CurrentCustomer, SystemCustomerFieldNames.LanguageId, language.Id,
+ CurrentStore.Id);
//then reset the cache value
_cachedLanguage = null;
@@ -359,7 +352,8 @@ namespace Grand.Web.Common
{
Language language = null;
- var adminAreaUrl = _httpContextAccessor.HttpContext?.Request?.Path.StartsWithSegments(new PathString("/Admin"));
+ var adminAreaUrl =
+ _httpContextAccessor.HttpContext?.Request.Path.StartsWithSegments(new PathString("/Admin"));
var allStoreLanguages = await _languageService.GetAllLanguages(showHidden: adminAreaUrl ?? false);
if (allStoreLanguages.Count == 1)
@@ -369,7 +363,8 @@ namespace Grand.Web.Common
language = await GetLanguageFromUrl(allStoreLanguages);
//get current lang identifier
- var customerLanguageId = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId, CurrentStore.Id);
+ var customerLanguageId =
+ customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.LanguageId, CurrentStore.Id);
if (_languageSettings.AutomaticallyDetectLanguage &&
language == null && string.IsNullOrEmpty(customerLanguageId))
@@ -378,23 +373,21 @@ namespace Grand.Web.Common
}
//check customer language
- var customerLanguage = language ??
- (!string.IsNullOrEmpty(customerLanguageId) ?
- allStoreLanguages.FirstOrDefault(language => language.Id == customerLanguageId) :
- allStoreLanguages.FirstOrDefault(language => language.Id == CurrentStore.DefaultLanguageId));
-
- //if the language for the current store not exist, then use the first
- if (customerLanguage == null)
- customerLanguage = allStoreLanguages.FirstOrDefault();
+ 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();
//cache the language
_cachedLanguage = customerLanguage;
//save the language identifier
- if (customerLanguage.Id != customerLanguageId)
+ if (customerLanguage != null && customerLanguage.Id != customerLanguageId)
{
await _userFieldService.SaveField(customer,
- SystemCustomerFieldNames.LanguageId, customerLanguage?.Id, CurrentStore.Id);
+ SystemCustomerFieldNames.LanguageId, customerLanguage.Id, CurrentStore.Id);
}
return _cachedLanguage ?? throw new Exception("No language could be loaded");
@@ -411,7 +404,8 @@ namespace Grand.Web.Common
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"));
+ var adminAreaUrl =
+ _httpContextAccessor.HttpContext?.Request.Path.StartsWithSegments(new PathString("/Admin"));
if (adminAreaUrl.HasValue && adminAreaUrl.Value)
{
var primaryStoreCurrency = await _currencyService.GetPrimaryStoreCurrency();
@@ -421,34 +415,26 @@ namespace Grand.Web.Common
return primaryStoreCurrency;
}
}
+
var allStoreCurrencies = await _currencyService.GetAllCurrencies(storeId: CurrentStore?.Id);
if (allStoreCurrencies.Count == 1)
return _cachedCurrency = allStoreCurrencies.FirstOrDefault();
- var customerCurrencyId = customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CurrencyId, CurrentStore.Id);
+ var customerCurrencyId =
+ customer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.CurrencyId, CurrentStore?.Id);
- var customerCurrency = allStoreCurrencies.FirstOrDefault(currency => currency.Id == customerCurrencyId);
-
- if (customerCurrency == null)
- {
- if (!string.IsNullOrEmpty(CurrentStore?.DefaultCurrencyId))
- customerCurrency = allStoreCurrencies.FirstOrDefault(currency => currency.Id == CurrentStore.DefaultCurrencyId);
- else
- customerCurrency = allStoreCurrencies.FirstOrDefault(currency => currency.Id == WorkingLanguage.DefaultCurrencyId);
- }
-
- if (customerCurrency == null)
- customerCurrency = allStoreCurrencies.FirstOrDefault();
+ 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();
//cache the currency
_cachedCurrency = customerCurrency;
//save the currency identifier
- if (customerCurrency.Id != customerCurrencyId)
+ if (customerCurrency?.Id != customerCurrencyId)
{
await _userFieldService.SaveField(customer,
- SystemCustomerFieldNames.CurrencyId, customerCurrency?.Id, CurrentStore.Id);
+ SystemCustomerFieldNames.CurrencyId, customerCurrency?.Id, CurrentStore?.Id);
}
return _cachedCurrency ?? throw new Exception("No currency could be loaded");
@@ -480,7 +466,8 @@ namespace Grand.Web.Common
if (_taxSettings.AllowCustomersToSelectTaxDisplayType && customer != null)
{
- var taxDisplayTypeId = customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.TaxDisplayTypeId, CurrentStore.Id);
+ var taxDisplayTypeId =
+ customer.GetUserFieldFromEntity<int>(SystemCustomerFieldNames.TaxDisplayTypeId, CurrentStore.Id);
taxDisplayType = (TaxDisplayType)taxDisplayTypeId;
}
else
@@ -488,6 +475,7 @@ namespace Grand.Web.Common
//or get the default tax display type
taxDisplayType = _taxSettings.TaxDisplayType;
}
+
//cache the value
_cachedTaxDisplayType = taxDisplayType;
@@ -522,4 +510,4 @@ namespace Grand.Web.Common
#endregion
}
-}
+}
\ No newline at end of file