From 5addb2ec1742776eaba9bbafeb959ac6da6b26e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roland=20M=C3=A1rkus?= Date: Sat, 20 Jan 2024 12:14:47 +0100 Subject: [PATCH] Addressing warnings. --- .../Controllers/TenantLoginController.cs | 50 ++++++--------- .../Filters/TenantsIndexFilter.cs | 37 ++++------- .../Filters/DashboardQuotaFilter.cs | 29 +++------ .../Filters/EmailSettingsQuotaFilter.cs | 29 +++------ .../Services/EmailQuotaService.cs | 58 +++++++----------- .../Services/EmailQuotaSubjectService.cs | 13 ++-- .../QuotaManagingSmtpServiceDecorator.cs | 61 +++++++------------ .../Startup.cs | 9 +-- .../Filters/EnvironmentRobotsMetaTagFilter.cs | 21 +++---- .../EnvironmentRobotsMiddleware.cs | 23 ++----- .../Startup.cs | 9 +-- .../Handlers/FeaturesEventHandler.cs | 6 +- .../Startup.cs | 7 +-- .../Middlewares/IdleTimeProviderMiddleware.cs | 10 +-- .../Services/IdleShutdown.cs | 45 +++++--------- .../Startup.cs | 9 +-- ...wnerPermissionToRoleMaintenanceProvider.cs | 21 ++----- .../AddSiteOwnerPermissionToRole/Startup.cs | 9 +-- ...UserSensitiveContentMaintenanceProvider.cs | 37 ++++------- .../ChangeUserSensitiveContent/Startup.cs | 9 +-- .../RemoveUsersMaintenanceProvider.cs | 27 +++----- .../Maintenance/RemoveUsers/Startup.cs | 9 +-- .../UpdateShellRequestUrl/Startup.cs | 9 +-- ...dateShellRequestUrlsMaintenanceProvider.cs | 49 ++++++--------- .../Maintenance/UpdateSiteUrl/Startup.cs | 9 +-- .../UpdateSiteUrlMaintenanceProvider.cs | 33 ++++------ .../Services/MaintenanceManager.cs | 53 ++++++---------- .../Services/MaintenanceRunnerService.cs | 27 +++----- .../ShellSettingsEditorController.cs | 45 +++++--------- ...ombiqHostingTenantsManagementExtensions.cs | 3 +- .../Filters/ForbiddenTenantsFilter.cs | 23 +++---- .../Filters/ShellSettingsEditorFilter.cs | 25 +++----- .../Service/SetupWithRecipesFilterService.cs | 27 +++----- Lombiq.Hosting.Tenants.Management/Startup.cs | 8 +-- .../Filters/UploadFileSizeShapeFilter.cs | 25 +++----- .../Service/MediaStorageQuotaService.cs | 17 ++---- .../Startup.cs | 10 +-- 37 files changed, 278 insertions(+), 613 deletions(-) diff --git a/Lombiq.Hosting.Tenants.Admin.Login/Controllers/TenantLoginController.cs b/Lombiq.Hosting.Tenants.Admin.Login/Controllers/TenantLoginController.cs index ed086af8..0dc73d74 100644 --- a/Lombiq.Hosting.Tenants.Admin.Login/Controllers/TenantLoginController.cs +++ b/Lombiq.Hosting.Tenants.Admin.Login/Controllers/TenantLoginController.cs @@ -17,45 +17,29 @@ namespace Lombiq.Hosting.Tenants.Admin.Login.Controllers; [Feature(SubTenant)] -public class TenantLoginController : Controller +public class TenantLoginController( + ISiteService siteService, + SignInManager userSignInManager, + IShellHost shellHost, + ShellSettings shellSettings, + ILogger logger, + INotifier notifier, + IHtmlLocalizer htmlLocalizer) : Controller { - private readonly ISiteService _siteService; - private readonly SignInManager _userSignInManager; - private readonly IShellHost _shellHost; - private readonly ShellSettings _shellSettings; - private readonly ILogger _logger; - private readonly INotifier _notifier; - private readonly IHtmlLocalizer H; - - public TenantLoginController( - ISiteService siteService, - SignInManager userSignInManager, - IShellHost shellHost, - ShellSettings shellSettings, - ILogger logger, - INotifier notifier, - IHtmlLocalizer htmlLocalizer) - { - _siteService = siteService; - _userSignInManager = userSignInManager; - _shellHost = shellHost; - _shellSettings = shellSettings; - _logger = logger; - _notifier = notifier; - H = htmlLocalizer; - } + private readonly ILogger _logger = logger; + private readonly IHtmlLocalizer H = htmlLocalizer; [HttpPost] // This is necessary because requests for this action will come from the Default tenant. [IgnoreAntiforgeryToken] public async Task Index(string password) { - if (_shellSettings.Name.EqualsOrdinalIgnoreCase(ShellSettings.DefaultShellName)) + if (shellSettings.Name.EqualsOrdinalIgnoreCase(ShellSettings.DefaultShellName)) { return NotFound(); } - var defaultShell = await _shellHost.GetScopeAsync(ShellSettings.DefaultShellName); + var defaultShell = await shellHost.GetScopeAsync(ShellSettings.DefaultShellName); var tenantLoginPasswordValidator = defaultShell?.ServiceProvider.GetService(); if (defaultShell == null || @@ -65,17 +49,17 @@ public async Task Index(string password) return NotFound(); } - var sitesettings = await _siteService.LoadSiteSettingsAsync(); - var adminUser = await _userSignInManager.UserManager.FindByIdAsync(sitesettings.SuperUser); - adminUser ??= (await _userSignInManager.UserManager.GetUsersInRoleAsync(Administrator)).FirstOrDefault(); + var sitesettings = await siteService.LoadSiteSettingsAsync(); + var adminUser = await userSignInManager.UserManager.FindByIdAsync(sitesettings.SuperUser); + adminUser ??= (await userSignInManager.UserManager.GetUsersInRoleAsync(Administrator)).FirstOrDefault(); if (adminUser == null) { - await _notifier.ErrorAsync(H["No user with administrator role in this tenant."]); + await notifier.ErrorAsync(H["No user with administrator role in this tenant."]); return Redirect("~/"); } - await _userSignInManager.SignInAsync(adminUser, isPersistent: false); + await userSignInManager.SignInAsync(adminUser, isPersistent: false); _logger.LogInformation(1, "An admin user logged in from the Default tenant."); return RedirectToAction("Index", "Admin", new { area = "OrchardCore.Admin" }); diff --git a/Lombiq.Hosting.Tenants.Admin.Login/Filters/TenantsIndexFilter.cs b/Lombiq.Hosting.Tenants.Admin.Login/Filters/TenantsIndexFilter.cs index 99302312..ba1d95e0 100644 --- a/Lombiq.Hosting.Tenants.Admin.Login/Filters/TenantsIndexFilter.cs +++ b/Lombiq.Hosting.Tenants.Admin.Login/Filters/TenantsIndexFilter.cs @@ -14,28 +14,13 @@ namespace Lombiq.Hosting.Tenants.Admin.Login.Filters; -public class TenantsIndexFilter : IAsyncResultFilter +public class TenantsIndexFilter( + ILayoutAccessor layoutAccessor, + IShapeFactory shapeFactory, + IShellHost shellHost, + IHttpContextAccessor hca, + IAuthorizationService authorizationService) : IAsyncResultFilter { - private readonly ILayoutAccessor _layoutAccessor; - private readonly IShapeFactory _shapeFactory; - private readonly IShellHost _shellHost; - private readonly IHttpContextAccessor _hca; - private readonly IAuthorizationService _authorizationService; - - public TenantsIndexFilter( - ILayoutAccessor layoutAccessor, - IShapeFactory shapeFactory, - IShellHost shellHost, - IHttpContextAccessor hca, - IAuthorizationService authorizationService) - { - _layoutAccessor = layoutAccessor; - _shapeFactory = shapeFactory; - _shellHost = shellHost; - _hca = hca; - _authorizationService = authorizationService; - } - public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { var actionRouteController = context.ActionDescriptor.RouteValues["Controller"]; @@ -46,20 +31,20 @@ public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultE actionRouteArea == $"{nameof(OrchardCore)}.{nameof(OrchardCore.Tenants)}" && actionRouteValue is nameof(AdminController.Edit) && context.Result is ViewResult && - await _authorizationService.AuthorizeAsync( - _hca.HttpContext.User, + await authorizationService.AuthorizeAsync( + hca.HttpContext.User, TenantAdminPermissions.LoginAsAdmin) ) { - var shellSettings = _shellHost.GetSettings(context.RouteData.Values["Id"].ToString()); + var shellSettings = shellHost.GetSettings(context.RouteData.Values["Id"].ToString()); if (shellSettings != null && shellSettings.State == TenantState.Running && !shellSettings.Name.EqualsOrdinalIgnoreCase(ShellSettings.DefaultShellName)) { - var layout = await _layoutAccessor.GetLayoutAsync(); + var layout = await layoutAccessor.GetLayoutAsync(); var contentZone = layout.Zones["Content"]; await contentZone.AddAsync( - await _shapeFactory.CreateAsync("TenantAdminShape", new + await shapeFactory.CreateAsync("TenantAdminShape", new { shellSettings.RequestUrlHost, shellSettings.RequestUrlPrefix, diff --git a/Lombiq.Hosting.Tenants.EmailQuotaManagement/Filters/DashboardQuotaFilter.cs b/Lombiq.Hosting.Tenants.EmailQuotaManagement/Filters/DashboardQuotaFilter.cs index 9804084f..e2fdd7fc 100644 --- a/Lombiq.Hosting.Tenants.EmailQuotaManagement/Filters/DashboardQuotaFilter.cs +++ b/Lombiq.Hosting.Tenants.EmailQuotaManagement/Filters/DashboardQuotaFilter.cs @@ -7,22 +7,11 @@ namespace Lombiq.Hosting.Tenants.EmailQuotaManagement.Filters; -public class DashboardQuotaFilter : IAsyncResultFilter +public class DashboardQuotaFilter( + IShapeFactory shapeFactory, + ILayoutAccessor layoutAccessor, + IEmailQuotaService emailQuotaService) : IAsyncResultFilter { - private readonly IShapeFactory _shapeFactory; - private readonly ILayoutAccessor _layoutAccessor; - private readonly IEmailQuotaService _emailQuotaService; - - public DashboardQuotaFilter( - IShapeFactory shapeFactory, - ILayoutAccessor layoutAccessor, - IEmailQuotaService emailQuotaService) - { - _shapeFactory = shapeFactory; - _layoutAccessor = layoutAccessor; - _emailQuotaService = emailQuotaService; - } - public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { if (!context.IsAdmin()) @@ -32,19 +21,19 @@ public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultE } if (context.Result is ViewResult && - _emailQuotaService.ShouldLimitEmails()) + emailQuotaService.ShouldLimitEmails()) { - var currentEmailQuota = await _emailQuotaService.IsQuotaOverTheLimitAsync(); + var currentEmailQuota = await emailQuotaService.IsQuotaOverTheLimitAsync(); var currentUsagePercentage = currentEmailQuota.EmailQuota - .CurrentUsagePercentage(_emailQuotaService.GetEmailQuotaPerMonth()); + .CurrentUsagePercentage(emailQuotaService.GetEmailQuotaPerMonth()); if (currentUsagePercentage >= 80) { - var layout = await _layoutAccessor.GetLayoutAsync(); + var layout = await layoutAccessor.GetLayoutAsync(); var contentZone = layout.Zones["Messages"]; await contentZone.AddAsync( - await _shapeFactory.CreateAsync("DashboardQuotaMessage", new + await shapeFactory.CreateAsync("DashboardQuotaMessage", new { currentEmailQuota.IsOverQuota, UsagePercentage = currentUsagePercentage, diff --git a/Lombiq.Hosting.Tenants.EmailQuotaManagement/Filters/EmailSettingsQuotaFilter.cs b/Lombiq.Hosting.Tenants.EmailQuotaManagement/Filters/EmailSettingsQuotaFilter.cs index b4543ede..35922c44 100644 --- a/Lombiq.Hosting.Tenants.EmailQuotaManagement/Filters/EmailSettingsQuotaFilter.cs +++ b/Lombiq.Hosting.Tenants.EmailQuotaManagement/Filters/EmailSettingsQuotaFilter.cs @@ -9,22 +9,11 @@ namespace Lombiq.Hosting.Tenants.EmailQuotaManagement.Filters; -public class EmailSettingsQuotaFilter : IAsyncResultFilter +public class EmailSettingsQuotaFilter( + IShapeFactory shapeFactory, + ILayoutAccessor layoutAccessor, + IEmailQuotaService emailQuotaService) : IAsyncResultFilter { - private readonly IShapeFactory _shapeFactory; - private readonly ILayoutAccessor _layoutAccessor; - private readonly IEmailQuotaService _emailQuotaService; - - public EmailSettingsQuotaFilter( - IShapeFactory shapeFactory, - ILayoutAccessor layoutAccessor, - IEmailQuotaService emailQuotaService) - { - _shapeFactory = shapeFactory; - _layoutAccessor = layoutAccessor; - _emailQuotaService = emailQuotaService; - } - public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { if (!context.IsAdmin()) @@ -43,17 +32,17 @@ actionRouteValue is nameof(AdminController.Index) && context.Result is ViewResult && context.RouteData.Values.TryGetValue("GroupId", out var groupId) && (string)groupId == "email" && - _emailQuotaService.ShouldLimitEmails()) + emailQuotaService.ShouldLimitEmails()) { - var layout = await _layoutAccessor.GetLayoutAsync(); + var layout = await layoutAccessor.GetLayoutAsync(); var contentZone = layout.Zones["Content"]; - var quota = await _emailQuotaService.GetOrCreateCurrentQuotaAsync(); + var quota = await emailQuotaService.GetOrCreateCurrentQuotaAsync(); await contentZone.AddAsync( - await _shapeFactory.CreateAsync("EmailSettingsQuotaMessage", new + await shapeFactory.CreateAsync("EmailSettingsQuotaMessage", new { quota.CurrentEmailUsageCount, - EmailQuotaPerMonth = _emailQuotaService.GetEmailQuotaPerMonth(), + EmailQuotaPerMonth = emailQuotaService.GetEmailQuotaPerMonth(), }), "0"); } diff --git a/Lombiq.Hosting.Tenants.EmailQuotaManagement/Services/EmailQuotaService.cs b/Lombiq.Hosting.Tenants.EmailQuotaManagement/Services/EmailQuotaService.cs index 92af9ffb..90e2b343 100644 --- a/Lombiq.Hosting.Tenants.EmailQuotaManagement/Services/EmailQuotaService.cs +++ b/Lombiq.Hosting.Tenants.EmailQuotaManagement/Services/EmailQuotaService.cs @@ -19,38 +19,22 @@ namespace Lombiq.Hosting.Tenants.EmailQuotaManagement.Services; -public class EmailQuotaService : IEmailQuotaService +public class EmailQuotaService( + ISession session, + IOptions emailQuotaOptions, + IShellConfiguration shellConfiguration, + IOptions smtpOptions, + IClock clock, + IRoleService roleService, + UserManager userManager) : IEmailQuotaService { - private readonly ISession _session; - private readonly EmailQuotaOptions _emailQuotaOptions; - private readonly IShellConfiguration _shellConfiguration; - private readonly SmtpSettings _smtpOptions; - private readonly IClock _clock; - private readonly IRoleService _roleService; - private readonly UserManager _userManager; - - public EmailQuotaService( - ISession session, - IOptions emailQuotaOptions, - IShellConfiguration shellConfiguration, - IOptions smtpOptions, - IClock clock, - IRoleService roleService, - UserManager userManager) - { - _session = session; - _emailQuotaOptions = emailQuotaOptions.Value; - _shellConfiguration = shellConfiguration; - _smtpOptions = smtpOptions.Value; - _clock = clock; - _roleService = roleService; - _userManager = userManager; - } + private readonly EmailQuotaOptions _emailQuotaOptions = emailQuotaOptions.Value; + private readonly SmtpSettings _smtpOptions = smtpOptions.Value; public async Task> GetUserEmailsForEmailReminderAsync() { // Get users with site owner permission. - var roles = await _roleService.GetRolesAsync(); + var roles = await roleService.GetRolesAsync(); var siteOwnerRoles = roles.Where(role => (role as Role)?.RoleClaims.Exists(claim => claim.ClaimType == ClaimType && claim.ClaimValue == SiteOwner.Name) == true); @@ -58,7 +42,7 @@ public async Task> GetUserEmailsForEmailReminderAsync() var siteOwners = new List(); foreach (var role in siteOwnerRoles) { - siteOwners.AddRange(await _userManager.GetUsersInRoleAsync(role.RoleName)); + siteOwners.AddRange(await userManager.GetUsersInRoleAsync(role.RoleName)); } return siteOwners.Select(user => (user as User)?.Email); @@ -66,7 +50,7 @@ public async Task> GetUserEmailsForEmailReminderAsync() public bool ShouldLimitEmails() { - var originalHost = _shellConfiguration.GetValue("SmtpSettings:Host"); + var originalHost = shellConfiguration.GetValue("SmtpSettings:Host"); return originalHost == _smtpOptions.Host; } @@ -82,16 +66,16 @@ public async Task IsQuotaOverTheLimitAsync() public async Task GetOrCreateCurrentQuotaAsync() { - var currentQuota = await _session.Query().FirstOrDefaultAsync(); + var currentQuota = await session.Query().FirstOrDefaultAsync(); if (currentQuota != null) return currentQuota; currentQuota = new EmailQuota { // Need to set default value otherwise the database might complain about being 01/01/0001 out of range. - LastReminderUtc = _clock.UtcNow.AddMonths(-1), + LastReminderUtc = clock.UtcNow.AddMonths(-1), }; - await _session.SaveAsync(currentQuota); + await session.SaveAsync(currentQuota); return currentQuota; } @@ -99,14 +83,14 @@ public async Task GetOrCreateCurrentQuotaAsync() public Task IncreaseEmailUsageAsync(EmailQuota emailQuota) { emailQuota.CurrentEmailUsageCount++; - return _session.SaveAsync(emailQuota); + return session.SaveAsync(emailQuota); } public Task SetQuotaOnEmailReminderAsync(EmailQuota emailQuota) { - emailQuota.LastReminderUtc = _clock.UtcNow; + emailQuota.LastReminderUtc = clock.UtcNow; emailQuota.LastReminderPercentage = emailQuota.CurrentUsagePercentage(GetEmailQuotaPerMonth()); - return _session.SaveAsync(emailQuota); + return session.SaveAsync(emailQuota); } public bool ShouldSendReminderEmail(EmailQuota emailQuota, int currentUsagePercentage) @@ -116,7 +100,7 @@ public bool ShouldSendReminderEmail(EmailQuota emailQuota, int currentUsagePerce return false; } - var isSameMonth = IsSameMonth(_clock.UtcNow, emailQuota.LastReminderUtc); + var isSameMonth = IsSameMonth(clock.UtcNow, emailQuota.LastReminderUtc); if (!isSameMonth) { @@ -131,7 +115,7 @@ public bool ShouldSendReminderEmail(EmailQuota emailQuota, int currentUsagePerce public Task ResetQuotaAsync(EmailQuota emailQuota) { emailQuota.CurrentEmailUsageCount = 0; - return _session.SaveAsync(emailQuota); + return session.SaveAsync(emailQuota); } public int GetEmailQuotaPerMonth() => diff --git a/Lombiq.Hosting.Tenants.EmailQuotaManagement/Services/EmailQuotaSubjectService.cs b/Lombiq.Hosting.Tenants.EmailQuotaManagement/Services/EmailQuotaSubjectService.cs index 433c8ab7..b1a37d1c 100644 --- a/Lombiq.Hosting.Tenants.EmailQuotaManagement/Services/EmailQuotaSubjectService.cs +++ b/Lombiq.Hosting.Tenants.EmailQuotaManagement/Services/EmailQuotaSubjectService.cs @@ -1,17 +1,12 @@ -using Microsoft.Extensions.Localization; +using Microsoft.Extensions.Localization; namespace Lombiq.Hosting.Tenants.EmailQuotaManagement.Services; -public class EmailQuotaSubjectService : IEmailQuotaSubjectService +public class EmailQuotaSubjectService(IStringLocalizer stringLocalizer) : IEmailQuotaSubjectService { - private readonly IStringLocalizer T; - - public EmailQuotaSubjectService(IStringLocalizer stringLocalizer) => - T = stringLocalizer; - public LocalizedString GetWarningEmailSubject(int percentage) => - T["[Warning] Your site has used {0}% of its e-mail quota", percentage]; + stringLocalizer["[Warning] Your site has used {0}% of its e-mail quota", percentage]; public LocalizedString GetExceededEmailSubject() => - T["[Action Required] Your site has run over its e-mail quota"]; + stringLocalizer["[Action Required] Your site has run over its e-mail quota"]; } diff --git a/Lombiq.Hosting.Tenants.EmailQuotaManagement/Services/QuotaManagingSmtpServiceDecorator.cs b/Lombiq.Hosting.Tenants.EmailQuotaManagement/Services/QuotaManagingSmtpServiceDecorator.cs index 703472e8..6bcbcd43 100644 --- a/Lombiq.Hosting.Tenants.EmailQuotaManagement/Services/QuotaManagingSmtpServiceDecorator.cs +++ b/Lombiq.Hosting.Tenants.EmailQuotaManagement/Services/QuotaManagingSmtpServiceDecorator.cs @@ -10,51 +10,34 @@ namespace Lombiq.Hosting.Tenants.EmailQuotaManagement.Services; -public class QuotaManagingSmtpServiceDecorator : ISmtpService +public class QuotaManagingSmtpServiceDecorator( + ISmtpService smtpService, + IStringLocalizer stringLocalizer, + IEmailQuotaService emailQuotaService, + ShellSettings shellSettings, + IEmailTemplateService emailTemplateService, + IEmailQuotaSubjectService emailQuotaSubjectService) : ISmtpService { - private readonly IStringLocalizer T; - private readonly ISmtpService _smtpService; - private readonly IEmailQuotaService _emailQuotaService; - private readonly ShellSettings _shellSettings; - private readonly IEmailTemplateService _emailTemplateService; - private readonly IEmailQuotaSubjectService _emailQuotaSubjectService; - - public QuotaManagingSmtpServiceDecorator( - ISmtpService smtpService, - IStringLocalizer stringLocalizer, - IEmailQuotaService emailQuotaService, - ShellSettings shellSettings, - IEmailTemplateService emailTemplateService, - IEmailQuotaSubjectService emailQuotaSubjectService) - { - _smtpService = smtpService; - T = stringLocalizer; - _emailQuotaService = emailQuotaService; - _shellSettings = shellSettings; - _emailTemplateService = emailTemplateService; - _emailQuotaSubjectService = emailQuotaSubjectService; - } - public async Task SendAsync(MailMessage message) { - if (!_emailQuotaService.ShouldLimitEmails()) + if (!emailQuotaService.ShouldLimitEmails()) { - return await _smtpService.SendAsync(message); + return await smtpService.SendAsync(message); } - var isQuotaOverResult = await _emailQuotaService.IsQuotaOverTheLimitAsync(); + var isQuotaOverResult = await emailQuotaService.IsQuotaOverTheLimitAsync(); await SendAlertEmailIfNecessaryAsync(isQuotaOverResult.EmailQuota); // Should send the email if the quota is not over the limit. if (isQuotaOverResult.IsOverQuota) { - return SmtpResult.Failed(T["The email quota for the site has been exceeded."]); + return SmtpResult.Failed(stringLocalizer["The email quota for the site has been exceeded."]); } - var emailResult = await _smtpService.SendAsync(message); + var emailResult = await smtpService.SendAsync(message); if (emailResult == SmtpResult.Success) { - await _emailQuotaService.IncreaseEmailUsageAsync(isQuotaOverResult.EmailQuota); + await emailQuotaService.IncreaseEmailUsageAsync(isQuotaOverResult.EmailQuota); } return emailResult; @@ -62,17 +45,17 @@ public async Task SendAsync(MailMessage message) private async Task SendAlertEmailIfNecessaryAsync(EmailQuota emailQuota) { - var currentUsagePercentage = emailQuota.CurrentUsagePercentage(_emailQuotaService.GetEmailQuotaPerMonth()); - if (!_emailQuotaService.ShouldSendReminderEmail(emailQuota, currentUsagePercentage)) return; + var currentUsagePercentage = emailQuota.CurrentUsagePercentage(emailQuotaService.GetEmailQuotaPerMonth()); + if (!emailQuotaService.ShouldSendReminderEmail(emailQuota, currentUsagePercentage)) return; - var siteOwnerEmails = (await _emailQuotaService.GetUserEmailsForEmailReminderAsync()).ToList(); + var siteOwnerEmails = (await emailQuotaService.GetUserEmailsForEmailReminderAsync()).ToList(); if (currentUsagePercentage >= 100) { await SendQuotaEmailAsync( emailQuota, siteOwnerEmails, "EmailQuotaExceededError", - _emailQuotaSubjectService.GetExceededEmailSubject(), + emailQuotaSubjectService.GetExceededEmailSubject(), currentUsagePercentage); return; } @@ -81,7 +64,7 @@ await SendQuotaEmailAsync( emailQuota, siteOwnerEmails, $"EmailQuotaWarning", - _emailQuotaSubjectService.GetWarningEmailSubject(currentUsagePercentage), + emailQuotaSubjectService.GetWarningEmailSubject(currentUsagePercentage), currentUsagePercentage); } @@ -102,17 +85,17 @@ private Task SendQuotaEmailAsync( ShellScope.AddDeferredTask(async _ => { emailMessage.To = siteOwnerEmail; - emailMessage.Body = await _emailTemplateService.RenderEmailTemplateAsync(emailTemplateName, new + emailMessage.Body = await emailTemplateService.RenderEmailTemplateAsync(emailTemplateName, new { - HostName = _shellSettings.Name, + HostName = shellSettings.Name, Percentage = percentage, }); // ISmtpService must be used within this class otherwise it won't call the original ISmtpService // implementation, but loop back to here. - await _smtpService.SendAsync(emailMessage); + await smtpService.SendAsync(emailMessage); }); } - return _emailQuotaService.SetQuotaOnEmailReminderAsync(emailQuota); + return emailQuotaService.SetQuotaOnEmailReminderAsync(emailQuota); } } diff --git a/Lombiq.Hosting.Tenants.EmailQuotaManagement/Startup.cs b/Lombiq.Hosting.Tenants.EmailQuotaManagement/Startup.cs index abeebcbf..3fadfb6a 100644 --- a/Lombiq.Hosting.Tenants.EmailQuotaManagement/Startup.cs +++ b/Lombiq.Hosting.Tenants.EmailQuotaManagement/Startup.cs @@ -16,20 +16,15 @@ namespace Lombiq.Hosting.Tenants.EmailQuotaManagement; [Feature(FeatureNames.EmailQuotaManagement)] -public class Startup : StartupBase +public class Startup(IShellConfiguration shellConfiguration) : StartupBase { - private readonly IShellConfiguration _shellConfiguration; - - public Startup(IShellConfiguration shellConfiguration) => - _shellConfiguration = shellConfiguration; - public override void ConfigureServices(IServiceCollection services) { services.AddDataMigration(); services.AddSingleton(); services.Configure(options => - options.EmailQuotaPerMonth = _shellConfiguration.GetValue("Lombiq_Hosting_Tenants_EmailQuotaManagement:EmailQuotaPerMonth") + options.EmailQuotaPerMonth = shellConfiguration.GetValue("Lombiq_Hosting_Tenants_EmailQuotaManagement:EmailQuotaPerMonth") ?? DefaultEmailQuota); services.Configure(options => diff --git a/Lombiq.Hosting.Tenants.EnvironmentRobots/Filters/EnvironmentRobotsMetaTagFilter.cs b/Lombiq.Hosting.Tenants.EnvironmentRobots/Filters/EnvironmentRobotsMetaTagFilter.cs index ee924d8a..63de9a36 100644 --- a/Lombiq.Hosting.Tenants.EnvironmentRobots/Filters/EnvironmentRobotsMetaTagFilter.cs +++ b/Lombiq.Hosting.Tenants.EnvironmentRobots/Filters/EnvironmentRobotsMetaTagFilter.cs @@ -7,21 +7,14 @@ namespace Lombiq.Hosting.Tenants.EnvironmentRobots.Filters; -public class EnvironmentRobotsMetaTagFilter : IResultFilter +public class EnvironmentRobotsMetaTagFilter( + IHostEnvironment hostEnvironment, + IOptions options, + IResourceManager resourceManager) : IResultFilter { - private readonly IHostEnvironment _hostEnvironment; - private readonly IOptions _options; - private readonly IResourceManager _resourceManager; - - public EnvironmentRobotsMetaTagFilter( - IHostEnvironment hostEnvironment, - IOptions options, - IResourceManager resourceManager) - { - _hostEnvironment = hostEnvironment; - _options = options; - _resourceManager = resourceManager; - } + private readonly IHostEnvironment _hostEnvironment = hostEnvironment; + private readonly IOptions _options = options; + private readonly IResourceManager _resourceManager = resourceManager; public void OnResultExecuting(ResultExecutingContext context) { diff --git a/Lombiq.Hosting.Tenants.EnvironmentRobots/Middlewares/EnvironmentRobotsMiddleware.cs b/Lombiq.Hosting.Tenants.EnvironmentRobots/Middlewares/EnvironmentRobotsMiddleware.cs index 5d9a96f0..ecf6ad92 100644 --- a/Lombiq.Hosting.Tenants.EnvironmentRobots/Middlewares/EnvironmentRobotsMiddleware.cs +++ b/Lombiq.Hosting.Tenants.EnvironmentRobots/Middlewares/EnvironmentRobotsMiddleware.cs @@ -9,25 +9,14 @@ namespace Lombiq.Hosting.Tenants.EnvironmentRobots.Middlewares; -public class EnvironmentRobotsMiddleware +public class EnvironmentRobotsMiddleware( + RequestDelegate next, + IHostEnvironment hostEnvironment, + IOptions options) { - private readonly RequestDelegate _next; - private readonly IHostEnvironment _hostEnvironment; - private readonly IOptions _options; - - public EnvironmentRobotsMiddleware( - RequestDelegate next, - IHostEnvironment hostEnvironment, - IOptions options) - { - _next = next; - _hostEnvironment = hostEnvironment; - _options = options; - } - public Task InvokeAsync(HttpContext context) { - if (!_hostEnvironment.IsProductionWithConfiguration(_options)) + if (!hostEnvironment.IsProductionWithConfiguration(options)) { var headerValue = context.Response.Headers["X-Robots-Tag"].FirstOrDefault() ?? string.Empty; @@ -57,6 +46,6 @@ public Task InvokeAsync(HttpContext context) } } - return _next(context); + return next(context); } } diff --git a/Lombiq.Hosting.Tenants.EnvironmentRobots/Startup.cs b/Lombiq.Hosting.Tenants.EnvironmentRobots/Startup.cs index d978e6e7..bdea74d4 100644 --- a/Lombiq.Hosting.Tenants.EnvironmentRobots/Startup.cs +++ b/Lombiq.Hosting.Tenants.EnvironmentRobots/Startup.cs @@ -13,17 +13,12 @@ namespace Lombiq.Hosting.Tenants.EnvironmentRobots; [Feature(FeatureNames.EnvironmentRobots)] -public class Startup : StartupBase +public class Startup(IShellConfiguration shellConfiguration) : StartupBase { - private readonly IShellConfiguration _shellConfiguration; - - public Startup(IShellConfiguration shellConfiguration) => - _shellConfiguration = shellConfiguration; - public override void ConfigureServices(IServiceCollection services) { var options = new EnvironmentRobotsOptions(); - var configSection = _shellConfiguration + var configSection = shellConfiguration .GetSection("Lombiq_Hosting_Tenants_EnvironmentRobots:EnvironmentRobotsOptions"); configSection.Bind(options); services.Configure(configSection); diff --git a/Lombiq.Hosting.Tenants.FeaturesGuard/Handlers/FeaturesEventHandler.cs b/Lombiq.Hosting.Tenants.FeaturesGuard/Handlers/FeaturesEventHandler.cs index e9b6682e..87afdff0 100644 --- a/Lombiq.Hosting.Tenants.FeaturesGuard/Handlers/FeaturesEventHandler.cs +++ b/Lombiq.Hosting.Tenants.FeaturesGuard/Handlers/FeaturesEventHandler.cs @@ -97,7 +97,7 @@ private Task HandleConditionallyEnabledFeaturesAsync() throw new InvalidOperationException("'IsAlwaysEnabled' feature can't be disabled by FeaturesGuard."); } - if (!featuresToEnable.Any() && !featuresToDisable.Any()) + if (featuresToEnable.Count == 0 && featuresToDisable.Count == 0) { return; } @@ -119,7 +119,7 @@ private Task HandleConditionallyEnabledFeaturesAsync() /// private static bool TryGetFeaturesToBeEnabledAndDisabled( IDictionary> conditionallyEnabledFeatures, - IReadOnlySet enabledFeatureIds, + HashSet enabledFeatureIds, out HashSet featuresToEnable, out HashSet featuresToDisable) { @@ -152,6 +152,6 @@ private static bool TryGetFeaturesToBeEnabledAndDisabled( featuresToEnable = featuresToEnableIds; featuresToDisable = featuresToDisableIds; - return featuresToEnableIds.Any() || featuresToDisableIds.Any(); + return featuresToEnableIds.Count != 0 || featuresToDisableIds.Count != 0; } } diff --git a/Lombiq.Hosting.Tenants.FeaturesGuard/Startup.cs b/Lombiq.Hosting.Tenants.FeaturesGuard/Startup.cs index fdd8251e..31a53b33 100644 --- a/Lombiq.Hosting.Tenants.FeaturesGuard/Startup.cs +++ b/Lombiq.Hosting.Tenants.FeaturesGuard/Startup.cs @@ -10,12 +10,9 @@ namespace Lombiq.Hosting.Tenants.FeaturesGuard; [Feature(FeatureNames.FeaturesGuard)] -public class Startup : StartupBase +public class Startup(IShellConfiguration shellConfiguration) : StartupBase { - private readonly IShellConfiguration _shellConfiguration; - - public Startup(IConfiguration configuration, IShellConfiguration shellConfiguration) => - _shellConfiguration = shellConfiguration; + private readonly IShellConfiguration _shellConfiguration = shellConfiguration; public override void ConfigureServices(IServiceCollection services) { diff --git a/Lombiq.Hosting.Tenants.IdleTenantManagement/Middlewares/IdleTimeProviderMiddleware.cs b/Lombiq.Hosting.Tenants.IdleTenantManagement/Middlewares/IdleTimeProviderMiddleware.cs index 76d1ac7e..d2243cb0 100644 --- a/Lombiq.Hosting.Tenants.IdleTenantManagement/Middlewares/IdleTimeProviderMiddleware.cs +++ b/Lombiq.Hosting.Tenants.IdleTenantManagement/Middlewares/IdleTimeProviderMiddleware.cs @@ -1,4 +1,4 @@ -using Lombiq.Hosting.Tenants.IdleTenantManagement.Services; +using Lombiq.Hosting.Tenants.IdleTenantManagement.Services; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using OrchardCore.Modules; @@ -6,16 +6,12 @@ namespace Lombiq.Hosting.Tenants.IdleTenantManagement.Middlewares; -public class IdleTimeProviderMiddleware +public class IdleTimeProviderMiddleware(RequestDelegate next) { - private readonly RequestDelegate _next; - - public IdleTimeProviderMiddleware(RequestDelegate next) => _next = next; - public Task InvokeAsync(HttpContext context, ILastActiveTimeAccessor lastActiveTimeAccessor) { lastActiveTimeAccessor.Update(context.RequestServices.GetService()); - return _next(context); + return next(context); } } diff --git a/Lombiq.Hosting.Tenants.IdleTenantManagement/Services/IdleShutdown.cs b/Lombiq.Hosting.Tenants.IdleTenantManagement/Services/IdleShutdown.cs index 9639bc4b..22861214 100644 --- a/Lombiq.Hosting.Tenants.IdleTenantManagement/Services/IdleShutdown.cs +++ b/Lombiq.Hosting.Tenants.IdleTenantManagement/Services/IdleShutdown.cs @@ -1,4 +1,4 @@ -using Lombiq.Hosting.Tenants.IdleTenantManagement.Models; +using Lombiq.Hosting.Tenants.IdleTenantManagement.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OrchardCore.Environment.Shell; @@ -7,44 +7,27 @@ namespace Lombiq.Hosting.Tenants.IdleTenantManagement.Services; -public class IdleShutdown : IIdleShutdown +public class IdleShutdown( + IOptions options, + ShellSettings shellSettings, + IClock clock, + ILastActiveTimeAccessor lastActiveTimeAccessor, + ILogger logger, + IShellHost shellHost) : IIdleShutdown { - private readonly IOptions _options; - private readonly ShellSettings _shellSettings; - private readonly IClock _clock; - private readonly ILastActiveTimeAccessor _lastActiveTimeAccessor; - private readonly ILogger _logger; - private readonly IShellHost _shellHost; - - public IdleShutdown( - IOptions options, - ShellSettings shellSettings, - IClock clock, - ILastActiveTimeAccessor lastActiveTimeAccessor, - ILogger logger, - IShellHost shellHost) - { - _options = options; - _shellSettings = shellSettings; - _clock = clock; - _lastActiveTimeAccessor = lastActiveTimeAccessor; - _logger = logger; - _shellHost = shellHost; - } - public async Task ShutDownIdleTenantsAsync() { - var maxIdleMinutes = _options.Value.MaxIdleMinutes; + var maxIdleMinutes = options.Value.MaxIdleMinutes; - if (maxIdleMinutes <= 0 || _shellSettings.IsDefaultShell()) return; + if (maxIdleMinutes <= 0 || shellSettings.IsDefaultShell()) return; - var lastActiveDateTimeUtc = _lastActiveTimeAccessor.LastActiveDateTimeUtc; + var lastActiveDateTimeUtc = lastActiveTimeAccessor.LastActiveDateTimeUtc; - if (lastActiveDateTimeUtc.AddMinutes(maxIdleMinutes) <= _clock?.UtcNow) + if (lastActiveDateTimeUtc.AddMinutes(maxIdleMinutes) <= clock?.UtcNow) { - _logger?.LogInformation("Shutting down tenant \"{ShellName}\" because of idle timeout.", _shellSettings.Name); + logger?.LogInformation("Shutting down tenant \"{ShellName}\" because of idle timeout.", shellSettings.Name); - await _shellHost.ReleaseShellContextAsync(_shellSettings, eventSource: false); + await shellHost.ReleaseShellContextAsync(shellSettings, eventSource: false); } } } diff --git a/Lombiq.Hosting.Tenants.IdleTenantManagement/Startup.cs b/Lombiq.Hosting.Tenants.IdleTenantManagement/Startup.cs index 43f4fe8f..b4ac8e90 100644 --- a/Lombiq.Hosting.Tenants.IdleTenantManagement/Startup.cs +++ b/Lombiq.Hosting.Tenants.IdleTenantManagement/Startup.cs @@ -14,13 +14,8 @@ namespace Lombiq.Hosting.Tenants.IdleTenantManagement; [Feature(FeatureNames.ShutDownIdleTenants)] -public class ShutDownIdleTenantsStartup : StartupBase +public class ShutDownIdleTenantsStartup(IShellConfiguration shellConfiguration) : StartupBase { - private readonly IShellConfiguration _shellConfiguration; - - public ShutDownIdleTenantsStartup(IShellConfiguration shellConfiguration) => - _shellConfiguration = shellConfiguration; - public override void Configure( IApplicationBuilder app, IEndpointRouteBuilder routes, @@ -35,7 +30,7 @@ public override void ConfigureServices(IServiceCollection services) // Idle Minutes Settings services.Configure(options => - _shellConfiguration + shellConfiguration .GetSection("Lombiq_Hosting_Tenants_IdleTenantManagement:IdleShutdownOptions") .Bind(options)); } diff --git a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/AddSiteOwnerPermissionToRole/AddSiteOwnerPermissionToRoleMaintenanceProvider.cs b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/AddSiteOwnerPermissionToRole/AddSiteOwnerPermissionToRoleMaintenanceProvider.cs index d346d9ea..68eab3cf 100644 --- a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/AddSiteOwnerPermissionToRole/AddSiteOwnerPermissionToRoleMaintenanceProvider.cs +++ b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/AddSiteOwnerPermissionToRole/AddSiteOwnerPermissionToRoleMaintenanceProvider.cs @@ -10,32 +10,23 @@ namespace Lombiq.Hosting.Tenants.Maintenance.Maintenance.AddSiteOwnerPermissionToRole; -public class AddSiteOwnerPermissionToRoleMaintenanceProvider : MaintenanceProviderBase +public class AddSiteOwnerPermissionToRoleMaintenanceProvider( + IOptions options, + RoleManager roleManager) : MaintenanceProviderBase { - private readonly IOptions _options; - private readonly RoleManager _roleManager; - - public AddSiteOwnerPermissionToRoleMaintenanceProvider( - IOptions options, - RoleManager roleManager) - { - _options = options; - _roleManager = roleManager; - } - public override Task ShouldExecuteAsync(MaintenanceTaskExecutionContext context) => Task.FromResult( - _options.Value.IsEnabled && + options.Value.IsEnabled && !context.WasLatestExecutionSuccessful()); public override async Task ExecuteAsync(MaintenanceTaskExecutionContext context) { - if (await _roleManager.FindByNameAsync(_options.Value.Role) is not Role role) return; + if (await roleManager.FindByNameAsync(options.Value.Role) is not Role role) return; if (role.RoleClaims.Exists(claim => claim.ClaimType == ClaimType && claim.ClaimValue == SiteOwner.Name)) return; role.RoleClaims.Add(new RoleClaim { ClaimType = ClaimType, ClaimValue = SiteOwner.Name }); - await _roleManager.UpdateAsync(role); + await roleManager.UpdateAsync(role); } } diff --git a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/AddSiteOwnerPermissionToRole/Startup.cs b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/AddSiteOwnerPermissionToRole/Startup.cs index 4722717d..24487a73 100644 --- a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/AddSiteOwnerPermissionToRole/Startup.cs +++ b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/AddSiteOwnerPermissionToRole/Startup.cs @@ -8,17 +8,12 @@ namespace Lombiq.Hosting.Tenants.Maintenance.Maintenance.AddSiteOwnerPermissionToRole; [Feature(FeatureNames.AddSiteOwnerPermissionToRole)] -public class Startup : StartupBase +public class Startup(IShellConfiguration shellConfiguration) : StartupBase { - private readonly IShellConfiguration _shellConfiguration; - - public Startup(IShellConfiguration shellConfiguration) => - _shellConfiguration = shellConfiguration; - public override void ConfigureServices(IServiceCollection services) { var options = new AddSiteOwnerPermissionToRoleMaintenanceOptions(); - var configSection = _shellConfiguration.GetSection("Lombiq_Hosting_Tenants_Maintenance:AddSiteOwnerPermissionToRole"); + var configSection = shellConfiguration.GetSection("Lombiq_Hosting_Tenants_Maintenance:AddSiteOwnerPermissionToRole"); configSection.Bind(options); services.Configure(configSection); diff --git a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/ChangeUserSensitiveContent/ChangeUserSensitiveContentMaintenanceProvider.cs b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/ChangeUserSensitiveContent/ChangeUserSensitiveContentMaintenanceProvider.cs index 0327d3f4..c574b882 100644 --- a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/ChangeUserSensitiveContent/ChangeUserSensitiveContentMaintenanceProvider.cs +++ b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/ChangeUserSensitiveContent/ChangeUserSensitiveContentMaintenanceProvider.cs @@ -15,39 +15,24 @@ namespace Lombiq.Hosting.Tenants.Maintenance.Maintenance.ChangeUserSensitiveContent; -public class ChangeUserSensitiveContentMaintenanceProvider : MaintenanceProviderBase +public class ChangeUserSensitiveContentMaintenanceProvider( + IOptions options, + ISession session, + UserManager userManager, + IPasswordHasher passwordHasher, + ShellSettings shellSettings) : MaintenanceProviderBase { - private readonly IOptions _options; - private readonly ISession _session; - private readonly UserManager _userManager; - private readonly IPasswordHasher _passwordHasher; - private readonly ShellSettings _shellSettings; - - public ChangeUserSensitiveContentMaintenanceProvider( - IOptions options, - ISession session, - UserManager userManager, - IPasswordHasher passwordHasher, - ShellSettings shellSettings) - { - _options = options; - _session = session; - _userManager = userManager; - _passwordHasher = passwordHasher; - _shellSettings = shellSettings; - } - public override Task ShouldExecuteAsync(MaintenanceTaskExecutionContext context) => Task.FromResult( - _options.Value.IsEnabled && + options.Value.IsEnabled && !context.WasLatestExecutionSuccessful() && - _options.Value.TenantNames.Replace(" ", string.Empty).SplitByCommas().Contains(_shellSettings.Name)); + options.Value.TenantNames.Replace(" ", string.Empty).SplitByCommas().Contains(shellSettings.Name)); public override async Task ExecuteAsync(MaintenanceTaskExecutionContext context) { var randomNameGenerator = new PersonNameGenerator(); - var users = await _session.Query().ListAsync(); + var users = await session.Query().ListAsync(); foreach (var user in users.Where(user => !user.Email.Trim().EndsWith($"@lombiq.com", StringComparison.InvariantCulture))) { @@ -60,9 +45,9 @@ public override async Task ExecuteAsync(MaintenanceTaskExecutionContext context) user.NormalizedUserName = formattedFullName.ToUpperInvariant(); user.Email = formattedEmail; user.NormalizedEmail = formattedEmail.ToUpperInvariant(); - user.PasswordHash = _passwordHasher.HashPassword(user, GenerateRandomPassword(32)); + user.PasswordHash = passwordHasher.HashPassword(user, GenerateRandomPassword(32)); - await _userManager.UpdateAsync(user); + await userManager.UpdateAsync(user); } } diff --git a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/ChangeUserSensitiveContent/Startup.cs b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/ChangeUserSensitiveContent/Startup.cs index 23e7e97e..905e1ea3 100644 --- a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/ChangeUserSensitiveContent/Startup.cs +++ b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/ChangeUserSensitiveContent/Startup.cs @@ -8,17 +8,12 @@ namespace Lombiq.Hosting.Tenants.Maintenance.Maintenance.ChangeUserSensitiveContent; [Feature(FeatureNames.ChangeUserSensitiveContent)] -public class Startup : StartupBase +public class Startup(IShellConfiguration shellConfiguration) : StartupBase { - private readonly IShellConfiguration _shellConfiguration; - - public Startup(IShellConfiguration shellConfiguration) => - _shellConfiguration = shellConfiguration; - public override void ConfigureServices(IServiceCollection services) { var options = new ChangeUserSensitiveContentMaintenanceOptions(); - var configSection = _shellConfiguration + var configSection = shellConfiguration .GetSection("Lombiq_Hosting_Tenants_Maintenance:ChangeUserSensitiveContent"); configSection.Bind(options); services.Configure(configSection); diff --git a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/RemoveUsers/RemoveUsersMaintenanceProvider.cs b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/RemoveUsers/RemoveUsersMaintenanceProvider.cs index 61820da9..c38e7717 100644 --- a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/RemoveUsers/RemoveUsersMaintenanceProvider.cs +++ b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/RemoveUsers/RemoveUsersMaintenanceProvider.cs @@ -12,34 +12,23 @@ namespace Lombiq.Hosting.Tenants.Maintenance.Maintenance.RemoveUsers; -public class RemoveUsersMaintenanceProvider : MaintenanceProviderBase +public class RemoveUsersMaintenanceProvider( + IOptions options, + ISession session, + UserManager userManager) : MaintenanceProviderBase { - private readonly IOptions _options; - private readonly ISession _session; - private readonly UserManager _userManager; - - public RemoveUsersMaintenanceProvider( - IOptions options, - ISession session, - UserManager userManager) - { - _options = options; - _session = session; - _userManager = userManager; - } - public override Task ShouldExecuteAsync(MaintenanceTaskExecutionContext context) => Task.FromResult( - _options.Value.IsEnabled && + options.Value.IsEnabled && !context.WasLatestExecutionSuccessful()); public override async Task ExecuteAsync(MaintenanceTaskExecutionContext context) { - var users = await _session.Query().ListAsync(); + var users = await session.Query().ListAsync(); foreach (var user in users.Where(user => - user.Email.EndsWith($"@{_options.Value.EmailDomain}", StringComparison.InvariantCulture))) + user.Email.EndsWith($"@{options.Value.EmailDomain}", StringComparison.InvariantCulture))) { - await _userManager.DeleteAsync(user); + await userManager.DeleteAsync(user); } } } diff --git a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/RemoveUsers/Startup.cs b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/RemoveUsers/Startup.cs index 58fa4760..ed3d1c62 100644 --- a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/RemoveUsers/Startup.cs +++ b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/RemoveUsers/Startup.cs @@ -8,17 +8,12 @@ namespace Lombiq.Hosting.Tenants.Maintenance.Maintenance.RemoveUsers; [Feature(FeatureNames.RemoveUsers)] -public class Startup : StartupBase +public class Startup(IShellConfiguration shellConfiguration) : StartupBase { - private readonly IShellConfiguration _shellConfiguration; - - public Startup(IShellConfiguration shellConfiguration) => - _shellConfiguration = shellConfiguration; - public override void ConfigureServices(IServiceCollection services) { var options = new RemoveUsersMaintenanceOptions(); - var configSection = _shellConfiguration.GetSection("Lombiq_Hosting_Tenants_Maintenance:RemoveUsers"); + var configSection = shellConfiguration.GetSection("Lombiq_Hosting_Tenants_Maintenance:RemoveUsers"); configSection.Bind(options); services.Configure(configSection); diff --git a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/UpdateShellRequestUrl/Startup.cs b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/UpdateShellRequestUrl/Startup.cs index 2b21fa1e..26fcf43e 100644 --- a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/UpdateShellRequestUrl/Startup.cs +++ b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/UpdateShellRequestUrl/Startup.cs @@ -8,17 +8,12 @@ namespace Lombiq.Hosting.Tenants.Maintenance.Maintenance.UpdateShellRequestUrl; [Feature(FeatureNames.UpdateShellRequestUrls)] -public class Startup : StartupBase +public class Startup(IShellConfiguration shellConfiguration) : StartupBase { - private readonly IShellConfiguration _shellConfiguration; - - public Startup(IShellConfiguration shellConfiguration) => - _shellConfiguration = shellConfiguration; - public override void ConfigureServices(IServiceCollection services) { var options = new UpdateShellRequestUrlMaintenanceOptions(); - var configSection = _shellConfiguration.GetSection("Lombiq_Hosting_Tenants_Maintenance:UpdateShellRequestUrl"); + var configSection = shellConfiguration.GetSection("Lombiq_Hosting_Tenants_Maintenance:UpdateShellRequestUrl"); configSection.Bind(options); services.Configure(configSection); diff --git a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/UpdateShellRequestUrl/UpdateShellRequestUrlsMaintenanceProvider.cs b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/UpdateShellRequestUrl/UpdateShellRequestUrlsMaintenanceProvider.cs index 6d7759c5..13e56bc4 100644 --- a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/UpdateShellRequestUrl/UpdateShellRequestUrlsMaintenanceProvider.cs +++ b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/UpdateShellRequestUrl/UpdateShellRequestUrlsMaintenanceProvider.cs @@ -8,45 +8,32 @@ namespace Lombiq.Hosting.Tenants.Maintenance.Maintenance.UpdateShellRequestUrl; -public class UpdateShellRequestUrlsMaintenanceProvider : MaintenanceProviderBase +public class UpdateShellRequestUrlsMaintenanceProvider( + ShellSettings shellSettings, + IOptions options, + IShellSettingsManager shellSettingsManager, + IShellHost shellHost) : MaintenanceProviderBase { - private readonly ShellSettings _shellSettings; - private readonly IOptions _options; - private readonly IShellSettingsManager _shellSettingsManager; - private readonly IShellHost _shellHost; - - public UpdateShellRequestUrlsMaintenanceProvider( - ShellSettings shellSettings, - IOptions options, - IShellSettingsManager shellSettingsManager, - IShellHost shellHost) - { - _shellSettings = shellSettings; - _options = options; - _shellSettingsManager = shellSettingsManager; - _shellHost = shellHost; - } - public override Task ShouldExecuteAsync(MaintenanceTaskExecutionContext context) => - Task.FromResult(_options.Value.IsEnabled && - _shellSettings.IsDefaultShell() && + Task.FromResult(options.Value.IsEnabled && + shellSettings.IsDefaultShell() && !context.WasLatestExecutionSuccessful()); public override async Task ExecuteAsync(MaintenanceTaskExecutionContext context) { - var allShellSettings = await _shellSettingsManager.LoadSettingsAsync(); - foreach (var shellSettings in allShellSettings) + var allShellSettings = await shellSettingsManager.LoadSettingsAsync(); + foreach (var settings in allShellSettings) { - shellSettings.RequestUrlHost = TenantUrlHelpers.GetEvaluatedValueForTenant( - _options.Value.DefaultShellRequestUrl, - _options.Value.RequestUrl, - shellSettings); - shellSettings.RequestUrlPrefix = TenantUrlHelpers.GetEvaluatedValueForTenant( - _options.Value.DefaultShellRequestUrlPrefix, - _options.Value.RequestUrlPrefix, - shellSettings); + settings.RequestUrlHost = TenantUrlHelpers.GetEvaluatedValueForTenant( + options.Value.DefaultShellRequestUrl, + options.Value.RequestUrl, + settings); + settings.RequestUrlPrefix = TenantUrlHelpers.GetEvaluatedValueForTenant( + options.Value.DefaultShellRequestUrlPrefix, + options.Value.RequestUrlPrefix, + settings); - await _shellHost.UpdateShellSettingsAsync(shellSettings); + await shellHost.UpdateShellSettingsAsync(settings); } context.ReloadShellAfterMaintenanceCompletion = true; diff --git a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/UpdateSiteUrl/Startup.cs b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/UpdateSiteUrl/Startup.cs index ff86c21c..717ed5c4 100644 --- a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/UpdateSiteUrl/Startup.cs +++ b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/UpdateSiteUrl/Startup.cs @@ -8,17 +8,12 @@ namespace Lombiq.Hosting.Tenants.Maintenance.Maintenance.UpdateSiteUrl; [Feature(FeatureNames.UpdateSiteUrl)] -public class Startup : StartupBase +public class Startup(IShellConfiguration shellConfiguration) : StartupBase { - private readonly IShellConfiguration _shellConfiguration; - - public Startup(IShellConfiguration shellConfiguration) => - _shellConfiguration = shellConfiguration; - public override void ConfigureServices(IServiceCollection services) { var options = new UpdateSiteUrlMaintenanceOptions(); - var configSection = _shellConfiguration.GetSection("Lombiq_Hosting_Tenants_Maintenance:UpdateSiteUrl"); + var configSection = shellConfiguration.GetSection("Lombiq_Hosting_Tenants_Maintenance:UpdateSiteUrl"); configSection.Bind(options); services.Configure(configSection); diff --git a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/UpdateSiteUrl/UpdateSiteUrlMaintenanceProvider.cs b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/UpdateSiteUrl/UpdateSiteUrlMaintenanceProvider.cs index f27eca5c..97e111e4 100644 --- a/Lombiq.Hosting.Tenants.Maintenance/Maintenance/UpdateSiteUrl/UpdateSiteUrlMaintenanceProvider.cs +++ b/Lombiq.Hosting.Tenants.Maintenance/Maintenance/UpdateSiteUrl/UpdateSiteUrlMaintenanceProvider.cs @@ -9,34 +9,23 @@ namespace Lombiq.Hosting.Tenants.Maintenance.Maintenance.UpdateSiteUrl; -public class UpdateSiteUrlMaintenanceProvider : MaintenanceProviderBase +public class UpdateSiteUrlMaintenanceProvider( + ISiteService siteService, + ShellSettings shellSettings, + IOptions options) : MaintenanceProviderBase { - private readonly ISiteService _siteService; - private readonly ShellSettings _shellSettings; - private readonly IOptions _options; - - public UpdateSiteUrlMaintenanceProvider( - ISiteService siteService, - ShellSettings shellSettings, - IOptions options) - { - _siteService = siteService; - _shellSettings = shellSettings; - _options = options; - } - public override Task ShouldExecuteAsync(MaintenanceTaskExecutionContext context) => - Task.FromResult(_options.Value.IsEnabled && !context.WasLatestExecutionSuccessful()); + Task.FromResult(options.Value.IsEnabled && !context.WasLatestExecutionSuccessful()); public override async Task ExecuteAsync(MaintenanceTaskExecutionContext context) { - var siteSettings = await _siteService.LoadSiteSettingsAsync(); + var siteSettings = await siteService.LoadSiteSettingsAsync(); siteSettings.BaseUrl = TenantUrlHelpers.GetEvaluatedValueForTenant( - _options.Value.DefaultTenantSiteUrl, - _options.Value.SiteUrl, - _shellSettings, - _options.Value.SiteUrlFromTenantName); + options.Value.DefaultTenantSiteUrl, + options.Value.SiteUrl, + shellSettings, + options.Value.SiteUrlFromTenantName); - await _siteService.UpdateSiteSettingsAsync(siteSettings); + await siteService.UpdateSiteSettingsAsync(siteSettings); } } diff --git a/Lombiq.Hosting.Tenants.Maintenance/Services/MaintenanceManager.cs b/Lombiq.Hosting.Tenants.Maintenance/Services/MaintenanceManager.cs index dcc9ce1f..be1bea6d 100644 --- a/Lombiq.Hosting.Tenants.Maintenance/Services/MaintenanceManager.cs +++ b/Lombiq.Hosting.Tenants.Maintenance/Services/MaintenanceManager.cs @@ -12,46 +12,29 @@ namespace Lombiq.Hosting.Tenants.Maintenance.Services; -public class MaintenanceManager : IMaintenanceManager +public class MaintenanceManager( + IOrchardClock clock, + ILogger logger, + IEnumerable maintenanceProviders, + ISession session, + IShellHost shellHost, + ShellSettings shellSettings) : IMaintenanceManager { - private readonly IOrchardClock _clock; - private readonly ILogger _logger; - private readonly IEnumerable _maintenanceProviders; - private readonly ISession _session; - private readonly IShellHost _shellHost; - private readonly ShellSettings _shellSettings; - - public MaintenanceManager( - IOrchardClock clock, - ILogger logger, - IEnumerable maintenanceProviders, - ISession session, - IShellHost shellHost, - ShellSettings shellSettings) - { - _clock = clock; - _logger = logger; - _maintenanceProviders = maintenanceProviders; - _session = session; - _shellHost = shellHost; - _shellSettings = shellSettings; - } - public Task GetLatestExecutionByMaintenanceIdAsync(string maintenanceId) => - _session.Query(collection: DocumentCollections.Maintenance) + session.Query(collection: DocumentCollections.Maintenance) .Where(execution => execution.MaintenanceId == maintenanceId) .OrderByDescending(execution => execution.ExecutionTimeUtc) .FirstOrDefaultAsync(); public async Task ExecuteMaintenanceTasksAsync() { - var orderedProviders = _maintenanceProviders.OrderBy(provider => provider.Order); + var orderedProviders = maintenanceProviders.OrderBy(provider => provider.Order); foreach (var provider in orderedProviders) { var currentExecution = new MaintenanceTaskExecutionData { MaintenanceId = provider.Id, - ExecutionTimeUtc = _clock.UtcNow, + ExecutionTimeUtc = clock.UtcNow, }; var context = new MaintenanceTaskExecutionContext { @@ -68,7 +51,7 @@ private async Task ExecuteMaintenanceTaskIfNeededAsync( MaintenanceTaskExecutionContext context, MaintenanceTaskExecutionData execution) { - _logger.LogDebug("Executing maintenance task {MaintenanceId}, if needed.", provider.Id); + logger.LogDebug("Executing maintenance task {MaintenanceId}, if needed.", provider.Id); if (await provider.ShouldExecuteAsync(context)) { @@ -78,11 +61,11 @@ private async Task ExecuteMaintenanceTaskIfNeededAsync( execution.IsSuccess = string.IsNullOrEmpty(execution.Error); if (execution.IsSuccess) { - _logger.LogDebug("Maintenance task {MaintenanceId} executed successfully.", provider.Id); + logger.LogDebug("Maintenance task {MaintenanceId} executed successfully.", provider.Id); } else { - _logger.LogError( + logger.LogError( "Maintenance task {MaintenanceId} executed with error: {Error}", provider.Id, execution.Error); @@ -93,20 +76,20 @@ private async Task ExecuteMaintenanceTaskIfNeededAsync( execution.IsSuccess = false; execution.Error = exception.ToString(); - _logger.LogError( + logger.LogError( exception, "Maintenance task {MaintenanceId} failed to execute due to an exception.", provider.Id); } - await _session.SaveAsync(execution, collection: DocumentCollections.Maintenance); - await _session.SaveChangesAsync(); + await session.SaveAsync(execution, collection: DocumentCollections.Maintenance); + await session.SaveChangesAsync(); - if (context.ReloadShellAfterMaintenanceCompletion) await _shellHost.ReloadShellContextAsync(_shellSettings); + if (context.ReloadShellAfterMaintenanceCompletion) await shellHost.ReloadShellContextAsync(shellSettings); } else { - _logger.LogDebug("Maintenance task {MaintenanceId} is not needed.", provider.Id); + logger.LogDebug("Maintenance task {MaintenanceId} is not needed.", provider.Id); } } } diff --git a/Lombiq.Hosting.Tenants.Maintenance/Services/MaintenanceRunnerService.cs b/Lombiq.Hosting.Tenants.Maintenance/Services/MaintenanceRunnerService.cs index 2ef3fc85..a78953d4 100644 --- a/Lombiq.Hosting.Tenants.Maintenance/Services/MaintenanceRunnerService.cs +++ b/Lombiq.Hosting.Tenants.Maintenance/Services/MaintenanceRunnerService.cs @@ -7,29 +7,18 @@ namespace Lombiq.Hosting.Tenants.Maintenance.Services; -public class MaintenanceRunnerService : ModularTenantEvents +public class MaintenanceRunnerService( + ShellSettings shellSettings, + ILogger logger, + Lazy maintenanceManagerLazy) : ModularTenantEvents { - private readonly ShellSettings _shellSettings; - private readonly ILogger _logger; - private readonly Lazy _maintenanceManagerLazy; - - public MaintenanceRunnerService( - ShellSettings shellSettings, - ILogger logger, - Lazy maintenanceManagerLazy) - { - _shellSettings = shellSettings; - _logger = logger; - _maintenanceManagerLazy = maintenanceManagerLazy; - } - public override async Task ActivatedAsync() { - if (_shellSettings.State != TenantState.Running) return; + if (shellSettings.State != TenantState.Running) return; - _logger.LogDebug( + logger.LogDebug( "Executing maintenance tasks on shell '{ShellName}'.", - _shellSettings.Name); - await _maintenanceManagerLazy.Value.ExecuteMaintenanceTasksAsync(); + shellSettings.Name); + await maintenanceManagerLazy.Value.ExecuteMaintenanceTasksAsync(); } } diff --git a/Lombiq.Hosting.Tenants.Management/Controllers/ShellSettingsEditorController.cs b/Lombiq.Hosting.Tenants.Management/Controllers/ShellSettingsEditorController.cs index 8b4df56e..f6d10f63 100644 --- a/Lombiq.Hosting.Tenants.Management/Controllers/ShellSettingsEditorController.cs +++ b/Lombiq.Hosting.Tenants.Management/Controllers/ShellSettingsEditorController.cs @@ -1,4 +1,4 @@ -using Lombiq.Hosting.Tenants.Management.Constants; +using Lombiq.Hosting.Tenants.Management.Constants; using Lombiq.Hosting.Tenants.Management.Models; using Lombiq.Hosting.Tenants.Management.Service; using Microsoft.AspNetCore.Authorization; @@ -22,37 +22,20 @@ namespace Lombiq.Hosting.Tenants.Management.Controllers; [Feature(FeatureNames.ShellSettingsEditor)] -public class ShellSettingsEditorController : Controller +public class ShellSettingsEditorController( + IAuthorizationService authorizationService, + IShellHost shellHost, + IShellConfigurationSources shellConfigurationSources, + IDistributedLock distributedLock, + INotifier notifier, + IHtmlLocalizer htmlLocalizer) : Controller { - private readonly IAuthorizationService _authorizationService; - private readonly IShellHost _shellHost; - private readonly IShellConfigurationSources _shellConfigurationSources; - private readonly IDistributedLock _distributedLock; - private readonly INotifier _notifier; - private readonly IHtmlLocalizer H; - - public ShellSettingsEditorController( - IAuthorizationService authorizationService, - IShellHost shellHost, - IShellConfigurationSources shellConfigurationSources, - IDistributedLock distributedLock, - INotifier notifier, - IHtmlLocalizer htmlLocalizer) - { - _authorizationService = authorizationService; - _shellHost = shellHost; - _shellConfigurationSources = shellConfigurationSources; - _distributedLock = distributedLock; - _notifier = notifier; - H = htmlLocalizer; - } - [HttpPost] [ValidateAntiForgeryToken] public async Task Edit(ShellSettingsEditorViewModel model) { - if (!await _authorizationService.AuthorizeAsync(User, ManageTenants) || - !_shellHost.TryGetSettings(model.TenantId, out var shellSettings)) + if (!await authorizationService.AuthorizeAsync(User, ManageTenants) || + !shellHost.TryGetSettings(model.TenantId, out var shellSettings)) { return NotFound(); } @@ -60,7 +43,7 @@ public async Task Edit(ShellSettingsEditorViewModel model) model.Json ??= "{}"; if (!IsValidJson(model.Json)) { - await _notifier.ErrorAsync(H["Please provide valid JSON input for shell settings."]); + await notifier.ErrorAsync(htmlLocalizer["Please provide valid JSON input for shell settings."]); TempData["ValidationErrorJson"] = model.Json; return RedirectToAction( @@ -104,7 +87,7 @@ public async Task Edit(ShellSettingsEditorViewModel model) } var (locker, locked) = - await _distributedLock.TryAcquireLockAsync( + await distributedLock.TryAcquireLockAsync( "LOMBIQ_HOSTING_TENANTS_MANAGEMENT_SHELL_SETTINGS_EDITOR_LOCK", TimeSpan.FromSeconds(10)); @@ -119,8 +102,8 @@ await _distributedLock.TryAcquireLockAsync( // not save settings that has a key with multiple sections, see // https://github.com/OrchardCMS/OrchardCore/issues/14481. Once this is fixed, we can get rid of the locking and // retrieve and save the shell settings settings with IShellHost. - await _shellConfigurationSources.SaveAsync(shellSettings.Name, newTenantConfiguration); - await _shellHost.UpdateShellSettingsAsync(shellSettings); + await shellConfigurationSources.SaveAsync(shellSettings.Name, newTenantConfiguration); + await shellHost.UpdateShellSettingsAsync(shellSettings); return RedirectToAction( nameof(AdminController.Edit), diff --git a/Lombiq.Hosting.Tenants.Management/Extensions/LombiqHostingTenantsManagementExtensions.cs b/Lombiq.Hosting.Tenants.Management/Extensions/LombiqHostingTenantsManagementExtensions.cs index 52bdbf47..0982f8f2 100644 --- a/Lombiq.Hosting.Tenants.Management/Extensions/LombiqHostingTenantsManagementExtensions.cs +++ b/Lombiq.Hosting.Tenants.Management/Extensions/LombiqHostingTenantsManagementExtensions.cs @@ -1,6 +1,5 @@ using Lombiq.Hosting.Tenants.Management.Settings; using Microsoft.Extensions.DependencyInjection; -using System.Linq; using static Lombiq.Hosting.Tenants.Management.Constants.FeatureNames; namespace Lombiq.Hosting.Tenants.Management.Extensions; @@ -21,7 +20,7 @@ public static OrchardCoreBuilder HideRecipesByTagsFromSetup(this OrchardCoreBuil .ConfigureServices(services => services.Configure(options => { - if (tags.Any()) + if (tags.Length != 0) { options.HiddenTags = tags; } diff --git a/Lombiq.Hosting.Tenants.Management/Filters/ForbiddenTenantsFilter.cs b/Lombiq.Hosting.Tenants.Management/Filters/ForbiddenTenantsFilter.cs index e33c13ad..eaa24710 100644 --- a/Lombiq.Hosting.Tenants.Management/Filters/ForbiddenTenantsFilter.cs +++ b/Lombiq.Hosting.Tenants.Management/Filters/ForbiddenTenantsFilter.cs @@ -14,18 +14,11 @@ namespace Lombiq.Hosting.Tenants.Management.Filters; -public class ForbiddenTenantsFilter : IAsyncActionFilter +public class ForbiddenTenantsFilter( + IStringLocalizer stringLocalizer, + IOptions forbiddenTenantsOptions) : IAsyncActionFilter { - private readonly IStringLocalizer T; - private readonly IOptions _forbiddenTenantsOptions; - - public ForbiddenTenantsFilter( - IStringLocalizer stringLocalizer, - IOptions forbiddenTenantsOptions) - { - _forbiddenTenantsOptions = forbiddenTenantsOptions; - T = stringLocalizer; - } + private readonly IStringLocalizer T = stringLocalizer; public Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { @@ -44,18 +37,16 @@ public Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecuti return next(); } - var forbiddenRequestUrlHosts = _forbiddenTenantsOptions.Value.RequestUrlHosts; + var forbiddenRequestUrlHosts = forbiddenTenantsOptions.Value.RequestUrlHosts; if (forbiddenRequestUrlHosts != null && forbiddenRequestUrlHosts.Any()) { var requestUrlHost = context.HttpContext.Request.Form[nameof(CreateApiViewModel.RequestUrlHost)].ToString(); var hosts = requestUrlHost.Split(',').Select(host => host.Trim()); - List unacceptableHostnames = new(); - - unacceptableHostnames.AddRange(hosts.Where(hostname => forbiddenRequestUrlHosts.Contains(hostname))); + List unacceptableHostnames = [.. hosts.Where(hostname => forbiddenRequestUrlHosts.Contains(hostname))]; - if (unacceptableHostnames.Any()) + if (unacceptableHostnames.Count != 0) { var unacceptableHostnamesString = string.Join(", ", unacceptableHostnames); context.ModelState.AddModelError( diff --git a/Lombiq.Hosting.Tenants.Management/Filters/ShellSettingsEditorFilter.cs b/Lombiq.Hosting.Tenants.Management/Filters/ShellSettingsEditorFilter.cs index 1866e363..61122bd1 100644 --- a/Lombiq.Hosting.Tenants.Management/Filters/ShellSettingsEditorFilter.cs +++ b/Lombiq.Hosting.Tenants.Management/Filters/ShellSettingsEditorFilter.cs @@ -11,22 +11,11 @@ namespace Lombiq.Hosting.Tenants.Management.Filters; -public class ShellSettingsEditorFilter : IAsyncResultFilter +public class ShellSettingsEditorFilter( + ILayoutAccessor layoutAccessor, + IShapeFactory shapeFactory, + IShellHost shellHost) : IAsyncResultFilter { - private readonly ILayoutAccessor _layoutAccessor; - private readonly IShapeFactory _shapeFactory; - private readonly IShellHost _shellHost; - - public ShellSettingsEditorFilter( - ILayoutAccessor layoutAccessor, - IShapeFactory shapeFactory, - IShellHost shellHost) - { - _layoutAccessor = layoutAccessor; - _shapeFactory = shapeFactory; - _shellHost = shellHost; - } - public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { var actionRouteController = context.ActionDescriptor.RouteValues["Controller"]; @@ -39,13 +28,13 @@ actionRouteValue is nameof(AdminController.Edit) && context.Result is ViewResult) { var tenantName = context.RouteData.Values["Id"].ToString(); - if (!_shellHost.TryGetSettings(tenantName, out var shellSettings)) + if (!shellHost.TryGetSettings(tenantName, out var shellSettings)) { await next(); return; } - var layout = await _layoutAccessor.GetLayoutAsync(); + var layout = await layoutAccessor.GetLayoutAsync(); var contentZone = layout.Zones["Content"]; (context.Controller as Controller) @@ -60,7 +49,7 @@ actionRouteValue is nameof(AdminController.Edit) && : validationErrorJson.ToString(); await contentZone.AddAsync( - await _shapeFactory.CreateAsync( + await shapeFactory.CreateAsync( "ShellSettingsEditor", viewModel => { diff --git a/Lombiq.Hosting.Tenants.Management/Service/SetupWithRecipesFilterService.cs b/Lombiq.Hosting.Tenants.Management/Service/SetupWithRecipesFilterService.cs index 0c712bf5..a42a27e9 100644 --- a/Lombiq.Hosting.Tenants.Management/Service/SetupWithRecipesFilterService.cs +++ b/Lombiq.Hosting.Tenants.Management/Service/SetupWithRecipesFilterService.cs @@ -11,37 +11,26 @@ namespace Lombiq.Hosting.Tenants.Management.Service; -public class SetupWithRecipesFilterService : ISetupService +public class SetupWithRecipesFilterService( + IOptions hideRecipesFromSetupOptions, + ShellSettings shellSettings, + ISetupService setupService) : ISetupService { - private readonly IOptions _hideRecipesFromSetupOptions; - private readonly ShellSettings _shellSettings; - private readonly ISetupService _setupService; - - public SetupWithRecipesFilterService( - IOptions hideRecipesFromSetupOptions, - ShellSettings shellSettings, - ISetupService setupService) - { - _hideRecipesFromSetupOptions = hideRecipesFromSetupOptions; - _shellSettings = shellSettings; - _setupService = setupService; - } - public async Task> GetSetupRecipesAsync() { - var recipesDescriptors = await _setupService.GetSetupRecipesAsync(); + var recipesDescriptors = await setupService.GetSetupRecipesAsync(); // The first case is when we specify the tenant recipe name via the Default tenant admin UI or AutoSetup // feature, the second case is necessary because the Default tenant doesn't fill in RecipeName even if we use // auto setup. - if (_shellSettings["RecipeName"] != null || _shellSettings.Name.EqualsOrdinalIgnoreCase("Default")) + if (shellSettings["RecipeName"] != null || shellSettings.Name.EqualsOrdinalIgnoreCase("Default")) { return recipesDescriptors; } - var hiddenTags = _hideRecipesFromSetupOptions.Value.HiddenTags; + var hiddenTags = hideRecipesFromSetupOptions.Value.HiddenTags; return recipesDescriptors.Where(recipe => !recipe.Tags.Exists(tag => hiddenTags.Contains(tag))); } - public Task SetupAsync(SetupContext context) => _setupService.SetupAsync(context); + public Task SetupAsync(SetupContext context) => setupService.SetupAsync(context); } diff --git a/Lombiq.Hosting.Tenants.Management/Startup.cs b/Lombiq.Hosting.Tenants.Management/Startup.cs index 4547afbe..409832c0 100644 --- a/Lombiq.Hosting.Tenants.Management/Startup.cs +++ b/Lombiq.Hosting.Tenants.Management/Startup.cs @@ -12,16 +12,12 @@ namespace Lombiq.Hosting.Tenants.Management; [Feature(FeatureNames.ForbiddenTenantNames)] -public class ForbiddenTenantNamesStartup : StartupBase +public class ForbiddenTenantNamesStartup(IShellConfiguration shellConfiguration) : StartupBase { - private readonly IShellConfiguration _shellConfiguration; - - public ForbiddenTenantNamesStartup(IShellConfiguration shellConfiguration) => _shellConfiguration = shellConfiguration; - public override void ConfigureServices(IServiceCollection services) { services.Configure(options => - _shellConfiguration + shellConfiguration .GetSection("Lombiq_Hosting_Tenants_Management:Forbidden_Tenants_Options") .Bind(options)); diff --git a/Lombiq.Hosting.Tenants.MediaStorageManagement/Filters/UploadFileSizeShapeFilter.cs b/Lombiq.Hosting.Tenants.MediaStorageManagement/Filters/UploadFileSizeShapeFilter.cs index dd200e84..250da4e4 100644 --- a/Lombiq.Hosting.Tenants.MediaStorageManagement/Filters/UploadFileSizeShapeFilter.cs +++ b/Lombiq.Hosting.Tenants.MediaStorageManagement/Filters/UploadFileSizeShapeFilter.cs @@ -10,22 +10,11 @@ namespace Lombiq.Hosting.Tenants.MediaStorageManagement.Filters; -public class UploadFileSizeShapeFilter : IAsyncResultFilter +public class UploadFileSizeShapeFilter( + IShapeFactory shapeFactory, + ILayoutAccessor layoutAccessor, + IMediaStorageQuotaService mediaStorageQuotaService) : IAsyncResultFilter { - private readonly IShapeFactory _shapeFactory; - private readonly ILayoutAccessor _layoutAccessor; - private readonly IMediaStorageQuotaService _mediaStorageQuotaService; - - public UploadFileSizeShapeFilter( - IShapeFactory shapeFactory, - ILayoutAccessor layoutAccessor, - IMediaStorageQuotaService mediaStorageQuotaService) - { - _shapeFactory = shapeFactory; - _layoutAccessor = layoutAccessor; - _mediaStorageQuotaService = mediaStorageQuotaService; - } - public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { if (!context.IsAdmin()) @@ -43,10 +32,10 @@ public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultE actionRouteValue is nameof(AdminController.Index) && context.Result is ViewResult) { - var layout = await _layoutAccessor.GetLayoutAsync(); + var layout = await layoutAccessor.GetLayoutAsync(); var contentZone = layout.Zones["Footer"]; - var maximumStorageQuotaMegabytes = _mediaStorageQuotaService.GetMaxStorageQuotaMegabytes(); - await contentZone.AddAsync(await _shapeFactory.CreateAsync( + var maximumStorageQuotaMegabytes = mediaStorageQuotaService.GetMaxStorageQuotaMegabytes(); + await contentZone.AddAsync(await shapeFactory.CreateAsync( "UploadFileSize", viewModel => viewModel.MaximumStorageQuotaMegabytes = maximumStorageQuotaMegabytes)); } diff --git a/Lombiq.Hosting.Tenants.MediaStorageManagement/Service/MediaStorageQuotaService.cs b/Lombiq.Hosting.Tenants.MediaStorageManagement/Service/MediaStorageQuotaService.cs index 06cbd9c7..29aa88ad 100644 --- a/Lombiq.Hosting.Tenants.MediaStorageManagement/Service/MediaStorageQuotaService.cs +++ b/Lombiq.Hosting.Tenants.MediaStorageManagement/Service/MediaStorageQuotaService.cs @@ -6,22 +6,15 @@ namespace Lombiq.Hosting.Tenants.MediaStorageManagement.Service; -public class MediaStorageQuotaService : IMediaStorageQuotaService +public class MediaStorageQuotaService( + IOptions mediaStorageManagementOptions, + IMediaFileStore mediaFileStore) : IMediaStorageQuotaService { - private readonly MediaStorageManagementOptions _mediaStorageManagementOptions; - private readonly IMediaFileStore _mediaFileStore; - - public MediaStorageQuotaService( - IOptions mediaStorageManagementOptions, - IMediaFileStore mediaFileStore) - { - _mediaStorageManagementOptions = mediaStorageManagementOptions.Value; - _mediaFileStore = mediaFileStore; - } + private readonly MediaStorageManagementOptions _mediaStorageManagementOptions = mediaStorageManagementOptions.Value; public async Task GetRemainingMediaStorageQuotaBytesAsync() { - var directoryContent = _mediaFileStore.GetDirectoryContentAsync(includeSubDirectories: true); + var directoryContent = mediaFileStore.GetDirectoryContentAsync(includeSubDirectories: true); var listed = await directoryContent.ToListAsync(); var sumBytes = listed.Where(item => item.Length > 0).Sum(item => item.Length); diff --git a/Lombiq.Hosting.Tenants.MediaStorageManagement/Startup.cs b/Lombiq.Hosting.Tenants.MediaStorageManagement/Startup.cs index 300b24d8..5ae428fb 100644 --- a/Lombiq.Hosting.Tenants.MediaStorageManagement/Startup.cs +++ b/Lombiq.Hosting.Tenants.MediaStorageManagement/Startup.cs @@ -10,18 +10,14 @@ namespace Lombiq.Hosting.Tenants.MediaStorageManagement; -public class Startup : StartupBase +public class Startup(IShellConfiguration shellConfiguration) : StartupBase { - private readonly IShellConfiguration _shellConfiguration; - - public Startup(IShellConfiguration shellConfiguration) => _shellConfiguration = shellConfiguration; - public override void ConfigureServices(IServiceCollection services) { var maximumStorageQuotaBytes = - _shellConfiguration.GetValue( + shellConfiguration.GetValue( "Lombiq_Hosting_Tenants_MediaStorageManagement:MaximumStorageQuotaBytes") ?? - _shellConfiguration.GetValue( + shellConfiguration.GetValue( "Lombiq_Hosting_Tenants_MediaStorageManagement:Media_Storage_Management_Options:MaximumSpace"); services.Configure(options => options.MaximumStorageQuotaBytes = maximumStorageQuotaBytes ?? MaximumStorageQuotaBytes);